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

  const cache = {};

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

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

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

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

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

    return name;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    const plugin = require(plugin_entry);

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

    return plugin;
  }

  return main;
})
([
/* main.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(2) /* ./index */, exports);
    // TODO: remove this when models are split up from core
    require(76) /* ./models/main */;
},
/* tslib/tslib.es6.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.__extends = __extends;
    exports.__rest = __rest;
    exports.__decorate = __decorate;
    exports.__param = __param;
    exports.__esDecorate = __esDecorate;
    exports.__runInitializers = __runInitializers;
    exports.__propKey = __propKey;
    exports.__setFunctionName = __setFunctionName;
    exports.__metadata = __metadata;
    exports.__awaiter = __awaiter;
    exports.__generator = __generator;
    exports.__exportStar = __exportStar;
    exports.__values = __values;
    exports.__read = __read;
    exports.__spread = __spread;
    exports.__spreadArrays = __spreadArrays;
    exports.__spreadArray = __spreadArray;
    exports.__await = __await;
    exports.__asyncGenerator = __asyncGenerator;
    exports.__asyncDelegator = __asyncDelegator;
    exports.__asyncValues = __asyncValues;
    exports.__makeTemplateObject = __makeTemplateObject;
    exports.__importStar = __importStar;
    exports.__importDefault = __importDefault;
    exports.__classPrivateFieldGet = __classPrivateFieldGet;
    exports.__classPrivateFieldSet = __classPrivateFieldSet;
    exports.__classPrivateFieldIn = __classPrivateFieldIn;
    exports.__addDisposableResource = __addDisposableResource;
    exports.__disposeResources = __disposeResources;
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) {
                for (var p in b)
                    if (Object.prototype.hasOwnProperty.call(b, p))
                        d[p] = b[p];
            };
        return extendStatics(d, b);
    };
    function __extends(d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    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;
    }
    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;
    }
    function __param(paramIndex, decorator) {
        return function (target, key) { decorator(target, key, paramIndex); };
    }
    function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
        function accept(f) {
            if (f !== void 0 && typeof f !== "function")
                throw new TypeError("Function expected");
            return f;
        }
        var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
        var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
        var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
        var _, done = false;
        for (var i = decorators.length - 1; i >= 0; i--) {
            var context = {};
            for (var p in contextIn)
                context[p] = p === "access" ? {} : contextIn[p];
            for (var p in contextIn.access)
                context.access[p] = contextIn.access[p];
            context.addInitializer = function (f) {
                if (done)
                    throw new TypeError("Cannot add initializers after decoration has completed");
                extraInitializers.push(accept(f || null));
            };
            var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
            if (kind === "accessor") {
                if (result === void 0)
                    continue;
                if (result === null || typeof result !== "object")
                    throw new TypeError("Object expected");
                if (_ = accept(result.get))
                    descriptor.get = _;
                if (_ = accept(result.set))
                    descriptor.set = _;
                if (_ = accept(result.init))
                    initializers.unshift(_);
            }
            else if (_ = accept(result)) {
                if (kind === "field")
                    initializers.unshift(_);
                else
                    descriptor[key] = _;
            }
        }
        if (target)
            Object.defineProperty(target, contextIn.name, descriptor);
        done = true;
    }
    ;
    function __runInitializers(thisArg, initializers, value) {
        var useValue = arguments.length > 2;
        for (var i = 0; i < initializers.length; i++) {
            value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
        }
        return useValue ? value : void 0;
    }
    ;
    function __propKey(x) {
        return typeof x === "symbol" ? x : "".concat(x);
    }
    ;
    function __setFunctionName(f, name, prefix) {
        if (typeof name === "symbol")
            name = name.description ? "[".concat(name.description, "]") : "";
        return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
    }
    ;
    function __metadata(metadataKey, metadataValue) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
            return Reflect.metadata(metadataKey, metadataValue);
    }
    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());
        });
    }
    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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
        return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f)
                throw new TypeError("Generator is already executing.");
            while (g && (g = 0, op[0] && (_ = 0)), _)
                try {
                    if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
                        return t;
                    if (y = 0, t)
                        op = [op[0] & 2, t.value];
                    switch (op[0]) {
                        case 0:
                        case 1:
                            t = op;
                            break;
                        case 4:
                            _.label++;
                            return { value: op[1], done: false };
                        case 5:
                            _.label++;
                            y = op[1];
                            op = [0];
                            continue;
                        case 7:
                            op = _.ops.pop();
                            _.trys.pop();
                            continue;
                        default:
                            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                                _ = 0;
                                continue;
                            }
                            if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
                                _.label = op[1];
                                break;
                            }
                            if (op[0] === 6 && _.label < t[1]) {
                                _.label = t[1];
                                t = op;
                                break;
                            }
                            if (t && _.label < t[2]) {
                                _.label = t[2];
                                _.ops.push(op);
                                break;
                            }
                            if (t[2])
                                _.ops.pop();
                            _.trys.pop();
                            continue;
                    }
                    op = body.call(thisArg, _);
                }
                catch (e) {
                    op = [6, e];
                    y = 0;
                }
                finally {
                    f = t = 0;
                }
            if (op[0] & 5)
                throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
        }
    }
    exports.__createBinding = Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    });
    function __exportStar(m, o) {
        for (var p in m)
            if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
                (0, exports.__createBinding)(o, m, p);
    }
    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.");
    }
    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;
    }
    /** @deprecated */
    function __spread() {
        for (var ar = [], i = 0; i < arguments.length; i++)
            ar = ar.concat(__read(arguments[i]));
        return ar;
    }
    /** @deprecated */
    function __spreadArrays() {
        for (var s = 0, i = 0, il = arguments.length; i < il; i++)
            s += arguments[i].length;
        for (var r = Array(s), k = 0, i = 0; i < il; i++)
            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
                r[k] = a[j];
        return r;
    }
    function __spreadArray(to, from, pack) {
        if (pack || arguments.length === 2)
            for (var i = 0, l = from.length, ar; i < l; i++) {
                if (ar || !(i in from)) {
                    if (!ar)
                        ar = Array.prototype.slice.call(from, 0, i);
                    ar[i] = from[i];
                }
            }
        return to.concat(ar || Array.prototype.slice.call(from));
    }
    function __await(v) {
        return this instanceof __await ? (this.v = v, this) : new __await(v);
    }
    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 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
        function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
        function verb(n, f) {
            if (g[n]) {
                i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); };
                if (f)
                    i[n] = f(i[n]);
            }
        }
        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]);
        }
    }
    function __asyncDelegator(o) {
        var i, p;
        return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
    }
    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); }
    }
    function __makeTemplateObject(cooked, raw) {
        if (Object.defineProperty) {
            Object.defineProperty(cooked, "raw", { value: raw });
        }
        else {
            cooked.raw = raw;
        }
        return cooked;
    }
    ;
    var __setModuleDefault = Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    };
    function __importStar(mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k in mod)
                if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
                    (0, exports.__createBinding)(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    }
    function __importDefault(mod) {
        return (mod && mod.__esModule) ? mod : { default: mod };
    }
    function __classPrivateFieldGet(receiver, state, kind, f) {
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a getter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot read private member from an object whose class did not declare it");
        return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    }
    function __classPrivateFieldSet(receiver, state, value, kind, f) {
        if (kind === "m")
            throw new TypeError("Private method is not writable");
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a setter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot write private member to an object whose class did not declare it");
        return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
    }
    function __classPrivateFieldIn(state, receiver) {
        if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function"))
            throw new TypeError("Cannot use 'in' operator on non-object");
        return typeof state === "function" ? receiver === state : state.has(receiver);
    }
    function __addDisposableResource(env, value, async) {
        if (value !== null && value !== void 0) {
            if (typeof value !== "object" && typeof value !== "function")
                throw new TypeError("Object expected.");
            var dispose, inner;
            if (async) {
                if (!Symbol.asyncDispose)
                    throw new TypeError("Symbol.asyncDispose is not defined.");
                dispose = value[Symbol.asyncDispose];
            }
            if (dispose === void 0) {
                if (!Symbol.dispose)
                    throw new TypeError("Symbol.dispose is not defined.");
                dispose = value[Symbol.dispose];
                if (async)
                    inner = dispose;
            }
            if (typeof dispose !== "function")
                throw new TypeError("Object not disposable.");
            if (inner)
                dispose = function () {
                    try {
                        inner.call(this);
                    }
                    catch (e) {
                        return Promise.reject(e);
                    }
                };
            env.stack.push({ value: value, dispose: dispose, async: async });
        }
        else if (async) {
            env.stack.push({ async: true });
        }
        return value;
    }
    var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
        var e = new Error(message);
        return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    };
    function __disposeResources(env) {
        function fail(e) {
            env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1)
                        return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async)
                            return s |= 2, Promise.resolve(result).then(next, function (e) { fail(e); return next(); });
                    }
                    else
                        s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1)
                return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError)
                throw env.error;
        }
        return next();
    }
    exports.default = {
        __extends: __extends,
        __assign: exports.__assign,
        __rest: __rest,
        __decorate: __decorate,
        __param: __param,
        __metadata: __metadata,
        __awaiter: __awaiter,
        __generator: __generator,
        __createBinding: exports.__createBinding,
        __exportStar: __exportStar,
        __values: __values,
        __read: __read,
        __spread: __spread,
        __spreadArrays: __spreadArrays,
        __spreadArray: __spreadArray,
        __await: __await,
        __asyncGenerator: __asyncGenerator,
        __asyncDelegator: __asyncDelegator,
        __asyncValues: __asyncValues,
        __makeTemplateObject: __makeTemplateObject,
        __importStar: __importStar,
        __importDefault: __importDefault,
        __classPrivateFieldGet: __classPrivateFieldGet,
        __classPrivateFieldSet: __classPrivateFieldSet,
        __classPrivateFieldIn: __classPrivateFieldIn,
        __addDisposableResource: __addDisposableResource,
        __disposeResources: __disposeResources,
    };
},
/* index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    var version_1 = require(3) /* ./version */;
    __esExport("version", version_1.version);
    var embed_1 = require(4) /* ./embed */;
    __esExport("index", embed_1.index);
    exports.embed = tslib_1.__importStar(require(4) /* ./embed */);
    exports.protocol = tslib_1.__importStar(require(74) /* ./protocol */);
    var logging_1 = require(19) /* ./core/logging */;
    __esExport("logger", logging_1.logger);
    __esExport("set_log_level", logging_1.set_log_level);
    var settings_1 = require(29) /* ./core/settings */;
    __esExport("settings", settings_1.settings);
    var base_1 = require(7) /* ./base */;
    __esExport("Models", base_1.Models);
    var document_1 = require(5) /* ./document */;
    __esExport("documents", document_1.documents);
    var safely_1 = require(75) /* ./safely */;
    __esExport("safely", safely_1.safely);
},
/* version.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.version = "3.6.0";
},
/* embed/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.embed_item = embed_item;
    exports.embed_items = embed_items;
    const document_1 = require(5) /* ../document */;
    const settings_1 = require(29) /* ../core/settings */;
    const logging_1 = require(19) /* ../core/logging */;
    const string_1 = require(40) /* ../core/util/string */;
    const object_1 = require(9) /* ../core/util/object */;
    const types_1 = require(8) /* ../core/util/types */;
    const defer_1 = require(16) /* ../core/util/defer */;
    const standalone_1 = require(54) /* ./standalone */;
    const server_1 = require(67) /* ./server */;
    const dom_1 = require(72) /* ./dom */;
    var standalone_2 = require(54) /* ./standalone */;
    __esExport("add_document_standalone", standalone_2.add_document_standalone);
    __esExport("index", standalone_2.index);
    var server_2 = require(67) /* ./server */;
    __esExport("add_document_from_session", server_2.add_document_from_session);
    var notebook_1 = require(73) /* ./notebook */;
    __esExport("embed_items_notebook", notebook_1.embed_items_notebook);
    __esExport("kernels", notebook_1.kernels);
    async function embed_item(item, target) {
        const docs_json = {};
        const doc_id = (0, string_1.uuid4)();
        docs_json[doc_id] = item.doc;
        if (target == null) {
            target = item.target_id;
        }
        const roots = { [item.root_id]: target };
        const render_item = { roots, root_ids: [item.root_id], docid: doc_id };
        await (0, defer_1.defer)();
        const [views] = await _embed_items(docs_json, [render_item]);
        return views;
    }
    // TODO (bev) this is currently clunky. Standalone embeds only provide
    // the first two args, whereas server provide the app_app, and *may* prove and
    // absolute_url as well if non-relative links are needed for resources. This function
    // should probably be split in to two pieces to reflect the different usage patterns
    async function embed_items(docs_json, render_items, app_path, absolute_url) {
        await (0, defer_1.defer)();
        return _embed_items(docs_json, render_items, app_path, absolute_url);
    }
    async function _embed_items(docs_json, render_items, app_path, absolute_url) {
        if ((0, types_1.isString)(docs_json)) {
            docs_json = JSON.parse((0, string_1.unescape)(docs_json));
        }
        const docs = {};
        for (const [docid, doc_json] of (0, object_1.entries)(docs_json)) {
            docs[docid] = document_1.Document.from_json(doc_json);
        }
        const views = [];
        for (const item of render_items) {
            const element = (0, dom_1._resolve_element)(item);
            const roots = (0, dom_1._resolve_root_elements)(item);
            if (item.docid != null) {
                views.push(await (0, standalone_1.add_document_standalone)(docs[item.docid], element, roots, item.use_for_title));
            }
            else if (item.token != null) {
                const websocket_url = (0, server_1._get_ws_url)(app_path, absolute_url);
                logging_1.logger.debug(`embed: computed ws url: ${websocket_url}`);
                try {
                    views.push(await (0, server_1.add_document_from_session)(websocket_url, item.token, element, roots, item.use_for_title));
                    console.log("Bokeh items were rendered successfully");
                }
                catch (error) {
                    if (settings_1.settings.dev) {
                        throw error;
                    }
                    else {
                        console.error("Error rendering Bokeh items:", error);
                    }
                }
            }
            else {
                throw new Error("Error rendering Bokeh items: either 'docid' or 'token' was expected.");
            }
        }
        return views;
    }
},
/* document/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(6) /* ./document */, exports);
    tslib_1.__exportStar(require(41) /* ./events */, exports);
},
/* document/document.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const base_1 = require(7) /* ../base */;
    const version_1 = require(3) /* ../version */;
    const logging_1 = require(19) /* ../core/logging */;
    const resolvers_1 = require(46) /* ../core/resolvers */;
    const serialization_1 = require(32) /* ../core/serialization */;
    const deserializer_1 = require(47) /* ../core/serialization/deserializer */;
    const version_2 = require(49) /* ../core/util/version */;
    const signaling_1 = require(15) /* ../core/signaling */;
    const types_1 = require(8) /* ../core/util/types */;
    const eq_1 = require(26) /* ../core/util/eq */;
    const array_1 = require(10) /* ../core/util/array */;
    const object_1 = require(9) /* ../core/util/object */;
    const sets = tslib_1.__importStar(require(44) /* ../core/util/set */);
    const callbacks_1 = require(50) /* ../core/util/callbacks */;
    const assert_1 = require(12) /* ../core/util/assert */;
    const model_1 = require(51) /* ../model */;
    const defs_1 = require(52) /* ./defs */;
    const bokeh_events_1 = require(53) /* ../core/bokeh_events */;
    const bokeh_events_2 = require(53) /* ../core/bokeh_events */;
    const events_1 = require(41) /* ./events */;
    deserializer_1.Deserializer.register("model", defs_1.decode_def);
    // Dispatches events to the subscribed models
    class EventManager {
        constructor(document) {
            this.subscribed_models = new Set();
            this.document = document;
        }
        send_event(bokeh_event) {
            if (bokeh_event.publish) {
                const event = new events_1.MessageSentEvent(this.document, "bokeh_event", bokeh_event);
                this.document._trigger_on_change(event);
            }
            this.document._trigger_on_event(bokeh_event);
        }
        trigger(event) {
            for (const model of this.subscribed_models) {
                if (event.origin != null && event.origin != model) {
                    continue;
                }
                model._process_event(event);
            }
        }
    }
    exports.EventManager = EventManager;
    EventManager.__name__ = "EventManager";
    exports.documents = [];
    exports.DEFAULT_TITLE = "Bokeh Application";
    // This class should match the API of the Python Document class
    // as much as possible.
    class Document {
        constructor(options = {}) {
            exports.documents.push(this);
            this._init_timestamp = Date.now();
            this._resolver = options.resolver ?? new resolvers_1.ModelResolver(base_1.default_resolver);
            this._title = exports.DEFAULT_TITLE;
            this._roots = [];
            this._all_models = new Map();
            this._new_models = new Set();
            this._all_models_freeze_count = 0;
            this._callbacks = new Map();
            this._document_callbacks = new Map();
            this._message_callbacks = new Map();
            this.event_manager = new EventManager(this);
            this.idle = new signaling_1.Signal0(this, "idle");
            this._idle_roots = new WeakSet();
            this._interactive_timestamp = null;
            this._interactive_plot = null;
            if (options.roots != null) {
                this._add_roots(...options.roots);
            }
            this.on_message("bokeh_event", (event) => {
                (0, assert_1.assert)(event instanceof bokeh_events_1.ModelEvent);
                this.event_manager.trigger(event);
            });
        }
        [eq_1.equals](that, _cmp) {
            return this == that;
        }
        get all_models() {
            return new Set(this._all_models.values());
        }
        get is_idle() {
            // TODO: models without views, e.g. data models
            for (const root of this._roots) {
                if (!this._idle_roots.has(root)) {
                    return false;
                }
            }
            return true;
        }
        notify_idle(model) {
            this._idle_roots.add(model);
            if (this.is_idle) {
                logging_1.logger.info(`document idle at ${Date.now() - this._init_timestamp} ms`);
                this.event_manager.send_event(new bokeh_events_2.DocumentReady());
                this.idle.emit();
            }
        }
        clear() {
            this._push_all_models_freeze();
            try {
                while (this._roots.length > 0) {
                    this.remove_root(this._roots[0]);
                }
            }
            finally {
                this._pop_all_models_freeze();
            }
        }
        interactive_start(plot, finalize = null) {
            if (this._interactive_plot == null) {
                this._interactive_plot = plot;
                this._interactive_plot.trigger_event(new bokeh_events_2.LODStart());
            }
            this._interactive_finalize = finalize;
            this._interactive_timestamp = Date.now();
        }
        interactive_stop() {
            if (this._interactive_plot != null) {
                this._interactive_plot.trigger_event(new bokeh_events_2.LODEnd());
                if (this._interactive_finalize != null) {
                    this._interactive_finalize();
                }
            }
            this._interactive_plot = null;
            this._interactive_timestamp = null;
            this._interactive_finalize = null;
        }
        interactive_duration() {
            if (this._interactive_timestamp == null) {
                return -1;
            }
            else {
                return Date.now() - this._interactive_timestamp;
            }
        }
        destructively_move(dest_doc) {
            if (dest_doc === this) {
                throw new Error("Attempted to overwrite a document with itself");
            }
            dest_doc.clear();
            // we have to remove ALL roots before adding any
            // to the new doc or else models referenced from multiple
            // roots could be in both docs at once, which isn't allowed.
            const roots = (0, array_1.copy)(this._roots);
            this.clear();
            for (const root of roots) {
                if (root.document != null) {
                    throw new Error(`Somehow we didn't detach ${root}`);
                }
            }
            if (this._all_models.size != 0) {
                throw new Error(`this._all_models still had stuff in it: ${this._all_models}`);
            }
            for (const root of roots) {
                dest_doc.add_root(root);
            }
            dest_doc.set_title(this._title);
        }
        // TODO other fields of doc
        _push_all_models_freeze() {
            this._all_models_freeze_count += 1;
        }
        _pop_all_models_freeze() {
            this._all_models_freeze_count -= 1;
            if (this._all_models_freeze_count === 0) {
                this._recompute_all_models();
            }
        }
        /*protected*/ _invalidate_all_models() {
            logging_1.logger.debug("invalidating document models");
            // if freeze count is > 0, we'll recompute on unfreeze
            if (this._all_models_freeze_count === 0) {
                this._recompute_all_models();
            }
        }
        _recompute_all_models() {
            let new_all_models_set = new Set();
            for (const r of this._roots) {
                new_all_models_set = sets.union(new_all_models_set, r.references());
            }
            const old_all_models_set = new Set(this._all_models.values());
            const to_detach = sets.difference(old_all_models_set, new_all_models_set);
            const to_attach = sets.difference(new_all_models_set, old_all_models_set);
            const recomputed = new Map();
            for (const model of new_all_models_set) {
                recomputed.set(model.id, model);
            }
            for (const d of to_detach) {
                d.detach_document();
            }
            for (const model of to_attach) {
                model.attach_document(this);
                this._new_models.add(model);
            }
            this._all_models = recomputed; // XXX
        }
        roots() {
            return this._roots;
        }
        _add_roots(...models) {
            models = models.filter((model) => !this._roots.includes(model));
            if (models.length == 0) {
                return false;
            }
            this._push_all_models_freeze();
            try {
                this._roots.push(...models);
            }
            finally {
                this._pop_all_models_freeze();
            }
            return true;
        }
        _remove_root(model) {
            const i = this._roots.indexOf(model);
            if (i < 0) {
                return false;
            }
            this._push_all_models_freeze();
            try {
                this._roots.splice(i, 1);
            }
            finally {
                this._pop_all_models_freeze();
            }
            return true;
        }
        _set_title(title) {
            const new_title = title != this._title;
            if (new_title) {
                this._title = title;
            }
            return new_title;
        }
        add_root(model, { sync } = {}) {
            if (this._add_roots(model)) {
                const event = new events_1.RootAddedEvent(this, model);
                event.sync = sync ?? true;
                this._trigger_on_change(event);
            }
        }
        remove_root(model, { sync } = {}) {
            if (this._remove_root(model)) {
                const event = new events_1.RootRemovedEvent(this, model);
                event.sync = sync ?? true;
                this._trigger_on_change(event);
            }
        }
        set_title(title, { sync } = {}) {
            if (this._set_title(title)) {
                const event = new events_1.TitleChangedEvent(this, title);
                event.sync = sync ?? true;
                this._trigger_on_change(event);
            }
        }
        title() {
            return this._title;
        }
        get_model_by_id(model_id) {
            return this._all_models.get(model_id) ?? 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) {
            this._message_callbacks.get(msg_type)?.delete(callback);
        }
        _trigger_on_message(msg_type, msg_data) {
            const message_callbacks = this._message_callbacks.get(msg_type);
            if (message_callbacks != null) {
                for (const cb of message_callbacks) {
                    cb(msg_data);
                }
            }
        }
        on_change(callback, allow_batches = false) {
            if (!this._callbacks.has(callback)) {
                this._callbacks.set(callback, allow_batches);
            }
        }
        remove_on_change(callback) {
            this._callbacks.delete(callback);
        }
        _trigger_on_change(event) {
            for (const [callback, allow_batches] of this._callbacks) {
                if (!allow_batches && event instanceof events_1.DocumentEventBatch) {
                    for (const ev of event.events) {
                        callback(ev);
                    }
                }
                else {
                    callback(event); // TODO
                }
            }
        }
        _trigger_on_event(event) {
            const callbacks = this._document_callbacks.get(event.event_name);
            if (callbacks != null) {
                for (const callback of callbacks) {
                    void (0, callbacks_1.execute)(callback, this, event);
                }
            }
        }
        on_event(event, ...callbacks) {
            const name = (0, types_1.isString)(event) ? event : event.prototype.event_name;
            const existing = this._document_callbacks.get(name) ?? [];
            const added = callbacks;
            this._document_callbacks.set(name, [...existing, ...added]);
        }
        to_json_string(include_defaults = true) {
            return JSON.stringify(this.to_json(include_defaults));
        }
        to_json(include_defaults = true) {
            const serializer = new serialization_1.Serializer({ include_defaults });
            const roots = serializer.encode(this._roots);
            return {
                version: version_1.version,
                title: this._title,
                roots,
            };
        }
        static from_json_string(s, events) {
            const json = JSON.parse(s);
            return Document.from_json(json, events);
        }
        static _handle_version(json) {
            if (json.version == null) {
                logging_1.logger.warn("'version' field is missing");
            }
            const py_version = json.version ?? "0.0.0";
            const py_ver = version_2.Version.from(py_version);
            const js_ver = version_2.Version.from(version_1.version);
            const message = `new document using Bokeh ${py_version} and BokehJS ${version_1.version}`;
            if ((0, eq_1.is_equal)(py_ver, js_ver)) {
                logging_1.logger.debug(message);
            }
            else {
                logging_1.logger.warn(`Bokeh/BokehJS version mismatch: ${message}`);
            }
        }
        static from_json(doc_json, events) {
            logging_1.logger.debug("Creating Document from JSON");
            Document._handle_version(doc_json);
            const resolver = new resolvers_1.ModelResolver(base_1.default_resolver);
            if (doc_json.defs != null) {
                const deserializer = new deserializer_1.Deserializer(resolver);
                deserializer.decode(doc_json.defs);
            }
            const doc = new Document({ resolver });
            doc._push_all_models_freeze();
            const listener = (event) => events?.push(event);
            doc.on_change(listener, true);
            const deserializer = new deserializer_1.Deserializer(resolver, doc._all_models, (obj) => obj.attach_document(doc));
            const roots = deserializer.decode(doc_json.roots);
            const callbacks = (() => {
                if (doc_json.callbacks != null) {
                    return deserializer.decode(doc_json.callbacks);
                }
                else {
                    return {};
                }
            })();
            doc.remove_on_change(listener);
            for (const [event, event_callbacks] of (0, object_1.entries)(callbacks)) {
                doc.on_event(event, ...event_callbacks);
            }
            for (const root of roots) {
                doc.add_root(root);
            }
            if (doc_json.title != null) {
                doc.set_title(doc_json.title);
            }
            doc._pop_all_models_freeze();
            return doc;
        }
        replace_with_json(json) {
            const replacement = Document.from_json(json);
            replacement.destructively_move(this);
        }
        create_json_patch(events) {
            for (const event of events) {
                if (event.document != this) {
                    throw new Error("Cannot create a patch using events from a different document");
                }
            }
            const references = new Map();
            for (const model of this._all_models.values()) {
                if (!this._new_models.has(model)) {
                    references.set(model, model.ref());
                }
            }
            const serializer = new serialization_1.Serializer({ references, binary: true });
            const patch = { events: serializer.encode(events) };
            this._new_models.clear();
            return patch;
        }
        apply_json_patch(patch, buffers = new Map()) {
            this._push_all_models_freeze();
            const deserializer = new deserializer_1.Deserializer(this._resolver, this._all_models, (obj) => obj.attach_document(this));
            const events = deserializer.decode(patch.events, buffers);
            for (const event of events) {
                switch (event.kind) {
                    case "MessageSent": {
                        const { msg_type, msg_data } = event;
                        this._trigger_on_message(msg_type, msg_data);
                        break;
                    }
                    case "ModelChanged": {
                        const { model, attr, new: value } = event;
                        model.setv({ [attr]: value }, { sync: false });
                        break;
                    }
                    case "ColumnDataChanged": {
                        const { model, attr, data, cols } = event;
                        if (cols != null) {
                            const new_data = (0, object_1.dict)(data);
                            const current_data = (0, object_1.dict)(model.property(attr).get_value());
                            for (const [name, column] of current_data) {
                                if (!new_data.has(name)) {
                                    new_data.set(name, column);
                                }
                            }
                        }
                        model.setv({ data }, { sync: false, check_eq: false });
                        break;
                    }
                    case "ColumnsStreamed": {
                        const { model, attr, data, rollover } = event;
                        const prop = model.property(attr);
                        model.stream_to(prop, data, rollover, { sync: false });
                        break;
                    }
                    case "ColumnsPatched": {
                        const { model, attr, patches } = event;
                        const prop = model.property(attr);
                        model.patch_to(prop, patches, { sync: false });
                        break;
                    }
                    case "RootAdded": {
                        this.add_root(event.model, { sync: false });
                        break;
                    }
                    case "RootRemoved": {
                        this.remove_root(event.model, { sync: false });
                        break;
                    }
                    case "TitleChanged": {
                        this.set_title(event.title, { sync: false });
                        break;
                    }
                    default: {
                        throw new Error(`unknown patch event type '${event.kind}'`); // XXX
                    }
                }
            }
            this._pop_all_models_freeze();
        }
    }
    exports.Document = Document;
    Document.__name__ = "Document";
},
/* base.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.register_models = register_models;
    const types_1 = require(8) /* ./core/util/types */;
    const object_1 = require(9) /* ./core/util/object */;
    const types_2 = require(8) /* ./core/util/types */;
    const has_props_1 = require(14) /* ./core/has_props */;
    const resolvers_1 = require(46) /* ./core/resolvers */;
    exports.default_resolver = new resolvers_1.ModelResolver(null);
    exports.Models = new Proxy(exports.default_resolver, {
        get(target, name, receiver) {
            if ((0, types_2.isString)(name)) {
                const model = target.get(name);
                if (model != null) {
                    return model;
                }
            }
            return Reflect.get(target, name, receiver);
        },
        has(target, name) {
            if ((0, types_2.isString)(name)) {
                const model = target.get(name);
                if (model != null) {
                    return true;
                }
            }
            return Reflect.has(target, name);
        },
        ownKeys(target) {
            return target.names;
        },
        getOwnPropertyDescriptor(target, name) {
            if ((0, types_2.isString)(name)) {
                const model = target.get(name);
                if (model != null) {
                    return { configurable: true, enumerable: true, writable: false, value: model };
                }
            }
            return Reflect.getOwnPropertyDescriptor(target, name);
        },
    });
    function is_HasProps(obj) {
        return (0, types_1.isObject)(obj) && obj.prototype instanceof has_props_1.HasProps;
    }
    function register_models(models, force = false) {
        for (const model of (0, types_1.isArray)(models) ? models : (0, object_1.values)(models)) {
            if (is_HasProps(model)) {
                exports.default_resolver.register(model, force);
            }
        }
    }
},
/* core/util/types.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_undefined = is_undefined;
    exports.is_defined = is_defined;
    exports.is_nullish = is_nullish;
    exports.isBoolean = isBoolean;
    exports.isNumber = isNumber;
    exports.isInteger = isInteger;
    exports.isString = isString;
    exports.isSymbol = isSymbol;
    exports.isPrimitive = isPrimitive;
    exports.isFunction = isFunction;
    exports.isArray = isArray;
    exports.isArrayOf = isArrayOf;
    exports.isArrayableOf = isArrayableOf;
    exports.isTypedArray = isTypedArray;
    exports.isObject = isObject;
    exports.isBasicObject = isBasicObject;
    exports.isPlainObject = isPlainObject;
    exports.isDict = isDict;
    exports.isIterable = isIterable;
    exports.isArrayable = isArrayable;
    //     Underscore.js 1.8.3
    //     http://underscorejs.org
    //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
    //     Underscore may be freely distributed under the MIT license.
    const { toString } = Object.prototype;
    function is_undefined(obj) {
        return typeof obj === "undefined";
    }
    function is_defined(obj) {
        return typeof obj !== "undefined";
    }
    // XXX: use only to work around strict conditional expressions
    function is_nullish(obj) {
        return obj == null;
    }
    function isBoolean(obj) {
        return obj === true || obj === false || toString.call(obj) === "[object Boolean]";
    }
    function isNumber(obj) {
        return toString.call(obj) === "[object Number]";
    }
    function isInteger(obj) {
        return isNumber(obj) && Number.isInteger(obj);
    }
    function isString(obj) {
        return toString.call(obj) === "[object String]";
    }
    function isSymbol(obj) {
        return typeof obj === "symbol";
    }
    function isPrimitive(obj) {
        return obj === null || isBoolean(obj) || isNumber(obj) || isString(obj) || isSymbol(obj);
    }
    function isFunction(obj) {
        const rep = toString.call(obj);
        switch (rep) {
            case "[object Function]":
            case "[object AsyncFunction]":
            case "[object GeneratorFunction]":
            case "[object AsyncGeneratorFunction]":
                return true;
            default:
                return false;
        }
    }
    function isArray(obj) {
        return Array.isArray(obj);
    }
    function isArrayOf(array, predicate) {
        for (const item of array) {
            if (!predicate(item)) {
                return false;
            }
        }
        return true;
    }
    function isArrayableOf(array, predicate) {
        for (const item of array) {
            if (!predicate(item)) {
                return false;
            }
        }
        return true;
    }
    function isTypedArray(obj) {
        return ArrayBuffer.isView(obj) && !(obj instanceof DataView);
    }
    function isObject(obj) {
        const tp = typeof obj;
        return tp === "function" || tp === "object" && !!obj;
    }
    function isBasicObject(obj) {
        return isObject(obj) && is_nullish(obj.constructor);
    }
    function isPlainObject(obj) {
        return isObject(obj) && (is_nullish(obj.constructor) || obj.constructor === Object);
    }
    function isDict(obj) {
        return obj instanceof Map || isPlainObject(obj);
    }
    function isIterable(obj) {
        return isObject(obj) && Symbol.iterator in obj;
    }
    function isArrayable(obj) {
        return isIterable(obj) && "length" in obj;
    }
},
/* core/util/object.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    exports.to_object = to_object;
    exports.keys = keys;
    exports.values = values;
    exports.entries = entries;
    exports.clone = clone;
    exports.merge = merge;
    exports.size = size;
    exports.is_empty = is_empty;
    exports.dict = dict;
    const types_1 = require(8) /* ./types */;
    const array_1 = require(10) /* ./array */;
    exports.assign = Object.assign;
    exports.extend = exports.assign;
    function to_object(obj) {
        return (0, types_1.isPlainObject)(obj) ? obj : Object.fromEntries(obj);
    }
    function keys(obj) {
        return obj instanceof Map ? [...obj.keys()] : Object.keys(obj);
    }
    function values(obj) {
        return obj instanceof Map ? [...obj.values()] : Object.values(obj);
    }
    function entries(obj) {
        return obj instanceof Map ? [...obj.entries()] : Object.entries(obj);
    }
    exports.typed_keys = Object.keys;
    exports.typed_values = Object.values;
    exports.typed_entries = Object.entries;
    function clone(obj) {
        return obj instanceof Map ? new Map(obj) : { ...obj };
    }
    function merge(obj0, obj1) {
        /*
        * Returns an object with the array values for obj1 and obj2 unioned by key.
        */
        const result = new Map();
        const keys = [...obj0.keys(), ...obj1.keys()];
        for (const key of keys) {
            const v0 = obj0.get(key);
            const v1 = obj1.get(key);
            const arr0 = v0 === undefined ? [] : v0;
            const arr1 = v1 === undefined ? [] : v1;
            result.set(key, (0, array_1.union)(arr0, arr1));
        }
        return result;
    }
    function size(obj) {
        return obj instanceof Map ? obj.size : Object.keys(obj).length;
    }
    function is_empty(obj) {
        return size(obj) == 0;
    }
    const { hasOwnProperty } = Object.prototype;
    class PlainObjectProxy {
        constructor(obj) {
            this[_a] = "PlainObjectProxy";
            this.obj = obj;
        }
        clear() {
            for (const key of this.keys()) {
                delete this.obj[key];
            }
        }
        delete(key) {
            const exists = this.has(key);
            if (exists) {
                delete this.obj[key];
            }
            return exists;
        }
        has(key) {
            return hasOwnProperty.call(this.obj, key);
        }
        get(key) {
            return this.has(key) ? this.obj[key] : undefined;
        }
        set(key, value) {
            this.obj[key] = value;
            return this;
        }
        get size() {
            return size(this.obj);
        }
        [(_a = Symbol.toStringTag, Symbol.iterator)]() {
            return this.entries();
        }
        *keys() {
            yield* keys(this.obj);
        }
        *values() {
            yield* values(this.obj);
        }
        *entries() {
            yield* entries(this.obj);
        }
        forEach(callback, that) {
            for (const [key, value] of this.entries()) {
                callback.call(that, value, key, this);
            }
        }
    }
    exports.PlainObjectProxy = PlainObjectProxy;
    PlainObjectProxy.__name__ = "PlainObjectProxy";
    function dict(obj) {
        return (0, types_1.isPlainObject)(obj) ? new PlainObjectProxy(obj) : obj;
    }
},
/* core/util/array.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.head = head;
    exports.last = last;
    exports.copy = copy;
    exports.concat = concat;
    exports.nth = nth;
    exports.zip = zip;
    exports.unzip = unzip;
    exports.range = range;
    exports.linspace = linspace;
    exports.transpose = transpose;
    exports.argmin = argmin;
    exports.argmax = argmax;
    exports.uniq = uniq;
    exports.uniq_by = uniq_by;
    exports._union = _union;
    exports.union = union;
    exports.intersection = intersection;
    exports.difference = difference;
    exports.symmetric_difference = symmetric_difference;
    exports.remove_at = remove_at;
    exports.remove = remove;
    exports.remove_by = remove_by;
    exports.clear = clear;
    exports.split = split;
    exports.shuffle = shuffle;
    exports.pairwise = pairwise;
    exports.elementwise = elementwise;
    exports.reversed = reversed;
    exports.repeat = repeat;
    exports.resize = resize;
    //     Underscore.js 1.8.3
    //     http://underscorejs.org
    //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
    //     Underscore may be freely distributed under the MIT license.
    const math_1 = require(11) /* ./math */;
    const assert_1 = require(12) /* ./assert */;
    const types_1 = require(8) /* ./types */;
    const arrayable_1 = require(13) /* ./arrayable */;
    var arrayable_2 = require(13) /* ./arrayable */;
    __esExport("map", arrayable_2.map);
    __esExport("reduce", arrayable_2.reduce);
    __esExport("min", arrayable_2.min);
    __esExport("min_by", arrayable_2.min_by);
    __esExport("max", arrayable_2.max);
    __esExport("max_by", arrayable_2.max_by);
    __esExport("sum", arrayable_2.sum);
    __esExport("cumsum", arrayable_2.cumsum);
    __esExport("every", arrayable_2.every);
    __esExport("some", arrayable_2.some);
    __esExport("find", arrayable_2.find);
    __esExport("find_last", arrayable_2.find_last);
    __esExport("find_index", arrayable_2.find_index);
    __esExport("find_last_index", arrayable_2.find_last_index);
    __esExport("sorted_index", arrayable_2.sorted_index);
    __esExport("is_empty", arrayable_2.is_empty);
    __esExport("includes", arrayable_2.includes);
    __esExport("contains", arrayable_2.contains);
    __esExport("sort_by", arrayable_2.sort_by);
    const { slice } = Array.prototype;
    function head(array) {
        if (array.length != 0) {
            return array[0];
        }
        else {
            throw new Error("out of bounds access");
        }
    }
    function last(array) {
        if (array.length != 0) {
            return array[array.length - 1];
        }
        else {
            throw new Error("out of bounds access");
        }
    }
    function copy(array) {
        return slice.call(array);
    }
    function concat(arrays) {
        return [].concat(...arrays);
    }
    function nth(array, index) {
        return array[index >= 0 ? index : array.length + index];
    }
    function zip(...arrays) {
        if (arrays.length == 0) {
            return [];
        }
        const n = (0, arrayable_1.min)(arrays.map((a) => a.length));
        const k = arrays.length;
        const result = new Array(n);
        for (let i = 0; i < n; i++) {
            result[i] = new Array(k);
            for (let j = 0; j < k; j++) {
                result[i][j] = arrays[j][i];
            }
        }
        return result;
    }
    function unzip(array) {
        const n = array.length;
        if (n == 0) {
            return [];
        }
        const k = (0, arrayable_1.min)(array.map((a) => a.length));
        const results = Array(k);
        for (let j = 0; j < k; j++) {
            results[j] = new Array(n);
        }
        for (let i = 0; i < n; i++) {
            for (let j = 0; j < k; j++) {
                results[j][i] = array[i][j];
            }
        }
        return results;
    }
    function range(start, stop, step = 1) {
        (0, assert_1.assert)(step > 0, "'step' must be a positive number");
        if (stop == null) {
            stop = start;
            start = 0;
        }
        const { max, ceil, abs } = Math;
        const delta = start <= stop ? step : -step;
        const length = max(ceil(abs(stop - start) / step), 0);
        const range = new Array(length);
        for (let i = 0; i < length; i++, start += delta) {
            range[i] = start;
        }
        return range;
    }
    function linspace(start, stop, num = 100) {
        const step = num == 1 ? 0 : (stop - start) / (num - 1);
        const array = new Array(num);
        for (let i = 0; i < num; i++) {
            array[i] = start + step * i;
        }
        return array;
    }
    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;
    }
    function argmin(array) {
        return (0, arrayable_1.min_by)(range(array.length), (i) => array[i]);
    }
    function argmax(array) {
        return (0, arrayable_1.max_by)(range(array.length), (i) => array[i]);
    }
    function uniq(array) {
        const result = new Set();
        for (const value of array) {
            result.add(value);
        }
        return [...result];
    }
    function uniq_by(array, key) {
        const result = [];
        const seen = [];
        for (const value of array) {
            const computed = key(value);
            if (!(0, arrayable_1.includes)(seen, computed)) {
                seen.push(computed);
                result.push(value);
            }
        }
        return result;
    }
    function _union(arrays) {
        const result = new Set();
        for (const array of arrays) {
            for (const value of array) {
                result.add(value);
            }
        }
        return result;
    }
    function union(...arrays) {
        return [..._union(arrays)];
    }
    function intersection(array, ...arrays) {
        const result = [];
        top: for (const item of array) {
            if ((0, arrayable_1.includes)(result, item)) {
                continue;
            }
            for (const other of arrays) {
                if (!(0, arrayable_1.includes)(other, item)) {
                    continue top;
                }
            }
            result.push(item);
        }
        return result;
    }
    function difference(array, ...arrays) {
        const rest = _union(arrays);
        return (0, arrayable_1.filter)(array, (value) => !rest.has(value));
    }
    function symmetric_difference(array0, array1) {
        const set0 = new Set(array0);
        const set1 = new Set(array1);
        const result = [];
        for (const val of set0) {
            if (!set1.has(val)) {
                result.push(val);
            }
        }
        for (const val of set1) {
            if (!set0.has(val)) {
                result.push(val);
            }
        }
        return result;
    }
    function remove_at(array, i) {
        (0, assert_1.assert)((0, types_1.isInteger)(i) && i >= 0);
        const result = copy(array);
        result.splice(i, 1);
        return result;
    }
    function remove(array, item) {
        remove_by(array, (value) => value == item);
    }
    function remove_by(array, key) {
        for (let i = 0; i < array.length;) {
            if (key(array[i])) {
                array.splice(i, 1);
            }
            else {
                i++;
            }
        }
    }
    function clear(array) {
        array.splice(0, array.length);
    }
    function split(array, separator) {
        const chunks = [];
        const n = array.length;
        let i = 0;
        let j = 0;
        while (j < n) {
            if (array[j] === separator) {
                chunks.push(array.slice(i, j));
                i = ++j;
            }
            else {
                ++j;
            }
        }
        chunks.push(array.slice(i));
        return chunks;
    }
    // Shuffle a collection, using the modern version of the
    // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
    function shuffle(array) {
        const length = array.length;
        const shuffled = new Array(length);
        for (let i = 0; i < length; i++) {
            const rand = (0, math_1.randomIn)(0, i);
            if (rand !== i) {
                shuffled[i] = shuffled[rand];
            }
            shuffled[rand] = array[i];
        }
        return shuffled;
    }
    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;
    }
    function elementwise(array0, array1, fn) {
        const n = Math.min(array0.length, array1.length);
        const result = Array(n);
        for (let i = 0; i < n; i++) {
            result[i] = fn(array0[i], array1[i]);
        }
        return result;
    }
    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;
    }
    function repeat(value, n) {
        const result = new Array(n).fill(value);
        return result;
    }
    function resize(array, new_length, fill_value) {
        if (array.length >= new_length) {
            return array.slice(0, new_length);
        }
        else {
            const suffix = new Array(new_length - array.length);
            if (fill_value !== undefined) {
                suffix.fill(fill_value);
            }
            return array.concat(suffix);
        }
    }
},
/* core/util/math.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.angle_norm = angle_norm;
    exports.angle_dist = angle_dist;
    exports.angle_between = angle_between;
    exports.randomIn = randomIn;
    exports.atan2 = atan2;
    exports.radians = radians;
    exports.degrees = degrees;
    exports.compute_angle = compute_angle;
    exports.invert_angle = invert_angle;
    exports.to_radians_coeff = to_radians_coeff;
    exports.minmax = minmax;
    exports.clamp = clamp;
    exports.cycle = cycle;
    exports.log = log;
    exports.gcd = gcd;
    exports.lcm = lcm;
    exports.is_Floating = is_Floating;
    exports.factorial = factorial;
    exports.hermite = hermite;
    exports.eval_poly = eval_poly;
    const types_1 = require(8) /* ./types */;
    const assert_1 = require(12) /* ./assert */;
    const { PI, abs, sign, sqrt } = Math;
    exports.PI = PI;
    exports.abs = abs;
    exports.sqrt = sqrt;
    function angle_norm(angle) {
        if (angle == 0) {
            return 0;
        }
        while (angle <= 0) {
            angle += 2 * PI;
        }
        while (angle > 2 * PI) {
            angle -= 2 * PI;
        }
        return angle;
    }
    function angle_dist(lhs, rhs) {
        return angle_norm(lhs - rhs);
    }
    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;
    }
    function randomIn(min, max) {
        if (max == null) {
            max = min;
            min = 0;
        }
        return min + Math.floor(Math.random() * (max - min + 1));
    }
    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]);
    }
    function radians(degrees) {
        return degrees * (PI / 180);
    }
    function degrees(radians) {
        return radians / (PI / 180);
    }
    function compute_angle(angle, units, dir = "anticlock") {
        /**
         * Convert math CCW(default)/CW angle with units to CW radians (canvas).
         */
        const sign = dir == "anticlock" ? 1 : -1;
        return -sign * angle * to_radians_coeff(units);
    }
    exports.resolve_angle = compute_angle;
    function invert_angle(angle, units, dir = "anticlock") {
        /**
         * Convert CW radians (canvas) to math CCW(default)/CW angle with units.
         */
        const sign = dir == "anticlock" ? 1 : -1;
        return -sign * angle / to_radians_coeff(units);
    }
    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;
        }
    }
    function minmax(v0, v1) {
        return v0 <= v1 ? [v0, v1] : [v1, v0];
    }
    function clamp(val, min, max) {
        return val < min ? min : (val > max ? max : val);
    }
    function cycle(val, min, max) {
        if (val > max) {
            return min;
        }
        if (val < min) {
            return max;
        }
        return val;
    }
    function log(x, base = Math.E) {
        return Math.log(x) / Math.log(base);
    }
    function gcd(a, b) {
        a = Math.abs(a);
        b = Math.abs(b);
        while (b != 0) {
            [a, b] = [b, a % b];
        }
        return a;
    }
    function lcm(a, ...rest) {
        for (const b of rest) {
            a = Math.floor((a * b) / gcd(a, b));
        }
        return a;
    }
    exports.float = Symbol("float");
    function is_Floating(obj) {
        return (0, types_1.isObject)(obj) && exports.float in obj;
    }
    class Fraction {
        constructor(numer, denom) {
            (0, assert_1.assert)(denom != 0, "Zero divisor");
            const div = gcd(numer, denom);
            const sgn = sign(numer) * sign(denom);
            this.numer = sgn * abs(numer) / div;
            this.denom = abs(denom) / div;
        }
        [exports.float]() {
            return this.numer / this.denom;
        }
        toString() {
            return `${this.numer}/${this.denom}`;
        }
    }
    exports.Fraction = Fraction;
    Fraction.__name__ = "Fraction";
    exports.float32_epsilon = 1.1920928955078125e-7; // IEEE-754
    function factorial(x) {
        let y = 1;
        for (let i = 2; i <= x; i++) {
            y *= i;
        }
        return y;
    }
    function hermite(n) {
        const poly = new Array(n + 1);
        poly.fill(0);
        const fn = factorial(n);
        for (let k = 0; k <= Math.floor(n / 2); k++) {
            const c = (-1) ** k * fn / (factorial(k) * factorial(n - 2 * k)) * 2 ** (n - 2 * k);
            poly[2 * k] = c;
        }
        return poly;
    }
    function eval_poly(poly, x) {
        const n = poly.length - 1;
        let y = 0;
        let x_n = 1;
        for (let i = n; i >= 0; i--) {
            y += x_n * poly[i];
            x_n *= x;
        }
        return y;
    }
},
/* core/util/assert.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.assert = assert;
    exports.assert_debug = assert_debug;
    exports.unreachable = unreachable;
    class AssertionError extends Error {
    }
    exports.AssertionError = AssertionError;
    AssertionError.__name__ = "AssertionError";
    class UnreachableError extends Error {
    }
    exports.UnreachableError = UnreachableError;
    UnreachableError.__name__ = "UnreachableError";
    function assert(condition, message) {
        if (condition === true || (condition !== false && condition())) {
            return;
        }
        throw new AssertionError(message ?? "Assertion failed");
    }
    function assert_debug(condition, message) {
        if (typeof DEBUG !== "undefined" && DEBUG) {
            assert(condition, message);
        }
    }
    function unreachable(msg) {
        const suffix = msg != null ? `: ${msg}` : "";
        throw new UnreachableError(`unreachable code${suffix}`);
    }
},
/* core/util/arrayable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_empty = is_empty;
    exports.is_sorted = is_sorted;
    exports.copy = copy;
    exports.splice = splice;
    exports.head = head;
    exports.insert = insert;
    exports.append = append;
    exports.prepend = prepend;
    exports.index_of = index_of;
    exports.includes = includes;
    exports.subselect = subselect;
    exports.mul = mul;
    exports.map = map;
    exports.inplace_map = inplace_map;
    exports.filter = filter;
    exports.reduce = reduce;
    exports.sort_by = sort_by;
    exports.min = min;
    exports.max = max;
    exports.minmax = minmax;
    exports.minmax2 = minmax2;
    exports.min_by = min_by;
    exports.max_by = max_by;
    exports.sum = sum;
    exports.cumsum = cumsum;
    exports.every = every;
    exports.some = some;
    exports.find = find;
    exports.find_last = find_last;
    exports.bisect_left_by = bisect_left_by;
    exports.bisect_right_by = bisect_right_by;
    exports.bisect_left = bisect_left;
    exports.bisect_right = bisect_right;
    exports.binary_search = binary_search;
    exports.bin_counts = bin_counts;
    exports.interpolate = interpolate;
    exports.left_edge_index = left_edge_index;
    exports.norm = norm;
    const math_1 = require(11) /* ./math */;
    const assert_1 = require(12) /* ./assert */;
    const { floor } = Math;
    function is_empty(array) {
        return array.length == 0;
    }
    function is_sorted(array) {
        const n = array.length;
        if (n == 0) {
            return true;
        }
        let prev = array[0];
        for (let i = 1; i < n; i++) {
            const curr = array[i];
            if (prev <= curr) {
                prev = curr;
            }
            else {
                return false;
            }
        }
        return true;
    }
    function copy(array) {
        if (Array.isArray(array)) {
            return array.slice();
        }
        else {
            return new array.constructor(array);
        }
    }
    function splice(array, start, k, ...items) {
        if (Array.isArray(array)) {
            const result = copy(array);
            if (k === undefined) {
                result.splice(start);
            }
            else {
                result.splice(start, k, ...items);
            }
            return result;
        }
        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;
    }
    function head(array, n) {
        return splice(array, n, array.length - n);
    }
    function insert(array, item, i) {
        return splice(array, i, 0, item);
    }
    function append(array, item) {
        return splice(array, array.length, 0, item);
    }
    function prepend(array, item) {
        return splice(array, 0, 0, item);
    }
    function index_of(array, item) {
        return array.indexOf(item);
    }
    function includes(array, value) {
        return array.indexOf(value) !== -1;
    }
    exports.contains = includes;
    function subselect(array, indices) {
        const n = indices.length;
        const result = new array.constructor(n);
        for (let i = 0; i < n; i++) {
            result[i] = array[indices[i]];
        }
        return result;
    }
    function mul(array, coeff, output) {
        const n = array.length;
        const result = output ?? new array.constructor(n);
        for (let i = 0; i < n; i++) {
            result[i] = array[i] * coeff;
        }
        return result;
    }
    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;
    }
    function inplace_map(array, fn, output) {
        const n = array.length;
        const result = output ?? array;
        for (let i = 0; i < n; i++) {
            result[i] = fn(array[i], i);
        }
    }
    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);
    }
    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;
    }
    function sort_by(array, key) {
        const tmp = Array.from(array, (value, index) => {
            return { index, key: key(value) };
        });
        tmp.sort((left, right) => {
            const a = left.key;
            const b = right.key;
            if (a !== b) {
                if (a > b) {
                    return 1;
                }
                if (a < b) {
                    return -1;
                }
            }
            return left.index - right.index;
        });
        return map(array, (_, i) => array[tmp[i].index]);
    }
    function min(iterable) {
        let result = Infinity;
        for (const value of iterable) {
            if (!isNaN(value) && value < result) {
                result = value;
            }
        }
        return result;
    }
    function max(iterable) {
        let result = -Infinity;
        for (const value of iterable) {
            if (!isNaN(value) && value > result) {
                result = value;
            }
        }
        return result;
    }
    function minmax(iterable) {
        let min = +Infinity;
        let max = -Infinity;
        for (const value of iterable) {
            if (!isNaN(value)) {
                if (value < min) {
                    min = value;
                }
                if (value > max) {
                    max = value;
                }
            }
        }
        return [min, max];
    }
    function minmax2(arr, brr) {
        let a;
        let b;
        let a_min = +Infinity;
        let a_max = -Infinity;
        let b_min = +Infinity;
        let b_max = -Infinity;
        const n = Math.min(arr.length, brr.length);
        for (let i = 0; i < n; i++) {
            a = arr[i];
            b = brr[i];
            if (!isNaN(a) && !isNaN(b)) {
                if (a < a_min) {
                    a_min = a;
                }
                if (a > a_max) {
                    a_max = a;
                }
                if (b < b_min) {
                    b_min = b;
                }
                if (b > b_max) {
                    b_max = b;
                }
            }
        }
        return [a_min, a_max, b_min, b_max];
    }
    function min_by(array, key) {
        if (array.length == 0) {
            throw new Error("min_by() called with an empty array");
        }
        let result = array[0];
        let result_computed = key(result, 0);
        for (let i = 1, length = array.length; i < length; i++) {
            const value = array[i];
            const computed = key(value, i);
            if (computed < result_computed) {
                result = value;
                result_computed = computed;
            }
        }
        return result;
    }
    function max_by(array, key) {
        if (array.length == 0) {
            throw new Error("max_by() called with an empty array");
        }
        let result = array[0];
        let result_computed = key(result, 0);
        for (let i = 1, length = array.length; i < length; i++) {
            const value = array[i];
            const computed = key(value, i);
            if (computed > result_computed) {
                result = value;
                result_computed = computed;
            }
        }
        return result;
    }
    function sum(array) {
        let result = 0;
        for (let i = 0, n = array.length; i < n; i++) {
            result += array[i];
        }
        return result;
    }
    function cumsum(array) {
        const result = new array.constructor(array.length);
        reduce(array, (a, b, i) => result[i] = a + b, 0);
        return result;
    }
    function every(iter, predicate) {
        for (const item of iter) {
            if (!predicate(item)) {
                return false;
            }
        }
        return true;
    }
    function some(iter, predicate) {
        for (const item of iter) {
            if (predicate(item)) {
                return true;
            }
        }
        return false;
    }
    function _find_index(dir) {
        return function (array, predicate) {
            const length = array.length;
            let index = dir > 0 ? 0 : length - 1;
            for (; index >= 0 && index < length; index += dir) {
                if (predicate(array[index])) {
                    return index;
                }
            }
            return -1;
        };
    }
    exports.find_index = _find_index(1);
    exports.find_last_index = _find_index(-1);
    function find(array, predicate) {
        const index = (0, exports.find_index)(array, predicate);
        return index == -1 ? undefined : array[index];
    }
    function find_last(array, predicate) {
        const index = (0, exports.find_last_index)(array, predicate);
        return index == -1 ? undefined : array[index];
    }
    function bisect_left_by(array, value, fn, low = 0, high = array.length) {
        (0, assert_1.assert_debug)(() => is_sorted(array));
        (0, assert_1.assert)(0 <= low && high <= array.length);
        while (low < high) {
            const mid = floor((low + high) / 2);
            if (fn(array[mid]) < value) {
                low = mid + 1;
            }
            else {
                high = mid;
            }
        }
        return low;
    }
    function bisect_right_by(array, value, fn, low = 0, high = array.length) {
        (0, assert_1.assert_debug)(() => is_sorted(array));
        (0, assert_1.assert)(0 <= low && high <= array.length);
        while (low < high) {
            const mid = floor((low + high) / 2);
            if (fn(array[mid]) <= value) {
                low = mid + 1;
            }
            else {
                high = mid;
            }
        }
        return low;
    }
    function bisect_left(array, value, low = 0, high) {
        return bisect_left_by(array, value, (item) => item, low, high);
    }
    function bisect_right(array, value, low = 0, high) {
        return bisect_right_by(array, value, (item) => item, low, high);
    }
    function binary_search(array, value) {
        const i = bisect_left(array, value);
        return i != array.length && array[i] == value ? i : null;
    }
    exports.sorted_index = bisect_left;
    function bin_counts(data, bin_edges) {
        const nbins = bin_edges.length - 1;
        const counts = Array(nbins).fill(0);
        for (let i = 0; i < data.length; i++) {
            const sample = data[i];
            const index = (0, exports.sorted_index)(bin_edges, sample);
            const bin = (0, math_1.clamp)(index - 1, 0, nbins - 1);
            counts[bin] += 1;
        }
        return counts;
    }
    function interpolate(points, x_values, y_values) {
        // Implementation ported from np.interp
        const n = points.length;
        const results = new Array(n);
        for (let i = 0; i < n; i++) {
            const point = points[i];
            if (isNaN(point) || x_values.length == 0) {
                results[i] = NaN;
                continue;
            }
            const index = left_edge_index(point, x_values);
            if (index == -1) {
                results[i] = y_values[0];
            }
            else if (index == x_values.length) {
                results[i] = y_values[y_values.length - 1];
            }
            else if (index == x_values.length - 1 || x_values[index] == point) {
                results[i] = y_values[index];
            }
            else {
                const x0 = x_values[index];
                const y0 = y_values[index];
                const x1 = x_values[index + 1];
                const y1 = y_values[index + 1];
                results[i] = lerp(point, x0, y0, x1, y1);
            }
        }
        return results;
    }
    function lerp(x, x0, y0, x1, y1) {
        const slope = (y1 - y0) / (x1 - x0);
        let res = slope * (x - x0) + y0;
        if (!isFinite(res)) {
            res = slope * (x - x1) + y1;
            if (!isFinite(res) && (y0 == y1)) {
                res = y0;
            }
        }
        return res;
    }
    function left_edge_index(point, intervals) {
        if (point < intervals[0]) {
            return -1;
        }
        if (point > intervals[intervals.length - 1]) {
            return intervals.length;
        }
        if (intervals.length == 1) {
            // Implies point == intervals[0]
            return 0;
        }
        let leftEdgeIndex = 0;
        let rightEdgeIndex = intervals.length - 1;
        while (rightEdgeIndex - leftEdgeIndex != 1) {
            const indexOfNumberToCompare = leftEdgeIndex + Math.floor((rightEdgeIndex - leftEdgeIndex) / 2);
            if (point >= intervals[indexOfNumberToCompare]) {
                leftEdgeIndex = indexOfNumberToCompare;
            }
            else {
                rightEdgeIndex = indexOfNumberToCompare;
            }
        }
        return leftEdgeIndex;
    }
    function norm(array, start, end) {
        const span = end - start;
        return map(array, (x) => (x - start) / span);
    }
},
/* core/has_props.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const signaling_1 = require(15) /* ./signaling */;
    const refs_1 = require(17) /* ./util/refs */;
    const p = tslib_1.__importStar(require(18) /* ./properties */);
    const k = tslib_1.__importStar(require(21) /* ./kinds */);
    const assert_1 = require(12) /* ./util/assert */;
    const string_1 = require(40) /* ./util/string */;
    const object_1 = require(9) /* ./util/object */;
    const types_1 = require(8) /* ./util/types */;
    const serialization_1 = require(32) /* ./serialization */;
    const events_1 = require(41) /* ../document/events */;
    const eq_1 = require(26) /* ./util/eq */;
    const pretty_1 = require(42) /* ./util/pretty */;
    const cloneable_1 = require(31) /* ./util/cloneable */;
    const kinds = tslib_1.__importStar(require(21) /* ./kinds */);
    const vectorization_1 = require(28) /* ./vectorization */;
    const patching_1 = require(43) /* ./patching */;
    const _qualified_names = new WeakMap();
    class HasProps extends (0, signaling_1.Signalable)() {
        get is_syncable() {
            return true;
        }
        get type() {
            return this.constructor.__qualified__;
        }
        static get __qualified__() {
            let qualified = _qualified_names.get(this);
            if (qualified == null) {
                const { __module__, __name__ } = this;
                qualified = __module__ != null ? `${__module__}.${__name__}` : __name__;
                _qualified_names.set(this, qualified);
            }
            return qualified;
        }
        static set __qualified__(qualified) {
            _qualified_names.set(this, qualified);
        }
        get [Symbol.toStringTag]() {
            return this.constructor.__qualified__;
        }
        static _fix_default(default_value, _attr) {
            if (default_value === undefined || default_value === p.unset) {
                return () => p.unset;
            }
            else if ((0, types_1.isFunction)(default_value)) {
                return default_value;
            }
            else if ((0, types_1.isPrimitive)(default_value)) {
                return () => default_value;
            }
            else {
                const cloner = new cloneable_1.Cloner();
                return () => cloner.clone(default_value);
            }
        }
        // TODO: don't use Partial<>, but exclude inherited properties
        static define(obj) {
            for (const [name, prop] of (0, object_1.entries)((0, types_1.isFunction)(obj) ? obj(kinds) : obj)) {
                if (name in this.prototype._props) {
                    throw new Error(`attempted to redefine property '${this.prototype.type}.${name}'`);
                }
                if (name in this.prototype) {
                    throw new Error(`attempted to redefine attribute '${this.prototype.type}.${name}'`);
                }
                Object.defineProperty(this.prototype, name, {
                    // XXX: don't use tail calls in getters/setters due to https://bugs.webkit.org/show_bug.cgi?id=164306
                    get() {
                        const value = this.properties[name].get_value();
                        return value;
                    },
                    set(value) {
                        this.setv({ [name]: value });
                        return this;
                    },
                    configurable: false,
                    enumerable: true,
                });
                const [type, default_value, options = {}] = prop;
                const refined_prop = {
                    type,
                    default_value: this._fix_default(default_value, name),
                    options,
                };
                this.prototype._props = {
                    ...this.prototype._props,
                    [name]: refined_prop,
                };
            }
        }
        static internal(obj) {
            const _object = {};
            for (const [name, prop] of (0, object_1.entries)((0, types_1.isFunction)(obj) ? obj(kinds) : obj)) {
                const [type, default_value, options = {}] = prop;
                _object[name] = [type, default_value, { ...options, internal: true }];
            }
            this.define(_object);
        }
        static mixins(defs) {
            function rename(prefix, mixin) {
                const result = {};
                for (const [name, prop] of (0, object_1.entries)(mixin)) {
                    result[prefix + name] = prop;
                }
                return result;
            }
            const mixin_defs = {};
            const mixins = [];
            for (const def of (0, types_1.isArray)(defs) ? defs : [defs]) {
                if ((0, types_1.isArray)(def)) {
                    const [prefix, mixin] = def;
                    (0, object_1.extend)(mixin_defs, rename(prefix, mixin));
                    mixins.push([prefix, mixin]);
                }
                else {
                    const mixin = def;
                    (0, object_1.extend)(mixin_defs, mixin);
                    mixins.push(["", mixin]);
                }
            }
            this.define(mixin_defs);
            this.prototype._mixins = [...this.prototype._mixins, ...mixins];
        }
        static override(obj) {
            for (const [name, prop] of (0, object_1.entries)(obj)) {
                const default_value = this._fix_default(prop, name);
                if (!(name in this.prototype._props)) {
                    throw new Error(`attempted to override nonexistent '${this.prototype.type}.${name}'`);
                }
                const value = this.prototype._props[name];
                const props = { ...this.prototype._props };
                props[name] = { ...value, default_value };
                this.prototype._props = props;
            }
        }
        static toString() {
            return this.__qualified__;
        }
        toString() {
            return `${this.type}(${this.id})`;
        }
        property(name) {
            if (name in this.properties) {
                return this.properties[name];
            }
            else {
                throw new Error(`unknown property ${this.type}.${name}`);
            }
        }
        get attributes() {
            const attrs = {};
            for (const prop of this) {
                if (!prop.is_unset) {
                    attrs[prop.attr] = prop.get_value();
                }
            }
            return attrs;
        }
        [cloneable_1.clone](cloner) {
            const attrs = new Map();
            for (const prop of this) {
                if (prop.dirty) {
                    attrs.set(prop.attr, cloner.clone(prop.get_value()));
                }
            }
            return new this.constructor(attrs);
        }
        [eq_1.equals](that, cmp) {
            for (const p0 of this) {
                const p1 = that.property(p0.attr);
                if (!cmp.eq(p0.get_value(), p1.get_value())) {
                    return false;
                }
            }
            return true;
        }
        [pretty_1.pretty](printer) {
            const T = printer.token;
            const items = [];
            for (const prop of this) {
                if (prop.dirty) {
                    const value = prop.get_value();
                    items.push(`${prop.attr}${T(":")} ${printer.to_string(value)}`);
                }
            }
            const cls = this.constructor.__qualified__;
            return `${cls}${T("(")}${T("{")}${items.join(`${T(",")} `)}${T("}")}${T(")")}`;
        }
        [serialization_1.serialize](serializer) {
            const ref = this.ref();
            serializer.add_ref(this, ref);
            const attributes = {};
            for (const prop of this) {
                if (prop.syncable && (serializer.include_defaults || prop.dirty) && !(prop.readonly && prop.is_unset)) {
                    const value = prop.get_value();
                    attributes[prop.attr] = serializer.encode(value);
                }
            }
            const { type: name, id } = this;
            const rep = { type: "object", name, id };
            return (0, object_1.is_empty)(attributes) ? rep : { ...rep, attributes };
        }
        constructor(attrs = {}) {
            super();
            this.document = null;
            this.destroyed = new signaling_1.Signal0(this, "destroyed");
            this.change = new signaling_1.Signal0(this, "change");
            this.transformchange = new signaling_1.Signal0(this, "transformchange");
            this.exprchange = new signaling_1.Signal0(this, "exprchange");
            this.streaming = new signaling_1.Signal0(this, "streaming");
            this.patching = new signaling_1.Signal(this, "patching");
            this.properties = {};
            this._watchers = new WeakMap();
            this._pending = false;
            this._changing = false;
            const deferred = (0, types_1.isPlainObject)(attrs) && "id" in attrs;
            this.id = deferred ? attrs.id : (0, string_1.unique_id)();
            for (const [name, { type, default_value, options }] of (0, object_1.entries)(this._props)) {
                let property;
                if (type instanceof p.PropertyAlias) {
                    const property = this.properties[type.attr];
                    if (typeof property === "undefined") {
                        throw new Error(`can't resolve ${type.attr} before ${name} to create an alias`);
                    }
                    Object.defineProperty(this.properties, name, {
                        get: () => property,
                        configurable: false,
                        enumerable: false,
                    });
                }
                else {
                    if (type instanceof k.Kind) {
                        property = new p.PrimitiveProperty(this, name, type, default_value, options);
                    }
                    else {
                        property = new type(this, name, k.Any, default_value, options);
                    }
                    this.properties[name] = property;
                }
            }
            // allowing us to defer initialization when loading many models
            // when loading a bunch of models, we want to do initialization as a second pass
            // because other objects that this one depends on might not be loaded yet
            if (deferred) {
                (0, assert_1.assert)((0, object_1.keys)(attrs).length == 1, "'id' cannot be used together with property initializers");
            }
            else {
                this.initialize_props(attrs);
                this.finalize();
                this.connect_signals();
            }
        }
        initialize_props(vals) {
            const vals_proxy = (0, object_1.dict)(vals);
            const visited = new Set();
            for (const prop of this) {
                const val = vals_proxy.get(prop.attr);
                prop.initialize(val);
                visited.add(prop.attr);
            }
            for (const [attr, val] of vals_proxy) {
                if (!visited.has(attr)) {
                    // either throws for unknown properties or updates aliased properties
                    this.property(attr).set_value(val);
                }
            }
        }
        finalize() {
            this.initialize();
        }
        initialize() { }
        assert_initialized() {
            for (const prop of this) {
                if (prop.syncable && !prop.readonly) {
                    prop.get_value();
                }
            }
        }
        connect_signals() {
            for (const prop of this) {
                if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec)) {
                    continue;
                }
                if (prop.is_unset) {
                    continue;
                }
                const value = prop.get_value();
                if (value.transform != null) {
                    this.connect(value.transform.change, () => this.transformchange.emit());
                }
                if ((0, vectorization_1.isExpr)(value)) {
                    this.connect(value.expr.change, () => this.exprchange.emit());
                }
            }
        }
        disconnect_signals() {
            signaling_1.Signal.disconnect_receiver(this);
        }
        destroy() {
            this.disconnect_signals();
            this.destroyed.emit();
        }
        // Create a new model with exact attribute values to this one, but new identity.
        clone(attrs) {
            const cloner = new cloneable_1.Cloner();
            const that = cloner.clone(this);
            if (attrs != null) {
                that.setv(attrs);
            }
            return that;
        }
        _clear_watchers() {
            this._watchers = new WeakMap();
        }
        changed_for(obj) {
            const changed = this._watchers.get(obj);
            this._watchers.set(obj, false);
            return changed ?? true;
        }
        // Set a hash of model attributes on the object, firing `"change"`. This is
        // the core primitive operation of a model, updating the data and notifying
        // anyone who needs to know about the change in state. The heart of the beast.
        _setv(changes, options) {
            // Extract attributes and options.
            const check_eq = options.check_eq;
            const changed = new Set();
            const changing = this._changing;
            this._changing = true;
            for (const [prop, value] of changes) {
                if (check_eq === false || prop.is_unset || !(0, eq_1.is_equal)(prop.get_value(), value)) {
                    prop.set_value(value);
                    changed.add(prop);
                }
            }
            // Trigger all relevant attribute changes.
            if (changed.size > 0) {
                this._clear_watchers();
                this._pending = true;
            }
            for (const prop of changed) {
                prop.change.emit();
            }
            // You might be wondering why there's a `while` loop here. Changes can
            // be recursively nested within `"change"` events.
            if (!changing) {
                if (!(options.no_change ?? false)) {
                    while (this._pending) {
                        this._pending = false;
                        this.change.emit();
                    }
                }
                this._pending = false;
                this._changing = false;
            }
            return changed;
        }
        setv(changed_attrs, options = {}) {
            const changes = (0, object_1.entries)(changed_attrs);
            if (changes.length == 0) {
                return;
            }
            if (options.silent ?? false) {
                this._clear_watchers();
                for (const [attr, value] of changes) {
                    this.properties[attr].set_value(value);
                }
                return;
            }
            const changed = new Map();
            const previous = new Map();
            for (const [attr, value] of changes) {
                const prop = this.properties[attr];
                changed.set(prop, value);
                previous.set(prop, prop.is_unset ? undefined : prop.get_value());
            }
            const updated = this._setv(changed, options);
            const { document } = this;
            if (document != null) {
                const changed = [];
                for (const [prop, value] of previous) {
                    if (updated.has(prop)) {
                        changed.push([prop, value, prop.get_value()]);
                    }
                }
                for (const [prop, old_value, new_value] of changed) {
                    if (prop.may_have_refs && this._needs_invalidate(old_value, new_value)) {
                        document._invalidate_all_models();
                        break;
                    }
                }
                const sync = options.sync ?? true;
                this._push_changes(changed, sync);
            }
        }
        ref() {
            return { id: this.id };
        }
        *[Symbol.iterator]() {
            yield* (0, object_1.values)(this.properties);
        }
        *syncable_properties() {
            for (const prop of this) {
                if (prop.syncable) {
                    yield prop;
                }
            }
        }
        *own_properties() {
            const self = Object.getPrototypeOf(this);
            const base = Object.getPrototypeOf(self);
            const exclude = new Set((0, object_1.keys)(base._props));
            for (const prop of this) {
                if (!exclude.has(prop.attr)) {
                    yield prop;
                }
            }
        }
        // add all references from 'v' to 'result', if recurse
        // is true then descend into refs, if false only
        // descend into non-refs
        static _value_record_references(value, refs, options) {
            if (!(0, types_1.isObject)(value) || !(0, refs_1.may_have_refs)(value)) {
                return;
            }
            const { recursive } = options;
            if (value instanceof _a) {
                if (!refs.has(value)) {
                    refs.add(value);
                    if (recursive) {
                        for (const prop of value.syncable_properties()) {
                            if (!prop.is_unset && prop.may_have_refs) {
                                const value = prop.get_value();
                                _a._value_record_references(value, refs, { recursive });
                            }
                        }
                    }
                }
            }
            else if ((0, types_1.isIterable)(value)) {
                for (const elem of value) {
                    _a._value_record_references(elem, refs, { recursive });
                }
            }
            else if ((0, types_1.isPlainObject)(value)) {
                for (const elem of (0, object_1.values)(value)) {
                    _a._value_record_references(elem, refs, { recursive });
                }
            }
        }
        static references(value, options) {
            const refs = new Set();
            _a._value_record_references(value, refs, options);
            return refs;
        }
        references() {
            return _a.references(this, { recursive: true });
        }
        _doc_attached() { }
        _doc_detached() { }
        attach_document(doc) {
            // This should only be called by the Document implementation to set the document field
            if (this.document != null) {
                if (this.document == doc) {
                    return;
                }
                else {
                    throw new Error("models must be owned by only a single document");
                }
            }
            this.document = doc;
            this._doc_attached();
        }
        detach_document() {
            // This should only be called by the Document implementation to unset the document field
            this._doc_detached();
            this.document = null;
        }
        _needs_invalidate(old_value, new_value) {
            const new_refs = new Set();
            _a._value_record_references(new_value, new_refs, { recursive: false });
            const old_refs = new Set();
            _a._value_record_references(old_value, old_refs, { recursive: false });
            for (const new_id of new_refs) {
                if (!old_refs.has(new_id)) {
                    return true;
                }
            }
            for (const old_id of old_refs) {
                if (!new_refs.has(old_id)) {
                    return true;
                }
            }
            return false;
        }
        _push_changes(changes, sync) {
            if (!this.is_syncable) {
                return;
            }
            const { document } = this;
            if (document == null) {
                return;
            }
            const events = [];
            for (const [prop, , new_value] of changes) {
                if (prop.syncable) {
                    const event = new events_1.ModelChangedEvent(document, this, prop.attr, new_value);
                    event.sync = sync;
                    events.push(event);
                }
            }
            if (events.length != 0) {
                let event;
                if (events.length == 1) {
                    [event] = events;
                }
                else {
                    event = new events_1.DocumentEventBatch(document, events);
                }
                document._trigger_on_change(event);
            }
        }
        on_change(properties, fn) {
            for (const property of (0, types_1.isArray)(properties) ? properties : [properties]) {
                this.connect(property.change, fn);
            }
        }
        stream_to(prop, new_data, rollover, { sync } = {}) {
            const data = prop.get_value();
            (0, patching_1.stream_to_columns)(data, new_data, rollover);
            this._clear_watchers();
            prop.set_value(data);
            this.streaming.emit();
            if (this.document != null) {
                const event = new events_1.ColumnsStreamedEvent(this.document, this, prop.attr, new_data, rollover);
                event.sync = sync ?? true;
                this.document._trigger_on_change(event);
            }
        }
        patch_to(prop, patches, { sync } = {}) {
            const data = prop.get_value();
            const patched = (0, patching_1.patch_to_columns)(data, patches);
            this._clear_watchers();
            prop.set_value(data);
            this.patching.emit([...patched]);
            if (this.document != null) {
                const event = new events_1.ColumnsPatchedEvent(this.document, this, prop.attr, patches);
                event.sync = sync ?? true;
                this.document._trigger_on_change(event);
            }
        }
    }
    exports.HasProps = HasProps;
    _a = HasProps;
    (() => {
        _a.prototype._props = {};
        _a.prototype._mixins = [];
    })();
},
/* core/signaling.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.Signalable = Signalable;
    // Based on https://github.com/phosphorjs/phosphor/blob/master/packages/signaling/src/index.ts
    const defer_1 = require(16) /* ./util/defer */;
    const array_1 = require(10) /* ./util/array */;
    class Signal {
        constructor(sender, name) {
            this.sender = sender;
            this.name = name;
        }
        connect(slot, context = null) {
            if (!exports.receivers_for_sender.has(this.sender)) {
                exports.receivers_for_sender.set(this.sender, []);
            }
            const receivers = exports.receivers_for_sender.get(this.sender);
            if (find_connection(receivers, this, slot, context) != null) {
                return false;
            }
            const receiver = context ?? slot;
            if (!senders_for_receiver.has(receiver)) {
                senders_for_receiver.set(receiver, []);
            }
            const senders = senders_for_receiver.get(receiver);
            const connection = { signal: this, slot, context };
            receivers.push(connection);
            senders.push(connection);
            return true;
        }
        disconnect(slot, context = null) {
            const receivers = exports.receivers_for_sender.get(this.sender);
            if (receivers == null || receivers.length === 0) {
                return false;
            }
            const connection = find_connection(receivers, this, slot, context);
            if (connection == null) {
                return false;
            }
            const receiver = context ?? slot;
            const senders = senders_for_receiver.get(receiver);
            connection.signal = null;
            schedule_cleanup(receivers);
            schedule_cleanup(senders);
            return true;
        }
        emit(args) {
            const receivers = exports.receivers_for_sender.get(this.sender) ?? [];
            for (const { signal, slot, context } of receivers) {
                if (signal === this) {
                    slot.call(context, args, this.sender);
                }
            }
        }
    }
    exports.Signal = Signal;
    Signal.__name__ = "Signal";
    class Signal0 extends Signal {
        emit() {
            super.emit(undefined);
        }
    }
    exports.Signal0 = Signal0;
    Signal0.__name__ = "Signal0";
    (function (Signal) {
        function disconnect_between(sender, receiver) {
            const receivers = exports.receivers_for_sender.get(sender);
            if (receivers == null || receivers.length === 0) {
                return;
            }
            const senders = senders_for_receiver.get(receiver);
            if (senders == null || senders.length === 0) {
                return;
            }
            for (const connection of senders) {
                if (connection.signal == null) {
                    return;
                }
                if (connection.signal.sender === sender) {
                    connection.signal = null;
                }
            }
            schedule_cleanup(receivers);
            schedule_cleanup(senders);
        }
        Signal.disconnect_between = disconnect_between;
        function disconnect_sender(sender) {
            const receivers = exports.receivers_for_sender.get(sender);
            if (receivers == null || receivers.length === 0) {
                return;
            }
            for (const connection of receivers) {
                if (connection.signal == null) {
                    return;
                }
                const receiver = connection.context ?? connection.slot;
                connection.signal = null;
                schedule_cleanup(senders_for_receiver.get(receiver));
            }
            schedule_cleanup(receivers);
        }
        Signal.disconnect_sender = disconnect_sender;
        function disconnect_receiver(receiver, slot, except_senders) {
            const senders = senders_for_receiver.get(receiver);
            if (senders == null || senders.length === 0) {
                return;
            }
            for (const connection of senders) {
                if (connection.signal == null) {
                    return;
                }
                if (slot != null && connection.slot != slot) {
                    continue;
                }
                const sender = connection.signal.sender;
                if (except_senders != null && except_senders.has(sender)) {
                    continue;
                }
                connection.signal = null;
                schedule_cleanup(exports.receivers_for_sender.get(sender));
            }
            schedule_cleanup(senders);
        }
        Signal.disconnect_receiver = disconnect_receiver;
        function disconnect_all(obj) {
            const receivers = exports.receivers_for_sender.get(obj);
            if (receivers != null && receivers.length !== 0) {
                for (const connection of receivers) {
                    connection.signal = null;
                }
                schedule_cleanup(receivers);
            }
            const senders = senders_for_receiver.get(obj);
            if (senders != null && senders.length !== 0) {
                for (const connection of senders) {
                    connection.signal = null;
                }
                schedule_cleanup(senders);
            }
        }
        Signal.disconnect_all = disconnect_all;
    })(Signal || (exports.Signal = Signal = {}));
    function Signalable() {
        return class {
            connect(signal, slot) {
                return signal.connect(slot, this);
            }
            disconnect(signal, slot) {
                return signal.disconnect(slot, this);
            }
        };
    }
    /** @internal */
    exports.receivers_for_sender = new WeakMap();
    const senders_for_receiver = new WeakMap();
    function find_connection(conns, signal, slot, context) {
        return (0, array_1.find)(conns, conn => conn.signal === signal && conn.slot === slot && conn.context === context);
    }
    const dirty_set = new Set();
    function schedule_cleanup(connections) {
        if (dirty_set.size == 0) {
            void (async () => {
                await (0, defer_1.defer)();
                cleanup_dirty_set();
            })();
        }
        dirty_set.add(connections);
    }
    function cleanup_dirty_set() {
        for (const connections of dirty_set) {
            (0, array_1.remove_by)(connections, (connection) => connection.signal == null);
        }
        dirty_set.clear();
    }
},
/* core/util/defer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.defer = defer;
    exports.delay = delay;
    exports.poll = poll;
    exports.paint = paint;
    exports.idle = idle;
    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);
        });
    }
    function delay(ms) {
        return new Promise((resolve) => setTimeout(resolve, ms));
    }
    async function poll(fn, interval = 50, timeout = 500) {
        while (!fn() && timeout >= 0) {
            await delay(interval);
            timeout -= interval;
        }
    }
    function paint() {
        return new Promise((resolve) => {
            requestAnimationFrame(() => resolve());
        });
    }
    function idle() {
        return new Promise((resolve) => {
            requestIdleCallback(() => resolve());
        });
    }
},
/* core/util/refs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_ref = is_ref;
    exports.is_HasRefs = is_HasRefs;
    exports.may_have_refs = may_have_refs;
    const types_1 = require(8) /* ./types */;
    function is_ref(obj) {
        return (0, types_1.isPlainObject)(obj) && "id" in obj && !("type" in obj);
    }
    exports.has_refs = Symbol("has_refs");
    function _is_HasRefs(v) {
        return exports.has_refs in v;
    }
    function is_HasRefs(v) {
        return (0, types_1.isObject)(v) && _is_HasRefs(v);
    }
    function may_have_refs(obj) {
        if (_is_HasRefs(obj)) {
            return obj[exports.has_refs];
        }
        const type = obj.constructor;
        if (is_HasRefs(type)) {
            return type[exports.has_refs];
        }
        return true;
    }
},
/* core/properties.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.TextBaselineSpec = exports.TextAlignSpec = exports.FontStyleSpec = exports.FontSizeSpec = exports.FontSpec = exports.LineDashSpec = exports.LineCapSpec = exports.LineJoinSpec = exports.MarkerSpec = exports.ArraySpec = exports.NullStringSpec = void 0;
    exports.isSpec = isSpec;
    exports.use_theme = use_theme;
    exports.Alias = Alias;
    const tslib_1 = require(1) /* tslib */;
    const signaling_1 = require(15) /* ./signaling */;
    const logging_1 = require(19) /* ./logging */;
    const enums = tslib_1.__importStar(require(20) /* ./enums */);
    const types_1 = require(24) /* ./types */;
    const array_1 = require(10) /* ./util/array */;
    const arrayable_1 = require(13) /* ./util/arrayable */;
    const math_1 = require(11) /* ./util/math */;
    const color_1 = require(22) /* ./util/color */;
    const platform_1 = require(27) /* ./util/platform */;
    const types_2 = require(8) /* ./util/types */;
    const vectorization_1 = require(28) /* ./vectorization */;
    const settings_1 = require(29) /* ./settings */;
    const ndarray_1 = require(30) /* ./util/ndarray */;
    const diagnostics_1 = require(38) /* ./diagnostics */;
    const assert_1 = require(12) /* ./util/assert */;
    const serialization_1 = require(32) /* ./serialization */;
    const uniforms_1 = require(39) /* ./uniforms */;
    __esExport("Uniform", uniforms_1.Uniform);
    __esExport("UniformScalar", uniforms_1.UniformScalar);
    __esExport("UniformVector", uniforms_1.UniformVector);
    function valueToString(value) {
        try {
            return JSON.stringify(value);
        }
        catch {
            return value.toString();
        }
    }
    function isSpec(obj) {
        return (0, types_2.isPlainObject)(obj) &&
            ((obj.value === undefined ? 0 : 1) +
                (obj.field === undefined ? 0 : 1) +
                (obj.expr === undefined ? 0 : 1) == 1); // garbage JS XOR
    }
    let global_theme = null;
    function use_theme(theme = null) {
        global_theme = theme;
    }
    exports.unset = Symbol("unset");
    class UnsetValueError extends Error {
    }
    exports.UnsetValueError = UnsetValueError;
    UnsetValueError.__name__ = "UnsetValueError";
    class Property {
        get syncable() {
            return !this.internal;
        }
        get is_unset() {
            return this._value === exports.unset;
        }
        get initialized() {
            return this._initialized;
        }
        initialize(initial_value = exports.unset) {
            if (this._initialized) {
                throw new Error("already initialized");
            }
            let attr_value = exports.unset;
            if (initial_value !== exports.unset) {
                attr_value = initial_value;
                this._dirty = true;
            }
            else {
                const value = this._default_override();
                if (value !== exports.unset) {
                    attr_value = value;
                }
                else {
                    let themed = false;
                    if (global_theme != null) {
                        const value = global_theme.get(this.obj, this.attr);
                        if (value !== undefined) {
                            attr_value = value;
                            themed = true;
                        }
                    }
                    if (!themed) {
                        attr_value = this.default_value(this.obj);
                    }
                }
            }
            if (attr_value !== exports.unset) {
                if (this.kind.coerce != null) {
                    attr_value = this.kind.coerce(attr_value);
                }
                this._update(attr_value);
            }
            else {
                this._value = exports.unset;
            }
            this._initialized = true;
        }
        get_value() {
            if (this._value !== exports.unset) {
                return this._value;
            }
            else {
                throw new UnsetValueError(`${this.obj}.${this.attr} is unset`);
            }
        }
        set_value(val) {
            if (!this._initialized) {
                this.initialize(val);
            }
            else {
                this._update(val);
                this._dirty = true;
            }
            diagnostics_1.diagnostics.report(this);
        }
        // abstract _intrinsic_default(): T
        _default_override() {
            return exports.unset;
        }
        get dirty() {
            return this._dirty;
        }
        constructor(obj, attr, kind, default_value, options = {}) {
            this._value = exports.unset;
            this._initialized = false;
            this._dirty = false;
            this.obj = obj;
            this.attr = attr;
            this.kind = kind;
            this.default_value = default_value;
            this.change = new signaling_1.Signal0(this.obj, "change");
            this.internal = options.internal ?? false;
            this.readonly = options.readonly ?? false;
            this.convert = options.convert;
            this.on_update = options.on_update;
            this.may_have_refs = kind.may_have_refs();
        }
        //protected abstract _update(attr_value: T): void
        _update(attr_value) {
            this.validate(attr_value);
            if (this.convert != null) {
                const converted = this.convert(attr_value, this.obj);
                if (converted !== undefined) {
                    attr_value = converted;
                }
            }
            this._value = attr_value;
            this.on_update?.(attr_value, this.obj);
        }
        toString() {
            /*${this.name}*/
            return `Prop(${this.obj}.${this.attr}, value: ${valueToString(this._value)})`;
        }
        // ----- customizable policies
        normalize(values) {
            return values;
        }
        validate(value) {
            if (!this.valid(value)) {
                throw new Error(`${this.obj}.${this.attr} given invalid value: ${valueToString(value)}`);
            }
        }
        valid(value) {
            return this.kind.valid(value);
        }
    }
    exports.Property = Property;
    Property.__name__ = "Property";
    class PropertyAlias {
        constructor(attr) {
            this.attr = attr;
        }
    }
    exports.PropertyAlias = PropertyAlias;
    PropertyAlias.__name__ = "PropertyAlias";
    function Alias(attr) {
        return new PropertyAlias(attr);
    }
    //
    // Primitive Properties
    //
    class PrimitiveProperty extends Property {
    }
    exports.PrimitiveProperty = PrimitiveProperty;
    PrimitiveProperty.__name__ = "PrimitiveProperty";
    class Font extends PrimitiveProperty {
        _default_override() {
            return settings_1.settings.dev ? "Bokeh" : exports.unset;
        }
    }
    exports.Font = Font;
    Font.__name__ = "Font";
    //
    // DataSpec properties
    //
    class ScalarSpec extends Property {
        constructor() {
            super(...arguments);
            this._value = exports.unset;
        }
        get_value() {
            if (this._value !== exports.unset) {
                return this._value;
            }
            else {
                throw new Error(`${this.obj}.${this.attr} is unset`);
            }
        }
        _update(attr_value) {
            if (isSpec(attr_value)) {
                this._value = attr_value;
            }
            else {
                this._value = { value: attr_value }; // Value<T>
            }
            if ((0, types_2.isPlainObject)(this._value)) {
                const { _value } = this;
                this._value[serialization_1.serialize] = (serializer) => {
                    const { value, field, expr, transform, units } = _value;
                    return serializer.encode_struct((() => {
                        if (value !== undefined) {
                            return { type: "value", value, transform, units };
                        }
                        else if (field !== undefined) {
                            return { type: "field", field, transform, units };
                        }
                        else {
                            return { type: "expr", expr, transform, units };
                        }
                    })());
                };
            }
            if ((0, vectorization_1.isValue)(this._value)) {
                this.validate(this._value.value);
            }
        }
        materialize(value) {
            return value;
        }
        scalar(value, n) {
            return new uniforms_1.UniformScalar(value, n);
        }
        uniform(source) {
            const obj = this.get_value();
            const n = source.get_length() ?? 1;
            if ((0, vectorization_1.isExpr)(obj)) {
                const { expr, transform } = obj;
                let result = expr.compute(source);
                if (transform != null) {
                    result = transform.compute(result);
                }
                result = this.materialize(result);
                return this.scalar(result, n);
            }
            else {
                const { value, transform } = obj;
                let result = value;
                if (transform != null) {
                    result = transform.compute(result);
                }
                result = this.materialize(result);
                return this.scalar(result, n);
            }
        }
    }
    exports.ScalarSpec = ScalarSpec;
    ScalarSpec.__name__ = "ScalarSpec";
    /** @deprecated */
    class AnyScalar extends ScalarSpec {
    }
    exports.AnyScalar = AnyScalar;
    AnyScalar.__name__ = "AnyScalar";
    class DictScalar extends ScalarSpec {
    }
    exports.DictScalar = DictScalar;
    DictScalar.__name__ = "DictScalar";
    class ColorScalar extends ScalarSpec {
    }
    exports.ColorScalar = ColorScalar;
    ColorScalar.__name__ = "ColorScalar";
    class NumberScalar extends ScalarSpec {
    }
    exports.NumberScalar = NumberScalar;
    NumberScalar.__name__ = "NumberScalar";
    class StringScalar extends ScalarSpec {
    }
    exports.StringScalar = StringScalar;
    StringScalar.__name__ = "StringScalar";
    class NullStringScalar extends ScalarSpec {
    }
    exports.NullStringScalar = NullStringScalar;
    NullStringScalar.__name__ = "NullStringScalar";
    class ArrayScalar extends ScalarSpec {
    }
    exports.ArrayScalar = ArrayScalar;
    ArrayScalar.__name__ = "ArrayScalar";
    class LineJoinScalar extends ScalarSpec {
    }
    exports.LineJoinScalar = LineJoinScalar;
    LineJoinScalar.__name__ = "LineJoinScalar";
    class LineCapScalar extends ScalarSpec {
    }
    exports.LineCapScalar = LineCapScalar;
    LineCapScalar.__name__ = "LineCapScalar";
    class LineDashScalar extends ScalarSpec {
    }
    exports.LineDashScalar = LineDashScalar;
    LineDashScalar.__name__ = "LineDashScalar";
    class FontScalar extends ScalarSpec {
        _default_override() {
            return settings_1.settings.dev ? "Bokeh" : exports.unset;
        }
    }
    exports.FontScalar = FontScalar;
    FontScalar.__name__ = "FontScalar";
    class FontSizeScalar extends ScalarSpec {
    }
    exports.FontSizeScalar = FontSizeScalar;
    FontSizeScalar.__name__ = "FontSizeScalar";
    class FontStyleScalar extends ScalarSpec {
    }
    exports.FontStyleScalar = FontStyleScalar;
    FontStyleScalar.__name__ = "FontStyleScalar";
    class TextAlignScalar extends ScalarSpec {
    }
    exports.TextAlignScalar = TextAlignScalar;
    TextAlignScalar.__name__ = "TextAlignScalar";
    class TextBaselineScalar extends ScalarSpec {
    }
    exports.TextBaselineScalar = TextBaselineScalar;
    TextBaselineScalar.__name__ = "TextBaselineScalar";
    class VectorSpec extends Property {
        constructor() {
            super(...arguments);
            this._value = exports.unset;
        }
        get_value() {
            if (this._value !== exports.unset) {
                return this._value;
            }
            else {
                throw new Error(`${this.obj}.${this.attr} is unset`);
            }
        }
        _update(attr_value) {
            if (isSpec(attr_value)) {
                this._value = attr_value;
            }
            else {
                this._value = { value: attr_value };
            } // Value<T>
            if ((0, types_2.isPlainObject)(this._value)) {
                const { _value } = this;
                this._value[serialization_1.serialize] = (serializer) => {
                    const { value, field, expr, transform, units } = _value;
                    return serializer.encode_struct((() => {
                        if (value !== undefined) {
                            return { type: "value", value, transform, units };
                        }
                        else if (field !== undefined) {
                            return { type: "field", field, transform, units };
                        }
                        else {
                            return { type: "expr", expr, transform, units };
                        }
                    })());
                };
            }
            if ((0, vectorization_1.isValue)(this._value)) {
                this.validate(this._value.value);
            }
        }
        materialize(value) {
            return value;
        }
        v_materialize(values) {
            return values;
        }
        scalar(value, n) {
            return new uniforms_1.UniformScalar(value, n);
        }
        vector(values) {
            return new uniforms_1.UniformVector(values);
        }
        uniform(source) {
            const obj = this.get_value();
            const n = source.get_length() ?? 1;
            if ((0, vectorization_1.isField)(obj)) {
                const { field, transform } = obj;
                let array = source.get_column(field);
                if (array != null) {
                    if (transform != null) {
                        array = transform.v_compute(array);
                    }
                    array = this.v_materialize(array);
                    return this.vector(array);
                }
                else {
                    const message = `attempted to retrieve property array for nonexistent field '${field}'`;
                    if (settings_1.settings.force_fields) {
                        throw new Error(message);
                    }
                    else {
                        logging_1.logger.warn(message);
                    }
                    return this.scalar(null, n);
                }
            }
            else if ((0, vectorization_1.isExpr)(obj)) {
                const { expr, transform } = obj;
                let array = expr.v_compute(source);
                if (transform != null) {
                    array = transform.v_compute(array);
                }
                array = this.v_materialize(array);
                return this.vector(array);
            }
            else if ((0, vectorization_1.isValue)(obj)) {
                const { value, transform } = obj;
                let result = value;
                if (transform != null) {
                    result = transform.compute(result);
                }
                result = this.materialize(result);
                return this.scalar(result, n);
            }
            else {
                (0, assert_1.unreachable)();
            }
        }
        array(source) {
            let array;
            const length = source.get_length() ?? 1;
            const obj = this.get_value();
            if ((0, vectorization_1.isField)(obj)) {
                const { field } = obj;
                const column = source.get_column(field);
                if (column != null) {
                    array = this.normalize(column);
                }
                else {
                    const message = `attempted to retrieve property array for nonexistent field '${field}'`;
                    if (settings_1.settings.force_fields) {
                        throw new Error(message);
                    }
                    else {
                        logging_1.logger.warn(message);
                    }
                    const missing = new Float64Array(length);
                    missing.fill(NaN);
                    array = missing;
                }
            }
            else if ((0, vectorization_1.isExpr)(obj)) {
                const { expr } = obj;
                array = this.normalize(expr.v_compute(source));
            }
            else {
                const value = this.normalize([obj.value])[0];
                if ((0, types_2.isNumber)(value)) {
                    const values = new Float64Array(length);
                    values.fill(value);
                    array = values;
                }
                else {
                    array = (0, array_1.repeat)(value, length);
                }
            }
            const { transform } = obj;
            if (transform != null) {
                array = transform.v_compute(array);
            }
            return array;
        }
    }
    exports.VectorSpec = VectorSpec;
    VectorSpec.__name__ = "VectorSpec";
    class DataSpec extends VectorSpec {
    }
    exports.DataSpec = DataSpec;
    DataSpec.__name__ = "DataSpec";
    class UnitsSpec extends VectorSpec {
        constructor() {
            super(...arguments);
            this._value = exports.unset;
        }
        _update(attr_value) {
            super._update(attr_value);
            if (this._value !== exports.unset) {
                const { units } = this._value;
                if (units != null && !(0, array_1.includes)(this.valid_units, units)) {
                    throw new Error(`units must be one of ${this.valid_units.join(", ")}; got: ${units}`);
                }
            }
        }
        get units() {
            return this._value !== exports.unset ? this._value.units ?? this.default_units : this.default_units;
        }
        set units(units) {
            if (this._value !== exports.unset) {
                if (units != this.default_units) {
                    this._value.units = units;
                }
                else {
                    delete this._value.units;
                }
            }
            else {
                throw new Error(`${this.obj}.${this.attr} is unset`);
            }
        }
    }
    exports.UnitsSpec = UnitsSpec;
    UnitsSpec.__name__ = "UnitsSpec";
    class NumberUnitsSpec extends UnitsSpec {
        array(source) {
            return new Float64Array(super.array(source));
        }
    }
    exports.NumberUnitsSpec = NumberUnitsSpec;
    NumberUnitsSpec.__name__ = "NumberUnitsSpec";
    class BaseCoordinateSpec extends DataSpec {
    }
    exports.BaseCoordinateSpec = BaseCoordinateSpec;
    BaseCoordinateSpec.__name__ = "BaseCoordinateSpec";
    class CoordinateSpec extends BaseCoordinateSpec {
    }
    exports.CoordinateSpec = CoordinateSpec;
    CoordinateSpec.__name__ = "CoordinateSpec";
    class CoordinateSeqSpec extends BaseCoordinateSpec {
    }
    exports.CoordinateSeqSpec = CoordinateSeqSpec;
    CoordinateSeqSpec.__name__ = "CoordinateSeqSpec";
    class CoordinateSeqSeqSeqSpec extends BaseCoordinateSpec {
    }
    exports.CoordinateSeqSeqSeqSpec = CoordinateSeqSeqSeqSpec;
    CoordinateSeqSeqSeqSpec.__name__ = "CoordinateSeqSeqSeqSpec";
    class XCoordinateSpec extends CoordinateSpec {
        constructor() {
            super(...arguments);
            this.dimension = "x";
        }
    }
    exports.XCoordinateSpec = XCoordinateSpec;
    XCoordinateSpec.__name__ = "XCoordinateSpec";
    class YCoordinateSpec extends CoordinateSpec {
        constructor() {
            super(...arguments);
            this.dimension = "y";
        }
    }
    exports.YCoordinateSpec = YCoordinateSpec;
    YCoordinateSpec.__name__ = "YCoordinateSpec";
    class XCoordinateSeqSpec extends CoordinateSeqSpec {
        constructor() {
            super(...arguments);
            this.dimension = "x";
        }
    }
    exports.XCoordinateSeqSpec = XCoordinateSeqSpec;
    XCoordinateSeqSpec.__name__ = "XCoordinateSeqSpec";
    class YCoordinateSeqSpec extends CoordinateSeqSpec {
        constructor() {
            super(...arguments);
            this.dimension = "y";
        }
    }
    exports.YCoordinateSeqSpec = YCoordinateSeqSpec;
    YCoordinateSeqSpec.__name__ = "YCoordinateSeqSpec";
    class XCoordinateSeqSeqSeqSpec extends CoordinateSeqSeqSeqSpec {
        constructor() {
            super(...arguments);
            this.dimension = "x";
        }
    }
    exports.XCoordinateSeqSeqSeqSpec = XCoordinateSeqSeqSeqSpec;
    XCoordinateSeqSeqSeqSpec.__name__ = "XCoordinateSeqSeqSeqSpec";
    class YCoordinateSeqSeqSeqSpec extends CoordinateSeqSeqSeqSpec {
        constructor() {
            super(...arguments);
            this.dimension = "y";
        }
    }
    exports.YCoordinateSeqSeqSeqSpec = YCoordinateSeqSeqSeqSpec;
    YCoordinateSeqSeqSeqSpec.__name__ = "YCoordinateSeqSeqSeqSpec";
    class AngleSpec extends NumberUnitsSpec {
        get default_units() {
            return "rad";
        }
        get valid_units() {
            return [...enums.AngleUnits];
        }
        materialize(value) {
            const coeff = -(0, math_1.to_radians_coeff)(this.units);
            return value * coeff;
        }
        v_materialize(values) {
            const coeff = -(0, math_1.to_radians_coeff)(this.units);
            const result = new Float32Array(values.length);
            (0, arrayable_1.mul)(values, coeff, result); // TODO: in-place?
            return result;
        }
        array(_source) {
            throw new Error("not supported");
        }
    }
    exports.AngleSpec = AngleSpec;
    AngleSpec.__name__ = "AngleSpec";
    class DistanceSpec extends NumberUnitsSpec {
        get default_units() {
            return "data";
        }
        get valid_units() {
            return [...enums.SpatialUnits];
        }
    }
    exports.DistanceSpec = DistanceSpec;
    DistanceSpec.__name__ = "DistanceSpec";
    class NullDistanceSpec extends DistanceSpec {
        materialize(value) {
            return value ?? NaN;
        }
    }
    exports.NullDistanceSpec = NullDistanceSpec;
    NullDistanceSpec.__name__ = "NullDistanceSpec";
    class BooleanSpec extends DataSpec {
        v_materialize(values) {
            return new Uint8Array(values);
        }
        array(source) {
            return new Uint8Array(super.array(source));
        }
    }
    exports.BooleanSpec = BooleanSpec;
    BooleanSpec.__name__ = "BooleanSpec";
    class IntSpec extends DataSpec {
        v_materialize(values) {
            return (0, types_2.isTypedArray)(values) ? values : new Int32Array(values);
        }
        array(source) {
            return new Int32Array(super.array(source));
        }
    }
    exports.IntSpec = IntSpec;
    IntSpec.__name__ = "IntSpec";
    class NumberSpec extends DataSpec {
        v_materialize(values) {
            return (0, types_2.isTypedArray)(values) ? values : new Float64Array(values);
        }
        array(source) {
            return new Float64Array(super.array(source));
        }
    }
    exports.NumberSpec = NumberSpec;
    NumberSpec.__name__ = "NumberSpec";
    class ScreenSizeSpec extends NumberSpec {
        valid(value) {
            return (0, types_2.isNumber)(value) && value >= 0;
        }
    }
    exports.ScreenSizeSpec = ScreenSizeSpec;
    ScreenSizeSpec.__name__ = "ScreenSizeSpec";
    class ColorSpec extends DataSpec {
        materialize(color) {
            return (0, color_1.encode_rgba)((0, color_1.color2rgba)(color));
        }
        v_materialize(colors) {
            if ((0, ndarray_1.is_NDArray)(colors)) {
                if (colors.dtype == "uint32" && colors.dimension == 1) {
                    return (0, platform_1.to_big_endian)(colors);
                }
                else if (colors.dtype == "uint8" && colors.dimension == 1) {
                    const [n] = colors.shape;
                    const array = new types_1.RGBAArray(4 * n);
                    let j = 0;
                    for (const gray of colors) {
                        array[j++] = gray;
                        array[j++] = gray;
                        array[j++] = gray;
                        array[j++] = 255;
                    }
                    return new types_1.ColorArray(array.buffer);
                }
                else if (colors.dtype == "uint8" && colors.dimension == 2) {
                    const [n, d] = colors.shape;
                    if (d == 4) {
                        return new types_1.ColorArray(colors.buffer);
                    }
                    else if (d == 3) {
                        const array = new types_1.RGBAArray(4 * n);
                        for (let i = 0, j = 0; i < d * n;) {
                            array[j++] = colors[i++];
                            array[j++] = colors[i++];
                            array[j++] = colors[i++];
                            array[j++] = 255;
                        }
                        return new types_1.ColorArray(array.buffer);
                    }
                }
                else if ((colors.dtype == "float32" || colors.dtype == "float64") && colors.dimension == 2) {
                    const [n, d] = colors.shape;
                    if (d == 3 || d == 4) {
                        const array = new types_1.RGBAArray(4 * n);
                        for (let i = 0, j = 0; i < d * n;) {
                            array[j++] = colors[i++] * 255;
                            array[j++] = colors[i++] * 255;
                            array[j++] = colors[i++] * 255;
                            array[j++] = (d == 3 ? 1 : colors[i++]) * 255;
                        }
                        return new types_1.ColorArray(array.buffer);
                    }
                }
                else if (colors.dtype == "object" && colors.dimension == 1) {
                    return this._from_css_array(colors);
                }
            }
            else {
                return this._from_css_array(colors);
            }
            throw new Error("invalid color array");
        }
        _from_css_array(colors) {
            const n = colors.length;
            const array = new types_1.RGBAArray(4 * n);
            let j = 0;
            for (const color of colors) {
                const [r, g, b, a] = (0, color_1.color2rgba)(color);
                array[j++] = r;
                array[j++] = g;
                array[j++] = b;
                array[j++] = a;
            }
            return new types_1.ColorArray(array.buffer);
        }
        vector(values) {
            return new uniforms_1.ColorUniformVector(values);
        }
    }
    exports.ColorSpec = ColorSpec;
    ColorSpec.__name__ = "ColorSpec";
    class NDArraySpec extends DataSpec {
    }
    exports.NDArraySpec = NDArraySpec;
    NDArraySpec.__name__ = "NDArraySpec";
    /** @deprecated */
    class AnySpec extends DataSpec {
    }
    exports.AnySpec = AnySpec;
    AnySpec.__name__ = "AnySpec";
    class StringSpec extends DataSpec {
    }
    exports.StringSpec = StringSpec;
    StringSpec.__name__ = "StringSpec";
    class NullStringSpec extends DataSpec {
    }
    exports.NullStringSpec = NullStringSpec;
    NullStringSpec.__name__ = "NullStringSpec";
    class ArraySpec extends DataSpec {
    }
    exports.ArraySpec = ArraySpec;
    ArraySpec.__name__ = "ArraySpec";
    class MarkerSpec extends DataSpec {
    }
    exports.MarkerSpec = MarkerSpec;
    MarkerSpec.__name__ = "MarkerSpec";
    class LineJoinSpec extends DataSpec {
    }
    exports.LineJoinSpec = LineJoinSpec;
    LineJoinSpec.__name__ = "LineJoinSpec";
    class LineCapSpec extends DataSpec {
    }
    exports.LineCapSpec = LineCapSpec;
    LineCapSpec.__name__ = "LineCapSpec";
    class LineDashSpec extends DataSpec {
    }
    exports.LineDashSpec = LineDashSpec;
    LineDashSpec.__name__ = "LineDashSpec";
    class FontSpec extends DataSpec {
        _default_override() {
            return settings_1.settings.dev ? "Bokeh" : exports.unset;
        }
    }
    exports.FontSpec = FontSpec;
    FontSpec.__name__ = "FontSpec";
    class FontSizeSpec extends DataSpec {
    }
    exports.FontSizeSpec = FontSizeSpec;
    FontSizeSpec.__name__ = "FontSizeSpec";
    class FontStyleSpec extends DataSpec {
    }
    exports.FontStyleSpec = FontStyleSpec;
    FontStyleSpec.__name__ = "FontStyleSpec";
    class TextAlignSpec extends DataSpec {
    }
    exports.TextAlignSpec = TextAlignSpec;
    TextAlignSpec.__name__ = "TextAlignSpec";
    class TextBaselineSpec extends DataSpec {
    }
    exports.TextBaselineSpec = TextBaselineSpec;
    TextBaselineSpec.__name__ = "TextBaselineSpec";
},
/* core/logging.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.set_log_level = set_log_level;
    exports.with_log_level = with_log_level;
    // This is based on https://github.com/pimterry/loglevel
    const types_1 = require(8) /* ./util/types */;
    const object_1 = require(9) /* ./util/object */;
    const version_1 = require(3) /* ../version */;
    const _loggers = {};
    class LogLevel {
        constructor(name, level, method) {
            this.name = name;
            this.level = level;
            this.method = method;
        }
    }
    exports.LogLevel = LogLevel;
    LogLevel.__name__ = "LogLevel";
    class Logger {
        static get levels() {
            return Object.keys(Logger.log_levels);
        }
        static get(name, level = Logger.INFO) {
            if (name.length > 0) {
                if (name in _loggers) {
                    return _loggers[name];
                }
                else {
                    return _loggers[name] = new Logger(name, level);
                }
            }
            else {
                throw new TypeError("Logger.get() expects a non-empty string name and an optional log-level");
            }
        }
        constructor(name, level = Logger.INFO) {
            this._name = name;
            this.set_level(level);
        }
        get level() {
            return this.get_level();
        }
        get_level() {
            return this._log_level;
        }
        set_level(log_level) {
            if (log_level instanceof LogLevel) {
                this._log_level = log_level;
            }
            else if (Logger.log_levels.hasOwnProperty(log_level)) {
                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 prefix = `[${this._name}]`;
            for (const { level, method } of (0, object_1.values)(Logger.log_levels)) {
                if (level < this._log_level.level || this._log_level.level === Logger.OFF.level) {
                    this[method] = function () { };
                }
                else {
                    this[method] = _method_factory(method, prefix);
                }
            }
            this.log = _method_factory("log", prefix);
        }
        log(..._args) { }
        trace(..._args) { }
        debug(..._args) { }
        info(..._args) { }
        warn(..._args) { }
        error(..._args) { }
    }
    exports.Logger = Logger;
    Logger.__name__ = "Logger";
    Logger.TRACE = new LogLevel("trace", 0, "trace");
    Logger.DEBUG = new LogLevel("debug", 1, "debug");
    Logger.INFO = new LogLevel("info", 2, "info");
    Logger.WARN = new LogLevel("warn", 6, "warn");
    Logger.ERROR = new LogLevel("error", 7, "error");
    Logger.FATAL = new LogLevel("fatal", 8, "error");
    Logger.OFF = new LogLevel("off", 9, "log");
    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, prefix) {
        const method = console[method_name];
        const fn = typeof method != "undefined" ? method : console.log;
        return fn.bind(console, prefix);
    }
    exports.logger = Logger.get(`bokeh ${version_1.version}`);
    function set_log_level(level) {
        const previous_level = exports.logger.level;
        if ((0, types_1.isString)(level) && !(level in Logger.log_levels)) {
            exports.logger.log(`unrecognized logging level '${level}' passed to Bokeh.set_log_level(), ignoring`);
            exports.logger.log(`valid log levels are: ${Logger.levels.join(", ")}`);
        }
        else {
            exports.logger.log(`setting log level to: '${(0, types_1.isString)(level) ? level : level.level}'`);
            exports.logger.set_level(level);
        }
        return previous_level;
    }
    function with_log_level(level, fn) {
        const original = set_log_level(level);
        try {
            fn();
        }
        finally {
            set_log_level(original);
        }
    }
},
/* core/enums.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.ToolIcon = exports.VerticalAlign = exports.UpdateMode = exports.TooltipAttachment = exports.LabelOrientation = exports.TextureRepetition = exports.TextBaseline = exports.TextAlign = exports.TapGesture = exports.TapBehavior = exports.StepMode = exports.StartEnd = exports.SpatialUnits = exports.Sort = exports.SizingMode = exports.Side = exports.SelectionMode = exports.RegionSelectionMode = void 0;
    const kinds_1 = require(21) /* ./kinds */;
    exports.Align = (0, kinds_1.Enum)("start", "center", "end");
    exports.HAlign = (0, kinds_1.Enum)("left", "center", "right");
    exports.VAlign = (0, kinds_1.Enum)("top", "center", "bottom");
    exports.Anchor = (0, kinds_1.Enum)("top_left", "top_center", "top_right", "center_left", "center_center", "center_right", "bottom_left", "bottom_center", "bottom_right", "top", "left", "center", "right", "bottom");
    exports.AngleUnits = (0, kinds_1.Enum)("deg", "rad", "grad", "turn");
    exports.AlternationPolicy = (0, kinds_1.Enum)("none", "even", "odd", "every");
    exports.BoxOrigin = (0, kinds_1.Enum)("corner", "center");
    exports.ButtonType = (0, kinds_1.Enum)("default", "primary", "success", "warning", "danger", "light");
    exports.CalendarPosition = (0, kinds_1.Enum)("auto", "above", "below");
    exports.Clock = (0, kinds_1.Enum)("12h", "24h");
    exports.CoordinateUnits = (0, kinds_1.Enum)("canvas", "screen", "data");
    exports.ContextWhich = (0, kinds_1.Enum)("start", "center", "end", "all");
    exports.Dimension = (0, kinds_1.Enum)("width", "height");
    exports.Dimensions = (0, kinds_1.Enum)("width", "height", "both");
    exports.Direction = (0, kinds_1.Enum)("clock", "anticlock");
    exports.Distribution = (0, kinds_1.Enum)("uniform", "normal");
    exports.Face = (0, kinds_1.Enum)("front", "back");
    exports.FlowMode = (0, kinds_1.Enum)("block", "inline");
    exports.FontStyle = (0, kinds_1.Enum)("normal", "italic", "bold", "bold italic");
    exports.HatchPatternType = (0, kinds_1.Enum)("blank", "dot", "ring", "horizontal_line", "vertical_line", "cross", "horizontal_dash", "vertical_dash", "spiral", "right_diagonal_line", "left_diagonal_line", "diagonal_cross", "right_diagonal_dash", "left_diagonal_dash", "horizontal_wave", "vertical_wave", "criss_cross", " ", ".", "o", "-", "|", "+", '"', ":", "@", "/", "\\", "x", ",", "`", "v", ">", "*");
    exports.BuiltinFormatter = (0, kinds_1.Enum)("raw", "basic", "numeral", "printf", "datetime");
    exports.HTTPMethod = (0, kinds_1.Enum)("POST", "GET");
    exports.HexTileOrientation = (0, kinds_1.Enum)("pointytop", "flattop");
    exports.HoverMode = (0, kinds_1.Enum)("mouse", "hline", "vline");
    exports.ImageOrigin = (0, kinds_1.Enum)("bottom_left", "top_left", "bottom_right", "top_right");
    exports.LatLon = (0, kinds_1.Enum)("lat", "lon");
    exports.LegendClickPolicy = (0, kinds_1.Enum)("none", "hide", "mute");
    exports.LegendLocation = exports.Anchor;
    exports.LineCap = (0, kinds_1.Enum)("butt", "round", "square");
    exports.LineDash = (0, kinds_1.Enum)("solid", "dashed", "dotted", "dotdash", "dashdot");
    exports.LineJoin = (0, kinds_1.Enum)("miter", "round", "bevel");
    exports.LinePolicy = (0, kinds_1.Enum)("prev", "next", "nearest", "interp", "none");
    exports.Location = (0, kinds_1.Enum)("above", "below", "left", "right");
    exports.Logo = (0, kinds_1.Enum)("normal", "grey");
    exports.MapType = (0, kinds_1.Enum)("satellite", "roadmap", "terrain", "hybrid");
    exports.MarkerType = (0, kinds_1.Enum)("asterisk", "circle", "circle_cross", "circle_dot", "circle_x", "circle_y", "cross", "dash", "diamond", "diamond_cross", "diamond_dot", "dot", "hex", "hex_dot", "inverted_triangle", "plus", "square", "square_cross", "square_dot", "square_pin", "square_x", "star", "star_dot", "triangle", "triangle_dot", "triangle_pin", "x", "y");
    exports.MutedPolicy = (0, kinds_1.Enum)("show", "ignore");
    exports.Orientation = (0, kinds_1.Enum)("vertical", "horizontal");
    exports.OutlineShapeName = (0, kinds_1.Enum)("none", "box", "rectangle", "square", "circle", "ellipse", "trapezoid", "parallelogram", "diamond", "triangle");
    exports.OutputBackend = (0, kinds_1.Enum)("canvas", "svg", "webgl");
    exports.PaddingUnits = (0, kinds_1.Enum)("percent", "absolute");
    exports.PanDirection = (0, kinds_1.Enum)("left", "right", "up", "down", "west", "east", "north", "south");
    exports.Place = (0, kinds_1.Enum)("above", "below", "left", "right", "center");
    exports.PointPolicy = (0, kinds_1.Enum)("snap_to_data", "follow_mouse", "none");
    exports.RadiusDimension = (0, kinds_1.Enum)("x", "y", "max", "min");
    exports.RenderLevel = (0, kinds_1.Enum)("image", "underlay", "glyph", "guide", "annotation", "overlay");
    exports.ResetPolicy = (0, kinds_1.Enum)("standard", "event_only");
    exports.ResolutionType = (0, kinds_1.Enum)("microseconds", "milliseconds", "seconds", "minsec", "minutes", "hourmin", "hours", "days", "months", "years");
    exports.RoundingFunction = (0, kinds_1.Enum)("round", "nearest", "floor", "rounddown", "ceil", "roundup");
    exports.ScrollbarPolicy = (0, kinds_1.Enum)("auto", "visible", "hidden");
    exports.RegionSelectionMode = (0, kinds_1.Enum)("replace", "append", "intersect", "subtract", "xor");
    exports.SelectionMode = (0, kinds_1.Enum)(...exports.RegionSelectionMode, "toggle");
    exports.Side = (0, kinds_1.Enum)("above", "below", "left", "right");
    exports.SizingMode = (0, kinds_1.Enum)("stretch_width", "stretch_height", "stretch_both", "scale_width", "scale_height", "scale_both", "fixed", "inherit");
    exports.Sort = (0, kinds_1.Enum)("ascending", "descending");
    exports.SpatialUnits = (0, kinds_1.Enum)("screen", "data");
    exports.StartEnd = (0, kinds_1.Enum)("start", "end");
    exports.StepMode = (0, kinds_1.Enum)("after", "before", "center");
    exports.TapBehavior = (0, kinds_1.Enum)("select", "inspect");
    exports.TapGesture = (0, kinds_1.Enum)("tap", "doubletap");
    exports.TextAlign = (0, kinds_1.Enum)("left", "right", "center");
    exports.TextBaseline = (0, kinds_1.Enum)("top", "middle", "bottom", "alphabetic", "hanging", "ideographic");
    exports.TextureRepetition = (0, kinds_1.Enum)("repeat", "repeat_x", "repeat_y", "no_repeat");
    exports.LabelOrientation = (0, kinds_1.Enum)("vertical", "horizontal", "parallel", "normal");
    exports.TooltipAttachment = (0, kinds_1.Enum)("horizontal", "vertical", "left", "right", "above", "below");
    exports.UpdateMode = (0, kinds_1.Enum)("replace", "append");
    exports.VerticalAlign = (0, kinds_1.Enum)("top", "middle", "bottom");
    // Keep this in sync with bokehjs/src/less/icons.less
    exports.ToolIcon = (0, kinds_1.Enum)("append_mode", "arrow_down_to_bar", "arrow_up_from_bar", "auto_box_zoom", "bold", "box_edit", "box_select", "box_zoom", "caret_down", "caret_left", "caret_right", "caret_up", "check", "chevron_down", "chevron_left", "chevron_right", "chevron_up", "clear_selection", "copy", "crosshair", "delete", "freehand_draw", "fullscreen", "help", "hover", "intersect_mode", "invert_selection", "italic", "lasso_select", "line_edit", "maximize", "minimize", "pan", "pin", "point_draw", "pointer", "poly_draw", "poly_edit", "polygon_select", "range", "redo", "replace_mode", "reset", "save", "see_off", "see_on", "settings", "square", "square_check", "subtract_mode", "tap_select", "text_align_center", "text_align_left", "text_align_right", "undo", "unknown", "unpin", "wheel_pan", "wheel_zoom", "x_box_select", "x_box_zoom", "x_grip", "x_pan", "xor_mode", "y_box_select", "y_box_zoom", "y_grip", "y_pan", "zoom_in", "zoom_out");
},
/* core/kinds.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const tp = tslib_1.__importStar(require(8) /* ./util/types */);
    const color_1 = require(22) /* ./util/color */;
    const object_1 = require(9) /* ./util/object */;
    const refs_1 = require(17) /* ./util/refs */;
    const ESMap = globalThis.Map;
    const ESSet = globalThis.Set;
    const DOMNode = globalThis.Node;
    class Kind {
    }
    exports.Kind = Kind;
    Kind.__name__ = "Kind";
    (function (Kinds) {
        class Primitive extends Kind {
            may_have_refs() {
                return false;
            }
        }
        Primitive.__name__ = "Primitive";
        Kinds.Primitive = Primitive;
        class Any extends Primitive {
            valid(value) {
                return value !== undefined;
            }
            toString() {
                return "Any";
            }
            may_have_refs() {
                return true;
            }
        }
        Any.__name__ = "Any";
        Kinds.Any = Any;
        class Unknown extends Primitive {
            valid(value) {
                return value !== undefined;
            }
            toString() {
                return "Unknown";
            }
            may_have_refs() {
                return true;
            }
        }
        Unknown.__name__ = "Unknown";
        Kinds.Unknown = Unknown;
        class Bool extends Primitive {
            valid(value) {
                return tp.isBoolean(value);
            }
            toString() {
                return "Bool";
            }
        }
        Bool.__name__ = "Bool";
        Kinds.Bool = Bool;
        class Ref extends Kind {
            constructor(obj_type) {
                super();
                this.obj_type = obj_type;
            }
            valid(value) {
                return value instanceof this.obj_type;
            }
            toString() {
                const tp = this.obj_type;
                // NOTE: `__name__` is injected by a compiler transform
                const name = tp.__name__ ?? tp.toString();
                return `Ref(${name})`;
            }
            may_have_refs() {
                const { obj_type } = this;
                return refs_1.has_refs in obj_type ? obj_type[refs_1.has_refs] : true;
            }
        }
        Ref.__name__ = "Ref";
        Kinds.Ref = Ref;
        class AnyRef extends Kind {
            valid(value) {
                return tp.isObject(value);
            }
            toString() {
                return "AnyRef";
            }
            may_have_refs() {
                return true;
            }
        }
        AnyRef.__name__ = "AnyRef";
        Kinds.AnyRef = AnyRef;
        class Float extends Primitive {
            valid(value) {
                return tp.isNumber(value);
            }
            toString() {
                return "Float";
            }
        }
        Float.__name__ = "Float";
        Kinds.Float = Float;
        class Int extends Float {
            valid(value) {
                return super.valid(value) && tp.isInteger(value);
            }
            toString() {
                return "Int";
            }
        }
        Int.__name__ = "Int";
        Kinds.Int = Int;
        class Percent extends Float {
            valid(value) {
                return super.valid(value) && 0 <= value && value <= 1;
            }
            toString() {
                return "Percent";
            }
        }
        Percent.__name__ = "Percent";
        Kinds.Percent = Percent;
        class Or extends Kind {
            constructor(types) {
                super();
                this.types = types;
                this.types = types;
            }
            valid(value) {
                return this.types.some((type) => type.valid(value));
            }
            toString() {
                return `Or(${this.types.map((type) => type.toString()).join(", ")})`;
            }
            may_have_refs() {
                return this.types.some((type) => type.may_have_refs());
            }
        }
        Or.__name__ = "Or";
        Kinds.Or = Or;
        class And extends Kind {
            constructor(type0, type1) {
                super();
                this.types = [type0, type1];
            }
            valid(value) {
                return this.types.some((type) => type.valid(value)); // TODO not sure if this is correct, probably not
            }
            toString() {
                return `And(${this.types.map((type) => type.toString()).join(", ")})`;
            }
            may_have_refs() {
                return this.types.some((type) => type.may_have_refs());
            }
        }
        And.__name__ = "And";
        Kinds.And = And;
        class Tuple extends Kind {
            constructor(types) {
                super();
                this.types = types;
                this.types = types;
            }
            valid(value) {
                if (!tp.isArray(value)) {
                    return false;
                }
                for (let i = 0; i < this.types.length; i++) {
                    const type = this.types[i];
                    const item = value[i];
                    if (!type.valid(item)) {
                        return false;
                    }
                }
                return true;
            }
            toString() {
                return `Tuple(${this.types.map((type) => type.toString()).join(", ")})`;
            }
            may_have_refs() {
                return this.types.some((type) => type.may_have_refs());
            }
        }
        Tuple.__name__ = "Tuple";
        Kinds.Tuple = Tuple;
        class Struct extends Kind {
            constructor(struct_type) {
                super();
                this.struct_type = struct_type;
            }
            valid(value) {
                if (!tp.isPlainObject(value)) {
                    return false;
                }
                const struct_type_proxy = new object_1.PlainObjectProxy(this.struct_type);
                for (const key of (0, object_1.keys)(value)) {
                    if (!struct_type_proxy.has(key)) {
                        return false;
                    }
                }
                for (const [key, item_type] of struct_type_proxy) {
                    const item = value[key];
                    if (!item_type.valid(item)) {
                        return false;
                    }
                }
                return true;
            }
            toString() {
                const items = (0, object_1.typed_entries)(this.struct_type).map(([key, kind]) => `${key.toString()}: ${kind}`).join(", ");
                return `Struct({${items}})`;
            }
            may_have_refs() {
                return (0, object_1.typed_values)(this.struct_type).some((kind) => kind.may_have_refs());
            }
        }
        Struct.__name__ = "Struct";
        Kinds.Struct = Struct;
        class PartialStruct extends Kind {
            constructor(struct_type) {
                super();
                this.struct_type = struct_type;
            }
            valid(value) {
                if (!tp.isPlainObject(value)) {
                    return false;
                }
                const value_proxy = new object_1.PlainObjectProxy(value);
                const struct_type_proxy = new object_1.PlainObjectProxy(this.struct_type);
                for (const key of value_proxy.keys()) {
                    if (!struct_type_proxy.has(key)) {
                        return false;
                    }
                }
                for (const [key, item_type] of struct_type_proxy) {
                    const item = value_proxy.get(key);
                    if (item === undefined) {
                        continue;
                    }
                    if (!item_type.valid(item)) {
                        return false;
                    }
                }
                return true;
            }
            toString() {
                const items = (0, object_1.typed_entries)(this.struct_type).map(([key, kind]) => `${key.toString()}?: ${kind}`).join(", ");
                return `Struct({${items}})`;
            }
            may_have_refs() {
                return (0, object_1.typed_values)(this.struct_type).some((kind) => kind.may_have_refs());
            }
        }
        PartialStruct.__name__ = "PartialStruct";
        Kinds.PartialStruct = PartialStruct;
        class Iterable extends Kind {
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                return tp.isIterable(value);
            }
            toString() {
                return `Iterable(${this.item_type.toString()})`;
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Iterable.__name__ = "Iterable";
        Kinds.Iterable = Iterable;
        class Arrayable extends Kind {
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                return tp.isArray(value) || tp.isTypedArray(value); // TODO: too specific
            }
            toString() {
                return `Arrayable(${this.item_type.toString()})`;
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Arrayable.__name__ = "Arrayable";
        Kinds.Arrayable = Arrayable;
        class List extends Kind {
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                return tp.isArray(value) && value.every((item) => this.item_type.valid(item));
            }
            toString() {
                return `List(${this.item_type.toString()})`;
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        List.__name__ = "List";
        Kinds.List = List;
        class NonEmptyList extends List {
            valid(value) {
                return super.valid(value) && value.length != 0;
            }
            toString() {
                return `NonEmptyList(${this.item_type.toString()})`;
            }
        }
        NonEmptyList.__name__ = "NonEmptyList";
        Kinds.NonEmptyList = NonEmptyList;
        class Null extends Primitive {
            valid(value) {
                return value === null;
            }
            toString() {
                return "Null";
            }
        }
        Null.__name__ = "Null";
        Kinds.Null = Null;
        class Nullable extends Kind {
            constructor(base_type) {
                super();
                this.base_type = base_type;
            }
            valid(value) {
                return value === null || this.base_type.valid(value);
            }
            toString() {
                return `Nullable(${this.base_type.toString()})`;
            }
            may_have_refs() {
                return this.base_type.may_have_refs();
            }
        }
        Nullable.__name__ = "Nullable";
        Kinds.Nullable = Nullable;
        class Opt extends Kind {
            constructor(base_type) {
                super();
                this.base_type = base_type;
            }
            valid(value) {
                return value === undefined || this.base_type.valid(value);
            }
            toString() {
                return `Opt(${this.base_type.toString()})`;
            }
            may_have_refs() {
                return this.base_type.may_have_refs();
            }
        }
        Opt.__name__ = "Opt";
        Kinds.Opt = Opt;
        class Bytes extends Kind {
            valid(value) {
                return value instanceof ArrayBuffer;
            }
            toString() {
                return "Bytes";
            }
            may_have_refs() {
                return false;
            }
        }
        Bytes.__name__ = "Bytes";
        Kinds.Bytes = Bytes;
        class Str extends Primitive {
            valid(value) {
                return tp.isString(value);
            }
            toString() {
                return "Str";
            }
        }
        Str.__name__ = "Str";
        Kinds.Str = Str;
        class Regex extends Str {
            constructor(regex) {
                super();
                this.regex = regex;
            }
            valid(value) {
                return super.valid(value) && this.regex.test(value);
            }
            toString() {
                return `Regex(${this.regex.toString()})`;
            }
        }
        Regex.__name__ = "Regex";
        Kinds.Regex = Regex;
        class Enum extends Primitive {
            constructor(values) {
                super();
                this.values = new ESSet(values);
            }
            valid(value) {
                return this.values.has(value);
            }
            *[Symbol.iterator]() {
                yield* this.values;
            }
            toString() {
                return `Enum(${[...this.values].map((v) => v.toString()).join(", ")})`;
            }
        }
        Enum.__name__ = "Enum";
        Kinds.Enum = Enum;
        class Dict extends Kind {
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                if (!(value instanceof ESMap || tp.isPlainObject(value))) {
                    return false;
                }
                for (const item of (0, object_1.values)(value)) {
                    if (!this.item_type.valid(item)) {
                        return false;
                    }
                }
                return true;
            }
            toString() {
                return `Dict(${this.item_type.toString()})`;
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Dict.__name__ = "Dict";
        Kinds.Dict = Dict;
        class Mapping extends Kind {
            constructor(key_type, item_type) {
                super();
                this.key_type = key_type;
                this.item_type = item_type;
            }
            coerce(value) {
                // HACK accommodate for deserialization of {type: "map"}
                if (tp.isPlainObject(value) && (0, object_1.is_empty)(value)) {
                    return new ESMap();
                }
                else {
                    return value;
                }
            }
            valid(value) {
                if (!(value instanceof ESMap)) {
                    return false;
                }
                for (const [key, item] of value.entries()) {
                    if (!(this.key_type.valid(key) && this.item_type.valid(item))) {
                        return false;
                    }
                }
                return true;
            }
            toString() {
                return `Mapping(${this.key_type.toString()}, ${this.item_type.toString()})`;
            }
            may_have_refs() {
                return this.key_type.may_have_refs() || this.item_type.may_have_refs();
            }
        }
        Mapping.__name__ = "Mapping";
        Kinds.Mapping = Mapping;
        class Set extends Kind {
            constructor(item_type) {
                super();
                this.item_type = item_type;
            }
            valid(value) {
                if (!(value instanceof ESSet)) {
                    return false;
                }
                for (const item of value) {
                    if (!this.item_type.valid(item)) {
                        return false;
                    }
                }
                return true;
            }
            toString() {
                return `Set(${this.item_type.toString()})`;
            }
            may_have_refs() {
                return this.item_type.may_have_refs();
            }
        }
        Set.__name__ = "Set";
        Kinds.Set = Set;
        class Color extends Kind {
            valid(value) {
                return (0, color_1.is_Color)(value);
            }
            toString() {
                return "Color";
            }
            may_have_refs() {
                return false;
            }
        }
        Color.__name__ = "Color";
        Kinds.Color = Color;
        class CSSLength extends Str {
            /*
            override valid(value: unknown): value is string {
              return super.valid(value) // TODO: && this._parse(value)
            }
            */
            toString() {
                return "CSSLength";
            }
        }
        CSSLength.__name__ = "CSSLength";
        Kinds.CSSLength = CSSLength;
        class Func extends Kind {
            valid(value) {
                return tp.isFunction(value);
            }
            toString() {
                return "Func(...)";
            }
            may_have_refs() {
                return false;
            }
        }
        Func.__name__ = "Func";
        Kinds.Func = Func;
        class NonNegative extends Kind {
            constructor(base_type) {
                super();
                this.base_type = base_type;
            }
            valid(value) {
                return this.base_type.valid(value) && value >= 0;
            }
            toString() {
                return `NonNegative(${this.base_type.toString()})`;
            }
            may_have_refs() {
                return this.base_type.may_have_refs();
            }
        }
        NonNegative.__name__ = "NonNegative";
        Kinds.NonNegative = NonNegative;
        class Positive extends Kind {
            constructor(base_type) {
                super();
                this.base_type = base_type;
            }
            valid(value) {
                return this.base_type.valid(value) && value > 0;
            }
            toString() {
                return `Positive(${this.base_type.toString()})`;
            }
            may_have_refs() {
                return this.base_type.may_have_refs();
            }
        }
        Positive.__name__ = "Positive";
        Kinds.Positive = Positive;
        class Node extends Kind {
            valid(value) {
                return value instanceof DOMNode;
            }
            toString() {
                return "Node";
            }
            may_have_refs() {
                return false;
            }
        }
        Node.__name__ = "Node";
        Kinds.Node = Node;
    })(exports.Kinds || (exports.Kinds = {}));
    exports.Any = new exports.Kinds.Any();
    exports.Unknown = new exports.Kinds.Unknown();
    exports.Bool = new exports.Kinds.Bool();
    exports.Float = new exports.Kinds.Float();
    exports.Int = new exports.Kinds.Int();
    exports.Bytes = new exports.Kinds.Bytes();
    exports.Str = new exports.Kinds.Str();
    const Regex = (regex) => new exports.Kinds.Regex(regex);
    exports.Regex = Regex;
    exports.Null = new exports.Kinds.Null();
    const Nullable = (base_type) => new exports.Kinds.Nullable(base_type);
    exports.Nullable = Nullable;
    const Opt = (base_type) => new exports.Kinds.Opt(base_type);
    exports.Opt = Opt;
    const Or = (...types) => new exports.Kinds.Or(types);
    exports.Or = Or;
    const And = (type0, type1) => new exports.Kinds.And(type0, type1);
    exports.And = And;
    const Tuple = (...types) => new exports.Kinds.Tuple(types);
    exports.Tuple = Tuple;
    const Struct = (struct_type) => new exports.Kinds.Struct(struct_type);
    exports.Struct = Struct;
    const PartialStruct = (struct_type) => new exports.Kinds.PartialStruct(struct_type);
    exports.PartialStruct = PartialStruct;
    const Iterable = (item_type) => new exports.Kinds.Iterable(item_type);
    exports.Iterable = Iterable;
    const Arrayable = (item_type) => new exports.Kinds.Arrayable(item_type);
    exports.Arrayable = Arrayable;
    const List = (item_type) => new exports.Kinds.List(item_type);
    exports.List = List;
    const NonEmptyList = (item_type) => new exports.Kinds.NonEmptyList(item_type);
    exports.NonEmptyList = NonEmptyList;
    const Dict = (item_type) => new exports.Kinds.Dict(item_type);
    exports.Dict = Dict;
    const Mapping = (key_type, item_type) => new exports.Kinds.Mapping(key_type, item_type);
    exports.Mapping = Mapping;
    const Set = (item_type) => new exports.Kinds.Set(item_type);
    exports.Set = Set;
    const Enum = (...values) => new exports.Kinds.Enum(values);
    exports.Enum = Enum;
    const Ref = (obj_type) => new exports.Kinds.Ref(obj_type);
    exports.Ref = Ref;
    const AnyRef = () => new exports.Kinds.AnyRef();
    exports.AnyRef = AnyRef;
    const Func = () => new exports.Kinds.Func();
    exports.Func = Func;
    exports.Node = new exports.Kinds.Node();
    const NonNegative = (base_type) => new exports.Kinds.NonNegative(base_type);
    exports.NonNegative = NonNegative;
    const Positive = (base_type) => new exports.Kinds.Positive(base_type);
    exports.Positive = Positive;
    exports.Percent = new exports.Kinds.Percent();
    exports.Alpha = exports.Percent;
    exports.Color = new exports.Kinds.Color();
    exports.Auto = (0, exports.Enum)("auto");
    exports.CSSLength = new exports.Kinds.CSSLength();
    exports.FontSize = exports.Str;
    exports.Font = exports.Str;
    exports.Angle = exports.Float;
    // backwards compatibility aliases (these collide with built-in types)
    /** @deprecated */
    exports.Boolean = exports.Bool;
    /** @deprecated */
    exports.String = exports.Str;
    /** @deprecated */
    exports.Number = exports.Float;
    /** @deprecated */
    exports.Array = exports.List;
    /** @deprecated */
    exports.Map = exports.Mapping;
    /** @deprecated */
    exports.Function = exports.Func;
},
/* core/util/color.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.byte = byte;
    exports.transparent = transparent;
    exports.encode_rgba = encode_rgba;
    exports.decode_rgba = decode_rgba;
    exports.color2rgba = color2rgba;
    exports.rgba2css = rgba2css;
    exports.color2css = color2css;
    exports.color2hex = color2hex;
    exports.color2hexrgb = color2hexrgb;
    exports.css4_parse = css4_parse;
    exports.is_Color = is_Color;
    exports.is_dark = is_dark;
    exports.brightness = brightness;
    exports.luminance = luminance;
    const svg_colors_1 = require(23) /* ./svg_colors */;
    const math_1 = require(11) /* ./math */;
    const types_1 = require(8) /* ./types */;
    const { round, sqrt } = Math;
    function byte(v) {
        return (0, math_1.clamp)(round(v), 0, 255);
    }
    function transparent() {
        return [0, 0, 0, 0];
    }
    function encode_rgba([r, g, b, a]) {
        return r << 24 | g << 16 | b << 8 | a;
    }
    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];
    }
    function color2rgba(color, alpha = 1.0) {
        const [r, g, b, a] = (() => {
            if (color == null) {
                return transparent();
            }
            else if ((0, types_1.isInteger)(color)) {
                return decode_rgba(color);
            }
            else if ((0, types_1.isString)(color)) {
                return css4_parse(color) ?? transparent();
            }
            else {
                if (color.length == 2) {
                    const [name, alpha] = color;
                    return color2rgba(name, alpha);
                }
                else {
                    const [r, g, b, a = 1.0] = color;
                    return [r, g, b, byte(a * 255)];
                }
            }
        })();
        return [r, g, b, byte(alpha * a)];
    }
    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 rgba2css([r, g, b, a]) {
        const alpha = a == 255 ? "" : ` / ${a / 255}`;
        return `rgb(${r} ${g} ${b}${alpha})`;
    }
    function color2css(color, alpha) {
        if ((0, types_1.isString)(color) && (alpha == null || alpha == 1.0)) {
            return color; // passthrough to persist color in its original form
        }
        else {
            const [r, g, b, a] = color2rgba(color, alpha);
            return rgba2css([r, g, b, a]);
        }
    }
    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)}`;
    }
    function color2hexrgb(color) {
        const [r, g, b] = color2rgba(color);
        return `#${hex(r)}${hex(g)}${hex(b)}`;
    }
    /*
    let _last_color = "transparent"
    let _last_alpha = 1.0
    let _last_rgba = transparent()
    
    export function _color2rgba(color: string | null, alpha: number = 1.0): RGBA {
      if (color == _last_color && alpha == _last_alpha)
        return [..._last_rgba]
    
      const [r, g, b, a] = parsed
      const rgba: RGBA = [r, g, b, a == 255 ? byte(alpha*255) : a]
      _last_color = color
      _last_alpha = alpha
      _last_rgba = rgba
      return rgba
    }
    */
    const rgb_modern = /^rgba?\(\s*(?<r>[^\s,]+?)\s+(?<g>[^\s,]+?)\s+(?<b>[^\s,]+?)(?:\s*\/\s*(?<a>[^\s,]+?))?\s*\)$/;
    const rgb_legacy = /^rgba?\(\s*(?<r>[^\s,]+?)\s*,\s*(?<g>[^\s,]+?)\s*,\s*(?<b>[^\s,]+?)(?:\s*,\s*(?<a>[^\s,]+?))?\s*\)$/;
    const css4_normalize = (() => {
        const canvas = document.createElement("canvas");
        canvas.width = 1;
        canvas.height = 1;
        const ctx = canvas.getContext("2d");
        const gradient = ctx.createLinearGradient(0, 0, 1, 1);
        return (color) => {
            ctx.fillStyle = gradient; // lgtm [js/useless-assignment-to-property]
            ctx.fillStyle = color;
            const style = ctx.fillStyle;
            return style != gradient ? style : null;
        };
    })();
    function css4_parse(color) {
        /**
          Parses CSS4 color strings:
      
          - transparent
          - named color
          - #RRGGBB[AA]
          - #RGB[A]
          - rgb[a](R G B[ / A])
          - rgb[a](R, G, B[, A])
          - other CSS4 syntax (browser dependent)
      
        */
        color = color.trim().toLowerCase();
        if (color == "") {
            return null;
        }
        else if (color == "transparent") {
            return transparent();
        }
        else if ((0, svg_colors_1.is_named_color)(color)) {
            return decode_rgba(svg_colors_1.named_colors[color]);
        }
        else if (color[0] == "#") {
            const v = Number(`0x${color.substring(1)}`);
            if (isNaN(v)) {
                return null;
            }
            switch (color.length - 1) {
                case 3: {
                    const r = (v >> 8) & 0xf;
                    const g = (v >> 4) & 0xf;
                    const b = (v >> 0) & 0xf;
                    const rr = (r << 4) | r;
                    const gg = (g << 4) | g;
                    const bb = (b << 4) | b;
                    return [rr, gg, bb, 255];
                }
                case 4: {
                    const r = (v >> 12) & 0xf;
                    const g = (v >> 8) & 0xf;
                    const b = (v >> 4) & 0xf;
                    const a = (v >> 0) & 0xf;
                    const rr = (r << 4) | r;
                    const gg = (g << 4) | g;
                    const bb = (b << 4) | b;
                    const aa = (a << 4) | a;
                    return [rr, gg, bb, aa];
                }
                case 6: {
                    const rr = (v >> 16) & 0xff;
                    const gg = (v >> 8) & 0xff;
                    const bb = (v >> 0) & 0xff;
                    return [rr, gg, bb, 255];
                }
                case 8: {
                    const rr = (v >> 24) & 0xff;
                    const gg = (v >> 16) & 0xff;
                    const bb = (v >> 8) & 0xff;
                    const aa = (v >> 0) & 0xff;
                    return [rr, gg, bb, aa];
                }
            }
        }
        else if (color.startsWith("rgb")) {
            const result = color.match(rgb_modern) ?? color.match(rgb_legacy);
            if (result?.groups != null) {
                let { r, g, b, a = "1" } = result.groups;
                const rp = r.endsWith("%");
                const gp = g.endsWith("%");
                const bp = b.endsWith("%");
                const ap = a.endsWith("%");
                if (!(rp && gp && bp || (!rp && !gp && !bp))) {
                    return null;
                }
                if (rp) {
                    r = r.slice(0, -1);
                }
                if (gp) {
                    g = g.slice(0, -1);
                }
                if (bp) {
                    b = b.slice(0, -1);
                }
                if (ap) {
                    a = a.slice(0, -1);
                }
                let R = Number(r);
                let G = Number(g);
                let B = Number(b);
                let A = Number(a);
                if (isNaN(R + G + B + A)) {
                    return null;
                }
                if (rp) {
                    R = 255 * (R / 100);
                }
                if (gp) {
                    G = 255 * (G / 100);
                }
                if (bp) {
                    B = 255 * (B / 100);
                }
                A = 255 * (ap ? A / 100 : A);
                R = byte(R);
                G = byte(G);
                B = byte(B);
                A = byte(A);
                return [R, G, B, A];
            }
        }
        else {
            const style = css4_normalize(color);
            if (style != null) {
                return css4_parse(style);
            }
        }
        return null;
    }
    function is_Color(value) {
        if ((0, types_1.isInteger)(value)) {
            return true;
        }
        if ((0, types_1.isString)(value) && css4_parse(value) != null) {
            return true;
        }
        if ((0, types_1.isArray)(value) && (value.length == 3 || value.length == 4)) {
            return true;
        }
        return false;
    }
    function is_dark([r, g, b]) {
        const l = 1 - (0.299 * r + 0.587 * g + 0.114 * b) / 255;
        return l >= 0.6;
    }
    function brightness(color) {
        // Perceived brightness of a color in [0, 1] range.
        // http://alienryderflex.com/hsp.html
        const [r, g, b] = color2rgba(color);
        return sqrt(0.299 * r ** 2 + 0.587 * g ** 2 + 0.114 * b ** 2) / 255;
    }
    function luminance(color) {
        // Relative luminance of a color in [0, 1] range.
        // https://en.wikipedia.org/wiki/Relative_luminance
        const [r, g, b] = color2rgba(color);
        return (0.2126 * r ** 2.2 + 0.7152 * g ** 2.2 + 0.0722 * b ** 2.2) / 255 ** 2.2;
    }
},
/* core/util/svg_colors.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_named_color = is_named_color;
    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;
    }
},
/* core/types.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.infer_type = infer_type;
    exports.to_screen = to_screen;
    exports.GeneratorFunction = Object.getPrototypeOf(function* () { }).constructor;
    exports.AsyncGeneratorFunction = Object.getPrototypeOf(async 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.ScreenArray = Float32Array;
    function to_screen(array) {
        if (!(array instanceof Float32Array)) {
            return Float32Array.from(array);
        }
        else {
            return array;
        }
    }
    var bitset_1 = require(25) /* ./util/bitset */;
    __esExport("Indices", bitset_1.BitSet);
},
/* core/util/bitset.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b;
    __esModule();
    const eq_1 = require(26) /* ./eq */;
    const assert_1 = require(12) /* ./assert */;
    const refs_1 = require(17) /* ./refs */;
    class BitSet {
        constructor(size, init = 0) {
            this[_a] = "BitSet";
            this._count = null;
            this.size = size;
            this._nwords = Math.ceil(size / BitSet._word_length);
            if (init == 0 || init == 1) {
                this._array = new Uint32Array(this._nwords);
                if (init == 1) {
                    this._array.fill(0xffffffff);
                }
            }
            else {
                (0, assert_1.assert)(init.length == this._nwords, "Initializer size mismatch");
                this._array = init;
            }
        }
        clone() {
            return new BitSet(this.size, new Uint32Array(this._array));
        }
        [(_a = Symbol.toStringTag, _b = refs_1.has_refs, eq_1.equals)](that, cmp) {
            if (!cmp.eq(this.size, that.size)) {
                return false;
            }
            const { _nwords } = this;
            const trailing = this.size % BitSet._word_length;
            const n = trailing == 0 ? _nwords : _nwords - 1;
            for (let i = 0; i < n; i++) {
                if (this._array[i] != that._array[i]) {
                    return false;
                }
            }
            if (trailing == 0) {
                return true;
            }
            else {
                const msb = 1 << (trailing - 1);
                const mask = (msb - 1) ^ msb;
                return (this._array[n] & mask) == (that._array[n] & mask);
            }
        }
        static all_set(size) {
            return new BitSet(size, 1);
        }
        static all_unset(size) {
            return new BitSet(size, 0);
        }
        static from_indices(size, indices) {
            const bits = new BitSet(size);
            for (const i of indices) {
                bits.set(i);
            }
            return bits;
        }
        static from_booleans(size, booleans) {
            const bits = new BitSet(size);
            let i = 0;
            for (const boolean of booleans) {
                if (i == size) {
                    break;
                }
                if (boolean) {
                    bits.set(i);
                }
                i += 1;
            }
            return bits;
        }
        _check_bounds(k) {
            (0, assert_1.assert)(0 <= k && k < this.size, `Out of bounds: 0 <= ${k} < ${this.size}`);
        }
        get(k) {
            this._check_bounds(k);
            const i = k >>> 5; // Math.floor(k/32)
            const j = k & 0x1f; // k % 32
            return ((this._array[i] >> j) & 0b1) == 0b1;
        }
        set(k, v = true) {
            this._check_bounds(k);
            this._count = null;
            const i = k >>> 5; // Math.floor(k/32)
            const j = k & 0x1f; // k % 32
            if (v) {
                this._array[i] |= 0b1 << j;
            }
            else {
                this._array[i] &= ~(0b1 << j);
            }
        }
        unset(k) {
            this.set(k, false);
        }
        *[Symbol.iterator]() {
            yield* this.ones();
        }
        get count() {
            let count = this._count;
            if (count == null) {
                this._count = count = this._get_count();
            }
            return count;
        }
        _get_count() {
            const { _array, _nwords, size } = this;
            let c = 0;
            for (let k = 0, i = 0; i < _nwords; i++) {
                const word = _array[i];
                if (word == 0) {
                    k += BitSet._word_length;
                }
                else {
                    for (let j = 0; j < BitSet._word_length && k < size; j++, k++) {
                        if (((word >>> j) & 0b1) == 0b1) {
                            c += 1;
                        }
                    }
                }
            }
            return c;
        }
        *ones() {
            const { _array, _nwords, size } = this;
            for (let k = 0, i = 0; i < _nwords; i++) {
                const word = _array[i];
                if (word == 0) {
                    k += BitSet._word_length;
                    continue;
                }
                for (let j = 0; j < BitSet._word_length && k < size; j++, k++) {
                    if (((word >>> j) & 0b1) == 0b1) {
                        yield k;
                    }
                }
            }
        }
        *zeros() {
            const { _array, _nwords, size } = this;
            for (let k = 0, i = 0; i < _nwords; i++) {
                const word = _array[i];
                if (word == 0xffffffff) {
                    k += BitSet._word_length;
                    continue;
                }
                for (let j = 0; j < BitSet._word_length && k < size; j++, k++) {
                    if (((word >>> j) & 0b1) == 0b0) {
                        yield k;
                    }
                }
            }
        }
        _check_size(other) {
            (0, assert_1.assert)(this.size == other.size, `Size mismatch (${this.size} != ${other.size})`);
        }
        invert() {
            for (let i = 0; i < this._nwords; i++) {
                this._array[i] = ~this._array[i] >>> 0;
            }
        }
        add(other) {
            this._check_size(other);
            for (let i = 0; i < this._nwords; i++) {
                this._array[i] |= other._array[i];
            }
        }
        intersect(other) {
            this._check_size(other);
            for (let i = 0; i < this._nwords; i++) {
                this._array[i] &= other._array[i];
            }
        }
        subtract(other) {
            this._check_size(other);
            for (let i = 0; i < this._nwords; i++) {
                const a = this._array[i];
                const b = other._array[i];
                this._array[i] = (a ^ b) & a;
            }
        }
        symmetric_subtract(other) {
            this._check_size(other);
            for (let i = 0; i < this._nwords; i++) {
                this._array[i] ^= other._array[i];
            }
        }
        inversion() {
            const result = this.clone();
            result.invert();
            return result;
        }
        union(other) {
            const result = this.clone();
            result.add(other);
            return result;
        }
        intersection(other) {
            const result = this.clone();
            result.intersect(other);
            return result;
        }
        difference(other) {
            const result = this.clone();
            result.subtract(other);
            return result;
        }
        symmetric_difference(other) {
            const result = this.clone();
            result.symmetric_subtract(other);
            return result;
        }
        select(array) {
            (0, assert_1.assert)(this.size <= array.length, "Size mismatch");
            const n = this.count;
            const result = new array.constructor(n);
            let i = 0;
            for (const j of this) {
                result[i++] = array[j];
            }
            return result;
        }
    }
    exports.BitSet = BitSet;
    BitSet.__name__ = "BitSet";
    BitSet[_b] = false;
    BitSet._word_length = 32;
},
/* core/util/eq.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_equal = is_equal;
    exports.is_structurally_equal = is_structurally_equal;
    exports.is_similar = is_similar;
    // Based on Underscore.js 1.8.3 (http://underscorejs.org)
    const types_1 = require(8) /* ./types */;
    const { hasOwnProperty } = Object.prototype;
    exports.equals = Symbol("equals");
    function is_Equatable(obj) {
        return (0, types_1.isObject)(obj) && exports.equals in obj;
    }
    exports.wildcard = Symbol("wildcard");
    const toString = Object.prototype.toString;
    class EqNotImplemented extends Error {
    }
    exports.EqNotImplemented = EqNotImplemented;
    EqNotImplemented.__name__ = "EqNotImplemented";
    class Comparator {
        constructor(options) {
            this.a_stack = [];
            this.b_stack = [];
            this.structural = options?.structural ?? false;
        }
        eq(a, b) {
            if (a === b || Object.is(a, b)) {
                return true;
            }
            if (a === exports.wildcard || b === exports.wildcard) {
                return true;
            }
            if (a == null || b == null) {
                return a === b;
            }
            const class_name = toString.call(a);
            if (class_name != toString.call(b)) {
                return false;
            }
            switch (class_name) {
                case "[object Number]":
                    return this.numbers(a, b);
                case "[object Symbol]":
                    return a === b;
                case "[object RegExp]":
                case "[object String]":
                    return `${a}` == `${b}`;
                case "[object Date]":
                case "[object Boolean]":
                    return +a === +b;
            }
            // Assume equality for cyclic structures. The algorithm for detecting cyclic
            // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
            // Initializing stack of traversed objects.
            // It's done here since we only need them for objects and arrays comparison.
            const { a_stack, b_stack } = this;
            let length = a_stack.length;
            while (length-- > 0) {
                // Linear search. Performance is inversely proportional to the number of
                // unique nested structures.
                if (a_stack[length] === a) {
                    return b_stack[length] === b;
                }
            }
            a_stack.push(a);
            b_stack.push(b);
            const result = (() => {
                if (is_Equatable(a) && is_Equatable(b)) {
                    return a[exports.equals](b, this);
                }
                switch (class_name) {
                    case "[object Array]":
                    case "[object Uint8Array]":
                    case "[object Int8Array]":
                    case "[object Uint16Array]":
                    case "[object Int16Array]":
                    case "[object Uint32Array]":
                    case "[object Int32Array]":
                    case "[object Float32Array]":
                    case "[object Float64Array]": {
                        return this.arrays(a, b);
                    }
                    case "[object Map]":
                        return this.maps(a, b);
                    case "[object Set]":
                        return this.sets(a, b);
                    case "[object Object]": {
                        if (a.constructor == b.constructor && (a.constructor == null || a.constructor === Object)) {
                            return this.objects(a, b);
                        }
                    }
                    case "[object Function]": {
                        if (a.constructor == b.constructor && a.constructor === Function) {
                            return this.eq(`${a}`, `${b}`);
                        }
                    }
                }
                if (typeof Node !== "undefined" && a instanceof Node) {
                    return this.nodes(a, b);
                }
                throw new EqNotImplemented(`can't compare objects of type ${class_name}`);
            })();
            a_stack.pop();
            b_stack.pop();
            return result;
        }
        numbers(a, b) {
            return a === b || 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();
                const an_done = an.done ?? false;
                const bn_done = bn.done ?? false;
                if (an_done && bn_done) {
                    return true;
                }
                if (an_done || bn_done) {
                    return false;
                }
                if (!this.eq(an.value, bn.value)) {
                    return false;
                }
            }
        }
        maps(a, b) {
            if (a.size != b.size) {
                return false;
            }
            if (this.structural) {
                return this.iterables(a.entries(), b.entries());
            }
            else {
                for (const [key, val] of a) {
                    if (!b.has(key) || !this.eq(val, b.get(key))) {
                        return false;
                    }
                }
                return true;
            }
        }
        sets(a, b) {
            if (a.size != b.size) {
                return false;
            }
            if (this.structural) {
                return this.iterables(a.entries(), b.entries());
            }
            else {
                for (const key of a) {
                    if (!b.has(key)) {
                        return false;
                    }
                }
                return true;
            }
        }
        objects(a, b) {
            const keys = Object.keys(a);
            if (keys.length != Object.keys(b).length) {
                return false;
            }
            for (const key of keys) {
                if (!hasOwnProperty.call(b, key) || !this.eq(a[key], b[key])) {
                    return false;
                }
            }
            return true;
        }
        nodes(a, b) {
            if (a.nodeType != b.nodeType) {
                return false;
            }
            if (a.textContent != b.textContent) {
                return false;
            }
            if (!this.iterables(a.childNodes, b.childNodes)) {
                return false;
            }
            return true;
        }
    }
    exports.Comparator = Comparator;
    Comparator.__name__ = "Comparator";
    const { abs } = Math;
    class SimilarComparator extends Comparator {
        constructor(tolerance = 1e-4) {
            super();
            this.tolerance = tolerance;
        }
        numbers(a, b) {
            return super.numbers(a, b) || abs(a - b) < this.tolerance;
        }
    }
    exports.SimilarComparator = SimilarComparator;
    SimilarComparator.__name__ = "SimilarComparator";
    function is_equal(a, b) {
        const comparator = new Comparator();
        return comparator.eq(a, b);
    }
    function is_structurally_equal(a, b) {
        const comparator = new Comparator({ structural: true });
        return comparator.eq(a, b);
    }
    function is_similar(a, b, tolerance) {
        const comparator = new SimilarComparator(tolerance);
        return comparator.eq(a, b);
    }
},
/* core/util/platform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.to_big_endian = to_big_endian;
    exports.is_mobile = (() => {
        return "ontouchstart" in globalThis || (typeof navigator !== "undefined" && navigator.maxTouchPoints > 0);
    })();
    exports.is_little_endian = (() => {
        const buf = new ArrayBuffer(4);
        const buf8 = new Uint8Array(buf);
        const buf32 = new Uint32Array(buf);
        buf32[1] = 0x0a0b0c0d;
        let little_endian = true;
        if (buf8[4] == 0x0a && buf8[5] == 0x0b && buf8[6] == 0x0c && buf8[7] == 0x0d) {
            little_endian = false;
        }
        return little_endian;
    })();
    exports.BYTE_ORDER = exports.is_little_endian ? "little" : "big";
    function to_big_endian(values) {
        if (exports.is_little_endian) {
            const result = new Uint32Array(values.length);
            const view = new DataView(result.buffer);
            let j = 0;
            for (const color of values) {
                view.setUint32(j, color);
                j += 4;
            }
            return result;
        }
        else {
            return values;
        }
    }
},
/* core/vectorization.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.isValue = isValue;
    exports.isField = isField;
    exports.isExpr = isExpr;
    exports.isVectorized = isVectorized;
    const types_1 = require(8) /* ./util/types */;
    const object_1 = require(9) /* ./util/object */;
    function is_of_type(obj, field) {
        if (!(0, types_1.isPlainObject)(obj)) {
            return false;
        }
        if (!(field in obj)) {
            return false;
        }
        let n = (0, object_1.size)(obj) - 1;
        if ("transform" in obj) {
            n -= 1;
        }
        if ("units" in obj) {
            n -= 1;
        }
        return n == 0;
    }
    function isValue(obj) {
        return is_of_type(obj, "value");
    }
    function isField(obj) {
        return is_of_type(obj, "field");
    }
    function isExpr(obj) {
        return is_of_type(obj, "expr");
    }
    function isVectorized(obj) {
        return isValue(obj) || isField(obj) || isExpr(obj);
    }
},
/* core/settings.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class Settings {
        constructor() {
            this._dev = false;
            this._wireframe = false;
            this._force_webgl = false;
            this._force_fields = false;
        }
        set dev(dev) {
            this._dev = dev;
        }
        get dev() {
            return this._dev;
        }
        set wireframe(wireframe) {
            this._wireframe = wireframe;
        }
        get wireframe() {
            return this._wireframe;
        }
        set force_webgl(force_webgl) {
            this._force_webgl = force_webgl;
        }
        get force_webgl() {
            return this._force_webgl;
        }
        set force_fields(force_fields) {
            this._force_fields = force_fields;
        }
        get force_fields() {
            return this._force_fields;
        }
    }
    exports.Settings = Settings;
    Settings.__name__ = "Settings";
    exports.settings = new Settings();
},
/* core/util/ndarray.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
    __esModule();
    exports.is_NDArray = is_NDArray;
    exports.ndarray = ndarray;
    const types_1 = require(8) /* ./types */;
    const platform_1 = require(27) /* ./platform */;
    const eq_1 = require(26) /* ./eq */;
    const cloneable_1 = require(31) /* ./cloneable */;
    const serialization_1 = require(32) /* ../serialization */;
    const __ndarray__ = Symbol("__ndarray__");
    function encode_NDArray(array, serializer) {
        const encoded = serializer.encode(array.dtype == "object" ? Array.from(array) : array.buffer);
        return {
            type: "ndarray",
            array: encoded,
            order: platform_1.BYTE_ORDER,
            dtype: array.dtype,
            shape: array.shape,
        };
    }
    class BoolNDArray extends Uint8Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_a] = true;
            this.dtype = "bool";
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_a = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new BoolNDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i] == 1;
        }
    }
    exports.BoolNDArray = BoolNDArray;
    BoolNDArray.__name__ = "BoolNDArray";
    class Uint8NDArray extends Uint8Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_b] = true;
            this.dtype = "uint8";
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_b = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Uint8NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Uint8NDArray = Uint8NDArray;
    Uint8NDArray.__name__ = "Uint8NDArray";
    class Int8NDArray extends Int8Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_c] = true;
            this.dtype = "int8";
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_c = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Int8NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Int8NDArray = Int8NDArray;
    Int8NDArray.__name__ = "Int8NDArray";
    class Uint16NDArray extends Uint16Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_d] = true;
            this.dtype = "uint16";
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_d = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Uint16NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Uint16NDArray = Uint16NDArray;
    Uint16NDArray.__name__ = "Uint16NDArray";
    class Int16NDArray extends Int16Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_e] = true;
            this.dtype = "int16";
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_e = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Int16NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Int16NDArray = Int16NDArray;
    Int16NDArray.__name__ = "Int16NDArray";
    class Uint32NDArray extends Uint32Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_f] = true;
            this.dtype = "uint32";
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_f = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Uint32NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Uint32NDArray = Uint32NDArray;
    Uint32NDArray.__name__ = "Uint32NDArray";
    class Int32NDArray extends Int32Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_g] = true;
            this.dtype = "int32";
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_g = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Int32NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Int32NDArray = Int32NDArray;
    Int32NDArray.__name__ = "Int32NDArray";
    class Float32NDArray extends Float32Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_h] = true;
            this.dtype = "float32";
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_h = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Float32NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Float32NDArray = Float32NDArray;
    Float32NDArray.__name__ = "Float32NDArray";
    class Float64NDArray extends Float64Array {
        constructor(init, shape) {
            super(init); // XXX: typescript bug?
            this[_j] = true;
            this.dtype = "float64";
            this.shape = shape ?? (is_NDArray(init) ? init.shape : [this.length]);
            this.dimension = this.shape.length;
        }
        [(_j = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new Float64NDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.Float64NDArray = Float64NDArray;
    Float64NDArray.__name__ = "Float64NDArray";
    class ObjectNDArray extends Array {
        get shape() {
            return this._shape ?? [this.length];
        }
        get dimension() {
            return this.shape.length;
        }
        constructor(init_, shape) {
            const init = init_ instanceof ArrayBuffer ? new Float64Array(init_) : init_;
            const size = (0, types_1.isNumber)(init) ? init : init.length;
            super(size);
            this[_k] = true;
            this.dtype = "object";
            if (!(0, types_1.isNumber)(init)) {
                for (let i = 0; i < init.length; i++) {
                    this[i] = init[i];
                }
            }
            this._shape = shape ?? (is_NDArray(init) ? init.shape : undefined);
        }
        [(_k = __ndarray__, eq_1.equals)](that, cmp) {
            return cmp.eq(this.shape, that.shape) && cmp.arrays(this, that);
        }
        [cloneable_1.clone](cloner) {
            return new ObjectNDArray(this, cloner.clone(this.shape));
        }
        [serialization_1.serialize](serializer) {
            return encode_NDArray(this, serializer);
        }
        get(i) {
            return this[i];
        }
    }
    exports.ObjectNDArray = ObjectNDArray;
    ObjectNDArray.__name__ = "ObjectNDArray";
    function is_NDArray(v) {
        return (0, types_1.isObject)(v) && __ndarray__ in v;
    }
    function ndarray(init, { dtype, shape } = {}) {
        if (dtype == null) {
            dtype = (() => {
                switch (true) {
                    case init instanceof Uint8Array: return "uint8";
                    case init instanceof Int8Array: return "int8";
                    case init instanceof Uint16Array: return "uint16";
                    case init instanceof Int16Array: return "int16";
                    case init instanceof Uint32Array: return "uint32";
                    case init instanceof Int32Array: return "int32";
                    case init instanceof Float32Array: return "float32";
                    case init instanceof ArrayBuffer:
                    case init instanceof Float64Array: return "float64";
                    default: return "object";
                }
            })();
        }
        switch (dtype) {
            case "bool": return new BoolNDArray(init, shape);
            case "uint8": return new Uint8NDArray(init, shape);
            case "int8": return new Int8NDArray(init, shape);
            case "uint16": return new Uint16NDArray(init, shape);
            case "int16": return new Int16NDArray(init, shape);
            case "uint32": return new Uint32NDArray(init, shape);
            case "int32": return new Int32NDArray(init, shape);
            case "float32": return new Float32NDArray(init, shape);
            case "float64": return new Float64NDArray(init, shape);
            case "object": return new ObjectNDArray(init, shape);
        }
    }
},
/* core/util/cloneable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_Cloneable = is_Cloneable;
    const object_1 = require(9) /* ./object */;
    const types_1 = require(8) /* ./types */;
    exports.clone = Symbol("clone");
    function is_Cloneable(obj) {
        return (0, types_1.isObject)(obj) && exports.clone in obj;
    }
    class CloningError extends Error {
    }
    exports.CloningError = CloningError;
    CloningError.__name__ = "CloningError";
    class Cloner {
        constructor() { }
        clone(obj) {
            if (is_Cloneable(obj)) {
                return obj[exports.clone](this);
            }
            else if ((0, types_1.isPrimitive)(obj)) {
                return obj;
            }
            else if ((0, types_1.isArray)(obj)) {
                const n = obj.length;
                const result = new Array(n);
                for (let i = 0; i < n; i++) {
                    const value = obj[i];
                    result[i] = this.clone(value);
                }
                return result;
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                const result = {};
                for (const [key, value] of (0, object_1.entries)(obj)) {
                    result[key] = this.clone(value);
                }
                return result;
            }
            else if (obj instanceof Map) {
                return new Map([...obj].map(([k, v]) => [this.clone(k), this.clone(v)]));
            }
            else if (obj instanceof Set) {
                return new Set([...obj].map((v) => this.clone(v)));
            }
            else {
                throw new CloningError(`${Object.prototype.toString.call(obj)} is not cloneable`);
            }
        }
    }
    exports.Cloner = Cloner;
    Cloner.__name__ = "Cloner";
},
/* core/serialization/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    var serializer_1 = require(33) /* ./serializer */;
    __esExport("Serializer", serializer_1.Serializer);
    __esExport("SerializationError", serializer_1.SerializationError);
    __esExport("serialize", serializer_1.serialize);
    var buffer_1 = require(35) /* ./buffer */;
    __esExport("Buffer", buffer_1.Buffer);
    __esExport("Base64Buffer", buffer_1.Base64Buffer);
    tslib_1.__exportStar(require(37) /* ./reps */, exports);
},
/* core/serialization/serializer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const assert_1 = require(12) /* ../util/assert */;
    const object_1 = require(9) /* ../util/object */;
    const types_1 = require(8) /* ../util/types */;
    const iterator_1 = require(34) /* ../util/iterator */;
    const platform_1 = require(27) /* ../util/platform */;
    const buffer_1 = require(35) /* ./buffer */;
    // TypedArray?
    exports.serialize = Symbol("serialize");
    function is_Serializable(obj) {
        return (0, types_1.isObject)(obj) && exports.serialize in obj;
    }
    class SerializationError extends Error {
    }
    exports.SerializationError = SerializationError;
    SerializationError.__name__ = "SerializationError";
    class Serialized {
        constructor(value) {
            this.value = value;
        }
        to_json() {
            return JSON.stringify(this.value);
        }
    }
    Serialized.__name__ = "Serialized";
    class Serializer {
        constructor(options) {
            this._circular = new WeakSet();
            this.binary = options?.binary ?? false;
            this.include_defaults = options?.include_defaults ?? false;
            const references = options?.references;
            this._references = references != null ? new Map(references) : new Map();
        }
        get_ref(obj) {
            return this._references.get(obj);
        }
        add_ref(obj, ref) {
            (0, assert_1.assert)(!this._references.has(obj));
            this._references.set(obj, ref);
        }
        to_serializable(obj) {
            return new Serialized(this.encode(obj));
        }
        encode(obj) {
            const ref = this.get_ref(obj);
            if (ref != null) {
                return ref;
            }
            if (!(0, types_1.isObject)(obj)) {
                return this._encode(obj);
            }
            else {
                if (this._circular.has(obj)) {
                    this.error("circular reference");
                }
                this._circular.add(obj);
                try {
                    return this._encode(obj);
                }
                finally {
                    this._circular.delete(obj);
                }
            }
        }
        _encode(obj) {
            if (is_Serializable(obj)) {
                return obj[exports.serialize](this);
            }
            else if ((0, types_1.isArray)(obj)) {
                const n = obj.length;
                const result = new Array(n);
                for (let i = 0; i < n; i++) {
                    const value = obj[i];
                    result[i] = this.encode(value);
                }
                return result;
            }
            else if ((0, types_1.isTypedArray)(obj)) {
                return this._encode_typed_array(obj);
            }
            else if (obj instanceof ArrayBuffer) {
                const data = this.binary ? new buffer_1.Buffer(obj) : new buffer_1.Base64Buffer(obj);
                return { type: "bytes", data };
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                const items = (0, object_1.entries)(obj);
                if (items.length == 0) {
                    return { type: "map" };
                }
                else {
                    return { type: "map", entries: [...(0, iterator_1.map)(items, ([key, val]) => [this.encode(key), this.encode(val)])] };
                }
            }
            else if (obj === null || (0, types_1.isBoolean)(obj) || (0, types_1.isString)(obj)) {
                return obj;
            }
            else if ((0, types_1.isNumber)(obj)) {
                if (isNaN(obj)) {
                    return { type: "number", value: "nan" };
                }
                else if (!isFinite(obj)) {
                    return { type: "number", value: `${obj < 0 ? "-" : "+"}inf` };
                }
                else {
                    return obj;
                }
            }
            else if (obj instanceof Date) {
                const iso = obj.toISOString();
                return { type: "date", iso };
            }
            else if (obj instanceof Set) {
                if (obj.size == 0) {
                    return { type: "set" };
                }
                else {
                    return { type: "set", entries: [...(0, iterator_1.map)(obj.values(), (val) => this.encode(val))] };
                }
            }
            else if (obj instanceof Map) {
                if (obj.size == 0) {
                    return { type: "map" };
                }
                else {
                    return { type: "map", entries: [...(0, iterator_1.map)(obj.entries(), ([key, val]) => [this.encode(key), this.encode(val)])] };
                }
            }
            else if ((0, types_1.isSymbol)(obj) && obj.description != null) {
                return { type: "symbol", name: obj.description };
            }
            else {
                throw new SerializationError(`${Object.prototype.toString.call(obj)} is not serializable`);
            }
        }
        encode_struct(struct) {
            const result = {};
            for (const [key, val] of (0, object_1.entries)(struct)) {
                if (val !== undefined) {
                    result[key] = this.encode(val);
                }
            }
            return result;
        }
        error(message) {
            throw new SerializationError(message);
        }
        _encode_typed_array(obj) {
            const array = this.encode(obj.buffer);
            const dtype = (() => {
                switch (obj.constructor) {
                    case Uint8Array: return "uint8";
                    case Int8Array: return "int8";
                    case Uint16Array: return "uint16";
                    case Int16Array: return "int16";
                    case Uint32Array: return "uint32";
                    case Int32Array: return "int32";
                    // case BigUint64Array: return "uint64"
                    // case BigInt64Array: return "int64"
                    case Float32Array: return "float32";
                    case Float64Array: return "float64";
                    default:
                        this.error(`can't serialize typed array of type '${obj[Symbol.toStringTag]}'`);
                }
            })();
            return {
                type: "typed_array",
                array,
                order: platform_1.BYTE_ORDER,
                dtype,
            };
        }
    }
    exports.Serializer = Serializer;
    Serializer.__name__ = "Serializer";
},
/* core/util/iterator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.range = range;
    exports.reverse = reverse;
    exports.enumerate = enumerate;
    exports.take = take;
    exports.skip = skip;
    exports.tail = tail;
    exports.join = join;
    exports.zip = zip;
    exports.interleave = interleave;
    exports.map = map;
    exports.flat_map = flat_map;
    exports.filter = filter;
    exports.every = every;
    exports.some = some;
    exports.combinations = combinations;
    exports.subsets = subsets;
    const array_1 = require(10) /* ./array */;
    const assert_1 = require(12) /* ./assert */;
    var arrayable_1 = require(13) /* ./arrayable */;
    __esExport("min", arrayable_1.min);
    __esExport("max", arrayable_1.max);
    function* range(start, stop, step = 1) {
        (0, assert_1.assert)(step > 0);
        const { abs, ceil, max } = Math;
        if (stop == null) {
            stop = start;
            start = 0;
        }
        const delta = start <= stop ? step : -step;
        const length = max(ceil(abs(stop - start) / step), 0);
        for (let i = 0; i < length; i++, start += delta) {
            yield start;
        }
    }
    function* reverse(array) {
        const n = array.length;
        for (let i = 0; i < n; i++) {
            yield array[n - i - 1];
        }
    }
    function* enumerate(seq) {
        let i = 0;
        for (const item of seq) {
            yield [item, i++];
        }
    }
    function* take(seq, n) {
        (0, assert_1.assert)(n >= 0);
        let i = 0;
        for (const item of seq) {
            if (i++ < n) {
                yield item;
            }
            else {
                break;
            }
        }
    }
    function* skip(seq, n) {
        (0, assert_1.assert)(n >= 0);
        for (const value of seq) {
            if (n == 0) {
                yield value;
            }
            else {
                n -= 1;
            }
        }
    }
    function* tail(seq) {
        yield* skip(seq, 1);
    }
    function* join(seq, separator) {
        let first = true;
        for (const entry of seq) {
            if (first) {
                first = false;
            }
            else if (separator != null) {
                yield separator();
            }
            yield* entry;
        }
    }
    function* zip(iterable0, iterable1) {
        const it0 = iterable0[Symbol.iterator]();
        const it1 = iterable1[Symbol.iterator]();
        do {
            const r0 = it0.next();
            const r1 = it1.next();
            if (r0.done === true || r1.done === true) {
                break;
            }
            else {
                yield [r0.value, r1.value];
            }
        } while (true);
    }
    function* interleave(seq, separator) {
        let first = true;
        for (const entry of seq) {
            if (first) {
                first = false;
            }
            else {
                yield separator();
            }
            yield entry;
        }
    }
    function* map(iterable, fn) {
        let i = 0;
        for (const item of iterable) {
            yield fn(item, i++);
        }
    }
    function* flat_map(iterable, fn) {
        let i = 0;
        for (const item of iterable) {
            yield* fn(item, i++);
        }
    }
    function* filter(iterable, fn) {
        let i = 0;
        for (const item of iterable) {
            if (fn(item, i++)) {
                yield item;
            }
        }
    }
    function every(iterable, predicate) {
        for (const item of iterable) {
            if (!predicate(item)) {
                return false;
            }
        }
        return true;
    }
    function some(iterable, predicate) {
        for (const item of iterable) {
            if (predicate(item)) {
                return true;
            }
        }
        return false;
    }
    // https://docs.python.org/3.8/library/itertools.html#itertools.combinations
    function* combinations(seq, r) {
        const n = seq.length;
        if (r > n) {
            return;
        }
        const indices = (0, array_1.range)(r);
        yield indices.map((i) => seq[i]);
        while (true) {
            let k;
            for (const i of reverse((0, array_1.range)(r))) {
                if (indices[i] != i + n - r) {
                    k = i;
                    break;
                }
            }
            if (k == null) {
                return;
            }
            indices[k] += 1;
            for (const j of (0, array_1.range)(k + 1, r)) {
                indices[j] = indices[j - 1] + 1;
            }
            yield indices.map((i) => seq[i]);
        }
    }
    function* subsets(seq) {
        for (const k of (0, array_1.range)(seq.length + 1)) {
            yield* combinations(seq, k);
        }
    }
},
/* core/serialization/buffer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const buffer_1 = require(36) /* ../util/buffer */;
    const eq_1 = require(26) /* ../util/eq */;
    class Buffer {
        constructor(buffer) {
            this.buffer = buffer;
        }
        to_base64() {
            return (0, buffer_1.buffer_to_base64)(this.buffer);
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.buffer, that.buffer);
        }
    }
    exports.Buffer = Buffer;
    Buffer.__name__ = "Buffer";
    class Base64Buffer extends Buffer {
        toJSON() {
            return this.to_base64();
        }
    }
    exports.Base64Buffer = Base64Buffer;
    Base64Buffer.__name__ = "Base64Buffer";
},
/* core/util/buffer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.buffer_to_base64 = buffer_to_base64;
    exports.base64_to_buffer = base64_to_buffer;
    exports.swap = swap;
    function buffer_to_base64(buffer) {
        const bytes = new Uint8Array(buffer);
        const chars = Array.from(bytes).map((b) => String.fromCharCode(b));
        return btoa(chars.join(""));
    }
    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;
    }
    // NOTE: swap{16,32,64} assume byteOffset == 0
    function swap16(buffer) {
        const x = new Uint8Array(buffer);
        for (let i = 0, end = x.length; i < end; i += 2) {
            const t = x[i];
            x[i] = x[i + 1];
            x[i + 1] = t;
        }
    }
    function swap32(buffer) {
        const x = new Uint8Array(buffer);
        for (let i = 0, end = x.length; i < end; i += 4) {
            let t = x[i];
            x[i] = x[i + 3];
            x[i + 3] = t;
            t = x[i + 1];
            x[i + 1] = x[i + 2];
            x[i + 2] = t;
        }
    }
    function swap64(buffer) {
        const x = new Uint8Array(buffer);
        for (let i = 0, end = x.length; i < end; i += 8) {
            let t = x[i];
            x[i] = x[i + 7];
            x[i + 7] = t;
            t = x[i + 1];
            x[i + 1] = x[i + 6];
            x[i + 6] = t;
            t = x[i + 2];
            x[i + 2] = x[i + 5];
            x[i + 5] = t;
            t = x[i + 3];
            x[i + 3] = x[i + 4];
            x[i + 4] = t;
        }
    }
    function swap(buffer, dtype) {
        switch (dtype) {
            case "uint16":
            case "int16":
                swap16(buffer);
                break;
            case "uint32":
            case "int32":
            case "float32":
                swap32(buffer);
                break;
            case "float64":
                swap64(buffer);
                break;
            case "object":
            case "uint8":
            case "int8":
            case "bool":
                break;
        }
    }
},
/* core/serialization/reps.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
},
/* core/diagnostics.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class Diagnostics {
        constructor() {
            this.listeners = new Set();
        }
        connect(listener) {
            this.listeners.add(listener);
        }
        disconnect(listener) {
            this.listeners.delete(listener);
        }
        report(obj) {
            for (const listener of this.listeners) {
                listener(obj);
            }
        }
    }
    exports.Diagnostics = Diagnostics;
    Diagnostics.__name__ = "Diagnostics";
    exports.diagnostics = new Diagnostics();
},
/* core/uniforms.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.min = min;
    exports.max = max;
    const tslib_1 = require(1) /* tslib */;
    const eq_1 = require(26) /* ./util/eq */;
    const arrayable = tslib_1.__importStar(require(13) /* ./util/arrayable */);
    class Uniform {
        is_Scalar() {
            return this.is_scalar;
        }
        is_Vector() {
            return !this.is_scalar;
        }
    }
    exports.Uniform = Uniform;
    Uniform.__name__ = "Uniform";
    class UniformScalar extends Uniform {
        constructor(value, length) {
            super();
            this.is_scalar = true;
            this.value = value;
            this.length = length;
        }
        get(_i) {
            return this.value;
        }
        *[Symbol.iterator]() {
            const { length, value } = this;
            for (let i = 0; i < length; i++) {
                yield value;
            }
        }
        select(indices) {
            return new UniformScalar(this.value, indices.count);
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.length, that.length) && cmp.eq(this.value, that.value);
        }
        map(fn) {
            return new UniformScalar(fn(this.value), this.length);
        }
    }
    exports.UniformScalar = UniformScalar;
    UniformScalar.__name__ = "UniformScalar";
    class UniformVector extends Uniform {
        constructor(array) {
            super();
            this.is_scalar = false;
            this.array = array;
            this.length = this.array.length;
        }
        get(i) {
            return this.array[i];
        }
        *[Symbol.iterator]() {
            yield* this.array;
        }
        select(indices) {
            const array = indices.select(this.array);
            return new this.constructor(array);
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.length, that.length) && cmp.eq(this.array, that.array);
        }
        map(fn) {
            return new UniformVector(arrayable.map(this.array, fn));
        }
    }
    exports.UniformVector = UniformVector;
    UniformVector.__name__ = "UniformVector";
    class ColorUniformVector extends UniformVector {
        constructor(array) {
            super(array);
            this.array = array;
            this._view = new DataView(array.buffer);
        }
        get(i) {
            return this._view.getUint32(4 * i);
        }
        *[Symbol.iterator]() {
            const n = this.length;
            for (let i = 0; i < n; i++) {
                yield this.get(i);
            }
        }
    }
    exports.ColorUniformVector = ColorUniformVector;
    ColorUniformVector.__name__ = "ColorUniformVector";
    function min(u) {
        return u.is_Scalar() ? u.value : arrayable.min(u.array);
    }
    function max(u) {
        return u.is_Scalar() ? u.value : arrayable.max(u.array);
    }
},
/* core/util/string.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.uuid4 = uuid4;
    exports.unique_id = unique_id;
    exports.escape = escape;
    exports.unescape = unescape;
    exports.use_strict = use_strict;
    exports.to_fixed = to_fixed;
    exports.insert_text_on_position = insert_text_on_position;
    const settings_1 = require(29) /* ../settings */;
    function uuid4() {
        // from ipython project
        // http://www.ietf.org/rfc/rfc4122.txt
        const s = new Array(32);
        const hex_digits = "0123456789ABCDEF";
        for (let i = 0; i < 32; i++) {
            s[i] = hex_digits[Math.floor(Math.random() * 0x10)];
        }
        s[12] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[16] = hex_digits[(s[16].charCodeAt(0) & 0x3) | 0x8]; // bits 6-7 of the clock_seq_hi_and_reserved to 01
        return s.join("");
    }
    let counter = 1000;
    function unique_id(prefix) {
        const id = settings_1.settings.dev ? `j${counter++}` : uuid4();
        if (prefix != null) {
            return `${prefix}-${id}`;
        }
        else {
            return id;
        }
    }
    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;
            }
        });
    }
    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;
            }
        });
    }
    function use_strict(code) {
        return `'use strict';\n${code}`;
    }
    function to_fixed(val, precision) {
        return val.toFixed(precision).replace(/(\.[0-9]*?)0+$/, "$1").replace(/\.$/, "");
    }
    function insert_text_on_position(destination, position, text_to_be_inserted) {
        const result_text = [];
        result_text.push(destination.slice(0, position));
        result_text.push(text_to_be_inserted);
        result_text.push(destination.slice(position));
        return result_text.join("");
    }
},
/* document/events.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const eq_1 = require(26) /* ../core/util/eq */;
    const serialization_1 = require(32) /* ../core/serialization */;
    class DocumentEvent {
        constructor(document) {
            /**
             * Indicates whether this event should be emitted internally within bokehjs,
             * or whether it should also be synchronized with the server, if any session
             * is listening for such events.
             */
            this.sync = true;
            this.document = document;
        }
        get [Symbol.toStringTag]() {
            return this.constructor.__name__;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.document, that.document);
        }
    }
    exports.DocumentEvent = DocumentEvent;
    DocumentEvent.__name__ = "DocumentEvent";
    class DocumentEventBatch extends DocumentEvent {
        constructor(document, events) {
            super(document);
            this.events = events;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.events, that.events);
        }
    }
    exports.DocumentEventBatch = DocumentEventBatch;
    DocumentEventBatch.__name__ = "DocumentEventBatch";
    class DocumentChangedEvent extends DocumentEvent {
    }
    exports.DocumentChangedEvent = DocumentChangedEvent;
    DocumentChangedEvent.__name__ = "DocumentChangedEvent";
    class MessageSentEvent extends DocumentChangedEvent {
        constructor(document, msg_type, msg_data) {
            super(document);
            this.kind = "MessageSent";
            this.msg_type = msg_type;
            this.msg_data = msg_data;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.msg_type, that.msg_type) &&
                cmp.eq(this.msg_data, that.msg_data);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                msg_type: this.msg_type,
                msg_data: serializer.encode(this.msg_data),
            };
        }
    }
    exports.MessageSentEvent = MessageSentEvent;
    MessageSentEvent.__name__ = "MessageSentEvent";
    class ModelChangedEvent extends DocumentChangedEvent {
        constructor(document, model, attr, value) {
            super(document);
            this.kind = "ModelChanged";
            this.model = model;
            this.attr = attr;
            this.value = value;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model) &&
                cmp.eq(this.attr, that.attr) &&
                cmp.eq(this.value, that.value);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                model: this.model.ref(),
                attr: this.attr,
                new: serializer.encode(this.value),
            };
        }
    }
    exports.ModelChangedEvent = ModelChangedEvent;
    ModelChangedEvent.__name__ = "ModelChangedEvent";
    class ColumnDataChangedEvent extends DocumentChangedEvent {
        constructor(document, model, attr, data, cols) {
            super(document);
            this.kind = "ColumnDataChanged";
            this.model = model;
            this.attr = attr;
            this.data = data;
            this.cols = cols;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model) &&
                cmp.eq(this.attr, that.attr) &&
                cmp.eq(this.data, that.data) &&
                cmp.eq(this.cols, that.cols);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                model: this.model.ref(),
                attr: this.attr,
                data: serializer.encode(this.data),
                cols: this.cols,
            };
        }
    }
    exports.ColumnDataChangedEvent = ColumnDataChangedEvent;
    ColumnDataChangedEvent.__name__ = "ColumnDataChangedEvent";
    class ColumnsStreamedEvent extends DocumentChangedEvent {
        constructor(document, model, attr, data, rollover) {
            super(document);
            this.kind = "ColumnsStreamed";
            this.model = model;
            this.attr = attr;
            this.data = data;
            this.rollover = rollover;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model) &&
                cmp.eq(this.attr, that.attr) &&
                cmp.eq(this.data, that.data) &&
                cmp.eq(this.rollover, that.rollover);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                model: this.model.ref(),
                attr: this.attr,
                data: serializer.encode(this.data),
                rollover: this.rollover,
            };
        }
    }
    exports.ColumnsStreamedEvent = ColumnsStreamedEvent;
    ColumnsStreamedEvent.__name__ = "ColumnsStreamedEvent";
    class ColumnsPatchedEvent extends DocumentChangedEvent {
        constructor(document, model, attr, patches) {
            super(document);
            this.kind = "ColumnsPatched";
            this.model = model;
            this.attr = attr;
            this.patches = patches;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model) &&
                cmp.eq(this.attr, that.attr) &&
                cmp.eq(this.patches, that.patches);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                attr: this.attr,
                model: this.model.ref(),
                patches: serializer.encode(this.patches),
            };
        }
    }
    exports.ColumnsPatchedEvent = ColumnsPatchedEvent;
    ColumnsPatchedEvent.__name__ = "ColumnsPatchedEvent";
    class TitleChangedEvent extends DocumentChangedEvent {
        constructor(document, title) {
            super(document);
            this.kind = "TitleChanged";
            this.title = title;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.title, that.title);
        }
        [serialization_1.serialize](_serializer) {
            return {
                kind: this.kind,
                title: this.title,
            };
        }
    }
    exports.TitleChangedEvent = TitleChangedEvent;
    TitleChangedEvent.__name__ = "TitleChangedEvent";
    class RootAddedEvent extends DocumentChangedEvent {
        constructor(document, model) {
            super(document);
            this.kind = "RootAdded";
            this.model = model;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model);
        }
        [serialization_1.serialize](serializer) {
            return {
                kind: this.kind,
                model: serializer.encode(this.model),
            };
        }
    }
    exports.RootAddedEvent = RootAddedEvent;
    RootAddedEvent.__name__ = "RootAddedEvent";
    class RootRemovedEvent extends DocumentChangedEvent {
        constructor(document, model) {
            super(document);
            this.kind = "RootRemoved";
            this.model = model;
        }
        [eq_1.equals](that, cmp) {
            return super[eq_1.equals](that, cmp) &&
                cmp.eq(this.model, that.model);
        }
        [serialization_1.serialize](_serializer) {
            return {
                kind: this.kind,
                model: this.model.ref(),
            };
        }
    }
    exports.RootRemovedEvent = RootRemovedEvent;
    RootRemovedEvent.__name__ = "RootRemovedEvent";
},
/* core/util/pretty.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.to_string = to_string;
    const types_1 = require(8) /* ./types */;
    const object_1 = require(9) /* ./object */;
    exports.pretty = Symbol("pretty");
    function is_Printable(obj) {
        return (0, types_1.isObject)(obj) && exports.pretty in obj;
    }
    class Printer {
        constructor(options) {
            this.visited = new Set();
            this.precision = options?.precision;
        }
        to_string(obj) {
            if ((0, types_1.isObject)(obj)) {
                if (this.visited.has(obj)) {
                    return "<circular>";
                }
                else {
                    this.visited.add(obj);
                }
            }
            if (is_Printable(obj)) {
                return obj[exports.pretty](this);
            }
            else if ((0, types_1.isBoolean)(obj)) {
                return this.boolean(obj);
            }
            else if ((0, types_1.isNumber)(obj)) {
                return this.number(obj);
            }
            else if ((0, types_1.isString)(obj)) {
                return this.string(obj);
            }
            else if ((0, types_1.isArray)(obj)) {
                return this.array(obj);
            }
            else if ((0, types_1.isIterable)(obj)) {
                return this.iterable(obj);
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                return this.object(obj);
            }
            else if ((0, types_1.isSymbol)(obj)) {
                return this.symbol(obj);
            }
            else if (obj instanceof ArrayBuffer) {
                return this.array_buffer(obj);
            }
            else {
                return `${obj}`;
            }
        }
        token(val) {
            return val;
        }
        boolean(val) {
            return `${val}`;
        }
        number(val) {
            if (this.precision != null) {
                return val.toFixed(this.precision);
            }
            else {
                return `${val}`;
            }
        }
        string(val) {
            const sq = val.includes("'");
            const dq = val.includes('"');
            if (sq && dq) {
                return `\`${val.replace(/`/g, "\\`")}\``;
            }
            else if (dq) {
                return `'${val}'`;
            }
            else {
                return `"${val}"`;
            }
        }
        symbol(val) {
            return val.toString();
        }
        array(obj) {
            const T = this.token;
            const items = [];
            for (const entry of obj) {
                items.push(this.to_string(entry));
            }
            return `${T("[")}${items.join(`${T(",")} `)}${T("]")}`;
        }
        iterable(obj) {
            const T = this.token;
            const tag = Object(obj)[Symbol.toStringTag] ?? "Object";
            const items = this.array(obj);
            return `${tag}${T("(")}${items}${T(")")}`;
        }
        object(obj) {
            const T = this.token;
            const items = [];
            for (const [key, val] of (0, object_1.entries)(obj)) {
                items.push(`${key}${T(":")} ${this.to_string(val)}`);
            }
            return `${T("{")}${items.join(`${T(",")} `)}${T("}")}`;
        }
        array_buffer(obj) {
            return `ArrayBuffer(#${obj.byteLength})`;
        }
    }
    exports.Printer = Printer;
    Printer.__name__ = "Printer";
    function to_string(obj, options) {
        const printer = new Printer(options);
        return printer.to_string(obj);
    }
},
/* core/patching.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.stream_to_column = stream_to_column;
    exports.slice = slice;
    exports.patch_to_column = patch_to_column;
    exports.stream_to_columns = stream_to_columns;
    exports.patch_to_columns = patch_to_columns;
    const tslib_1 = require(1) /* tslib */;
    const types_1 = require(8) /* ./util/types */;
    const object_1 = require(9) /* ./util/object */;
    const set_1 = require(44) /* ./util/set */;
    const typed_array = tslib_1.__importStar(require(45) /* ./util/typed_array */);
    // exported for testing
    function stream_to_column(col, new_col, rollover) {
        if ((0, types_1.isArray)(col) && (0, types_1.isArray)(new_col)) {
            const result = col.concat(new_col);
            if (rollover != null && result.length > rollover) {
                return result.slice(-rollover);
            }
            else {
                return result;
            }
        }
        const total_len = col.length + new_col.length;
        // handle rollover case for typed arrays
        if (rollover != null && total_len > rollover) {
            const start = total_len - rollover;
            const end = col.length;
            // resize col if it is shorter than the rollover length
            const result = (() => {
                if (col.length < rollover) {
                    const ctor = (() => {
                        if ((0, types_1.isTypedArray)(col)) {
                            return col.constructor;
                        }
                        else if ((0, types_1.isTypedArray)(new_col)) {
                            return new_col.constructor;
                        }
                        else {
                            throw new Error("unsupported array types");
                        }
                    })();
                    const result = new ctor(rollover);
                    result.set(col, 0);
                    return result;
                }
                else {
                    return col;
                }
            })();
            // shift values in original col to accommodate new_col
            for (let i = start, endi = end; i < endi; i++) {
                result[i - start] = result[i];
            }
            // update end values in col with new_col
            for (let i = 0, endi = new_col.length; i < endi; i++) {
                result[i + (end - start)] = new_col[i];
            }
            return result;
        }
        else {
            const col_ = (() => {
                if ((0, types_1.isTypedArray)(col)) {
                    return col;
                }
                else if ((0, types_1.isTypedArray)(new_col)) {
                    return new new_col.constructor(col);
                }
                else {
                    throw new Error("unsupported array types");
                }
            })();
            return typed_array.concat(col_, new_col);
        }
    }
    // exported for testing
    function slice(ind, length) {
        let start, step, stop;
        if ((0, types_1.isNumber)(ind)) {
            start = ind;
            stop = ind + 1;
            step = 1;
        }
        else {
            start = ind.start != null ? ind.start : 0;
            stop = ind.stop != null ? ind.stop : length;
            step = ind.step != null ? ind.step : 1;
        }
        return [start, stop, step];
    }
    // exported for testing
    function patch_to_column(col, patch) {
        const patched = new Set();
        let patched_range = false;
        for (const [ind, val] of patch) {
            // make the single index case look like the length-3 multi-index case
            let shape;
            let item;
            let index;
            let value;
            if ((0, types_1.isArray)(ind)) {
                const [i] = ind;
                patched.add(i);
                shape = col[i].shape;
                item = col[i];
                value = val;
                // this is basically like NumPy's "newaxis", inserting an empty dimension
                // makes length 2 and 3 multi-index cases uniform, so that the same code
                // can handle both
                if (ind.length === 2) {
                    shape = [1, shape[0]];
                    index = [ind[0], 0, ind[1]];
                }
                else {
                    index = ind;
                }
            }
            else {
                if ((0, types_1.isNumber)(ind)) {
                    value = [val];
                    patched.add(ind);
                }
                else {
                    value = val;
                    patched_range = true;
                }
                index = [0, 0, ind];
                shape = [1, col.length];
                item = col;
            }
            // now this one nested loop handles all cases
            let flat_index = 0;
            const [istart, istop, istep] = slice(index[1], shape[0]);
            const [jstart, jstop, jstep] = slice(index[2], shape[1]);
            for (let i = istart; i < istop; i += istep) {
                for (let j = jstart; j < jstop; j += jstep) {
                    if (patched_range) {
                        patched.add(j);
                    }
                    item[i * shape[1] + j] = value[flat_index];
                    flat_index++;
                }
            }
        }
        return patched;
    }
    function stream_to_columns(old_data, new_data, rollover) {
        const data = (0, object_1.dict)(old_data);
        for (const [name, new_column] of (0, object_1.dict)(new_data)) {
            const old_column = data.get(name) ?? [];
            data.set(name, stream_to_column(old_column, new_column, rollover));
        }
    }
    function patch_to_columns(old_data, patches) {
        const data = (0, object_1.dict)(old_data);
        let patched = new Set();
        for (const [name, patch] of (0, object_1.dict)(patches)) {
            const old_column = data.get(name) ?? [];
            patched = (0, set_1.union)(patched, patch_to_column(old_column, patch)); // XXX: any
        }
        return patched;
    }
},
/* core/util/set.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.union = union;
    exports.intersection = intersection;
    exports.difference = difference;
    function union(...sets) {
        const result = new Set();
        for (const set of sets) {
            for (const item of set) {
                result.add(item);
            }
        }
        return result;
    }
    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;
    }
    function difference(set, ...sets) {
        const result = new Set(set);
        for (const item of union(...sets)) {
            result.delete(item);
        }
        return result;
    }
},
/* core/util/typed_array.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.concat = concat;
    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;
    }
},
/* core/resolvers.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class ModelResolver {
        constructor(parent, models = []) {
            this._known_models = new Map();
            this.parent = parent;
            for (const model of models) {
                this.register(model);
            }
        }
        get(name) {
            return this._known_models.get(name) ?? this.parent?.get(name) ?? null;
        }
        register(model, force = false) {
            const name = model.__qualified__;
            if (force || this.get(name) == null) {
                this._known_models.set(name, model);
            }
            else {
                console.warn(`Model '${name}' was already registered with this resolver`);
            }
        }
        get names() {
            return [...this._known_models.keys()].sort();
        }
    }
    exports.ModelResolver = ModelResolver;
    ModelResolver.__name__ = "ModelResolver";
},
/* core/serialization/deserializer.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const logging_1 = require(19) /* ../logging */;
    const refs_1 = require(17) /* ../util/refs */;
    const ndarray_1 = require(30) /* ../util/ndarray */;
    const object_1 = require(9) /* ../util/object */;
    const array_1 = require(10) /* ../util/array */;
    const platform_1 = require(27) /* ../util/platform */;
    const buffer_1 = require(36) /* ../util/buffer */;
    const types_1 = require(8) /* ../util/types */;
    const slice_1 = require(48) /* ../util/slice */;
    const _decoders = new Map();
    class DeserializationError extends Error {
    }
    exports.DeserializationError = DeserializationError;
    DeserializationError.__name__ = "DeserializationError";
    class Deserializer {
        static register(type, decoder) {
            if (!_decoders.has(type)) {
                _decoders.set(type, decoder);
            }
            else {
                throw new Error(`'${type}' already registered for decoding`);
            }
        }
        constructor(resolver, references = new Map(), finalize) {
            this._decoding = false;
            this._buffers = new Map();
            this._finalizable = new Set();
            this.resolver = resolver;
            this.references = references;
            this.finalize = finalize;
        }
        decode(obj /*AnyVal*/, buffers) {
            if (buffers != null) {
                for (const [id, buffer] of buffers) {
                    this._buffers.set(id, buffer);
                }
            }
            if (this._decoding) {
                return this._decode(obj);
            }
            this._decoding = true;
            let finalizable;
            const decoded = (() => {
                try {
                    return this._decode(obj);
                }
                finally {
                    finalizable = new Set(this._finalizable);
                    this._decoding = false;
                    this._buffers.clear();
                    this._finalizable.clear();
                }
            })();
            for (const instance of finalizable) {
                this.finalize?.(instance);
                instance.finalize();
                instance.assert_initialized();
            }
            // `connect_signals` has to be executed last because it may rely on properties
            // of dependencies that are initialized only in `finalize`. It's a problem
            // that appears when there are circular references, e.g. as in
            // CDS -> CustomJS (on data change) -> GlyphRenderer (in args) -> CDS.
            for (const instance of finalizable) {
                instance.connect_signals();
            }
            return decoded;
        }
        _decode(obj /*AnyVal*/) {
            if ((0, types_1.isArray)(obj)) {
                return this._decode_plain_array(obj);
            }
            else if ((0, types_1.isPlainObject)(obj)) {
                if ((0, types_1.isString)(obj.type)) {
                    const decoder = _decoders.get(obj.type);
                    if (decoder != null) {
                        return decoder(obj, this);
                    }
                    switch (obj.type) {
                        case "ref":
                            return this._decode_ref(obj);
                        case "symbol":
                            return this._decode_symbol(obj);
                        case "number":
                            return this._decode_number(obj);
                        case "array":
                            return this._decode_array(obj);
                        case "set":
                            return this._decode_set(obj);
                        case "map":
                            return this._decode_map(obj);
                        case "bytes":
                            return this._decode_bytes(obj);
                        case "slice":
                            return this._decode_slice(obj);
                        case "date":
                            return this._decode_date(obj);
                        case "value":
                            return this._decode_value(obj);
                        case "field":
                            return this._decode_field(obj);
                        case "expr":
                            return this._decode_expr(obj);
                        case "typed_array":
                            return this._decode_typed_array(obj);
                        case "ndarray":
                            return this._decode_ndarray(obj);
                        case "object": {
                            if ((0, types_1.isString)(obj.id)) {
                                return this._decode_object_ref(obj);
                            }
                            else {
                                return this._decode_object(obj);
                            }
                        }
                        default: {
                            this.error(`unable to decode an object of type '${obj.type}'`);
                        }
                    }
                }
                else if ((0, types_1.isString)(obj.id)) {
                    return this._decode_ref(obj);
                }
                else {
                    return this._decode_plain_object(obj);
                }
            }
            else {
                return obj;
            }
        }
        _decode_symbol(obj) {
            this.error(`can't resolve named symbol '${obj.name}'`); // TODO: implement symbol resolution
        }
        _decode_number(obj) {
            if ("value" in obj) {
                const { value } = obj;
                if ((0, types_1.isString)(value)) {
                    switch (value) {
                        case "nan": return NaN;
                        case "+inf": return +Infinity;
                        case "-inf": return -Infinity;
                    }
                }
                else if ((0, types_1.isNumber)(value)) {
                    return value;
                }
            }
            this.error(`invalid number representation '${obj}'`);
        }
        _decode_plain_array(obj) {
            return (0, array_1.map)(obj, (item) => this._decode(item));
        }
        _decode_plain_object(obj) {
            const decoded = {};
            for (const [key, val] of (0, object_1.entries)(obj)) {
                decoded[key] = this._decode(val);
            }
            return decoded;
        }
        _decode_array(obj) {
            const decoded = [];
            for (const entry of obj.entries ?? []) {
                decoded.push(this._decode(entry));
            }
            return decoded;
        }
        _decode_set(obj) {
            const decoded = new Set();
            for (const entry of obj.entries ?? []) {
                decoded.add(this._decode(entry));
            }
            return decoded;
        }
        _decode_map(obj) {
            const entries = (0, array_1.map)(obj.entries ?? [], ([key, val]) => [this._decode(key), this._decode(val)]);
            const is_plain = entries.every(([key, _val]) => (0, types_1.isString)(key));
            // An empty container will result in a plain object, not a Map, thus in the case of
            // kinds.Mapping property type, one needs to accommodate for this in all instances.
            // Fortunately there are few of these scattered across `src/lib/models/`. See HACK
            // in `Mapping.coerce()` in `core/util/kinds`.
            if (is_plain) {
                return Object.fromEntries(entries);
            }
            else {
                return new Map(entries);
            }
        }
        _decode_bytes(obj) {
            const { data } = obj;
            if ((0, refs_1.is_ref)(data)) {
                const buffer = this._buffers.get(data.id);
                if (buffer != null) {
                    return buffer;
                }
                else {
                    this.error(`buffer for id=${data.id} not found`);
                }
            }
            else if ((0, types_1.isString)(data)) {
                return (0, buffer_1.base64_to_buffer)(data);
            }
            else {
                return data.buffer;
            }
        }
        _decode_slice(obj) {
            const start = this._decode(obj.start);
            const stop = this._decode(obj.stop);
            const step = this._decode(obj.step);
            return new slice_1.Slice({ start, stop, step });
        }
        _decode_date(obj) {
            const iso = this._decode(obj.iso);
            return new Date(iso);
        }
        _decode_value(obj) {
            const value = this._decode(obj.value);
            const transform = obj.transform != null ? this._decode(obj.transform) : undefined;
            const units = obj.units != null ? this._decode(obj.units) : undefined;
            return { value, transform, units };
        }
        _decode_field(obj) {
            const field = this._decode(obj.field);
            const transform = obj.transform != null ? this._decode(obj.transform) : undefined;
            const units = obj.units != null ? this._decode(obj.units) : undefined;
            return { field, transform, units };
        }
        _decode_expr(obj) {
            const expr = this._decode(obj.expr);
            const transform = obj.transform != null ? this._decode(obj.transform) : undefined;
            const units = obj.units != null ? this._decode(obj.units) : undefined;
            return { expr, transform, units };
        }
        _decode_typed_array(obj) {
            const { array, order, dtype } = obj;
            const buffer = this._decode(array);
            if (order != platform_1.BYTE_ORDER) {
                (0, buffer_1.swap)(buffer, dtype);
            }
            switch (dtype) {
                case "uint8": return new Uint8Array(buffer);
                case "int8": return new Int8Array(buffer);
                case "uint16": return new Uint16Array(buffer);
                case "int16": return new Int16Array(buffer);
                case "uint32": return new Uint32Array(buffer);
                case "int32": return new Int32Array(buffer);
                // case "uint64": return new BigInt64Array(buffer)
                // case "int64":  return new BigInt64Array(buffer)
                case "float32": return new Float32Array(buffer);
                case "float64": return new Float64Array(buffer);
                default:
                    this.error(`unsupported dtype '${dtype}'`);
            }
        }
        _decode_ndarray(obj) {
            const { array, order, dtype, shape } = obj;
            const decoded = this._decode(array);
            if (decoded instanceof ArrayBuffer && order != platform_1.BYTE_ORDER) {
                (0, buffer_1.swap)(decoded, dtype);
            }
            return (0, ndarray_1.ndarray)(decoded /*XXX*/, { dtype, shape });
        }
        _decode_object(obj) {
            const { name: type, attributes } = obj;
            const cls = this._resolve_type(type);
            if (attributes != null) {
                return new cls(this._decode(attributes));
            }
            else {
                return new cls();
            }
        }
        _decode_ref(obj) {
            const instance = this.references.get(obj.id);
            if (instance != null) {
                return instance;
            }
            else {
                this.error(`reference ${obj.id} isn't known`);
            }
        }
        _decode_object_ref(obj) {
            const { id, name: type, attributes } = obj;
            const ref = this.references.get(id);
            if (ref != null) {
                if (ref.type == type) {
                    const decoded_attributes = this._decode(attributes ?? {});
                    ref.setv(decoded_attributes, { sync: false });
                    return ref;
                }
                else {
                    this.error(`type mismatch for an existing reference '${ref}', expected '${type}'`);
                }
            }
            else {
                const cls = this._resolve_type(type);
                const instance = new cls({ id });
                this.references.set(id, instance);
                const decoded_attributes = this._decode(attributes ?? {});
                instance.initialize_props(decoded_attributes);
                this._finalizable.add(instance);
                return instance;
            }
        }
        error(message) {
            throw new DeserializationError(message);
        }
        warning(message) {
            logging_1.logger.warn(message);
        }
        _resolve_type(type) {
            const cls = this.resolver.get(type);
            if (cls != null) {
                return cls;
            }
            else {
                this.error(`could not resolve type '${type}', which could be due to a widget or a custom model not being registered before first usage`);
            }
        }
    }
    exports.Deserializer = Deserializer;
    Deserializer.__name__ = "Deserializer";
},
/* core/util/slice.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const serialization_1 = require(32) /* ../serialization */;
    class Slice {
        constructor({ start, stop, step } = {}) {
            this.start = start ?? null;
            this.stop = stop ?? null;
            this.step = step ?? null;
        }
        [serialization_1.serialize](serializer) {
            return {
                type: "slice",
                start: serializer.encode(this.start),
                stop: serializer.encode(this.stop),
                step: serializer.encode(this.step),
            };
        }
    }
    exports.Slice = Slice;
    Slice.__name__ = "Slice";
},
/* core/util/version.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const eq_1 = require(26) /* ./eq */;
    const version_re = /^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:(?<type>-dev\.|-rc\.|.dev|rc)(?<revision>\d+))?(?:\+(?<build>\d+)\..+)?$/;
    (function (ReleaseType) {
        ReleaseType[ReleaseType["Dev"] = 0] = "Dev";
        ReleaseType[ReleaseType["Candidate"] = 1] = "Candidate";
        ReleaseType[ReleaseType["Release"] = 2] = "Release";
    })(exports.ReleaseType || (exports.ReleaseType = {}));
    class Version {
        constructor(major, minor, patch, type = exports.ReleaseType.Release, revision = 0, build = 0) {
            this.major = major;
            this.minor = minor;
            this.patch = patch;
            this.type = type;
            this.revision = revision;
            this.build = build;
        }
        static from(version) {
            return parse_version(version);
        }
        toString() {
            const { major, minor, patch, type, revision, build } = this;
            let version = `${major}.${minor}.${patch}`;
            switch (type) {
                case exports.ReleaseType.Dev: version += `-dev.${revision}`;
                case exports.ReleaseType.Candidate: version += `-rc.${revision}`;
                case exports.ReleaseType.Release:
            }
            if (build != 0) {
                version += `+${build}`;
            }
            return version;
        }
        [eq_1.equals](that) {
            // ignore build field, because bokehjs doesn't provide it
            const { major, minor, patch, type, revision } = this;
            return major == that.major &&
                minor == that.minor &&
                patch == that.patch &&
                type == that.type &&
                revision == that.revision;
        }
    }
    exports.Version = Version;
    Version.__name__ = "Version";
    function parse_version(version) {
        const result = version_re.exec(version);
        if (result == null || result.groups == null) {
            return null;
        }
        const { groups } = result;
        const major = Number(groups.major);
        const minor = Number(groups.minor);
        const patch = Number(groups.patch);
        const type = (() => {
            switch (groups.type) {
                case "-dev.":
                case ".dev": return exports.ReleaseType.Dev;
                case "-rc.":
                case "rc": return exports.ReleaseType.Candidate;
                default: return exports.ReleaseType.Release;
            }
        })();
        // typeof due to bad stdlib typings or enable exactOptionalPropertyTypes
        const revision = typeof groups.revision == "undefined" ? 0 : Number(groups.revision);
        const build = typeof groups.build == "undefined" ? 0 : Number(groups.build);
        return new Version(major, minor, patch, type, revision, build);
    }
},
/* core/util/callbacks.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.execute = execute;
    const types_1 = require(8) /* ./types */;
    function execute(cb, obj, ...args) {
        if ((0, types_1.isFunction)(cb)) {
            return cb(obj, ...args);
        }
        else {
            return cb.execute(obj, ...args);
        }
    }
},
/* model.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const has_props_1 = require(14) /* ./core/has_props */;
    const types_1 = require(8) /* ./core/util/types */;
    const object_1 = require(9) /* ./core/util/object */;
    const eq_1 = require(26) /* ./core/util/eq */;
    const logging_1 = require(19) /* ./core/logging */;
    const callbacks_1 = require(50) /* ./core/util/callbacks */;
    class Model extends has_props_1.HasProps {
        get is_syncable() {
            return this.syncable;
        }
        [eq_1.equals](that, cmp) {
            return (cmp.structural ? true : cmp.eq(this.id, that.id)) && super[eq_1.equals](that, cmp);
        }
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this._js_callbacks = new Map();
        }
        connect_signals() {
            super.connect_signals();
            this._update_property_callbacks();
            this.connect(this.properties.js_property_callbacks.change, () => this._update_property_callbacks());
            this.connect(this.properties.js_event_callbacks.change, () => this._update_event_callbacks());
            this.connect(this.properties.subscribed_events.change, () => this._update_event_callbacks());
        }
        /*protected*/ _process_event(event) {
            for (const callback of (0, object_1.dict)(this.js_event_callbacks).get(event.event_name) ?? []) {
                void (0, callbacks_1.execute)(callback, event);
            }
            if (this.document != null && this.subscribed_events.has(event.event_name)) {
                this.document.event_manager.send_event(event);
            }
        }
        trigger_event(event) {
            if (this.document != null) {
                event.origin = this;
                this.document.event_manager.trigger(event);
            }
        }
        _update_event_callbacks() {
            if (this.document == null) {
                logging_1.logger.warn("WARNING: Document not defined for updating event callbacks");
                return;
            }
            this.document.event_manager.subscribed_models.add(this);
        }
        _update_property_callbacks() {
            const signal_for = (event) => {
                const [evt, attr = null] = event.split(":");
                return attr != null ? this.properties[attr][evt] : this[evt];
            };
            for (const [event, callbacks] of this._js_callbacks) {
                const signal = signal_for(event);
                for (const cb of callbacks) {
                    this.disconnect(signal, cb);
                }
            }
            this._js_callbacks.clear();
            for (const [event, callbacks] of (0, object_1.dict)(this.js_property_callbacks)) {
                const wrappers = callbacks.map((cb) => () => (0, callbacks_1.execute)(cb, this));
                this._js_callbacks.set(event, wrappers);
                const signal = signal_for(event);
                for (const cb of wrappers) {
                    this.connect(signal, cb);
                }
            }
        }
        _doc_attached() {
            if (this.js_event_callbacks.size != 0 || this.subscribed_events.size != 0) {
                this._update_event_callbacks();
            }
        }
        _doc_detached() {
            this.document.event_manager.subscribed_models.delete(this);
        }
        select(selector) {
            if ((0, types_1.isString)(selector)) {
                return [...this.references()].filter((ref) => ref instanceof _a && ref.name === selector);
            }
            else if ((0, types_1.isPlainObject)(selector) && "type" in selector) {
                return [...this.references()].filter((ref) => ref.type == selector.type);
            }
            else if (selector.prototype instanceof has_props_1.HasProps) {
                return [...this.references()].filter((ref) => ref instanceof selector);
            }
            else {
                throw new Error(`invalid selector ${selector}`);
            }
        }
        select_one(selector) {
            const result = this.select(selector);
            switch (result.length) {
                case 0:
                    return null;
                case 1:
                    return result[0];
                default:
                    throw new Error(`found multiple objects matching the given selector ${selector}`);
            }
        }
        get_one(selector) {
            const result = this.select_one(selector);
            if (result != null) {
                return result;
            }
            else {
                throw new Error(`could not find any objects matching the given selector ${selector}`);
            }
        }
        on_event(event, callback) {
            const name = (0, types_1.isString)(event) ? event : event.prototype.event_name;
            const js_event_callbacks = (0, object_1.dict)(this.js_event_callbacks);
            const callbacks = js_event_callbacks.get(name) ?? [];
            js_event_callbacks.set(name, [...callbacks, callback]);
        }
    }
    exports.Model = Model;
    _a = Model;
    Model.__name__ = "Model";
    (() => {
        _a.define(({ Any, Unknown, Bool, Str, List, Set, Dict, Nullable }) => ({
            tags: [List(Unknown), []],
            name: [Nullable(Str), null],
            js_property_callbacks: [Dict(List(Any /*TODO*/)), {}],
            js_event_callbacks: [Dict(List(Any /*TODO*/)), {}],
            subscribed_events: [Set(Str), new globalThis.Set()],
            syncable: [Bool, true],
        }));
    })();
},
/* document/defs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.decode_def = decode_def;
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(51) /* ../model */;
    const kinds = tslib_1.__importStar(require(21) /* ../core/kinds */);
    const types_1 = require(8) /* ../core/util/types */;
    const object_1 = require(9) /* ../core/util/object */;
    function decode_def(def, deserializer) {
        var _a;
        function kind_of(ref) {
            if ((0, types_1.isString)(ref)) {
                switch (ref) {
                    case "Any": return kinds.Any;
                    case "Unknown": return kinds.Unknown;
                    case "Bool": return kinds.Bool;
                    case "Float": return kinds.Float;
                    case "Int": return kinds.Int;
                    case "Bytes": return kinds.Bytes;
                    case "Str": return kinds.Str;
                    case "Null": return kinds.Null;
                }
            }
            else {
                switch (ref[0]) {
                    case "Regex": {
                        const [, regex, flags] = ref;
                        return kinds.Regex(new RegExp(regex, flags));
                    }
                    case "Nullable": {
                        const [, sub_ref] = ref;
                        return kinds.Nullable(kind_of(sub_ref));
                    }
                    case "Or": {
                        const [, sub_ref, ...sub_refs] = ref;
                        return kinds.Or(kind_of(sub_ref), ...sub_refs.map(kind_of));
                    }
                    case "Tuple": {
                        const [, sub_ref, ...sub_refs] = ref;
                        return kinds.Tuple(kind_of(sub_ref), ...sub_refs.map(kind_of));
                    }
                    case "List": {
                        const [, sub_ref] = ref;
                        return kinds.List(kind_of(sub_ref));
                    }
                    case "Struct": {
                        const [, ...entry_refs] = ref;
                        const entries = entry_refs.map(([key, val_ref]) => [key, kind_of(val_ref)]);
                        return kinds.Struct((0, object_1.to_object)(entries));
                    }
                    case "Dict": {
                        const [, val_ref] = ref;
                        return kinds.Dict(kind_of(val_ref));
                    }
                    case "Mapping": {
                        const [, key_ref, val_ref] = ref;
                        return kinds.Mapping(kind_of(key_ref), kind_of(val_ref));
                    }
                    case "Enum": {
                        const [, ...items] = ref;
                        return kinds.Enum(...items);
                    }
                    case "Ref": {
                        const [, model_ref] = ref;
                        const model = deserializer.resolver.get(model_ref.id);
                        if (model != null) {
                            return kinds.Ref(model);
                        }
                        else {
                            throw new Error(`${model_ref.id} wasn't defined before referencing it`);
                        }
                    }
                    case "AnyRef": {
                        return kinds.AnyRef();
                    }
                }
            }
        }
        const base = (() => {
            const name = def.extends?.id ?? "Model";
            if (name == "Model") {
                // TODO: support base classes in general
                return model_1.Model;
            }
            const base = deserializer.resolver.get(name);
            if (base != null) {
                return base;
            }
            else {
                throw new Error(`base model ${name} of ${def.name} is not defined`);
            }
        })();
        const model = (_a = class extends base {
        },
            tslib_1.__setFunctionName(_a, "model"),
            _a.__qualified__ = def.name,
            _a);
        function decode(value) {
            if (value === undefined) {
                return value;
            }
            else {
                return deserializer.decode(value);
            }
        }
        for (const prop of def.properties ?? []) {
            const kind = kind_of(prop.kind);
            model.define({ [prop.name]: [kind, decode(prop.default)] });
        }
        for (const prop of def.overrides ?? []) {
            model.override({ [prop.name]: decode(prop.default) });
        }
        deserializer.resolver.register(model);
        return model;
    }
},
/* core/bokeh_events.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5;
    __esModule();
    exports.server_event = server_event;
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
            r = Reflect.decorate(decorators, target, key, desc);
        else
            for (var i = decorators.length - 1; i >= 0; i--)
                if (d = decorators[i])
                    r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    const model_1 = require(51) /* ../model */;
    const types_1 = require(8) /* ./util/types */;
    const assert_1 = require(12) /* ./util/assert */;
    const serialization_1 = require(32) /* ./serialization */;
    const deserializer_1 = require(47) /* ./serialization/deserializer */;
    const eq_1 = require(26) /* ./util/eq */;
    deserializer_1.Deserializer.register("event", (rep, deserializer) => {
        const cls = deserializable_events.get(rep.name);
        if (cls !== undefined && cls.from_values != null) {
            const values = deserializer.decode(rep.values);
            (0, assert_1.assert)((0, types_1.isPlainObject)(values));
            return cls.from_values(values);
        }
        else {
            deserializer.error(`deserialization of '${rep.name}' event is not supported`);
        }
    });
    function event(event_name) {
        return (cls) => {
            cls.prototype.event_name = event_name;
        };
    }
    const deserializable_events = new Map();
    /**
     * Marks and registers a class as a one way (server -> client) event.
     */
    function server_event(event_name) {
        return (cls) => {
            if (deserializable_events.has(event_name)) {
                throw new Error(`'${event_name}' event is already registered`);
            }
            deserializable_events.set(event_name, cls);
            cls.prototype.event_name = event_name;
            cls.prototype.publish = false;
        };
    }
    class BokehEvent {
        [serialization_1.serialize](serializer) {
            const { event_name: name, event_values } = this;
            const values = serializer.encode(event_values);
            return { type: "event", name, values };
        }
        [eq_1.equals](that, cmp) {
            return this.event_name == that.event_name && cmp.eq(this.event_values, that.event_values);
        }
    }
    exports.BokehEvent = BokehEvent;
    _a = BokehEvent;
    BokehEvent.__name__ = "BokehEvent";
    (() => {
        _a.prototype.publish = true;
    })();
    class ModelEvent extends BokehEvent {
        constructor() {
            super(...arguments);
            this.origin = null;
        }
        get event_values() {
            return { model: this.origin };
        }
    }
    exports.ModelEvent = ModelEvent;
    ModelEvent.__name__ = "ModelEvent";
    class UserEvent extends ModelEvent {
        constructor(values) {
            super();
            this.values = values;
        }
        get event_values() {
            return { ...super.event_values, ...this.values };
        }
        static from_values(values) {
            const origin = (() => {
                if ("model" in values) {
                    const { model } = values;
                    (0, assert_1.assert)(model === null || model instanceof model_1.Model);
                    delete values.model;
                    return model;
                }
                else {
                    return null;
                }
            })();
            const event = new this(values);
            event.origin = origin;
            return event;
        }
    }
    exports.UserEvent = UserEvent;
    UserEvent.__name__ = "UserEvent";
    class DocumentEvent extends BokehEvent {
    }
    exports.DocumentEvent = DocumentEvent;
    DocumentEvent.__name__ = "DocumentEvent";
    let DocumentReady = (_b = class DocumentReady extends DocumentEvent {
        get event_values() {
            return {};
        }
    },
        _b.__name__ = "DocumentReady",
        _b);
    exports.DocumentReady = DocumentReady;
    exports.DocumentReady = DocumentReady = __decorate([
        event("document_ready")
    ], DocumentReady);
    class ConnectionEvent extends DocumentEvent {
    }
    exports.ConnectionEvent = ConnectionEvent;
    ConnectionEvent.__name__ = "ConnectionEvent";
    class ConnectionLost extends ConnectionEvent {
        constructor() {
            super(...arguments);
            this.timestamp = new Date();
        }
        get event_values() {
            const { timestamp } = this;
            return { timestamp };
        }
    }
    exports.ConnectionLost = ConnectionLost;
    _c = ConnectionLost;
    ConnectionLost.__name__ = "ConnectionLost";
    (() => {
        _c.prototype.event_name = "connection_lost";
        _c.prototype.publish = false;
    })();
    let AxisClick = (_d = class AxisClick extends ModelEvent {
        constructor(model, value) {
            super();
            this.model = model;
            this.value = value;
        }
        get event_values() {
            const { value } = this;
            return { ...super.event_values, value };
        }
    },
        _d.__name__ = "AxisClick",
        _d);
    exports.AxisClick = AxisClick;
    exports.AxisClick = AxisClick = __decorate([
        event("axis_click")
    ], AxisClick);
    let ButtonClick = (_e = class ButtonClick extends ModelEvent {
    },
        _e.__name__ = "ButtonClick",
        _e);
    exports.ButtonClick = ButtonClick;
    exports.ButtonClick = ButtonClick = __decorate([
        event("button_click")
    ], ButtonClick);
    let LegendItemClick = (_f = class LegendItemClick extends ModelEvent {
        constructor(model, item) {
            super();
            this.model = model;
            this.item = item;
        }
        get event_values() {
            const { item } = this;
            return { ...super.event_values, item };
        }
    },
        _f.__name__ = "LegendItemClick",
        _f);
    exports.LegendItemClick = LegendItemClick;
    exports.LegendItemClick = LegendItemClick = __decorate([
        event("legend_item_click")
    ], LegendItemClick);
    let MenuItemClick = (_g = class MenuItemClick extends ModelEvent {
        constructor(item) {
            super();
            this.item = item;
        }
        get event_values() {
            const { item } = this;
            return { ...super.event_values, item };
        }
    },
        _g.__name__ = "MenuItemClick",
        _g);
    exports.MenuItemClick = MenuItemClick;
    exports.MenuItemClick = MenuItemClick = __decorate([
        event("menu_item_click")
    ], MenuItemClick);
    let ValueSubmit = (_h = class ValueSubmit extends ModelEvent {
        constructor(value) {
            super();
            this.value = value;
        }
        get event_values() {
            const { value } = this;
            return { ...super.event_values, value };
        }
    },
        _h.__name__ = "ValueSubmit",
        _h);
    exports.ValueSubmit = ValueSubmit;
    exports.ValueSubmit = ValueSubmit = __decorate([
        event("value_submit")
    ], ValueSubmit);
    // A UIEvent is an event originating on a canvas this includes.
    // DOM events such as keystrokes as well as hammer, LOD, and range events.
    class UIEvent extends ModelEvent {
    }
    exports.UIEvent = UIEvent;
    UIEvent.__name__ = "UIEvent";
    let LODStart = (_j = class LODStart extends UIEvent {
    },
        _j.__name__ = "LODStart",
        _j);
    exports.LODStart = LODStart;
    exports.LODStart = LODStart = __decorate([
        event("lodstart")
    ], LODStart);
    let LODEnd = (_k = class LODEnd extends UIEvent {
    },
        _k.__name__ = "LODEnd",
        _k);
    exports.LODEnd = LODEnd;
    exports.LODEnd = LODEnd = __decorate([
        event("lodend")
    ], LODEnd);
    let RangesUpdate = (_l = class RangesUpdate extends UIEvent {
        constructor(x0, x1, y0, y1) {
            super();
            this.x0 = x0;
            this.x1 = x1;
            this.y0 = y0;
            this.y1 = y1;
        }
        get event_values() {
            const { x0, x1, y0, y1 } = this;
            return { ...super.event_values, x0, x1, y0, y1 };
        }
    },
        _l.__name__ = "RangesUpdate",
        _l);
    exports.RangesUpdate = RangesUpdate;
    exports.RangesUpdate = RangesUpdate = __decorate([
        event("rangesupdate")
    ], RangesUpdate);
    let SelectionGeometry = (_m = class SelectionGeometry extends UIEvent {
        constructor(geometry, final) {
            super();
            this.geometry = geometry;
            this.final = final;
        }
        get event_values() {
            const { geometry, final } = this;
            return { ...super.event_values, geometry, final };
        }
    },
        _m.__name__ = "SelectionGeometry",
        _m);
    exports.SelectionGeometry = SelectionGeometry;
    exports.SelectionGeometry = SelectionGeometry = __decorate([
        event("selectiongeometry")
    ], SelectionGeometry);
    let Reset = (_o = class Reset extends UIEvent {
    },
        _o.__name__ = "Reset",
        _o);
    exports.Reset = Reset;
    exports.Reset = Reset = __decorate([
        event("reset")
    ], Reset);
    class PointEvent extends UIEvent {
        constructor(sx, sy, x, y, modifiers) {
            super();
            this.sx = sx;
            this.sy = sy;
            this.x = x;
            this.y = y;
            this.modifiers = modifiers;
        }
        get event_values() {
            const { sx, sy, x, y, modifiers } = this;
            return { ...super.event_values, sx, sy, x, y, modifiers };
        }
    }
    exports.PointEvent = PointEvent;
    PointEvent.__name__ = "PointEvent";
    let Pan = (_p = class Pan extends PointEvent {
        /* TODO: direction: -1 | 1 */
        constructor(sx, sy, x, y, delta_x, delta_y, modifiers) {
            super(sx, sy, x, y, modifiers);
            this.delta_x = delta_x;
            this.delta_y = delta_y;
        }
        get event_values() {
            const { delta_x, delta_y /*, direction*/ } = this;
            return { ...super.event_values, delta_x, delta_y /*, direction*/ };
        }
    },
        _p.__name__ = "Pan",
        _p);
    exports.Pan = Pan;
    exports.Pan = Pan = __decorate([
        event("pan")
    ], Pan);
    let Pinch = (_q = class Pinch extends PointEvent {
        constructor(sx, sy, x, y, scale, modifiers) {
            super(sx, sy, x, y, modifiers);
            this.scale = scale;
        }
        get event_values() {
            const { scale } = this;
            return { ...super.event_values, scale };
        }
    },
        _q.__name__ = "Pinch",
        _q);
    exports.Pinch = Pinch;
    exports.Pinch = Pinch = __decorate([
        event("pinch")
    ], Pinch);
    let Rotate = (_r = class Rotate extends PointEvent {
        constructor(sx, sy, x, y, rotation, modifiers) {
            super(sx, sy, x, y, modifiers);
            this.rotation = rotation;
        }
        get event_values() {
            const { rotation } = this;
            return { ...super.event_values, rotation };
        }
    },
        _r.__name__ = "Rotate",
        _r);
    exports.Rotate = Rotate;
    exports.Rotate = Rotate = __decorate([
        event("rotate")
    ], Rotate);
    let MouseWheel = (_s = class MouseWheel extends PointEvent {
        constructor(sx, sy, x, y, delta, modifiers) {
            super(sx, sy, x, y, modifiers);
            this.delta = delta;
        }
        get event_values() {
            const { delta } = this;
            return { ...super.event_values, delta };
        }
    },
        _s.__name__ = "MouseWheel",
        _s);
    exports.MouseWheel = MouseWheel;
    exports.MouseWheel = MouseWheel = __decorate([
        event("wheel")
    ], MouseWheel);
    let MouseMove = (_t = class MouseMove extends PointEvent {
    },
        _t.__name__ = "MouseMove",
        _t);
    exports.MouseMove = MouseMove;
    exports.MouseMove = MouseMove = __decorate([
        event("mousemove")
    ], MouseMove);
    let MouseEnter = (_u = class MouseEnter extends PointEvent {
    },
        _u.__name__ = "MouseEnter",
        _u);
    exports.MouseEnter = MouseEnter;
    exports.MouseEnter = MouseEnter = __decorate([
        event("mouseenter")
    ], MouseEnter);
    let MouseLeave = (_v = class MouseLeave extends PointEvent {
    },
        _v.__name__ = "MouseLeave",
        _v);
    exports.MouseLeave = MouseLeave;
    exports.MouseLeave = MouseLeave = __decorate([
        event("mouseleave")
    ], MouseLeave);
    let Tap = (_w = class Tap extends PointEvent {
    },
        _w.__name__ = "Tap",
        _w);
    exports.Tap = Tap;
    exports.Tap = Tap = __decorate([
        event("tap")
    ], Tap);
    let DoubleTap = (_x = class DoubleTap extends PointEvent {
    },
        _x.__name__ = "DoubleTap",
        _x);
    exports.DoubleTap = DoubleTap;
    exports.DoubleTap = DoubleTap = __decorate([
        event("doubletap")
    ], DoubleTap);
    let Press = (_y = class Press extends PointEvent {
    },
        _y.__name__ = "Press",
        _y);
    exports.Press = Press;
    exports.Press = Press = __decorate([
        event("press")
    ], Press);
    let PressUp = (_z = class PressUp extends PointEvent {
    },
        _z.__name__ = "PressUp",
        _z);
    exports.PressUp = PressUp;
    exports.PressUp = PressUp = __decorate([
        event("pressup")
    ], PressUp);
    let PanStart = (_0 = class PanStart extends PointEvent {
    },
        _0.__name__ = "PanStart",
        _0);
    exports.PanStart = PanStart;
    exports.PanStart = PanStart = __decorate([
        event("panstart")
    ], PanStart);
    let PanEnd = (_1 = class PanEnd extends PointEvent {
    },
        _1.__name__ = "PanEnd",
        _1);
    exports.PanEnd = PanEnd;
    exports.PanEnd = PanEnd = __decorate([
        event("panend")
    ], PanEnd);
    let PinchStart = (_2 = class PinchStart extends PointEvent {
    },
        _2.__name__ = "PinchStart",
        _2);
    exports.PinchStart = PinchStart;
    exports.PinchStart = PinchStart = __decorate([
        event("pinchstart")
    ], PinchStart);
    let PinchEnd = (_3 = class PinchEnd extends PointEvent {
    },
        _3.__name__ = "PinchEnd",
        _3);
    exports.PinchEnd = PinchEnd;
    exports.PinchEnd = PinchEnd = __decorate([
        event("pinchend")
    ], PinchEnd);
    let RotateStart = (_4 = class RotateStart extends PointEvent {
    },
        _4.__name__ = "RotateStart",
        _4);
    exports.RotateStart = RotateStart;
    exports.RotateStart = RotateStart = __decorate([
        event("rotatestart")
    ], RotateStart);
    let RotateEnd = (_5 = class RotateEnd extends PointEvent {
    },
        _5.__name__ = "RotateEnd",
        _5);
    exports.RotateEnd = RotateEnd;
    exports.RotateEnd = RotateEnd = __decorate([
        event("rotateend")
    ], RotateEnd);
},
/* embed/standalone.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.add_document_standalone = add_document_standalone;
    const document_1 = require(5) /* ../document */;
    const view_manager_1 = require(55) /* ../core/view_manager */;
    const dom_view_1 = require(57) /* ../core/dom_view */;
    const types_1 = require(8) /* ../core/util/types */;
    const assert_1 = require(12) /* ../core/util/assert */;
    // A map from the root model IDs to their views.
    exports.index = new Proxy(new view_manager_1.ViewManager(), {
        get(manager, property) {
            if ((0, types_1.isString)(property)) {
                const view = manager.get_by_id(property);
                if (view != null) {
                    return view;
                }
            }
            return Reflect.get(manager, property);
        },
        has(manager, property) {
            if ((0, types_1.isString)(property)) {
                const view = manager.get_by_id(property);
                if (view != null) {
                    return true;
                }
            }
            return Reflect.has(manager, property);
        },
        ownKeys(manager) {
            return manager.roots.map((root) => root.model.id);
        },
        getOwnPropertyDescriptor(manager, property) {
            if ((0, types_1.isString)(property)) {
                const view = manager.get_by_id(property);
                if (view != null) {
                    return { configurable: true, enumerable: true, writable: false, value: view };
                }
            }
            return Reflect.getOwnPropertyDescriptor(manager, property);
        },
    });
    async function add_document_standalone(document, element, roots = [], use_for_title = false) {
        // this is a LOCAL index of views used only by this particular rendering
        // call, so we can remove the views we create.
        (0, assert_1.assert)(document.views_manager == null);
        const views = new view_manager_1.ViewManager([], exports.index);
        document.views_manager = views;
        async function render_view(model) {
            const view = await views.build_view(model);
            if (view instanceof dom_view_1.DOMView) {
                const i = document.roots().indexOf(model);
                const root_el = roots[i] ?? element;
                view.build(root_el);
            }
            exports.index.add(view);
        }
        async function render_model(model) {
            if (model.default_view != null) {
                await render_view(model);
            }
            else {
                document.notify_idle(model);
            }
        }
        function unrender_model(model) {
            const view = views.get(model);
            view?.remove();
        }
        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) {
                void 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;
    }
},
/* core/view_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const build_views_1 = require(56) /* ./build_views */;
    class AbstractViewQuery {
        *all_views() {
            yield* this.query(() => true);
        }
        *query(fn) {
            const visited = new Set();
            function* descend(view) {
                if (visited.has(view)) {
                    return;
                }
                visited.add(view);
                if (fn(view)) {
                    yield view;
                }
                for (const child of view.children()) {
                    yield* descend(child);
                }
            }
            for (const view of this) {
                yield* descend(view);
            }
        }
        query_one(fn) {
            for (const view of this.query(fn)) {
                return view;
            }
            return null;
        }
        *find(model) {
            yield* this.query((view) => view.model == model);
        }
        *find_by_id(id) {
            yield* this.query((view) => view.model.id == id);
        }
        find_one(model) {
            for (const view of this.find(model)) {
                return view;
            }
            return null;
        }
        find_one_by_id(id) {
            for (const view of this.find_by_id(id)) {
                return view;
            }
            return null;
        }
        get_one(model) {
            const view = this.find_one(model);
            if (view != null) {
                return view;
            }
            else {
                throw new Error(`cannot find a view for ${model}`);
            }
        }
        get_one_by_id(id) {
            const view = this.find_one_by_id(id);
            if (view != null) {
                return view;
            }
            else {
                throw new Error(`cannot find a view for a model with '${id}' identity`);
            }
        }
        find_all(model) {
            return [...this.find(model)];
        }
        find_all_by_id(id) {
            return [...this.find_by_id(id)];
        }
    }
    AbstractViewQuery.__name__ = "AbstractViewQuery";
    class ViewQuery extends AbstractViewQuery {
        constructor(view) {
            super();
            this.view = view;
        }
        *[Symbol.iterator]() {
            yield this.view;
        }
        toString() {
            return `ViewQuery(${this.view})`;
        }
    }
    exports.ViewQuery = ViewQuery;
    ViewQuery.__name__ = "ViewQuery";
    class ViewManager extends AbstractViewQuery {
        constructor(roots = [], global) {
            super();
            this.global = global;
            this._roots = new Set(roots);
        }
        toString() {
            const views = [...this._roots].map((view) => `${view}`).join(", ");
            return `ViewManager(${views})`;
        }
        async build_view(model, parent = null) {
            const view = await (0, build_views_1.build_view)(model, { owner: this, parent });
            if (parent == null) {
                this.add(view);
            }
            return view;
        }
        get(model) {
            for (const view of this._roots) {
                if (view.model == model) {
                    return view;
                }
            }
            return null;
        }
        get_by_id(id) {
            for (const view of this._roots) {
                if (view.model.id == id) {
                    return view;
                }
            }
            return null;
        }
        add(view) {
            this._roots.add(view);
            this.global?.add(view);
        }
        delete(view) {
            this._roots.delete(view);
            this.global?.delete(view);
        }
        remove(view) {
            this.delete(view);
        }
        clear() {
            for (const view of this) {
                view.remove();
            }
        }
        /* TODO (TS 5.2)
        [Symbol.dispose](): void {
          this.clear()
        }
        */
        get roots() {
            return [...this._roots];
        }
        *[Symbol.iterator]() {
            yield* this._roots;
        }
    }
    exports.ViewManager = ViewManager;
    ViewManager.__name__ = "ViewManager";
},
/* core/build_views.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.build_view = build_view;
    exports.build_views = build_views;
    exports.remove_views = remove_views;
    exports.traverse_views = traverse_views;
    const array_1 = require(10) /* ./util/array */;
    const assert_1 = require(12) /* ./util/assert */;
    async function _build_view(view_cls, model, options) {
        (0, assert_1.assert)(view_cls != null, "model doesn't implement a view");
        const view = new view_cls({ ...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;
    }
    async function build_views(view_storage, models, options = { parent: null }, cls = (model) => model.default_view) {
        const to_remove = (0, array_1.difference)([...view_storage.keys()], models);
        const removed_views = [];
        for (const model of to_remove) {
            const view = view_storage.get(model);
            if (view != null) {
                view_storage.delete(model);
                removed_views.push(view);
                view.remove();
            }
        }
        const created_views = [];
        const new_models = models.filter((model) => !view_storage.has(model));
        for (const model of new_models) {
            const view = await _build_view(cls(model), model, options);
            view_storage.set(model, view);
            created_views.push(view);
        }
        for (const view of created_views) {
            view.connect_signals();
        }
        return {
            created: created_views,
            removed: removed_views,
        };
    }
    function remove_views(view_storage) {
        for (const [model, view] of view_storage) {
            view.remove();
            view_storage.delete(model);
        }
    }
    function traverse_views(views, fn) {
        const visited = new Set();
        const queue = [...views];
        while (true) {
            const view = queue.shift();
            if (view === undefined) {
                break;
            }
            if (visited.has(view)) {
                continue;
            }
            visited.add(view);
            queue.push(...view.children());
            fn(view);
        }
    }
},
/* core/dom_view.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const view_1 = require(58) /* ./view */;
    const dom_1 = require(63) /* ./dom */;
    const types_1 = require(8) /* ./util/types */;
    const assert_1 = require(12) /* ./util/assert */;
    const base_css_1 = tslib_1.__importDefault(require(66) /* ../styles/base.css */);
    class DOMView extends view_1.View {
        constructor() {
            super(...arguments);
            this._was_built = false;
        }
        get bbox() {
            return undefined;
        }
        serializable_state() {
            const state = super.serializable_state();
            const { bbox } = this;
            return bbox != null ? { ...state, bbox: bbox.round() } : state;
        }
        get children_el() {
            return this.shadow_el ?? this.el;
        }
        initialize() {
            super.initialize();
            this.el = this._create_element();
        }
        remove() {
            this.el.remove();
            super.remove();
        }
        stylesheets() {
            return [];
        }
        css_classes() {
            return [];
        }
        render_to(target) {
            this.render();
            target.appendChild(this.el);
        }
        after_render() {
            this.reposition();
        }
        r_after_render() {
            for (const child_view of this.children()) {
                if (child_view instanceof DOMView) {
                    child_view.r_after_render();
                }
            }
            this.after_render();
            this._was_built = true;
        }
        _create_element() {
            return (0, dom_1.create_element)(this.constructor.tag_name, {});
        }
        reposition(_displayed) { }
        /**
         * Build a top-level DOM view (e.g. during embedding).
         */
        build(target) {
            (0, assert_1.assert)(this.is_root);
            this.render_to(target);
            this.r_after_render();
            this.notify_finished();
        }
        /**
         * Define where to render this element or let the parent decide.
         *
         * This is useful when creating "floating" components or adding
         * components to canvas' layers.
         */
        rendering_target() {
            return null;
        }
    }
    exports.DOMView = DOMView;
    DOMView.__name__ = "DOMView";
    DOMView.tag_name = "div";
    class DOMElementView extends DOMView {
        initialize() {
            super.initialize();
            this.class_list = new dom_1.ClassList(this.el.classList);
        }
    }
    exports.DOMElementView = DOMElementView;
    DOMElementView.__name__ = "DOMElementView";
    class DOMComponentView extends DOMElementView {
        constructor() {
            super(...arguments);
            this._applied_stylesheets = [];
            this._applied_css_classes = [];
        }
        initialize() {
            super.initialize();
            this.shadow_el = this.el.attachShadow({ mode: "open" });
        }
        stylesheets() {
            return [...super.stylesheets(), base_css_1.default];
        }
        empty() {
            (0, dom_1.empty)(this.shadow_el);
            this.class_list.clear();
            this._applied_css_classes = [];
            this._applied_stylesheets = [];
        }
        render() {
            this.empty();
            this._update_stylesheets();
            this._update_css_classes();
            this._update_css_variables();
        }
        reposition(_displayed) {
            this._update_css_variables(); // TODO remove this when node invalidation is implemented
        }
        *_stylesheets() {
            for (const style of this.stylesheets()) {
                yield (0, types_1.isString)(style) ? new dom_1.InlineStyleSheet(style) : style;
            }
        }
        *_css_classes() {
            yield `bk-${this.model.type.replace(/\./g, "-")}`;
            yield* this.css_classes();
        }
        *_css_variables() { }
        _apply_stylesheets(stylesheets) {
            this._applied_stylesheets.push(...stylesheets);
            stylesheets.forEach((stylesheet) => stylesheet.install(this.shadow_el));
        }
        _apply_css_classes(classes) {
            this._applied_css_classes.push(...classes);
            this.class_list.add(...classes);
        }
        _update_stylesheets() {
            this._applied_stylesheets.forEach((stylesheet) => stylesheet.uninstall());
            this._applied_stylesheets = [];
            this._apply_stylesheets([...this._stylesheets()]);
        }
        _update_css_classes() {
            this.class_list.remove(this._applied_css_classes);
            this._applied_css_classes = [];
            this._apply_css_classes([...this._css_classes()]);
        }
        _update_css_variables() {
            for (const [name, value] of this._css_variables()) {
                const full_name = name.startsWith("--") ? name : `--${name}`;
                this.el.style.setProperty(full_name, value);
            }
        }
    }
    exports.DOMComponentView = DOMComponentView;
    DOMComponentView.__name__ = "DOMComponentView";
},
/* core/view.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const has_props_1 = require(14) /* ./has_props */;
    const signaling_1 = require(15) /* ./signaling */;
    const types_1 = require(8) /* ./util/types */;
    const node_1 = require(59) /* ../models/coordinates/node */;
    const xy_1 = require(61) /* ../models/coordinates/xy */;
    const indexed_1 = require(62) /* ../models/coordinates/indexed */;
    const view_manager_1 = require(55) /* ./view_manager */;
    const eq_1 = require(26) /* ./util/eq */;
    class View {
        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);
                    if (this.root != this) {
                        this.root._ready = this.root._ready.then(() => this._ready);
                    }
                };
                this._slots.set(slot, new_slot);
            }
            return signal.connect(new_slot, this);
        }
        disconnect(signal, slot) {
            return signal.disconnect(slot, this);
        }
        constructor(options) {
            this.removed = new signaling_1.Signal0(this, "removed");
            this.views = new view_manager_1.ViewQuery(this);
            this._ready = Promise.resolve(undefined);
            /** @internal */
            this._slots = new WeakMap();
            this._destroyed = false;
            this._has_finished = false;
            this._idle_notified = false;
            const { model, parent, owner } = options;
            this.model = model;
            this.parent = parent;
            if (parent == null) {
                this.root = this;
                this.owner = owner ?? new view_manager_1.ViewManager([this]);
            }
            else {
                this.root = parent.root;
                this.owner = this.root.owner;
            }
        }
        initialize() { }
        async lazy_initialize() { }
        remove() {
            this.disconnect_signals();
            this.owner.remove(this);
            this.removed.emit();
            this._destroyed = true;
        }
        get is_destroyed() {
            return this._destroyed;
        }
        toString() {
            return `${this.model.type}View(${this.model.id})`;
        }
        [eq_1.equals](that, _cmp) {
            return Object.is(this, that);
        }
        *children() { }
        mark_finished() {
            this._has_finished = true;
        }
        /**
         * Mark as finished even if e.g. external resources were not loaded yet.
         */
        force_finished() {
            this.mark_finished();
        }
        finish() {
            this.mark_finished();
            this.notify_finished();
        }
        notify_finished() {
            if (!this.is_root) {
                this.root.notify_finished();
            }
            else {
                if (!this._idle_notified && this.has_finished()) {
                    const { document } = this.model;
                    if (document != null) {
                        this._idle_notified = true;
                        document.notify_idle(this.model);
                    }
                }
            }
        }
        serializable_state() {
            const children = [...this.children()]
                .filter((view) => view.model.is_syncable)
                .map((view) => view.serializable_state())
                .filter((item) => item.bbox != null && item.bbox.is_valid && !item.bbox.is_empty);
            return {
                type: this.model.type,
                children,
            };
        }
        get is_root() {
            return this.parent == null;
        }
        has_finished() {
            return this._has_finished;
        }
        get is_idle() {
            return this.has_finished();
        }
        connect_signals() { }
        disconnect_signals() {
            signaling_1.Signal.disconnect_receiver(this);
        }
        on_change(properties, fn) {
            for (const property of (0, types_1.isArray)(properties) ? properties : [properties]) {
                this.connect(property.change, fn);
            }
        }
        on_transitive_change(property, fn) {
            const collect = () => {
                const value = property.is_unset ? [] : property.get_value();
                return has_props_1.HasProps.references(value, { recursive: false });
            };
            const connect = (models) => {
                for (const model of models) {
                    this.connect(model.change, fn);
                }
            };
            const disconnect = (models) => {
                for (const model of models) {
                    this.disconnect(model.change, fn);
                }
            };
            let models = collect();
            connect(models);
            this.on_change(property, () => {
                disconnect(models);
                models = collect();
                connect(models);
                fn();
            });
        }
        cursor(_sx, _sy) {
            return null;
        }
        resolve_frame() {
            return null;
        }
        resolve_canvas() {
            return null;
        }
        resolve_plot() {
            return null;
        }
        resolve_target(target) {
            if ((0, types_1.isString)(target)) {
                const ascend = (fn) => {
                    let obj = this;
                    while (obj != null) {
                        const view = fn(obj);
                        if (view != null) {
                            return view;
                        }
                        else {
                            obj = obj.parent;
                        }
                    }
                    return null;
                };
                switch (target) {
                    case "parent": return this.parent;
                    case "frame": return ascend((view) => view.resolve_frame());
                    case "canvas": return ascend((view) => view.resolve_canvas());
                    case "plot": return ascend((view) => view.resolve_plot());
                }
            }
            else {
                const queue = [this.root];
                while (true) {
                    const child = queue.shift();
                    if (child == null) {
                        break;
                    }
                    else if (child.model == target) {
                        return child;
                    }
                    else {
                        queue.push(...child.children());
                    }
                }
                return null;
            }
        }
        resolve_symbol(_node) {
            return { x: NaN, y: NaN };
        }
        resolve_node(node) {
            const target = this.resolve_target(node.target);
            if (target != null) {
                return target.resolve_symbol(node);
            }
            else {
                return { x: NaN, y: NaN };
            }
        }
        resolve_coordinate(coord) {
            if (coord instanceof xy_1.XY) {
                let obj = this;
                while (obj != null && obj.resolve_xy == null) {
                    obj = obj.parent;
                }
                return obj?.resolve_xy?.(coord) ?? { x: NaN, y: NaN };
            }
            else if (coord instanceof indexed_1.Indexed) {
                let obj = this;
                while (obj != null && obj.resolve_indexed == null) {
                    obj = obj.parent;
                }
                return obj?.resolve_indexed?.(coord) ?? { x: NaN, y: NaN };
            }
            else if (coord instanceof node_1.Node) {
                return this.resolve_node(coord);
            }
            else {
                return { x: NaN, y: NaN };
            }
        }
        resolve_as_xy(coord) {
            const value = this.resolve_coordinate(coord);
            return (0, types_1.isNumber)(value) ? { x: NaN, y: NaN } : value;
        }
        resolve_as_scalar(coord, dim) {
            const value = this.resolve_coordinate(coord);
            return (0, types_1.isNumber)(value) ? value : value[dim];
        }
    }
    exports.View = View;
    View.__name__ = "View";
},
/* models/coordinates/node.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const coordinate_1 = require(60) /* ./coordinate */;
    const model_1 = require(51) /* ../../model */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    exports.ImplicitTarget = (0, kinds_1.Enum)("canvas", "plot", "frame", "parent");
    exports.NodeTarget = (0, kinds_1.Or)((0, kinds_1.Ref)(model_1.Model), exports.ImplicitTarget);
    class BoxNodes {
        constructor(target, frozen = false) {
            this._left = null;
            this._right = null;
            this._top = null;
            this._bottom = null;
            this.target = target;
            this.frozen = frozen;
        }
        _node(symbol) {
            const { target, frozen } = this;
            const node = new Node({ target, symbol });
            if (frozen) {
                this[`_${symbol}`] = node;
            }
            return node;
        }
        get left() {
            return this._left ?? this._node("left");
        }
        get right() {
            return this._right ?? this._node("right");
        }
        get top() {
            return this._top ?? this._node("top");
        }
        get bottom() {
            return this._bottom ?? this._node("bottom");
        }
        freeze() {
            return new BoxNodes(this.target, true);
        }
    }
    exports.BoxNodes = BoxNodes;
    BoxNodes.__name__ = "BoxNodes";
    class Node extends coordinate_1.Coordinate {
        constructor(attrs) {
            super(attrs);
        }
        static get frame() {
            return this._frame_nodes;
        }
        static get canvas() {
            return this._canvas_nodes;
        }
    }
    exports.Node = Node;
    _a = Node;
    Node.__name__ = "Node";
    (() => {
        _a.define(({ Str, Int }) => ({
            target: [exports.NodeTarget],
            symbol: [Str],
            offset: [Int, 0],
        }));
    })();
    Node._frame_nodes = new BoxNodes("frame");
    Node._canvas_nodes = new BoxNodes("canvas");
},
/* models/coordinates/coordinate.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(51) /* ../../model */;
    class Coordinate extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Coordinate = Coordinate;
    Coordinate.__name__ = "Coordinate";
},
/* models/coordinates/xy.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const coordinate_1 = require(60) /* ./coordinate */;
    class XY extends coordinate_1.Coordinate {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.XY = XY;
    _a = XY;
    XY.__name__ = "XY";
    (() => {
        _a.define(({ Float }) => ({
            x: [Float],
            y: [Float],
        }));
    })();
},
/* models/coordinates/indexed.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const coordinate_1 = require(60) /* ./coordinate */;
    class Indexed extends coordinate_1.Coordinate {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Indexed = Indexed;
    _a = Indexed;
    Indexed.__name__ = "Indexed";
    (() => {
        _a.define(({ Int, AnyRef }) => ({
            index: [Int],
            renderer: [AnyRef()],
        }));
    })();
},
/* core/dom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.textarea = exports.template = exports.td = exports.tbody = exports.table = exports.sup = exports.summary = exports.sub = exports.style = exports.strong = exports.span = exports.source = exports.small = exports.slot = exports.select = exports.section = exports.search = exports.script = exports.samp = exports.s = exports.ruby = exports.rt = exports.rp = exports.q = exports.progress = exports.pre = exports.picture = exports.p = exports.output = exports.option = exports.optgroup = exports.ol = exports.object = exports.noscript = exports.nav = exports.meter = exports.meta = exports.menu = exports.mark = exports.map = exports.main = exports.link = exports.li = exports.legend = exports.label = exports.kbd = exports.ins = exports.input = exports.img = exports.iframe = void 0;
    exports.supports_adopted_stylesheets = exports.GlobalImportedStyleSheet = exports.ImportedStyleSheet = exports.GlobalInlineStyleSheet = exports.InlineStyleSheet = exports.StyleSheet = exports.MouseButton = exports.ClassList = exports.wbr = exports.video = exports.ul = exports.u = exports.track = exports.tr = exports.title = exports.time = exports.thead = exports.th = exports.tfoot = void 0;
    exports.create_element = create_element;
    exports.createSVGElement = createSVGElement;
    exports.text = text;
    exports.nbsp = nbsp;
    exports.prepend = prepend;
    exports.empty = empty;
    exports.contains = contains;
    exports.display = display;
    exports.undisplay = undisplay;
    exports.show = show;
    exports.hide = hide;
    exports.offset_bbox = offset_bbox;
    exports.parent = parent;
    exports.extents = extents;
    exports.size = size;
    exports.scroll_size = scroll_size;
    exports.outer_size = outer_size;
    exports.content_size = content_size;
    exports.bounding_box = bounding_box;
    exports.box_size = box_size;
    exports.position = position;
    exports.classes = classes;
    exports.toggle_attribute = toggle_attribute;
    exports.dom_ready = dom_ready;
    exports.px = px;
    const types_1 = require(8) /* ./util/types */;
    const object_1 = require(9) /* ./util/object */;
    const bbox_1 = require(64) /* ./util/bbox */;
    const css_1 = require(65) /* ./css */;
    const logging_1 = require(19) /* ./logging */;
    const _element = (tag) => {
        return (attrs = {}, ...children) => {
            const element = document.createElement(tag);
            if (!(0, types_1.isPlainObject)(attrs)) {
                children = [attrs, ...children];
                attrs = {};
            }
            else {
                attrs = { ...attrs };
            }
            if (attrs.class != null) {
                const classes = (() => {
                    if ((0, types_1.isString)(attrs.class)) {
                        return attrs.class.split(/\s+/);
                    }
                    else {
                        return attrs.class;
                    }
                })();
                for (const cls of classes) {
                    if (cls != null) {
                        element.classList.add(cls);
                    }
                }
                delete attrs.class;
            }
            if (attrs.style != null) {
                if ((0, types_1.isString)(attrs.style)) {
                    element.setAttribute("style", attrs.style);
                }
                else {
                    (0, css_1.apply_styles)(element.style, attrs.style);
                }
                delete attrs.style;
            }
            if (attrs.data != null) {
                for (const [key, data] of (0, object_1.entries)(attrs.data)) {
                    if (data != null) {
                        element.dataset[key] = data;
                    }
                }
                delete attrs.data;
            }
            for (const [attr, value] of (0, object_1.entries)(attrs)) {
                if (value == null) {
                    continue;
                }
                else if ((0, types_1.isBoolean)(value)) {
                    element.toggleAttribute(attr, value);
                }
                else if ((0, types_1.isNumber)(value)) {
                    element.setAttribute(attr, `${value}`);
                }
                else if ((0, types_1.isString)(value)) {
                    element.setAttribute(attr, value);
                }
                else {
                    logging_1.logger.warn(`unable to set attribute: ${attr} = ${value}`);
                }
            }
            function append(child) {
                if ((0, types_1.isString)(child)) {
                    element.append(document.createTextNode(child));
                }
                else if (child instanceof Node) {
                    element.append(child);
                }
                else if (child instanceof NodeList || child instanceof HTMLCollection) {
                    element.append(...child);
                }
                else if (child != null && child !== false) {
                    throw new Error(`expected a DOM element, string, false or null, got ${JSON.stringify(child)}`);
                }
            }
            for (const child of children) {
                if ((0, types_1.isArray)(child)) {
                    for (const _child of child) {
                        append(_child);
                    }
                }
                else {
                    append(child);
                }
            }
            return element;
        };
    };
    function create_element(tag, attrs, ...children) {
        return _element(tag)(attrs, ...children);
    }
    exports.a = _element("a");
    exports.abbr = _element("abbr");
    exports.address = _element("address");
    exports.area = _element("area");
    exports.article = _element("article");
    exports.aside = _element("aside");
    exports.audio = _element("audio");
    exports.b = _element("b");
    exports.base = _element("base");
    exports.bdi = _element("bdi");
    exports.bdo = _element("bdo");
    exports.blockquote = _element("blockquote");
    exports.body = _element("body");
    exports.br = _element("br");
    exports.button = _element("button");
    exports.canvas = _element("canvas");
    exports.caption = _element("caption");
    exports.cite = _element("cite");
    exports.code = _element("code");
    exports.col = _element("col");
    exports.colgroup = _element("colgroup");
    exports.data = _element("data");
    exports.datalist = _element("datalist");
    exports.dd = _element("dd");
    exports.del = _element("del");
    exports.details = _element("details");
    exports.dfn = _element("dfn");
    exports.dialog = _element("dialog");
    exports.div = _element("div");
    exports.dl = _element("dl");
    exports.dt = _element("dt");
    exports.em = _element("em");
    exports.embed = _element("embed");
    exports.fieldset = _element("fieldset");
    exports.figcaption = _element("figcaption");
    exports.figure = _element("figure");
    exports.footer = _element("footer");
    exports.form = _element("form");
    exports.h1 = _element("h1");
    exports.h2 = _element("h2");
    exports.h3 = _element("h3");
    exports.h4 = _element("h4");
    exports.h5 = _element("h5");
    exports.h6 = _element("h6");
    exports.head = _element("head");
    exports.header = _element("header");
    exports.hgroup = _element("hgroup");
    exports.hr = _element("hr");
    exports.html = _element("html");
    exports.i = _element("i");
    exports.iframe = _element("iframe");
    exports.img = _element("img");
    exports.input = _element("input");
    exports.ins = _element("ins");
    exports.kbd = _element("kbd");
    exports.label = _element("label");
    exports.legend = _element("legend");
    exports.li = _element("li");
    exports.link = _element("link");
    exports.main = _element("main");
    exports.map = _element("map");
    exports.mark = _element("mark");
    exports.menu = _element("menu");
    exports.meta = _element("meta");
    exports.meter = _element("meter");
    exports.nav = _element("nav");
    exports.noscript = _element("noscript");
    exports.object = _element("object");
    exports.ol = _element("ol");
    exports.optgroup = _element("optgroup");
    exports.option = _element("option");
    exports.output = _element("output");
    exports.p = _element("p");
    exports.picture = _element("picture");
    exports.pre = _element("pre");
    exports.progress = _element("progress");
    exports.q = _element("q");
    exports.rp = _element("rp");
    exports.rt = _element("rt");
    exports.ruby = _element("ruby");
    exports.s = _element("s");
    exports.samp = _element("samp");
    exports.script = _element("script");
    exports.search = _element("search");
    exports.section = _element("section");
    exports.select = _element("select");
    exports.slot = _element("slot");
    exports.small = _element("small");
    exports.source = _element("source");
    exports.span = _element("span");
    exports.strong = _element("strong");
    exports.style = _element("style");
    exports.sub = _element("sub");
    exports.summary = _element("summary");
    exports.sup = _element("sup");
    exports.table = _element("table");
    exports.tbody = _element("tbody");
    exports.td = _element("td");
    exports.template = _element("template");
    exports.textarea = _element("textarea");
    exports.tfoot = _element("tfoot");
    exports.th = _element("th");
    exports.thead = _element("thead");
    exports.time = _element("time");
    exports.title = _element("title");
    exports.tr = _element("tr");
    exports.track = _element("track");
    exports.u = _element("u");
    exports.ul = _element("ul");
    exports.video = _element("video");
    exports.wbr = _element("wbr");
    function createSVGElement(tag, attrs = null, ...children) {
        const element = document.createElementNS("http://www.w3.org/2000/svg", tag);
        for (const [attr, value] of (0, object_1.entries)(attrs ?? {})) {
            if (value == null || value === false) {
                continue;
            }
            element.setAttribute(attr, value);
        }
        function append(child) {
            if ((0, types_1.isString)(child)) {
                element.appendChild(document.createTextNode(child));
            }
            else if (child instanceof Node) {
                element.appendChild(child);
            }
            else if (child instanceof NodeList || child instanceof HTMLCollection) {
                for (const el of child) {
                    element.appendChild(el);
                }
            }
            else if (child != null && child !== false) {
                throw new Error(`expected a DOM element, string, false or null, got ${JSON.stringify(child)}`);
            }
        }
        for (const child of children) {
            if ((0, types_1.isArray)(child)) {
                for (const _child of child) {
                    append(_child);
                }
            }
            else {
                append(child);
            }
        }
        return element;
    }
    function text(str) {
        return document.createTextNode(str);
    }
    function nbsp() {
        return text("\u00a0");
    }
    function prepend(element, ...nodes) {
        const first = element.firstChild;
        for (const node of nodes) {
            element.insertBefore(node, first);
        }
    }
    function empty(node, attrs = false) {
        let child;
        while ((child = node.firstChild) != null) {
            node.removeChild(child);
        }
        if (attrs && node instanceof Element) {
            for (const attr of node.attributes) {
                node.removeAttributeNode(attr);
            }
        }
    }
    function contains(element, child) {
        /**
         * Like Node.contains(), but traverses Shadow DOM boundaries.
         */
        let current = child;
        while (current.parentNode != null) {
            const parent = current.parentNode;
            if (parent == element) {
                return true;
            }
            else if (parent instanceof ShadowRoot) {
                current = parent.host;
            }
            else {
                current = parent;
            }
        }
        return false;
    }
    function display(element, display = true) {
        element.style.display = display ? "" : "none";
    }
    function undisplay(element) {
        element.style.display = "none";
    }
    function show(element) {
        element.style.visibility = "";
    }
    function hide(element) {
        element.style.visibility = "hidden";
    }
    function offset_bbox(element) {
        const { top, left, width, height } = element.getBoundingClientRect();
        return new bbox_1.BBox({
            left: left + scrollX - document.documentElement.clientLeft,
            top: top + scrollY - document.documentElement.clientTop,
            width,
            height,
        });
    }
    function parent(el, selector) {
        let node = el;
        while ((node = node.parentElement) != null) {
            if (node.matches(selector)) {
                return node;
            }
        }
        return null;
    }
    function num(value) {
        const num = parseFloat(value);
        return isFinite(num) ? num : 0;
    }
    function extents(el) {
        const style = getComputedStyle(el);
        return {
            border: {
                top: num(style.borderTopWidth),
                bottom: num(style.borderBottomWidth),
                left: num(style.borderLeftWidth),
                right: num(style.borderRightWidth),
            },
            margin: {
                top: num(style.marginTop),
                bottom: num(style.marginBottom),
                left: num(style.marginLeft),
                right: num(style.marginRight),
            },
            padding: {
                top: num(style.paddingTop),
                bottom: num(style.paddingBottom),
                left: num(style.paddingLeft),
                right: num(style.paddingRight),
            },
        };
    }
    function size(el) {
        const rect = el.getBoundingClientRect();
        return {
            width: Math.ceil(rect.width),
            height: Math.ceil(rect.height),
        };
    }
    function scroll_size(el) {
        return {
            width: Math.ceil(el.scrollWidth),
            height: Math.ceil(el.scrollHeight),
        };
    }
    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),
        };
    }
    function content_size(el) {
        const { left, top } = el.getBoundingClientRect();
        const { padding } = extents(el);
        let width = 0;
        let height = 0;
        for (const child of (el.shadowRoot ?? 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 };
    }
    function bounding_box(el) {
        const { x, y, width, height } = el.getBoundingClientRect();
        return new bbox_1.BBox({ x, y, width, height });
    }
    function box_size(el) {
        const { width, height } = el.getBoundingClientRect();
        return { width, height };
    }
    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`;
        }
    }
    class ClassList {
        constructor(class_list) {
            this.class_list = class_list;
        }
        get values() {
            const values = [];
            for (let i = 0; i < this.class_list.length; i++) {
                const item = this.class_list.item(i);
                if (item != null) {
                    values.push(item);
                }
            }
            return values;
        }
        has(cls) {
            return this.class_list.contains(cls);
        }
        add(...classes) {
            for (const cls of classes) {
                this.class_list.add(cls);
            }
            return this;
        }
        remove(...classes) {
            for (const cls of classes) {
                if ((0, types_1.isArray)(cls)) {
                    cls.forEach((cls) => this.class_list.remove(cls));
                }
                else {
                    this.class_list.remove(cls);
                }
            }
            return this;
        }
        clear() {
            for (const cls of this.values) {
                this.class_list.remove(cls);
            }
            return this;
        }
        toggle(cls, activate) {
            const add = activate != null ? activate : !this.has(cls);
            if (add) {
                this.add(cls);
            }
            else {
                this.remove(cls);
            }
            return this;
        }
    }
    exports.ClassList = ClassList;
    ClassList.__name__ = "ClassList";
    function classes(el) {
        return new ClassList(el.classList);
    }
    function toggle_attribute(el, attr, state) {
        if (state == null) {
            state = !el.hasAttribute(attr);
        }
        if (state) {
            el.setAttribute(attr, "true");
        }
        else {
            el.removeAttribute(attr);
        }
    }
    (function (MouseButton) {
        MouseButton[MouseButton["None"] = 0] = "None";
        MouseButton[MouseButton["Primary"] = 1] = "Primary";
        MouseButton[MouseButton["Secondary"] = 2] = "Secondary";
        MouseButton[MouseButton["Auxiliary"] = 4] = "Auxiliary";
        MouseButton[MouseButton["Left"] = 1] = "Left";
        MouseButton[MouseButton["Right"] = 2] = "Right";
        MouseButton[MouseButton["Middle"] = 4] = "Middle";
    })(exports.MouseButton || (exports.MouseButton = {}));
    class StyleSheet {
        install(el) {
            el.append(this.el);
        }
        uninstall() {
            this.el.remove();
        }
    }
    exports.StyleSheet = StyleSheet;
    StyleSheet.__name__ = "StyleSheet";
    class InlineStyleSheet extends StyleSheet {
        constructor(css) {
            super();
            this.el = (0, exports.style)();
            if ((0, types_1.isString)(css)) {
                this._update(css);
            }
            else if (css != null) {
                this._update((0, css_1.compose_stylesheet)(css));
            }
        }
        get css() {
            return this.el.textContent ?? "";
        }
        _update(css) {
            this.el.textContent = css;
        }
        clear() {
            this.replace("");
        }
        _to_css(css, styles) {
            if (styles == null) {
                return css;
            }
            else {
                return (0, css_1.compose_stylesheet)({ [css]: styles });
            }
        }
        replace(css, styles) {
            this._update(this._to_css(css, styles));
        }
        prepend(css, styles) {
            this._update(`${this._to_css(css, styles)}\n${this.css}`);
        }
        append(css, styles) {
            this._update(`${this.css}\n${this._to_css(css, styles)}`);
        }
        remove() {
            this.el.remove();
        }
    }
    exports.InlineStyleSheet = InlineStyleSheet;
    InlineStyleSheet.__name__ = "InlineStyleSheet";
    class GlobalInlineStyleSheet extends InlineStyleSheet {
        install() {
            if (!this.el.isConnected) {
                document.head.appendChild(this.el);
            }
        }
    }
    exports.GlobalInlineStyleSheet = GlobalInlineStyleSheet;
    GlobalInlineStyleSheet.__name__ = "GlobalInlineStyleSheet";
    class ImportedStyleSheet extends StyleSheet {
        constructor(url) {
            super();
            this.el = (0, exports.link)({ rel: "stylesheet", href: url });
        }
        replace(url) {
            this.el.href = url;
        }
        remove() {
            this.el.remove();
        }
    }
    exports.ImportedStyleSheet = ImportedStyleSheet;
    ImportedStyleSheet.__name__ = "ImportedStyleSheet";
    class GlobalImportedStyleSheet extends ImportedStyleSheet {
        install() {
            if (!this.el.isConnected) {
                document.head.appendChild(this.el);
            }
        }
    }
    exports.GlobalImportedStyleSheet = GlobalImportedStyleSheet;
    GlobalImportedStyleSheet.__name__ = "GlobalImportedStyleSheet";
    async function dom_ready() {
        if (document.readyState == "loading") {
            return new Promise((resolve, _reject) => {
                document.addEventListener("DOMContentLoaded", () => resolve(), { once: true });
            });
        }
    }
    function px(value) {
        return (0, types_1.isNumber)(value) ? `${value}px` : value;
    }
    exports.supports_adopted_stylesheets = "adoptedStyleSheets" in ShadowRoot.prototype;
},
/* core/util/bbox.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.empty = empty;
    exports.positive_x = positive_x;
    exports.positive_y = positive_y;
    exports.union = union;
    exports.isXY = isXY;
    const types_1 = require(24) /* ../types */;
    const eq_1 = require(26) /* ./eq */;
    const arrayable_1 = require(13) /* ./arrayable */;
    const types_2 = require(8) /* ./types */;
    const { min, max, round } = Math;
    function empty() {
        return {
            x0: Infinity,
            y0: Infinity,
            x1: -Infinity,
            y1: -Infinity,
        };
    }
    function positive_x() {
        return {
            x0: Number.MIN_VALUE,
            y0: -Infinity,
            x1: Infinity,
            y1: Infinity,
        };
    }
    function positive_y() {
        return {
            x0: -Infinity,
            y0: Number.MIN_VALUE,
            x1: Infinity,
            y1: Infinity,
        };
    }
    function _min(a, b) {
        if (isNaN(a)) {
            return b;
        }
        else if (isNaN(b)) {
            return a;
        }
        else {
            return min(a, b);
        }
    }
    function _max(a, b) {
        if (isNaN(a)) {
            return b;
        }
        else if (isNaN(b)) {
            return a;
        }
        else {
            return max(a, b);
        }
    }
    function union(a, b) {
        return {
            x0: _min(a.x0, b.x0),
            x1: _max(a.x1, b.x1),
            y0: _min(a.y0, b.y0),
            y1: _max(a.y1, b.y1),
        };
    }
    function isXY(obj) {
        return (0, types_2.isPlainObject)(obj) && "x" in obj && "y" in obj;
    }
    class BBox {
        constructor(box, correct = false) {
            if (box == null) {
                this.x0 = 0;
                this.y0 = 0;
                this.x1 = 0;
                this.y1 = 0;
            }
            else if ("x0" in box) {
                const { x0, y0, x1, y1 } = box;
                if (!isFinite(x0 + y0 + x1 + y1)) {
                    this.x0 = NaN;
                    this.y0 = NaN;
                    this.x1 = NaN;
                    this.y1 = NaN;
                }
                else {
                    if (!(x0 <= x1 && y0 <= y1)) {
                        throw new Error(`invalid bbox {x0: ${x0}, y0: ${y0}, x1: ${x1}, y1: ${y1}}`);
                    }
                    this.x0 = x0;
                    this.y0 = y0;
                    this.x1 = x1;
                    this.y1 = y1;
                }
            }
            else if ("x" in box) {
                const { x, y, width, height, origin = "top_left" } = box;
                if (!(width >= 0 && height >= 0)) {
                    throw new Error(`invalid bbox {x: ${x}, y: ${y}, width: ${width}, height: ${height}}`);
                }
                const base_origin = (() => {
                    switch (origin) {
                        case "left": return "center_left";
                        case "right": return "center_right";
                        case "top": return "top_center";
                        case "bottom": return "bottom_center";
                        case "center": return "center_center";
                        default: return origin;
                    }
                })();
                const [y_align, x_align] = base_origin.split("_", 2);
                const y_coeff = (() => {
                    switch (y_align) {
                        case "top": return 0.0;
                        case "center": return 0.5;
                        case "bottom": return 1.0;
                    }
                })();
                const x_coeff = (() => {
                    switch (x_align) {
                        case "left": return 0.0;
                        case "center": return 0.5;
                        case "right": return 1.0;
                    }
                })();
                const d_width = x_coeff * width;
                const d_height = y_coeff * height;
                const x0 = x - d_width;
                const y0 = y - d_height;
                const x1 = x0 + width;
                const y1 = y0 + height;
                this.x0 = x0;
                this.y0 = y0;
                this.x1 = x1;
                this.y1 = y1;
            }
            else {
                let left, right;
                let top, bottom;
                if ("width" in box) {
                    if ("left" in box) {
                        left = box.left;
                        right = left + box.width;
                    }
                    else if ("right" in box) {
                        right = box.right;
                        left = right - box.width;
                    }
                    else {
                        const w2 = box.width / 2;
                        left = box.hcenter - w2;
                        right = box.hcenter + w2;
                    }
                }
                else {
                    left = box.left;
                    right = box.right;
                }
                if ("height" in box) {
                    if ("top" in box) {
                        top = box.top;
                        bottom = top + box.height;
                    }
                    else if ("bottom" in box) {
                        bottom = box.bottom;
                        top = bottom - box.height;
                    }
                    else {
                        const h2 = box.height / 2;
                        top = box.vcenter - h2;
                        bottom = box.vcenter + h2;
                    }
                }
                else {
                    top = box.top;
                    bottom = box.bottom;
                }
                if (left > right || top > bottom) {
                    if (correct) {
                        if (left > right) {
                            left = right;
                        }
                        if (top > bottom) {
                            top = bottom;
                        }
                    }
                    else {
                        throw new Error(`invalid bbox {left: ${left}, top: ${top}, right: ${right}, bottom: ${bottom}}`);
                    }
                }
                this.x0 = left;
                this.y0 = top;
                this.x1 = right;
                this.y1 = bottom;
            }
        }
        static from_lrtb({ left, right, top, bottom }) {
            return new BBox({
                x0: min(left, right),
                y0: min(top, bottom),
                x1: max(left, right),
                y1: max(top, bottom),
            });
        }
        static from_rect({ x0, y0, x1, y1 }) {
            return new BBox({
                x0: min(x0, x1),
                y0: min(y0, y1),
                x1: max(x0, x1),
                y1: max(y0, y1),
            });
        }
        static empty() {
            return new BBox({ x0: 0, y0: 0, x1: 0, y1: 0 });
        }
        static invalid() {
            return new BBox({ x0: NaN, y0: NaN, x1: NaN, y1: NaN });
        }
        clone() {
            return new BBox(this);
        }
        equals(that) {
            return this.x0 == that.x0 && this.y0 == that.y0 &&
                this.x1 == that.x1 && this.y1 == that.y1;
        }
        [eq_1.equals](that, cmp) {
            return cmp.eq(this.x0, that.x0) && cmp.eq(this.y0, that.y0) &&
                cmp.eq(this.x1, that.x1) && cmp.eq(this.y1, that.y1);
        }
        toString() {
            return `BBox({left: ${this.left}, top: ${this.top}, width: ${this.width}, height: ${this.height}})`;
        }
        get is_valid() {
            const { x0, x1, y0, y1 } = this;
            return isFinite(x0 + x1 + y0 + y1);
        }
        get is_empty() {
            const { x0, x1, y0, y1 } = this;
            return x0 == 0 && x1 == 0 && y0 == 0 && y1 == 0;
        }
        get left() {
            return this.x0;
        }
        get top() {
            return this.y0;
        }
        get right() {
            return this.x1;
        }
        get bottom() {
            return this.y1;
        }
        get p0() {
            return { x: this.x0, y: this.y0 };
        }
        get p1() {
            return { x: this.x1, y: this.y1 };
        }
        get x() {
            return this.x0;
        }
        get y() {
            return this.y0;
        }
        get width() {
            return this.x1 - this.x0;
        }
        get height() {
            return this.y1 - this.y0;
        }
        get size() {
            return { width: this.width, height: this.height };
        }
        get rect() {
            const { x0, y0, x1, y1 } = this;
            return {
                p0: { x: x0, y: y0 },
                p1: { x: x1, y: y0 },
                p2: { x: x1, y: y1 },
                p3: { x: x0, y: y1 },
            };
        }
        get box() {
            const { x, y, width, height } = this;
            return { x, y, width, height };
        }
        get lrtb() {
            const { left, right, top, bottom } = this;
            return { left, right, top, bottom };
        }
        get x_range() {
            return { start: this.x0, end: this.x1 };
        }
        get y_range() {
            return { start: this.y0, end: this.y1 };
        }
        get h_range() {
            return this.x_range;
        }
        get v_range() {
            return this.y_range;
        }
        get ranges() {
            return [this.x_range, this.y_range];
        }
        get aspect() {
            return this.width / this.height;
        }
        get x_center() {
            return (this.left + this.right) / 2;
        }
        get y_center() {
            return (this.top + this.bottom) / 2;
        }
        get hcenter() {
            return this.x_center;
        }
        get vcenter() {
            return this.y_center;
        }
        get area() {
            return this.width * this.height;
        }
        resolve(symbol) {
            switch (symbol) {
                case "top_left": return this.top_left;
                case "top_center": return this.top_center;
                case "top_right": return this.top_right;
                case "center_left": return this.center_left;
                case "center_center": return this.center_center;
                case "center_right": return this.center_right;
                case "bottom_left": return this.bottom_left;
                case "bottom_center": return this.bottom_center;
                case "bottom_right": return this.bottom_right;
                case "center": return this.center;
                case "top": return this.top;
                case "left": return this.left;
                case "right": return this.right;
                case "bottom": return this.bottom;
                case "width": return this.width;
                case "height": return this.height;
                default: return { x: NaN, y: NaN };
            }
        }
        get top_left() {
            return { x: this.left, y: this.top };
        }
        get top_center() {
            return { x: this.hcenter, y: this.top };
        }
        get top_right() {
            return { x: this.right, y: this.top };
        }
        get center_left() {
            return { x: this.left, y: this.vcenter };
        }
        get center_center() {
            return { x: this.hcenter, y: this.vcenter };
        }
        get center_right() {
            return { x: this.right, y: this.vcenter };
        }
        get bottom_left() {
            return { x: this.left, y: this.bottom };
        }
        get bottom_center() {
            return { x: this.hcenter, y: this.bottom };
        }
        get bottom_right() {
            return { x: this.right, y: this.bottom };
        }
        get center() {
            return { x: this.hcenter, y: this.vcenter };
        }
        round() {
            return new BBox({
                x0: round(this.x0),
                x1: round(this.x1),
                y0: round(this.y0),
                y1: round(this.y1),
            });
        }
        relative() {
            const { width, height } = this;
            return new BBox({ x: 0, y: 0, width, height });
        }
        translate(tx, ty) {
            const { x, y, width, height } = this;
            return new BBox({ x: tx + x, y: ty + y, width, height });
        }
        scale(factor) {
            return new BBox({
                x0: this.x0 * factor,
                x1: this.x1 * factor,
                y0: this.y0 * factor,
                y1: this.y1 * factor,
            });
        }
        relativize(x, y) {
            return [x - this.x, y - this.y];
        }
        contains(x, y) {
            return this.x0 <= x && x <= this.x1 && this.y0 <= y && y <= this.y1;
        }
        clip(x, y) {
            if (x < this.x0) {
                x = this.x0;
            }
            else if (x > this.x1) {
                x = this.x1;
            }
            if (y < this.y0) {
                y = this.y0;
            }
            else if (y > this.y1) {
                y = this.y1;
            }
            return [x, y];
        }
        grow_by(size) {
            return new BBox({
                left: this.left - size,
                right: this.right + size,
                top: this.top - size,
                bottom: this.bottom + size,
            });
        }
        shrink_by(size) {
            return new BBox({
                left: this.left + size,
                right: this.right - size,
                top: this.top + size,
                bottom: this.bottom - size,
            }, true);
        }
        union(that) {
            return new BBox({
                x0: min(this.x0, that.x0),
                y0: min(this.y0, that.y0),
                x1: max(this.x1, that.x1),
                y1: max(this.y1, that.y1),
            });
        }
        intersection(that) {
            if (!this.intersects(that)) {
                return null;
            }
            else {
                return new BBox({
                    x0: max(this.x0, that.x0),
                    y0: max(this.y0, that.y0),
                    x1: min(this.x1, that.x1),
                    y1: min(this.y1, that.y1),
                });
            }
        }
        intersects(that) {
            return !(that.x1 < this.x0 || that.x0 > this.x1 ||
                that.y1 < this.y0 || that.y0 > this.y1);
        }
        get x_percent() {
            const self = this;
            return this._x_percent ?? (this._x_percent = {
                compute(x) {
                    return self.left + x * self.width;
                },
                invert(sx) {
                    return (sx - self.left) / self.width;
                },
                v_compute(xs) {
                    const { left, width } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(xs, (x) => left + x * width));
                },
                v_invert(sxs) {
                    const { left, width } = self;
                    return (0, arrayable_1.map)(sxs, (sx) => (sx - left) / width);
                },
                get source_range() {
                    return self.x_range;
                },
                get target_range() {
                    return self.x_range;
                },
            });
        }
        get y_percent() {
            const self = this;
            return this._y_percent ?? (this._y_percent = {
                compute(y) {
                    return self.top + y * self.height;
                },
                invert(sy) {
                    return (sy - self.top) / self.height;
                },
                v_compute(ys) {
                    const { top, height } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(ys, (y) => top + y * height));
                },
                v_invert(sys) {
                    const { top, height } = self;
                    return (0, arrayable_1.map)(sys, (sy) => (sy - top) / height);
                },
                get source_range() {
                    return self.y_range;
                },
                get target_range() {
                    return self.y_range;
                },
            });
        }
        get x_screen() {
            const self = this;
            return this._x_screen ?? (this._x_screen = {
                compute(x) {
                    return self.left + x;
                },
                invert(sx) {
                    return sx - self.left;
                },
                v_compute(xs) {
                    const { left } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(xs, (x) => left + x));
                },
                v_invert(sxs) {
                    const { left } = self;
                    return (0, arrayable_1.map)(sxs, (sx) => sx - left);
                },
                get source_range() {
                    return self.x_range;
                },
                get target_range() {
                    return self.x_range;
                },
            });
        }
        get y_screen() {
            const self = this;
            return this._y_screen ?? (this._y_screen = {
                compute(y) {
                    return self.top + y;
                },
                invert(sy) {
                    return sy - self.top;
                },
                v_compute(ys) {
                    const { top } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(ys, (y) => top + y));
                },
                v_invert(sys) {
                    const { top } = self;
                    return (0, arrayable_1.map)(sys, (sy) => sy - top);
                },
                get source_range() {
                    return self.y_range;
                },
                get target_range() {
                    return self.y_range;
                },
            });
        }
        get x_view() {
            const self = this;
            return this._x_view ?? (this._x_view = {
                compute(x) {
                    return self.left + x;
                },
                invert(sx) {
                    return sx - self.left;
                },
                v_compute(xs) {
                    const { left } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(xs, (x) => left + x));
                },
                v_invert(sxs) {
                    const { left } = self;
                    return (0, arrayable_1.map)(sxs, (sx) => sx - left);
                },
                get source_range() {
                    return self.x_range;
                },
                get target_range() {
                    return self.x_range;
                },
            });
        }
        get y_view() {
            const self = this;
            return this._y_view ?? (this._y_view = {
                compute(y) {
                    return self.bottom - y;
                },
                invert(sy) {
                    return self.bottom - sy;
                },
                v_compute(ys) {
                    const { bottom } = self;
                    return new types_1.ScreenArray((0, arrayable_1.map)(ys, (y) => bottom - y));
                },
                v_invert(sys) {
                    const { bottom } = self;
                    return (0, arrayable_1.map)(sys, (sy) => bottom - sy);
                },
                get source_range() {
                    return self.y_range;
                },
                get target_range() {
                    return { start: self.bottom, end: self.top };
                },
            });
        }
        get xview() {
            return this.x_view;
        }
        get yview() {
            return this.y_view;
        }
    }
    exports.BBox = BBox;
    BBox.__name__ = "BBox";
},
/* core/css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.apply_styles = apply_styles;
    exports.compose_stylesheet = compose_stylesheet;
    const logging_1 = require(19) /* ./logging */;
    const object_1 = require(9) /* ./util/object */;
    const types_1 = require(8) /* ./util/types */;
    const _style_decl = document.createElement("div").style;
    function _css_name(attr) {
        if (attr.startsWith("--")) {
            return attr;
        }
        const name = attr.replaceAll(/_/g, "-").replaceAll(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
        // XXX hasOwnProperty() doesn't work for unknown reasons (e.g. in Firefox)
        if (name in _style_decl) {
            return name;
        }
        const webkit_name = `-webkit-${name}`;
        if (webkit_name in _style_decl) {
            return webkit_name;
        }
        const moz_name = `-moz-${name}`;
        if (moz_name in _style_decl) {
            return moz_name;
        }
        logging_1.logger.warn(`unknown CSS property '${attr}'`);
        return null;
    }
    function* _iter_styles(styles) {
        if ((0, types_1.isPlainObject)(styles) || styles instanceof Map) {
            for (const [key, val] of (0, object_1.entries)(styles)) {
                const name = _css_name(key);
                if (name != null) {
                    yield [name, val];
                }
            }
        }
        else {
            for (const prop of styles.own_properties()) {
                if (prop.dirty) {
                    const name = _css_name(prop.attr);
                    if (name != null) {
                        yield [name, prop.get_value()];
                    }
                }
            }
        }
    }
    function apply_styles(declaration, styles) {
        for (const [name, value] of _iter_styles(styles)) {
            if ((0, types_1.isString)(value)) {
                declaration.setProperty(name, value);
            }
            else {
                declaration.removeProperty(name);
            }
        }
    }
    function compose_stylesheet(stylesheet) {
        const css = [];
        for (const [selector, styles] of (0, object_1.entries)(stylesheet)) {
            css.push(`${selector} {`);
            for (const [name, value] of _iter_styles(styles)) {
                if ((0, types_1.isString)(value) && value.length != 0) {
                    css.push(`  ${name}: ${value};`);
                }
            }
            css.push("}");
        }
        return css.join("\n");
    }
},
/* styles/base.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{--base-font:var(--bokeh-base-font, Helvetica, Arial, sans-serif);--mono-font:var(--bokeh-mono-font, monospace);--font-size:var(--bokeh-font-size, 12px);--line-height:calc(20 / 14);--line-height-computed:calc(var(--font-size) * var(--line-height));--border-radius:4px;--padding-vertical:6px;--padding-horizontal:12px;--bokeh-top-level:10000;}:host{box-sizing:border-box;font-family:var(--base-font);font-size:var(--font-size);line-height:var(--line-height);}*,*:before,*:after{box-sizing:inherit;font-family:inherit;}pre,code{font-family:var(--mono-font);margin:0;}`;
},
/* embed/server.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports._get_ws_url = _get_ws_url;
    exports.add_document_from_session = add_document_from_session;
    const connection_1 = require(68) /* ../client/connection */;
    const logging_1 = require(19) /* ../core/logging */;
    const standalone_1 = require(54) /* ./standalone */;
    // @internal
    function _get_ws_url(app_path, absolute_url) {
        // if in an `srcdoc` iframe, try to get the absolute URL
        // from the `data-absolute-url` attribute if not passed explicitly
        if (absolute_url === undefined && _is_frame_HTMLElement(frameElement) && frameElement.dataset.absoluteUrl !== undefined) {
            absolute_url = frameElement.dataset.absoluteUrl;
        }
        let loc;
        if (absolute_url != null) {
            loc = document.createElement("a");
            loc.href = absolute_url;
        }
        else {
            loc = window.location;
        }
        const protocol = loc.protocol == "https:" ? "wss:" : "ws:";
        if (app_path != null) {
            if (app_path == "/") {
                app_path = "";
            }
        }
        else {
            app_path = loc.pathname.replace(/\/+$/, "");
        }
        return `${protocol}//${loc.host}${app_path}/ws`;
    }
    function _is_frame_HTMLElement(frame) {
        // `frameElement` is a delicate construct; it allows the document inside the frame to access
        // some (but not all) properties of the parent element in which the frame document is embedded.
        // Because it lives in a different DOM context than the frame's `window`, we cannot just use
        // `frameElement instanceof HTMLIFrameElement`; we could use `window.parent.HTMLIFrameElement`
        // but this can be blocked by CORS policy and throw an exception.
        if (frame === null) {
            return false;
        }
        if (frame.tagName.toUpperCase() === "IFRAME") {
            return true;
        }
        return false;
    }
    const _sessions = new Map();
    function _get_session(websocket_url, token, args_string) {
        const session_id = (0, connection_1.parse_token)(token).session_id;
        if (!_sessions.has(websocket_url)) {
            _sessions.set(websocket_url, new Map());
        }
        const subsessions = _sessions.get(websocket_url);
        if (!subsessions.has(session_id)) {
            subsessions.set(session_id, (0, connection_1.pull_session)(websocket_url, token, args_string));
        }
        return subsessions.get(session_id);
    }
    // Fill element with the roots from token
    async function add_document_from_session(websocket_url, token, element, roots = [], use_for_title = false) {
        const args_string = window.location.search.substring(1);
        let session;
        try {
            session = await _get_session(websocket_url, token, args_string);
        }
        catch (error) {
            const session_id = (0, connection_1.parse_token)(token).session_id;
            logging_1.logger.error(`Failed to load Bokeh session ${session_id}: ${error}`);
            throw error;
        }
        return (0, standalone_1.add_document_standalone)(session.document, element, roots, use_for_title);
    }
},
/* client/connection.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.parse_token = parse_token;
    exports.pull_session = pull_session;
    const logging_1 = require(19) /* ../core/logging */;
    const document_1 = require(5) /* ../document */;
    const message_1 = require(69) /* ../protocol/message */;
    const receiver_1 = require(70) /* ../protocol/receiver */;
    const session_1 = require(71) /* ./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, "+")));
    }
    class ClientConnection {
        constructor(url = exports.DEFAULT_SERVER_WEBSOCKET_URL, token = exports.DEFAULT_TOKEN, args_string = null) {
            this._number = _connection_count++;
            this.socket = null;
            this.session = null;
            this.closed_permanently = false;
            this._current_handler = null;
            this._pending_replies = new Map();
            this._pending_messages = [];
            this._receiver = new receiver_1.Receiver();
            this.url = url;
            this.token = token;
            this.args_string = args_string;
            this.id = parse_token(token).session_id.split(".")[0];
            logging_1.logger.debug(`Creating websocket ${this._number} to '${this.url}' session '${this.id}'`);
        }
        async connect() {
            if (this.closed_permanently) {
                throw new Error("Cannot connect() a closed ClientConnection");
            }
            if (this.socket != null) {
                throw new Error("Already connected");
            }
            this._current_handler = null;
            this._pending_replies.clear();
            this._pending_messages = [];
            try {
                let versioned_url = `${this.url}`;
                if (this.args_string != null && this.args_string.length > 0) {
                    versioned_url += `?${this.args_string}`;
                }
                this.socket = new WebSocket(versioned_url, ["bokeh", this.token]);
                return new Promise((resolve, reject) => {
                    // "arraybuffer" gives us binary data we can look at;
                    // if we just needed an opaque blob we could use "blob"
                    this.socket.binaryType = "arraybuffer";
                    this.socket.onopen = () => this._on_open(resolve, reject);
                    this.socket.onmessage = (event) => this._on_message(event);
                    this.socket.onclose = (event) => this._on_close(event, reject);
                    this.socket.onerror = () => this._on_error(reject);
                });
            }
            catch (error) {
                logging_1.logger.error(`websocket creation failed to url: ${this.url}`);
                logging_1.logger.error(` - ${error}`);
                throw error;
            }
        }
        close() {
            if (!this.closed_permanently) {
                logging_1.logger.debug(`Permanently closing websocket connection ${this._number}`);
                this.closed_permanently = true;
                if (this.socket != null) {
                    this.socket.close(1000, `close method called on ClientConnection ${this._number}`);
                }
                this.session._connection_closed();
            }
        }
        _schedule_reconnect(milliseconds) {
            const retry = () => {
                // 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`);
                    this.session?.notify_connection_lost();
                }
                return;
                /*
                } else {
                  logger.debug(`Attempting to reconnect websocket ${this._number}`)
                  this.connect()
                }
                */
            };
            setTimeout(retry, milliseconds);
        }
        send(message) {
            if (this.socket != null) {
                message.send(this.socket);
            }
            else {
                logging_1.logger.error("not connected so cannot send", message);
            }
        }
        async send_with_reply(message) {
            const reply = await new Promise((resolve, reject) => {
                this._pending_replies.set(message.msgid(), { resolve, reject });
                this.send(message);
            });
            if (reply.msgtype() == "ERROR") {
                throw new Error(`Error reply ${reply.content.text}`);
            }
            else {
                return reply;
            }
        }
        async _pull_doc_json() {
            const message = message_1.Message.create("PULL-DOC-REQ", {}, {});
            const reply = await this.send_with_reply(message);
            if (!("doc" in reply.content)) {
                throw new Error("No 'doc' field in PULL-DOC-REPLY");
            }
            return reply.content.doc;
        }
        async _repull_session_doc(resolve, reject) {
            logging_1.logger.debug(this.session != null ? "Repulling session" : "Pulling session for first time");
            try {
                const doc_json = await this._pull_doc_json();
                if (this.session == null) {
                    if (this.closed_permanently) {
                        logging_1.logger.debug("Got new document after connection was already closed");
                        reject(new Error("The connection has been closed"));
                    }
                    else {
                        const events = [];
                        const document = document_1.Document.from_json(doc_json, events);
                        this.session = new session_1.ClientSession(this, document);
                        // Send back change events that happend during model initialization.
                        for (const event of events) {
                            document._trigger_on_change(event);
                        }
                        for (const msg of this._pending_messages) {
                            this.session.handle(msg);
                        }
                        this._pending_messages = [];
                        logging_1.logger.debug("Created a new session from new pulled doc");
                        resolve(this.session);
                    }
                }
                else {
                    this.session.document.replace_with_json(doc_json);
                    logging_1.logger.debug("Updated existing session with new pulled doc");
                    // Since the session already exists, we don't need to call `resolve` again.
                }
            }
            catch (error) {
                console.trace(error);
                logging_1.logger.error(`Failed to repull session ${error}`);
                reject(error instanceof Error ? error : `${error}`);
            }
        }
        _on_open(resolve, reject) {
            logging_1.logger.info(`Websocket connection ${this._number} is now open`);
            this._current_handler = (message) => {
                this._awaiting_ack_handler(message, resolve, reject);
            };
        }
        _on_message(event) {
            if (this._current_handler == null) {
                logging_1.logger.error("Got a message with no current handler set");
            }
            try {
                this._receiver.consume(event.data);
            }
            catch (e) {
                this._close_bad_protocol(`${e}`);
            }
            const msg = this._receiver.message;
            if (msg != null) {
                const problem = msg.problem();
                if (problem != null) {
                    this._close_bad_protocol(problem);
                }
                this._current_handler(msg);
            }
        }
        _on_close(event, reject) {
            logging_1.logger.info(`Lost websocket ${this._number} connection, ${event.code} (${event.reason})`);
            this.socket = null;
            this._pending_replies.forEach((pr) => pr.reject("Disconnected"));
            this._pending_replies.clear();
            if (!this.closed_permanently) {
                this._schedule_reconnect(2000);
            }
            reject(new Error(`Lost websocket connection, ${event.code} (${event.reason})`));
        }
        _on_error(reject) {
            logging_1.logger.debug(`Websocket error on socket ${this._number}`);
            const msg = "Could not open websocket";
            logging_1.logger.error(`Failed to connect to Bokeh server: ${msg}`);
            reject(new Error(msg));
        }
        _close_bad_protocol(detail) {
            logging_1.logger.error(`Closing connection: ${detail}`);
            if (this.socket != null) {
                this.socket.close(1002, detail);
            } // 1002 = protocol error
        }
        _awaiting_ack_handler(message, resolve, reject) {
            if (message.msgtype() === "ACK") {
                this._current_handler = (message) => this._steady_state_handler(message);
                // Reload any sessions
                void this._repull_session_doc(resolve, reject);
            }
            else {
                this._close_bad_protocol("First message was not an ACK");
            }
        }
        _steady_state_handler(message) {
            const reqid = message.reqid();
            const pr = this._pending_replies.get(reqid);
            if (pr != null) {
                this._pending_replies.delete(reqid);
                pr.resolve(message);
            }
            else if (this.session != null) {
                this.session.handle(message);
            }
            else if (message.msgtype() != "PATCH-DOC") {
                // This branch can be executed only before we get the document.
                // When we get the document, all of the patches will already be incorporated.
                // In general, it's not possible to apply patches received before the document,
                // since they may change some models that were removed before serving the document.
                this._pending_messages.push(message);
            }
        }
    }
    exports.ClientConnection = ClientConnection;
    ClientConnection.__name__ = "ClientConnection";
    function pull_session(url, token, args_string) {
        const connection = new ClientConnection(url, token, args_string);
        return connection.connect();
    }
},
/* protocol/message.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const serialization_1 = require(32) /* ../core/serialization */;
    const string_1 = require(40) /* ../core/util/string */;
    const assert_1 = require(12) /* ../core/util/assert */;
    class Message {
        get buffers() {
            return this._buffers;
        }
        constructor(header, metadata, content) {
            this._buffers = new Map();
            this.header = header;
            this.metadata = metadata;
            this.content = content;
        }
        static assemble(header_json, metadata_json, content_json) {
            const header = JSON.parse(header_json);
            const metadata = JSON.parse(metadata_json);
            const content = JSON.parse(content_json);
            return new Message(header, metadata, content);
        }
        assemble_buffer(buf_header, buf_payload) {
            const nb = 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);
        }
        static create(msgtype, metadata, content) {
            const header = Message.create_header(msgtype);
            return new Message(header, metadata, content);
        }
        static create_header(msgtype) {
            return {
                msgid: (0, string_1.unique_id)(),
                msgtype,
            };
        }
        complete() {
            const { num_buffers } = this.header;
            return num_buffers == null || this._buffers.size == num_buffers;
        }
        send(socket) {
            (0, assert_1.assert)(this.header.num_buffers == null);
            const buffers = [];
            const content_json = JSON.stringify(this.content, (_, val) => {
                if (val instanceof serialization_1.Buffer) {
                    const ref = { id: `${buffers.length}` };
                    buffers.push([ref, val.buffer]);
                    return ref;
                }
                else {
                    return val;
                }
            });
            const num_buffers = buffers.length;
            if (num_buffers > 0) {
                this.header.num_buffers = num_buffers;
            }
            const header_json = JSON.stringify(this.header);
            const metadata_json = JSON.stringify(this.metadata);
            socket.send(header_json);
            socket.send(metadata_json);
            socket.send(content_json);
            for (const [ref, buffer] of buffers) {
                socket.send(JSON.stringify(ref));
                socket.send(buffer);
            }
        }
        msgid() {
            return this.header.msgid;
        }
        msgtype() {
            return this.header.msgtype;
        }
        reqid() {
            return this.header.reqid;
        }
        // return the reason we should close on bad protocol, if there is one
        problem() {
            if (!("msgid" in this.header)) {
                return "No msgid in header";
            }
            else if (!("msgtype" in this.header)) {
                return "No msgtype in header";
            }
            else {
                return null;
            }
        }
    }
    exports.Message = Message;
    Message.__name__ = "Message";
},
/* protocol/receiver.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const message_1 = require(69) /* ./message */;
    const types_1 = require(8) /* ../core/util/types */;
    const assert_1 = require(12) /* ../core/util/assert */;
    class Receiver {
        constructor() {
            this.message = null;
            this._partial = null;
            this._fragments = [];
            this._buf_header = null;
            this._current_consumer = this._HEADER;
        }
        consume(fragment) {
            this._current_consumer(fragment);
        }
        _HEADER(fragment) {
            this._assume_text(fragment);
            this.message = null;
            this._partial = null;
            this._fragments = [fragment];
            this._buf_header = null;
            this._current_consumer = this._METADATA;
        }
        _METADATA(fragment) {
            this._assume_text(fragment);
            this._fragments.push(fragment);
            this._current_consumer = this._CONTENT;
        }
        _CONTENT(fragment) {
            this._assume_text(fragment);
            this._fragments.push(fragment);
            const [header_json, metadata_json, content_json] = this._fragments;
            (0, assert_1.assert)(header_json != null && metadata_json != null && content_json != null);
            this._partial = message_1.Message.assemble(header_json, metadata_json, content_json);
            this._check_complete();
        }
        _BUFFER_HEADER(fragment) {
            this._assume_text(fragment);
            this._buf_header = fragment;
            this._current_consumer = this._BUFFER_PAYLOAD;
        }
        _BUFFER_PAYLOAD(fragment) {
            this._assume_binary(fragment);
            (0, assert_1.assert)(this._partial != null && this._buf_header != null);
            this._partial.assemble_buffer(this._buf_header, fragment);
            this._check_complete();
        }
        _assume_text(fragment) {
            if (!(0, types_1.isString)(fragment)) {
                throw new Error("Expected text fragment but received binary fragment");
            }
        }
        _assume_binary(fragment) {
            if (!(fragment instanceof ArrayBuffer)) {
                throw new Error("Expected binary fragment but received text fragment");
            }
        }
        _check_complete() {
            if (this._partial.complete()) {
                this.message = this._partial;
                this._current_consumer = this._HEADER;
            }
            else {
                this._current_consumer = this._BUFFER_HEADER;
            }
        }
    }
    exports.Receiver = Receiver;
    Receiver.__name__ = "Receiver";
},
/* client/session.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const document_1 = require(5) /* ../document */;
    const bokeh_events_1 = require(53) /* ../core/bokeh_events */;
    const message_1 = require(69) /* ../protocol/message */;
    const logging_1 = require(19) /* ../core/logging */;
    class ClientSession {
        constructor(_connection, document) {
            this._document_listener = (event) => {
                this._document_changed(event);
            };
            this._connection = _connection;
            this.document = document;
            this.document.on_change(this._document_listener, true);
        }
        // XXX: this is only needed in tests
        get id() {
            return this._connection.id;
        }
        handle(message) {
            const msgtype = message.msgtype();
            switch (msgtype) {
                case "PATCH-DOC": {
                    this._handle_patch(message);
                    break;
                }
                case "OK": {
                    this._handle_ok(message);
                    break;
                }
                case "ERROR": {
                    this._handle_error(message);
                    break;
                }
                default:
                    logging_1.logger.debug(`Doing nothing with message '${msgtype}'`);
            }
        }
        notify_connection_lost() {
            this.document.event_manager.send_event(new bokeh_events_1.ConnectionLost());
        }
        close() {
            this._connection.close();
        }
        /*protected*/ _connection_closed() {
            this.document.remove_on_change(this._document_listener);
        }
        // Sends a request to the server for info about the server, such as its Bokeh
        // version. Returns a promise, the value of the promise is a free-form dictionary
        // of server details.
        async request_server_info() {
            const message = message_1.Message.create("SERVER-INFO-REQ", {}, {});
            const reply = await this._connection.send_with_reply(message);
            return reply.content;
        }
        // Sends some request to the server (no guarantee about which one) and returns
        // a promise which is completed when the server replies. The purpose of this
        // is that if you wait for the promise to be completed, you know the server
        // has processed the request. This is useful when writing tests because once
        // the server has processed this request it should also have processed any
        // events or requests you sent previously, which means you can check for the
        // results of that processing without a race condition. (This assumes the
        // server processes events in sequence, which it mostly has to semantically,
        // since reordering events might change the final state.)
        async force_roundtrip() {
            await this.request_server_info();
        }
        _document_changed(event) {
            const events = (() => {
                const events = event instanceof document_1.DocumentEventBatch ? (event.sync ? event.events : []) : [event];
                return events.filter((event) => event.sync);
            })();
            if (events.length == 0) {
                return;
            }
            const patch = this.document.create_json_patch(events);
            // TODO (havocp) the connection may be closed here, which will
            // cause this send to throw an error - need to deal with it more cleanly.
            const message = message_1.Message.create("PATCH-DOC", {}, patch);
            this._connection.send(message);
        }
        _handle_patch(message) {
            this.document.apply_json_patch(message.content, message.buffers);
        }
        _handle_ok(message) {
            logging_1.logger.trace(`Unhandled OK reply to ${message.reqid()}`);
        }
        _handle_error(message) {
            logging_1.logger.error(`Unhandled ERROR reply to ${message.reqid()}: ${message.content.text}`);
        }
    }
    exports.ClientSession = ClientSession;
    ClientSession.__name__ = "ClientSession";
},
/* embed/dom.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports._resolve_element = _resolve_element;
    exports._resolve_root_elements = _resolve_root_elements;
    const dom_1 = require(63) /* ../core/dom */;
    const types_1 = require(8) /* ../core/util/types */;
    function _get_element(target) {
        let element = (0, types_1.isString)(target) ? document.getElementById(target) : target;
        if (element == null) {
            throw new Error(`Error rendering Bokeh model: could not find ${(0, types_1.isString)(target) ? `#${target}` : target} HTML tag`);
        }
        if (!(0, dom_1.contains)(document.body, element)) {
            throw new Error(`Error rendering Bokeh model: element ${(0, types_1.isString)(target) ? `#${target}` : target} must be under <body>`);
        }
        // If autoload script, replace script tag with div for embedding.
        if (element instanceof HTMLElement && element.tagName == "SCRIPT") {
            const root_el = (0, dom_1.div)();
            element.replaceWith(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;
        }
    }
    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;
    }
},
/* embed/notebook.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.embed_items_notebook = embed_items_notebook;
    const document_1 = require(5) /* ../document */;
    const receiver_1 = require(70) /* ../protocol/receiver */;
    const logging_1 = require(19) /* ../core/logging */;
    const object_1 = require(9) /* ../core/util/object */;
    const standalone_1 = require(54) /* ./standalone */;
    const dom_1 = require(72) /* ./dom */;
    // This exists to allow the @bokeh/jupyter_bokeh extension to store the
    // notebook kernel so that _init_comms can register the comms target.
    // This has to be available at Bokeh.embed.kernels in JupyterLab.
    exports.kernels = {};
    function _handle_notebook_comms(receiver, comm_msg) {
        if (comm_msg.buffers.length > 0) {
            receiver.consume(comm_msg.buffers[0].buffer);
        }
        else {
            receiver.consume(comm_msg.content.data);
        }
        const msg = receiver.message;
        if (msg != null) {
            this.apply_json_patch(msg.content, msg.buffers);
        }
    }
    function _init_comms(target, doc) {
        if (typeof Jupyter !== "undefined" && Jupyter.notebook.kernel != null) {
            logging_1.logger.info(`Registering Jupyter comms for target ${target}`);
            const comm_manager = Jupyter.notebook.kernel.comm_manager;
            try {
                comm_manager.register_target(target, (comm) => {
                    logging_1.logger.info(`Registering Jupyter comms for target ${target}`);
                    const r = new receiver_1.Receiver();
                    comm.on_msg(_handle_notebook_comms.bind(doc, r));
                });
            }
            catch (e) {
                logging_1.logger.warn(`Jupyter comms failed to register. push_notebook() will not function. (exception reported: ${e})`);
            }
        }
        else if (doc.roots()[0].id in exports.kernels) {
            logging_1.logger.info(`Registering JupyterLab comms for target ${target}`);
            const kernel = exports.kernels[doc.roots()[0].id];
            try {
                kernel.registerCommTarget(target, (comm) => {
                    logging_1.logger.info(`Registering JupyterLab comms for target ${target}`);
                    const r = new receiver_1.Receiver();
                    comm.onMsg = _handle_notebook_comms.bind(doc, r);
                });
            }
            catch (e) {
                logging_1.logger.warn(`Jupyter comms failed to register. push_notebook() will not function. (exception reported: ${e})`);
            }
        }
        else if (typeof google != "undefined" && google.colab.kernel != null) {
            logging_1.logger.info(`Registering Google Colab comms for target ${target}`);
            const comm_manager = google.colab.kernel.comms;
            try {
                comm_manager.registerTarget(target, async (comm) => {
                    logging_1.logger.info(`Registering Google Colab comms for target ${target}`);
                    const r = new receiver_1.Receiver();
                    for await (const message of comm.messages) {
                        const content = { data: message.data };
                        const buffers = [];
                        for (const buffer of message.buffers ?? []) {
                            buffers.push(new DataView(buffer));
                        }
                        const msg = { content, buffers };
                        _handle_notebook_comms.bind(doc)(r, msg);
                    }
                });
            }
            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.");
        }
    }
    async function embed_items_notebook(docs_json, render_items) {
        if ((0, object_1.size)(docs_json) != 1) {
            throw new Error("embed_items_notebook expects exactly one document in docs_json");
        }
        const document = document_1.Document.from_json((0, object_1.values)(docs_json)[0]);
        for (const item of render_items) {
            if (item.notebook_comms_target != null) {
                _init_comms(item.notebook_comms_target, document);
            }
            const element = (0, dom_1._resolve_element)(item);
            const roots = (0, dom_1._resolve_root_elements)(item);
            await (0, standalone_1.add_document_standalone)(document, element, roots);
            for (const root of roots) {
                if (root instanceof HTMLElement) {
                    root.removeAttribute("id");
                }
            }
        }
    }
},
/* protocol/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(69) /* ./message */, exports);
    tslib_1.__exportStar(require(70) /* ./receiver */, exports);
},
/* safely.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.safely = safely;
    // Keep this code as terse and as close to vanila JS as possible. If we
    // arrived here, it means we should trust no one and need to act properly.
    function _burst_into_flames(error) {
        // Make box
        const box = document.createElement("div");
        box.style.backgroundColor = "#f2dede";
        box.style.border = "1px solid #a94442";
        box.style.borderRadius = "4px";
        box.style.display = "inline-block";
        box.style.fontFamily = "sans-serif";
        box.style.marginTop = "5px";
        box.style.minWidth = "200px";
        box.style.padding = "5px 5px 5px 10px";
        box.classList.add("bokeh-error-box-into-flames");
        // Make button
        const button = document.createElement("span");
        button.style.backgroundColor = "#a94442";
        button.style.borderRadius = "0px 4px 0px 0px";
        button.style.color = "white";
        button.style.cursor = "pointer";
        button.style.cssFloat = "right";
        button.style.fontSize = "0.8em";
        button.style.margin = "-6px -6px 0px 0px";
        button.style.padding = "2px 5px 4px 5px";
        button.title = "close";
        button.setAttribute("aria-label", "close");
        button.appendChild(document.createTextNode("x"));
        button.addEventListener("click", () => body.removeChild(box));
        // Make title
        const title = document.createElement("h3");
        title.style.color = "#a94442";
        title.style.margin = "8px 0px 0px 0px";
        title.style.padding = "0px";
        title.appendChild(document.createTextNode("Bokeh Error"));
        // Make message
        const message = document.createElement("pre");
        message.style.whiteSpace = "unset";
        message.style.overflowX = "auto";
        message.appendChild(document.createTextNode(error));
        // Add pieces to box
        box.appendChild(button);
        box.appendChild(title);
        box.appendChild(message);
        // Put box in doc
        const body = document.getElementsByTagName("body")[0];
        body.insertBefore(box, body.firstChild);
    }
    function safely(fn, silent = false) {
        try {
            return fn();
        }
        catch (error) {
            const text = error instanceof Error && error.stack != null ? error.stack : `${error}`;
            _burst_into_flames(text);
            if (!silent) {
                throw error;
            }
            else {
                return;
            }
        }
    }
},
/* models/main.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const base_1 = require(7) /* ../base */;
    const AllModels = tslib_1.__importStar(require(77) /* ./ */);
    (0, base_1.register_models)(AllModels);
    const DOMModels = tslib_1.__importStar(require(540) /* ./dom */);
    (0, base_1.register_models)(DOMModels);
},
/* models/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(78) /* ./annotations */, exports);
    tslib_1.__exportStar(require(266) /* ./axes */, exports);
    tslib_1.__exportStar(require(314) /* ./callbacks */, exports);
    tslib_1.__exportStar(require(324) /* ./canvas */, exports);
    tslib_1.__exportStar(require(329) /* ./comparisons */, exports);
    tslib_1.__exportStar(require(333) /* ./coordinates */, exports);
    tslib_1.__exportStar(require(334) /* ./expressions */, exports);
    tslib_1.__exportStar(require(343) /* ./filters */, exports);
    tslib_1.__exportStar(require(242) /* ./formatters */, exports);
    tslib_1.__exportStar(require(352) /* ./glyphs */, exports);
    tslib_1.__exportStar(require(396) /* ./graphics */, exports);
    tslib_1.__exportStar(require(397) /* ./graphs */, exports);
    tslib_1.__exportStar(require(401) /* ./grids */, exports);
    tslib_1.__exportStar(require(403) /* ./layouts */, exports);
    tslib_1.__exportStar(require(271) /* ./mappers */, exports);
    tslib_1.__exportStar(require(426) /* ./misc */, exports);
    tslib_1.__exportStar(require(428) /* ./text */, exports);
    tslib_1.__exportStar(require(429) /* ./transforms */, exports);
    tslib_1.__exportStar(require(438) /* ./plots */, exports);
    tslib_1.__exportStar(require(454) /* ./policies */, exports);
    tslib_1.__exportStar(require(455) /* ./random */, exports);
    tslib_1.__exportStar(require(256) /* ./ranges */, exports);
    tslib_1.__exportStar(require(457) /* ./renderers */, exports);
    tslib_1.__exportStar(require(254) /* ./scales */, exports);
    tslib_1.__exportStar(require(460) /* ./selections */, exports);
    tslib_1.__exportStar(require(461) /* ./selectors */, exports);
    tslib_1.__exportStar(require(466) /* ./sources */, exports);
    tslib_1.__exportStar(require(200) /* ./tickers */, exports);
    tslib_1.__exportStar(require(471) /* ./tiles */, exports);
    tslib_1.__exportStar(require(480) /* ./textures */, exports);
    tslib_1.__exportStar(require(484) /* ./ui */, exports);
    tslib_1.__exportStar(require(494) /* ./tools */, exports);
},
/* models/annotations/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    var area_visuals_1 = require(79) /* ./area_visuals */;
    __esExport("AreaVisuals", area_visuals_1.AreaVisuals);
    var annotation_1 = require(81) /* ./annotation */;
    __esExport("Annotation", annotation_1.Annotation);
    var arrow_1 = require(126) /* ./arrow */;
    __esExport("Arrow", arrow_1.Arrow);
    var arrow_head_1 = require(168) /* ./arrow_head */;
    __esExport("ArrowHead", arrow_head_1.ArrowHead);
    var arrow_head_2 = require(168) /* ./arrow_head */;
    __esExport("OpenHead", arrow_head_2.OpenHead);
    var arrow_head_3 = require(168) /* ./arrow_head */;
    __esExport("NormalHead", arrow_head_3.NormalHead);
    var arrow_head_4 = require(168) /* ./arrow_head */;
    __esExport("TeeHead", arrow_head_4.TeeHead);
    var arrow_head_5 = require(168) /* ./arrow_head */;
    __esExport("VeeHead", arrow_head_5.VeeHead);
    var base_color_bar_1 = require(170) /* ./base_color_bar */;
    __esExport("BaseColorBar", base_color_bar_1.BaseColorBar);
    var band_1 = require(261) /* ./band */;
    __esExport("Band", band_1.Band);
    var box_annotation_1 = require(263) /* ./box_annotation */;
    __esExport("BoxAnnotation", box_annotation_1.BoxAnnotation);
    __esExport("BoxInteractionHandles", box_annotation_1.BoxInteractionHandles);
    var color_bar_1 = require(265) /* ./color_bar */;
    __esExport("ColorBar", color_bar_1.ColorBar);
    var contour_color_bar_1 = require(281) /* ./contour_color_bar */;
    __esExport("ContourColorBar", contour_color_bar_1.ContourColorBar);
    var label_1 = require(282) /* ./label */;
    __esExport("Label", label_1.Label);
    var label_set_1 = require(283) /* ./label_set */;
    __esExport("LabelSet", label_set_1.LabelSet);
    var legend_1 = require(284) /* ./legend */;
    __esExport("Legend", legend_1.Legend);
    var legend_item_1 = require(285) /* ./legend_item */;
    __esExport("LegendItem", legend_item_1.LegendItem);
    var poly_annotation_1 = require(286) /* ./poly_annotation */;
    __esExport("PolyAnnotation", poly_annotation_1.PolyAnnotation);
    var scale_bar_1 = require(287) /* ./scale_bar */;
    __esExport("ScaleBar", scale_bar_1.ScaleBar);
    var dimensional_1 = require(288) /* ./dimensional */;
    __esExport("Metric", dimensional_1.Metric);
    __esExport("ReciprocalMetric", dimensional_1.ReciprocalMetric);
    __esExport("MetricLength", dimensional_1.MetricLength);
    __esExport("ReciprocalMetricLength", dimensional_1.ReciprocalMetricLength);
    __esExport("ImperialLength", dimensional_1.ImperialLength);
    __esExport("Angular", dimensional_1.Angular);
    var slope_1 = require(289) /* ./slope */;
    __esExport("Slope", slope_1.Slope);
    var span_1 = require(290) /* ./span */;
    __esExport("Span", span_1.Span);
    var text_annotation_1 = require(172) /* ./text_annotation */;
    __esExport("TextAnnotation", text_annotation_1.TextAnnotation);
    var title_1 = require(171) /* ./title */;
    __esExport("Title", title_1.Title);
    var toolbar_panel_1 = require(291) /* ./toolbar_panel */;
    __esExport("ToolbarPanel", toolbar_panel_1.ToolbarPanel);
    var whisker_1 = require(308) /* ./whisker */;
    __esExport("Whisker", whisker_1.Whisker);
    tslib_1.__exportStar(require(309) /* ./html */, exports);
},
/* models/annotations/area_visuals.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(51) /* ../../model */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    class AreaVisuals extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        clone(attrs) {
            return super.clone(attrs);
        }
    }
    exports.AreaVisuals = AreaVisuals;
    _a = AreaVisuals;
    AreaVisuals.__name__ = "AreaVisuals";
    (() => {
        _a.mixins([
            mixins.Line,
            mixins.Fill,
            mixins.Hatch,
            ["hover_", mixins.Line],
            ["hover_", mixins.Fill],
            ["hover_", mixins.Hatch],
        ]);
    })();
},
/* core/property_mixins.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.attrs_of = attrs_of;
    const tslib_1 = require(1) /* tslib */;
    const p = tslib_1.__importStar(require(18) /* ./properties */);
    const enums_1 = require(20) /* ./enums */;
    const k = tslib_1.__importStar(require(21) /* ./kinds */);
    const object_1 = require(9) /* ./util/object */;
    const types_1 = require(8) /* ./util/types */;
    exports.Line = {
        line_color: [k.Nullable(k.Color), "black"],
        line_alpha: [k.Alpha, 1.0],
        line_width: [k.Float, 1],
        line_join: [enums_1.LineJoin, "bevel"],
        line_cap: [enums_1.LineCap, "butt"],
        line_dash: [k.Or(enums_1.LineDash, k.Array(k.Float)), []],
        line_dash_offset: [k.Float, 0],
    };
    exports.Fill = {
        fill_color: [k.Nullable(k.Color), "gray"],
        fill_alpha: [k.Alpha, 1.0],
    };
    exports.Image = {
        global_alpha: [k.Alpha, 1.0],
    };
    exports.Hatch = {
        hatch_color: [k.Nullable(k.Color), "black"],
        hatch_alpha: [k.Alpha, 1.0],
        hatch_scale: [k.Float, 12.0],
        hatch_pattern: [k.Nullable(k.Or(enums_1.HatchPatternType, k.Str)), null],
        hatch_weight: [k.Float, 1.0],
        hatch_extra: [k.Dict(k.AnyRef()), {}], // XXX: recursive imports
    };
    exports.Text = {
        text_color: [k.Nullable(k.Color), "#444444"],
        text_outline_color: [k.Nullable(k.Color), null],
        text_alpha: [k.Alpha, 1.0],
        text_font: [p.Font, "helvetica"],
        text_font_size: [k.FontSize, "16px"],
        text_font_style: [enums_1.FontStyle, "normal"],
        text_align: [enums_1.TextAlign, "left"],
        text_baseline: [enums_1.TextBaseline, "bottom"],
        text_line_height: [k.Float, 1.2],
    };
    exports.LineScalar = {
        line_color: [p.ColorScalar, "black"],
        line_alpha: [p.NumberScalar, 1.0],
        line_width: [p.NumberScalar, 1],
        line_join: [p.LineJoinScalar, "bevel"],
        line_cap: [p.LineCapScalar, "butt"],
        line_dash: [p.LineDashScalar, []],
        line_dash_offset: [p.NumberScalar, 0],
    };
    exports.FillScalar = {
        fill_color: [p.ColorScalar, "gray"],
        fill_alpha: [p.NumberScalar, 1.0],
    };
    exports.ImageScalar = {
        global_alpha: [p.NumberScalar, 1.0],
    };
    exports.HatchScalar = {
        hatch_color: [p.ColorScalar, "black"],
        hatch_alpha: [p.NumberScalar, 1.0],
        hatch_scale: [p.NumberScalar, 12.0],
        hatch_pattern: [p.NullStringScalar, null],
        hatch_weight: [p.NumberScalar, 1.0],
        hatch_extra: [p.DictScalar, {}],
    };
    exports.TextScalar = {
        text_color: [p.ColorScalar, "#444444"],
        text_outline_color: [p.ColorScalar, null],
        text_alpha: [p.NumberScalar, 1.0],
        text_font: [p.FontScalar, "helvetica"],
        text_font_size: [p.FontSizeScalar, "16px"],
        text_font_style: [p.FontStyleScalar, "normal"],
        text_align: [p.TextAlignScalar, "left"],
        text_baseline: [p.TextBaselineScalar, "bottom"],
        text_line_height: [p.NumberScalar, 1.2],
    };
    exports.LineVector = {
        line_color: [p.ColorSpec, "black"],
        line_alpha: [p.NumberSpec, 1.0],
        line_width: [p.NumberSpec, 1],
        line_join: [p.LineJoinSpec, "bevel"],
        line_cap: [p.LineCapSpec, "butt"],
        line_dash: [p.LineDashSpec, []],
        line_dash_offset: [p.NumberSpec, 0],
    };
    exports.FillVector = {
        fill_color: [p.ColorSpec, "gray"],
        fill_alpha: [p.NumberSpec, 1.0],
    };
    exports.ImageVector = {
        global_alpha: [p.NumberSpec, 1.0],
    };
    exports.HatchVector = {
        hatch_color: [p.ColorSpec, "black"],
        hatch_alpha: [p.NumberSpec, 1.0],
        hatch_scale: [p.NumberSpec, 12.0],
        hatch_pattern: [p.NullStringSpec, null],
        hatch_weight: [p.NumberSpec, 1.0],
        hatch_extra: [p.DictScalar, {}],
    };
    exports.TextVector = {
        text_color: [p.ColorSpec, "#444444"],
        text_outline_color: [p.ColorSpec, null],
        text_alpha: [p.NumberSpec, 1.0],
        text_font: [p.FontSpec, "helvetica"],
        text_font_size: [p.FontSizeSpec, "16px"],
        text_font_style: [p.FontStyleSpec, "normal"],
        text_align: [p.TextAlignSpec, "left"],
        text_baseline: [p.TextBaselineSpec, "bottom"],
        text_line_height: [p.NumberSpec, 1.2],
    };
    function attrs_of(model, prefix, mixin, new_prefix = false) {
        const attrs = {};
        for (const attr of (0, object_1.keys)(mixin)) {
            const prefixed_attr = `${prefix}${attr}`;
            const value = model[prefixed_attr];
            const new_attr = (() => {
                if ((0, types_1.isString)(new_prefix)) {
                    return `${new_prefix}${attr}`;
                }
                else if (new_prefix) {
                    return prefixed_attr;
                }
                else {
                    return attr;
                }
            })();
            attrs[new_attr] = value;
        }
        return attrs;
    }
},
/* models/annotations/annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const composite_renderer_1 = require(82) /* ../renderers/composite_renderer */;
    class AnnotationView extends composite_renderer_1.CompositeRendererView {
        get bbox() {
            return super.bbox ?? this.layout?.bbox;
        }
        get_size() {
            if (this.displayed) {
                const { width, height } = this._get_size();
                return { width: Math.round(width), height: Math.round(height) };
            }
            else {
                return { width: 0, height: 0 };
            }
        }
        _get_size() {
            throw new Error("not implemented");
        }
        connect_signals() {
            super.connect_signals();
            const p = this.model.properties;
            this.on_change(p.visible, () => {
                if (this.layout != null) {
                    this.layout.visible = this.model.visible;
                    this.plot_view.request_layout();
                }
            });
        }
        get needs_clip() {
            return this.layout == null; // TODO: change this, when center layout is fully implemented
        }
    }
    exports.AnnotationView = AnnotationView;
    AnnotationView.__name__ = "AnnotationView";
    class Annotation extends composite_renderer_1.CompositeRenderer {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Annotation = Annotation;
    _a = Annotation;
    Annotation.__name__ = "Annotation";
    (() => {
        _a.override({
            level: "annotation",
        });
    })();
},
/* models/renderers/composite_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const renderer_1 = require(83) /* ./renderer */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    const dom_node_1 = require(125) /* ../dom/dom_node */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    // TODO UIElement needs to inherit from DOMNode
    const ElementLike = (0, kinds_1.Or)((0, kinds_1.Ref)(ui_element_1.UIElement), (0, kinds_1.Ref)(dom_node_1.DOMNode));
    class CompositeRendererView extends renderer_1.RendererView {
        constructor() {
            super(...arguments);
            this._renderer_views = new Map();
            this._element_views = new Map();
            this._computed_renderers = [];
            this._computed_elements = [];
            this._has_rendered_elements = false;
        }
        get renderer_views() {
            return this.model.renderers.map((renderer) => this._renderer_views.get(renderer));
        }
        get element_views() {
            return this.model.elements.map((element) => this._element_views.get(element));
        }
        *children() {
            yield* super.children();
            yield* this.renderer_views;
            yield* this.element_views;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._build_renderers();
            await this._build_elements();
        }
        get computed_renderers() {
            return [...this.model.renderers, ...this._computed_renderers];
        }
        get computed_renderer_views() {
            return this.computed_renderers.map((item) => this._renderer_views.get(item)).filter((rv) => rv != null);
        }
        async _build_renderers() {
            return await (0, build_views_1.build_views)(this._renderer_views, this.computed_renderers, { parent: this.plot_view });
        }
        get computed_elements() {
            return [...this.model.elements, ...this._computed_elements];
        }
        get computed_element_views() {
            return this.computed_elements.map((item) => this._element_views.get(item)).filter((ev) => ev != null);
        }
        async _build_elements() {
            return await (0, build_views_1.build_views)(this._element_views, this.computed_elements, { parent: this.plot_view });
        }
        async _update_renderers() {
            await this._build_renderers();
        }
        async _update_elements() {
            const { created } = await this._build_elements();
            const created_elements = new Set(created);
            // First remove and then either reattach existing elements or render and
            // attach new elements, so that the order of children is consistent, while
            // avoiding expensive re-rendering of existing views.
            for (const element_view of this.element_views) {
                element_view.el.remove();
            }
            for (const element_view of this.element_views) {
                const is_new = created_elements.has(element_view);
                const target = element_view.rendering_target() ?? this.shadow_el;
                if (is_new) {
                    element_view.render_to(target);
                }
                else {
                    target.append(element_view.el);
                }
            }
            this.r_after_render();
        }
        remove() {
            (0, build_views_1.remove_views)(this._renderer_views);
            (0, build_views_1.remove_views)(this._element_views);
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            const { renderers, elements } = this.model.properties;
            this.on_change(renderers, async () => {
                await this._update_renderers();
            });
            this.on_change(elements, async () => {
                await this._update_elements();
            });
        }
        paint() {
            if (!this._has_rendered_elements) {
                for (const element_view of this.element_views) {
                    const target = element_view.rendering_target() ?? this.shadow_el;
                    element_view.render_to(target);
                }
                this._has_rendered_elements = true;
            }
            super.paint();
            if (this.displayed && this.is_renderable) {
                for (const renderer of this.computed_renderer_views) {
                    renderer.paint();
                }
            }
            const { displayed } = this;
            for (const element_view of this.element_views) {
                element_view.reposition(displayed);
            }
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            for (const renderer_view of this.renderer_views) {
                if (!renderer_view.has_finished()) {
                    return false;
                }
            }
            for (const element_view of this.element_views) {
                if (!element_view.has_finished()) {
                    return false;
                }
            }
            return true;
        }
    }
    exports.CompositeRendererView = CompositeRendererView;
    CompositeRendererView.__name__ = "CompositeRendererView";
    class CompositeRenderer extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.CompositeRenderer = CompositeRenderer;
    _a = CompositeRenderer;
    CompositeRenderer.__name__ = "CompositeRenderer";
    (() => {
        _a.define(({ List, Ref }) => ({
            renderers: [List(Ref(renderer_1.Renderer)), []],
            elements: [List(ElementLike), []],
        }));
    })();
},
/* models/renderers/renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const styled_element_1 = require(84) /* ../ui/styled_element */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const visuals = tslib_1.__importStar(require(87) /* ../../core/visuals */);
    const enums_1 = require(20) /* ../../core/enums */;
    const types_1 = require(8) /* ../../core/util/types */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const coordinate_mapping_1 = require(95) /* ../coordinates/coordinate_mapping */;
    const menu_1 = require(110) /* ../ui/menus/menu */;
    const renderer_group_1 = require(124) /* ./renderer_group */;
    const dom_1 = require(63) /* ../../core/dom */;
    class RendererView extends styled_element_1.StyledElementView {
        constructor() {
            super(...arguments);
            this.position = new dom_1.InlineStyleSheet();
            this._context_menu = null;
            this._custom_coordinates = null;
        }
        rendering_target() {
            return this.plot_view.canvas_view.underlays_el;
        }
        get context_menu() {
            return this._context_menu;
        }
        get coordinates() {
            const { _coordinates } = this;
            if (_coordinates != null) {
                return _coordinates;
            }
            else {
                return this._coordinates = this._initialize_coordinates();
            }
        }
        set coordinates(custom_coordinates) {
            this._custom_coordinates = custom_coordinates;
        }
        stylesheets() {
            return [...super.stylesheets(), this.position];
        }
        initialize() {
            super.initialize();
            this.visuals = new visuals.Visuals(this);
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { context_menu } = this.model;
            if (context_menu != null) {
                this._context_menu = await (0, build_views_1.build_view)(context_menu, { parent: this.plot_view });
            }
        }
        remove() {
            this._context_menu?.remove();
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            const { group } = this.model;
            if (group != null) {
                this.on_change(group.properties.visible, () => {
                    this.model.visible = group.visible;
                });
            }
            const { x_range_name, y_range_name } = this.model.properties;
            this.on_change([x_range_name, y_range_name], () => delete this._coordinates);
            this.connect(this.plot_view.frame.model.change, () => delete this._coordinates);
        }
        _initialize_coordinates() {
            if (this._custom_coordinates != null) {
                return this._custom_coordinates;
            }
            const { coordinates } = this.model;
            const { frame } = this.plot_view;
            if (coordinates != null) {
                return coordinates.get_transform(frame);
            }
            else {
                const { x_range_name, y_range_name } = this.model;
                const x_scale = frame.x_scales.get(x_range_name);
                const y_scale = frame.y_scales.get(y_range_name);
                (0, assert_1.assert)(x_scale != null, `missing '${x_range_name}' range`);
                (0, assert_1.assert)(y_scale != null, `missing '${y_range_name}' range`);
                return new coordinate_mapping_1.CoordinateTransform(x_scale, y_scale);
            }
        }
        get plot_view() {
            return this.parent;
        }
        get plot_model() {
            return this.parent.model;
        }
        get layer() {
            const { overlays, primary } = this.canvas;
            return this.model.level == "overlay" ? overlays : primary;
        }
        get canvas() {
            return this.plot_view.canvas_view;
        }
        request_paint() {
            this.plot_view.request_paint(this);
        }
        request_layout() {
            this.plot_view.request_layout();
        }
        notify_finished() {
            this.plot_view.notify_finished();
        }
        notify_finished_after_paint() {
            this.plot_view.notify_finished_after_paint();
        }
        get needs_clip() {
            return false;
        }
        get has_webgl() {
            return false;
        }
        /*
        get visible(): boolean {
          const {visible, group} = this.model
          return !visible ? false : (group?.visible ?? true)
        }
        */
        get displayed() {
            return this.model.visible;
        }
        get is_renderable() {
            return true;
        }
        paint() {
            // It would be better to update geometry (the internal layout) only when
            // necessary, but conditions for that are not clear, so for now update
            // at every paint.
            this.update_geometry();
            this.compute_geometry();
            this.update_position();
            if (this.displayed && this.is_renderable) {
                this._paint();
            }
            this.mark_finished();
        }
        renderer_view(_renderer) {
            return undefined;
        }
        /**
         * Geometry setup that doesn't change between paints.
         */
        update_geometry() { }
        /**
         * Geometry setup that changes between paints.
         */
        compute_geometry() { }
        /**
         * Updates the position of the associated DOM element.
         */
        update_position() {
            const { bbox, position } = this;
            if (bbox != null && bbox.is_valid) {
                position.replace(`
      :host {
        position: absolute;
        left:     ${bbox.left}px;
        top:      ${bbox.top}px;
        width:    ${bbox.width}px;
        height:   ${bbox.height}px;
      }
      `);
            }
            else {
                position.replace(`
      :host {
        display: none;
      }
      `);
            }
        }
        resolve_frame() {
            return this.plot_view.frame; // TODO CartesianFrameView (PR #13286)
        }
        resolve_canvas() {
            return this.plot_view.canvas;
        }
        resolve_plot() {
            return this.plot_view;
        }
        resolve_symbol(node) {
            const target = this;
            const { bbox } = target;
            if (bbox == null) {
                return { x: NaN, y: NaN };
            }
            else {
                const value = bbox.resolve(node.symbol);
                const { offset } = node;
                if ((0, types_1.isNumber)(value)) {
                    return value + offset;
                }
                else {
                    const { x, y } = value;
                    return { x: x + offset, y: y + offset };
                }
            }
        }
        get attribution() {
            return null;
        }
    }
    exports.RendererView = RendererView;
    RendererView.__name__ = "RendererView";
    class Renderer extends styled_element_1.StyledElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Renderer = Renderer;
    _a = Renderer;
    Renderer.__name__ = "Renderer";
    (() => {
        _a.define(({ Bool, Str, Ref, Nullable }) => ({
            group: [Nullable(Ref(renderer_group_1.RendererGroup)), null],
            level: [enums_1.RenderLevel, "image"],
            visible: [Bool, true],
            x_range_name: [Str, "default"],
            y_range_name: [Str, "default"],
            coordinates: [Nullable(Ref(coordinate_mapping_1.CoordinateMapping)), null],
            propagate_hover: [Bool, false],
            context_menu: [Nullable(Ref(menu_1.Menu)), null],
        }));
    })();
},
/* models/ui/styled_element.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const node_1 = require(59) /* ../coordinates/node */;
    const styles_1 = require(85) /* ../dom/styles */;
    const stylesheets_1 = require(86) /* ../dom/stylesheets */;
    const dom_view_1 = require(57) /* ../../core/dom_view */;
    const css_1 = require(65) /* ../../core/css */;
    const dom_1 = require(63) /* ../../core/dom */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    exports.StylesLike = (0, kinds_1.Or)((0, kinds_1.Dict)((0, kinds_1.Nullable)(kinds_1.Str)), (0, kinds_1.Ref)(styles_1.Styles)); // TODO: add validation for CSSStyles
    exports.StyleSheets = (0, kinds_1.List)((0, kinds_1.Or)((0, kinds_1.Ref)(stylesheets_1.StyleSheet), kinds_1.Str, (0, kinds_1.Dict)(exports.StylesLike)));
    exports.CSSVariables = (0, kinds_1.Dict)((0, kinds_1.Ref)(node_1.Node));
    class StyledElementView extends dom_view_1.DOMComponentView {
        constructor() {
            super(...arguments);
            this.style = new dom_1.InlineStyleSheet();
        }
        connect_signals() {
            super.connect_signals();
            const { styles, css_classes, css_variables, stylesheets } = this.model.properties;
            this.on_change(styles, () => this._update_styles());
            this.on_change(css_classes, () => this._update_css_classes());
            this.on_transitive_change(css_variables, () => this._update_css_variables());
            this.on_change(stylesheets, () => this._update_stylesheets());
        }
        render() {
            super.render();
            this._apply_styles();
        }
        *_css_classes() {
            yield* super._css_classes();
            yield* this.model.css_classes;
        }
        *_css_variables() {
            yield* super._css_variables();
            for (const [name, node] of (0, object_1.entries)(this.model.css_variables)) {
                const value = this.resolve_coordinate(node);
                if ((0, types_1.isNumber)(value)) {
                    yield [name, `${value}px`];
                }
            }
        }
        *_stylesheets() {
            yield* super._stylesheets();
            yield this.style;
            yield* this._computed_stylesheets();
        }
        *_computed_stylesheets() {
            for (const stylesheet of this.model.stylesheets) {
                if (stylesheet instanceof stylesheets_1.StyleSheet) {
                    yield stylesheet.underlying();
                }
                else {
                    yield new dom_1.InlineStyleSheet(stylesheet);
                }
            }
        }
        _apply_styles() {
            (0, css_1.apply_styles)(this.el.style, this.model.styles);
        }
        _update_styles() {
            this.el.removeAttribute("style"); // TODO: maintain _applied_styles
            this._apply_styles();
        }
    }
    exports.StyledElementView = StyledElementView;
    StyledElementView.__name__ = "StyledElementView";
    class StyledElement extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.StyledElement = StyledElement;
    _a = StyledElement;
    StyledElement.__name__ = "StyledElement";
    (() => {
        _a.define(({ List, Str }) => ({
            css_classes: [List(Str), []],
            css_variables: [exports.CSSVariables, {}],
            styles: [exports.StylesLike, {}],
            stylesheets: [exports.StyleSheets, []],
        }));
    })();
},
/* models/dom/styles.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    class Styles extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Styles = Styles;
    _a = Styles;
    Styles.__name__ = "Styles";
    (() => {
        _a.define(({ Str, Nullable }) => ({
            align_content: [Nullable(Str), null],
            align_items: [Nullable(Str), null],
            align_self: [Nullable(Str), null],
            alignment_baseline: [Nullable(Str), null],
            all: [Nullable(Str), null],
            animation: [Nullable(Str), null],
            animation_delay: [Nullable(Str), null],
            animation_direction: [Nullable(Str), null],
            animation_duration: [Nullable(Str), null],
            animation_fill_mode: [Nullable(Str), null],
            animation_iteration_count: [Nullable(Str), null],
            animation_name: [Nullable(Str), null],
            animation_play_state: [Nullable(Str), null],
            animation_timing_function: [Nullable(Str), null],
            aspect_ratio: [Nullable(Str), null],
            backface_visibility: [Nullable(Str), null],
            background: [Nullable(Str), null],
            background_attachment: [Nullable(Str), null],
            background_clip: [Nullable(Str), null],
            background_color: [Nullable(Str), null],
            background_image: [Nullable(Str), null],
            background_origin: [Nullable(Str), null],
            background_position: [Nullable(Str), null],
            background_position_x: [Nullable(Str), null],
            background_position_y: [Nullable(Str), null],
            background_repeat: [Nullable(Str), null],
            background_size: [Nullable(Str), null],
            baseline_shift: [Nullable(Str), null],
            block_size: [Nullable(Str), null],
            border: [Nullable(Str), null],
            border_block_end: [Nullable(Str), null],
            border_block_end_color: [Nullable(Str), null],
            border_block_end_style: [Nullable(Str), null],
            border_block_end_width: [Nullable(Str), null],
            border_block_start: [Nullable(Str), null],
            border_block_start_color: [Nullable(Str), null],
            border_block_start_style: [Nullable(Str), null],
            border_block_start_width: [Nullable(Str), null],
            border_bottom: [Nullable(Str), null],
            border_bottom_color: [Nullable(Str), null],
            border_bottom_left_radius: [Nullable(Str), null],
            border_bottom_right_radius: [Nullable(Str), null],
            border_bottom_style: [Nullable(Str), null],
            border_bottom_width: [Nullable(Str), null],
            border_collapse: [Nullable(Str), null],
            border_color: [Nullable(Str), null],
            border_image: [Nullable(Str), null],
            border_image_outset: [Nullable(Str), null],
            border_image_repeat: [Nullable(Str), null],
            border_image_slice: [Nullable(Str), null],
            border_image_source: [Nullable(Str), null],
            border_image_width: [Nullable(Str), null],
            border_inline_end: [Nullable(Str), null],
            border_inline_end_color: [Nullable(Str), null],
            border_inline_end_style: [Nullable(Str), null],
            border_inline_end_width: [Nullable(Str), null],
            border_inline_start: [Nullable(Str), null],
            border_inline_start_color: [Nullable(Str), null],
            border_inline_start_style: [Nullable(Str), null],
            border_inline_start_width: [Nullable(Str), null],
            border_left: [Nullable(Str), null],
            border_left_color: [Nullable(Str), null],
            border_left_style: [Nullable(Str), null],
            border_left_width: [Nullable(Str), null],
            border_radius: [Nullable(Str), null],
            border_right: [Nullable(Str), null],
            border_right_color: [Nullable(Str), null],
            border_right_style: [Nullable(Str), null],
            border_right_width: [Nullable(Str), null],
            border_spacing: [Nullable(Str), null],
            border_style: [Nullable(Str), null],
            border_top: [Nullable(Str), null],
            border_top_color: [Nullable(Str), null],
            border_top_left_radius: [Nullable(Str), null],
            border_top_right_radius: [Nullable(Str), null],
            border_top_style: [Nullable(Str), null],
            border_top_width: [Nullable(Str), null],
            border_width: [Nullable(Str), null],
            bottom: [Nullable(Str), null],
            box_shadow: [Nullable(Str), null],
            box_sizing: [Nullable(Str), null],
            break_after: [Nullable(Str), null],
            break_before: [Nullable(Str), null],
            break_inside: [Nullable(Str), null],
            caption_side: [Nullable(Str), null],
            caret_color: [Nullable(Str), null],
            clear: [Nullable(Str), null],
            clip: [Nullable(Str), null],
            clip_path: [Nullable(Str), null],
            clip_rule: [Nullable(Str), null],
            color: [Nullable(Str), null],
            color_interpolation: [Nullable(Str), null],
            color_interpolation_filters: [Nullable(Str), null],
            column_count: [Nullable(Str), null],
            column_fill: [Nullable(Str), null],
            column_gap: [Nullable(Str), null],
            column_rule: [Nullable(Str), null],
            column_rule_color: [Nullable(Str), null],
            column_rule_style: [Nullable(Str), null],
            column_rule_width: [Nullable(Str), null],
            column_span: [Nullable(Str), null],
            column_width: [Nullable(Str), null],
            columns: [Nullable(Str), null],
            content: [Nullable(Str), null],
            counter_increment: [Nullable(Str), null],
            counter_reset: [Nullable(Str), null],
            cursor: [Nullable(Str), null],
            direction: [Nullable(Str), null],
            display: [Nullable(Str), null],
            dominant_baseline: [Nullable(Str), null],
            empty_cells: [Nullable(Str), null],
            fill: [Nullable(Str), null],
            fill_opacity: [Nullable(Str), null],
            fill_rule: [Nullable(Str), null],
            filter: [Nullable(Str), null],
            flex: [Nullable(Str), null],
            flex_basis: [Nullable(Str), null],
            flex_direction: [Nullable(Str), null],
            flex_flow: [Nullable(Str), null],
            flex_grow: [Nullable(Str), null],
            flex_shrink: [Nullable(Str), null],
            flex_wrap: [Nullable(Str), null],
            float: [Nullable(Str), null],
            flood_color: [Nullable(Str), null],
            flood_opacity: [Nullable(Str), null],
            font: [Nullable(Str), null],
            font_family: [Nullable(Str), null],
            font_feature_settings: [Nullable(Str), null],
            font_kerning: [Nullable(Str), null],
            font_size: [Nullable(Str), null],
            font_size_adjust: [Nullable(Str), null],
            font_stretch: [Nullable(Str), null],
            font_style: [Nullable(Str), null],
            font_synthesis: [Nullable(Str), null],
            font_variant: [Nullable(Str), null],
            font_variant_caps: [Nullable(Str), null],
            font_variant_east_asian: [Nullable(Str), null],
            font_variant_ligatures: [Nullable(Str), null],
            font_variant_numeric: [Nullable(Str), null],
            font_variant_position: [Nullable(Str), null],
            font_weight: [Nullable(Str), null],
            gap: [Nullable(Str), null],
            glyph_orientation_vertical: [Nullable(Str), null],
            grid: [Nullable(Str), null],
            grid_area: [Nullable(Str), null],
            grid_auto_columns: [Nullable(Str), null],
            grid_auto_flow: [Nullable(Str), null],
            grid_auto_rows: [Nullable(Str), null],
            grid_column: [Nullable(Str), null],
            grid_column_end: [Nullable(Str), null],
            grid_column_gap: [Nullable(Str), null],
            grid_column_start: [Nullable(Str), null],
            grid_gap: [Nullable(Str), null],
            grid_row: [Nullable(Str), null],
            grid_row_end: [Nullable(Str), null],
            grid_row_gap: [Nullable(Str), null],
            grid_row_start: [Nullable(Str), null],
            grid_template: [Nullable(Str), null],
            grid_template_areas: [Nullable(Str), null],
            grid_template_columns: [Nullable(Str), null],
            grid_template_rows: [Nullable(Str), null],
            height: [Nullable(Str), null],
            hyphens: [Nullable(Str), null],
            image_orientation: [Nullable(Str), null],
            image_rendering: [Nullable(Str), null],
            inline_size: [Nullable(Str), null],
            justify_content: [Nullable(Str), null],
            justify_items: [Nullable(Str), null],
            justify_self: [Nullable(Str), null],
            left: [Nullable(Str), null],
            letter_spacing: [Nullable(Str), null],
            lighting_color: [Nullable(Str), null],
            line_break: [Nullable(Str), null],
            line_height: [Nullable(Str), null],
            list_style: [Nullable(Str), null],
            list_style_image: [Nullable(Str), null],
            list_style_position: [Nullable(Str), null],
            list_style_type: [Nullable(Str), null],
            margin: [Nullable(Str), null],
            margin_block_end: [Nullable(Str), null],
            margin_block_start: [Nullable(Str), null],
            margin_bottom: [Nullable(Str), null],
            margin_inline_end: [Nullable(Str), null],
            margin_inline_start: [Nullable(Str), null],
            margin_left: [Nullable(Str), null],
            margin_right: [Nullable(Str), null],
            margin_top: [Nullable(Str), null],
            marker: [Nullable(Str), null],
            marker_end: [Nullable(Str), null],
            marker_mid: [Nullable(Str), null],
            marker_start: [Nullable(Str), null],
            mask: [Nullable(Str), null],
            mask_composite: [Nullable(Str), null],
            mask_image: [Nullable(Str), null],
            mask_position: [Nullable(Str), null],
            mask_repeat: [Nullable(Str), null],
            mask_size: [Nullable(Str), null],
            mask_type: [Nullable(Str), null],
            max_block_size: [Nullable(Str), null],
            max_height: [Nullable(Str), null],
            max_inline_size: [Nullable(Str), null],
            max_width: [Nullable(Str), null],
            min_block_size: [Nullable(Str), null],
            min_height: [Nullable(Str), null],
            min_inline_size: [Nullable(Str), null],
            min_width: [Nullable(Str), null],
            object_fit: [Nullable(Str), null],
            object_position: [Nullable(Str), null],
            opacity: [Nullable(Str), null],
            order: [Nullable(Str), null],
            orphans: [Nullable(Str), null],
            outline: [Nullable(Str), null],
            outline_color: [Nullable(Str), null],
            outline_offset: [Nullable(Str), null],
            outline_style: [Nullable(Str), null],
            outline_width: [Nullable(Str), null],
            overflow: [Nullable(Str), null],
            overflow_anchor: [Nullable(Str), null],
            overflow_wrap: [Nullable(Str), null],
            overflow_x: [Nullable(Str), null],
            overflow_y: [Nullable(Str), null],
            overscroll_behavior: [Nullable(Str), null],
            overscroll_behavior_block: [Nullable(Str), null],
            overscroll_behavior_inline: [Nullable(Str), null],
            overscroll_behavior_x: [Nullable(Str), null],
            overscroll_behavior_y: [Nullable(Str), null],
            padding: [Nullable(Str), null],
            padding_block_end: [Nullable(Str), null],
            padding_block_start: [Nullable(Str), null],
            padding_bottom: [Nullable(Str), null],
            padding_inline_end: [Nullable(Str), null],
            padding_inline_start: [Nullable(Str), null],
            padding_left: [Nullable(Str), null],
            padding_right: [Nullable(Str), null],
            padding_top: [Nullable(Str), null],
            page_break_after: [Nullable(Str), null],
            page_break_before: [Nullable(Str), null],
            page_break_inside: [Nullable(Str), null],
            paint_order: [Nullable(Str), null],
            perspective: [Nullable(Str), null],
            perspective_origin: [Nullable(Str), null],
            place_content: [Nullable(Str), null],
            place_items: [Nullable(Str), null],
            place_self: [Nullable(Str), null],
            pointer_events: [Nullable(Str), null],
            position: [Nullable(Str), null],
            quotes: [Nullable(Str), null],
            resize: [Nullable(Str), null],
            right: [Nullable(Str), null],
            rotate: [Nullable(Str), null],
            row_gap: [Nullable(Str), null],
            ruby_align: [Nullable(Str), null],
            ruby_position: [Nullable(Str), null],
            scale: [Nullable(Str), null],
            scroll_behavior: [Nullable(Str), null],
            shape_rendering: [Nullable(Str), null],
            stop_color: [Nullable(Str), null],
            stop_opacity: [Nullable(Str), null],
            stroke: [Nullable(Str), null],
            stroke_dasharray: [Nullable(Str), null],
            stroke_dashoffset: [Nullable(Str), null],
            stroke_linecap: [Nullable(Str), null],
            stroke_linejoin: [Nullable(Str), null],
            stroke_miterlimit: [Nullable(Str), null],
            stroke_opacity: [Nullable(Str), null],
            stroke_width: [Nullable(Str), null],
            tab_size: [Nullable(Str), null],
            table_layout: [Nullable(Str), null],
            text_align: [Nullable(Str), null],
            text_align_last: [Nullable(Str), null],
            text_anchor: [Nullable(Str), null],
            text_combine_upright: [Nullable(Str), null],
            text_decoration: [Nullable(Str), null],
            text_decoration_color: [Nullable(Str), null],
            text_decoration_line: [Nullable(Str), null],
            text_decoration_style: [Nullable(Str), null],
            text_emphasis: [Nullable(Str), null],
            text_emphasis_color: [Nullable(Str), null],
            text_emphasis_position: [Nullable(Str), null],
            text_emphasis_style: [Nullable(Str), null],
            text_indent: [Nullable(Str), null],
            text_justify: [Nullable(Str), null],
            text_orientation: [Nullable(Str), null],
            text_overflow: [Nullable(Str), null],
            text_rendering: [Nullable(Str), null],
            text_shadow: [Nullable(Str), null],
            text_transform: [Nullable(Str), null],
            text_underline_position: [Nullable(Str), null],
            top: [Nullable(Str), null],
            touch_action: [Nullable(Str), null],
            transform: [Nullable(Str), null],
            transform_box: [Nullable(Str), null],
            transform_origin: [Nullable(Str), null],
            transform_style: [Nullable(Str), null],
            transition: [Nullable(Str), null],
            transition_delay: [Nullable(Str), null],
            transition_duration: [Nullable(Str), null],
            transition_property: [Nullable(Str), null],
            transition_timing_function: [Nullable(Str), null],
            translate: [Nullable(Str), null],
            unicode_bidi: [Nullable(Str), null],
            user_select: [Nullable(Str), null],
            vertical_align: [Nullable(Str), null],
            visibility: [Nullable(Str), null],
            white_space: [Nullable(Str), null],
            widows: [Nullable(Str), null],
            width: [Nullable(Str), null],
            will_change: [Nullable(Str), null],
            word_break: [Nullable(Str), null],
            word_spacing: [Nullable(Str), null],
            word_wrap: [Nullable(Str), null],
            writing_mode: [Nullable(Str), null],
            z_index: [Nullable(Str), null],
        }));
    })();
},
/* models/dom/stylesheets.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(51) /* ../../model */;
    const dom = tslib_1.__importStar(require(63) /* ../../core/dom */);
    class StyleSheet extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.StyleSheet = StyleSheet;
    StyleSheet.__name__ = "StyleSheet";
    class InlineStyleSheet extends StyleSheet {
        constructor(attrs) {
            super(attrs);
        }
        underlying() {
            return new dom.InlineStyleSheet(this.css);
        }
    }
    exports.InlineStyleSheet = InlineStyleSheet;
    _a = InlineStyleSheet;
    InlineStyleSheet.__name__ = "InlineStyleSheet";
    (() => {
        _a.define(({ Str }) => ({
            css: [Str],
        }));
    })();
    class ImportedStyleSheet extends StyleSheet {
        constructor(attrs) {
            super(attrs);
        }
        underlying() {
            return new dom.ImportedStyleSheet(this.url);
        }
    }
    exports.ImportedStyleSheet = ImportedStyleSheet;
    _b = ImportedStyleSheet;
    ImportedStyleSheet.__name__ = "ImportedStyleSheet";
    (() => {
        _b.define(({ Str }) => ({
            url: [Str],
        }));
    })();
    class GlobalInlineStyleSheet extends InlineStyleSheet {
        constructor(attrs) {
            super(attrs);
            this._underlying = null;
        }
        underlying() {
            if (this._underlying == null) {
                this._underlying = new dom.GlobalInlineStyleSheet(this.css);
            }
            return this._underlying;
        }
    }
    exports.GlobalInlineStyleSheet = GlobalInlineStyleSheet;
    GlobalInlineStyleSheet.__name__ = "GlobalInlineStyleSheet";
    class GlobalImportedStyleSheet extends ImportedStyleSheet {
        constructor(attrs) {
            super(attrs);
            this._underlying = null;
        }
        underlying() {
            if (this._underlying == null) {
                this._underlying = new dom.GlobalImportedStyleSheet(this.url);
            }
            return this._underlying;
        }
    }
    exports.GlobalImportedStyleSheet = GlobalImportedStyleSheet;
    GlobalImportedStyleSheet.__name__ = "GlobalImportedStyleSheet";
},
/* core/visuals/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const line_1 = require(88) /* ./line */;
    __esExport("Line", line_1.Line);
    __esExport("LineScalar", line_1.LineScalar);
    __esExport("LineVector", line_1.LineVector);
    const fill_1 = require(90) /* ./fill */;
    __esExport("Fill", fill_1.Fill);
    __esExport("FillScalar", fill_1.FillScalar);
    __esExport("FillVector", fill_1.FillVector);
    const text_1 = require(91) /* ./text */;
    __esExport("Text", text_1.Text);
    __esExport("TextScalar", text_1.TextScalar);
    __esExport("TextVector", text_1.TextVector);
    const hatch_1 = require(92) /* ./hatch */;
    __esExport("Hatch", hatch_1.Hatch);
    __esExport("HatchScalar", hatch_1.HatchScalar);
    __esExport("HatchVector", hatch_1.HatchVector);
    const image_1 = require(94) /* ./image */;
    __esExport("Image", image_1.Image);
    __esExport("ImageScalar", image_1.ImageScalar);
    __esExport("ImageVector", image_1.ImageVector);
    const mixins = tslib_1.__importStar(require(80) /* ../property_mixins */);
    const visual_1 = require(89) /* ./visual */;
    __esExport("VisualProperties", visual_1.VisualProperties);
    __esExport("VisualUniforms", visual_1.VisualUniforms);
    class Visuals {
        *[Symbol.iterator]() {
            yield* this._visuals;
        }
        constructor(view) {
            this._visuals = [];
            for (const [prefix, mixin] of view.model._mixins) {
                const visual = (() => {
                    switch (mixin) {
                        case mixins.Line: return new line_1.Line(view, prefix);
                        case mixins.LineScalar: return new line_1.LineScalar(view, prefix);
                        case mixins.LineVector: return new line_1.LineVector(view, prefix);
                        case mixins.Fill: return new fill_1.Fill(view, prefix);
                        case mixins.FillScalar: return new fill_1.FillScalar(view, prefix);
                        case mixins.FillVector: return new fill_1.FillVector(view, prefix);
                        case mixins.Text: return new text_1.Text(view, prefix);
                        case mixins.TextScalar: return new text_1.TextScalar(view, prefix);
                        case mixins.TextVector: return new text_1.TextVector(view, prefix);
                        case mixins.Hatch: return new hatch_1.Hatch(view, prefix);
                        case mixins.HatchScalar: return new hatch_1.HatchScalar(view, prefix);
                        case mixins.HatchVector: return new hatch_1.HatchVector(view, prefix);
                        case mixins.Image: return new image_1.Image(view, prefix);
                        case mixins.ImageScalar: return new image_1.ImageScalar(view, prefix);
                        case mixins.ImageVector: return new image_1.ImageVector(view, prefix);
                        default:
                            throw new Error("unknown visual");
                    }
                })();
                if (visual instanceof visual_1.VisualProperties) {
                    visual.update();
                }
                this._visuals.push(visual);
                Object.defineProperty(this, prefix + visual.type, {
                    get() {
                        return visual;
                    },
                    configurable: false,
                    enumerable: true,
                });
            }
        }
    }
    exports.Visuals = Visuals;
    Visuals.__name__ = "Visuals";
},
/* core/visuals/line.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.resolve_line_dash = resolve_line_dash;
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(89) /* ./visual */;
    const mixins = tslib_1.__importStar(require(80) /* ../property_mixins */);
    const enums_1 = require(20) /* ../enums */;
    const color_1 = require(22) /* ../util/color */;
    const types_1 = require(8) /* ../util/types */;
    function resolve_line_dash(line_dash) {
        if ((0, types_1.isArray)(line_dash)) {
            return line_dash;
        }
        else {
            switch (line_dash) {
                case "solid": return [];
                case "dashed": return [6];
                case "dotted": return [2, 4];
                case "dotdash": return [2, 4, 6, 4];
                case "dashdot": return [6, 4, 2, 4];
                default:
                    return line_dash.split(" ").map(Number).filter(types_1.isInteger);
            }
        }
    }
    class Line extends visual_1.VisualProperties {
        get doit() {
            const color = this.get_line_color();
            const alpha = this.get_line_alpha();
            const width = this.get_line_width();
            return !(color == null || alpha == 0 || width == 0);
        }
        apply(ctx) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.stroke();
            }
            return doit;
        }
        values() {
            return {
                color: this.get_line_color(),
                alpha: this.get_line_alpha(),
                width: this.get_line_width(),
                join: this.get_line_join(),
                cap: this.get_line_cap(),
                dash: this.get_line_dash(),
                offset: this.get_line_dash_offset(),
            };
        }
        set_value(ctx) {
            const color = this.get_line_color();
            const alpha = this.get_line_alpha();
            ctx.strokeStyle = (0, color_1.color2css)(color, alpha);
            ctx.lineWidth = this.get_line_width();
            ctx.lineJoin = this.get_line_join();
            ctx.lineCap = this.get_line_cap();
            ctx.setLineDash(resolve_line_dash(this.get_line_dash()));
            ctx.lineDashOffset = this.get_line_dash_offset();
        }
        get_line_color() {
            const css_color = this._get_css_value("line-color");
            if (css_color != "") {
                return css_color;
            }
            return this.line_color.get_value();
        }
        get_line_alpha() {
            const css_alpha = this._get_css_value("line-alpha");
            if (css_alpha != "") {
                const alpha = Number(css_alpha);
                if (isFinite(alpha)) {
                    return alpha;
                }
            }
            return this.line_alpha.get_value();
        }
        get_line_width() {
            const css_width = this._get_css_value("line-width");
            if (css_width != "") {
                const width = Number(css_width);
                if (isFinite(width)) {
                    return width;
                }
            }
            return this.line_width.get_value();
        }
        get_line_join() {
            const css_join = this._get_css_value("line-join");
            if (enums_1.LineJoin.valid(css_join)) {
                return css_join;
            }
            return this.line_join.get_value();
        }
        get_line_cap() {
            const css_cap = this._get_css_value("line-cap");
            if (enums_1.LineCap.valid(css_cap)) {
                return css_cap;
            }
            return this.line_cap.get_value();
        }
        get_line_dash() {
            const css_dash = this._get_css_value("line-dash");
            if (enums_1.LineDash.valid(css_dash)) {
                return css_dash;
            }
            return this.line_dash.get_value();
        }
        get_line_dash_offset() {
            const css_dash_offset = this._get_css_value("line-dash-offset");
            if (css_dash_offset != "") {
                const dash_offset = Number(css_dash_offset);
                if (isFinite(dash_offset)) {
                    return dash_offset;
                }
            }
            return this.line_dash_offset.get_value();
        }
    }
    exports.Line = Line;
    Line.__name__ = "Line";
    class LineScalar extends visual_1.VisualUniforms {
        get doit() {
            const color = this.line_color.value;
            const alpha = this.line_alpha.value;
            const width = this.line_width.value;
            return !(color == 0 || alpha == 0 || width == 0);
        }
        apply(ctx) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.stroke();
            }
            return doit;
        }
        values() {
            return {
                color: this.line_color.value,
                alpha: this.line_alpha.value,
                width: this.line_width.value,
                join: this.line_join.value,
                cap: this.line_cap.value,
                dash: this.line_dash.value,
                offset: this.line_dash_offset.value,
            };
        }
        set_value(ctx) {
            const color = this.line_color.value;
            const alpha = this.line_alpha.value;
            ctx.strokeStyle = (0, color_1.color2css)(color, alpha);
            ctx.lineWidth = this.line_width.value;
            ctx.lineJoin = this.line_join.value;
            ctx.lineCap = this.line_cap.value;
            ctx.setLineDash(resolve_line_dash(this.line_dash.value));
            ctx.lineDashOffset = this.line_dash_offset.value;
        }
    }
    exports.LineScalar = LineScalar;
    LineScalar.__name__ = "LineScalar";
    class LineVector extends visual_1.VisualUniforms {
        get doit() {
            const { line_color } = this;
            if (line_color.is_Scalar() && line_color.value == 0) {
                return false;
            }
            const { line_alpha } = this;
            if (line_alpha.is_Scalar() && line_alpha.value == 0) {
                return false;
            }
            const { line_width } = this;
            if (line_width.is_Scalar() && line_width.value == 0) {
                return false;
            }
            return true;
        }
        v_doit(i) {
            if (this.line_color.get(i) == 0) {
                return false;
            }
            if (this.line_alpha.get(i) == 0) {
                return false;
            }
            if (this.line_width.get(i) == 0) {
                return false;
            }
            return true;
        }
        apply(ctx, i) {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
                ctx.stroke();
            }
            return doit;
        }
        values(i) {
            return {
                color: this.line_color.get(i),
                alpha: this.line_alpha.get(i),
                width: this.line_width.get(i),
                join: this.line_join.get(i),
                cap: this.line_cap.get(i),
                dash: this.line_dash.get(i),
                offset: this.line_dash_offset.get(i),
            };
        }
        set_vectorize(ctx, i) {
            const color = this.line_color.get(i);
            const alpha = this.line_alpha.get(i);
            const width = this.line_width.get(i);
            const join = this.line_join.get(i);
            const cap = this.line_cap.get(i);
            const dash = this.line_dash.get(i);
            const offset = this.line_dash_offset.get(i);
            ctx.strokeStyle = (0, color_1.color2css)(color, alpha);
            ctx.lineWidth = width;
            ctx.lineJoin = join;
            ctx.lineCap = cap;
            ctx.setLineDash(resolve_line_dash(dash));
            ctx.lineDashOffset = offset;
        }
    }
    exports.LineVector = LineVector;
    LineVector.__name__ = "LineVector";
    Line.prototype.type = "line";
    Line.prototype.attrs = Object.keys(mixins.Line);
    LineScalar.prototype.type = "line";
    LineScalar.prototype.attrs = Object.keys(mixins.LineScalar);
    LineVector.prototype.type = "line";
    LineVector.prototype.attrs = Object.keys(mixins.LineVector);
},
/* core/visuals/visual.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const global_css_prefix = "--bk-";
    class VisualProperties {
        *[Symbol.iterator]() {
            yield* this._props;
        }
        constructor(obj, prefix = "") {
            this.obj = obj;
            this.prefix = prefix;
            this.css_prefix = `${global_css_prefix}${prefix.replaceAll("_", "-")}`;
            const self = this;
            this._props = [];
            for (const attr of this.attrs) {
                const prop = obj.model.properties[prefix + attr];
                prop.change.connect(() => this.update());
                self[attr] = prop;
                this._props.push(prop);
            }
        }
        update() { }
        _get_css_value(name) {
            const style = getComputedStyle(this.obj.el);
            return style.getPropertyValue(`${this.css_prefix}${name}`);
        }
    }
    exports.VisualProperties = VisualProperties;
    VisualProperties.__name__ = "VisualProperties";
    class VisualUniforms {
        *[Symbol.iterator]() {
            for (const attr of this.attrs) {
                yield this.obj.model.properties[this.prefix + attr];
            }
        }
        constructor(obj, prefix = "") {
            this.obj = obj;
            this.prefix = prefix;
            for (const attr of this.attrs) {
                Object.defineProperty(this, attr, {
                    get() {
                        return obj[prefix + attr];
                    },
                });
            }
        }
        update() { }
    }
    exports.VisualUniforms = VisualUniforms;
    VisualUniforms.__name__ = "VisualUniforms";
},
/* core/visuals/fill.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(89) /* ./visual */;
    const mixins = tslib_1.__importStar(require(80) /* ../property_mixins */);
    const color_1 = require(22) /* ../util/color */;
    class Fill extends visual_1.VisualProperties {
        get doit() {
            const color = this.get_fill_color();
            const alpha = this.get_fill_alpha();
            return !(color == null || alpha == 0);
        }
        apply(ctx, rule) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.fill(rule);
            }
            return doit;
        }
        values() {
            return {
                color: this.get_fill_color(),
                alpha: this.get_fill_alpha(),
            };
        }
        set_value(ctx) {
            const color = this.get_fill_color();
            const alpha = this.get_fill_alpha();
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
        }
        get_fill_color() {
            const css_color = this._get_css_value("fill-color");
            if (css_color != "") {
                return css_color;
            }
            return this.fill_color.get_value();
        }
        get_fill_alpha() {
            const css_alpha = this._get_css_value("fill-alpha");
            if (css_alpha != "") {
                const alpha = Number(css_alpha);
                if (isFinite(alpha)) {
                    return alpha;
                }
            }
            return this.fill_alpha.get_value();
        }
    }
    exports.Fill = Fill;
    Fill.__name__ = "Fill";
    class FillScalar extends visual_1.VisualUniforms {
        get doit() {
            const color = this.fill_color.value;
            const alpha = this.fill_alpha.value;
            return !(color == 0 || alpha == 0);
        }
        apply(ctx, rule) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.fill(rule);
            }
            return doit;
        }
        values() {
            return {
                color: this.fill_color.value,
                alpha: this.fill_alpha.value,
            };
        }
        set_value(ctx) {
            const color = this.fill_color.value;
            const alpha = this.fill_alpha.value;
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
        }
    }
    exports.FillScalar = FillScalar;
    FillScalar.__name__ = "FillScalar";
    class FillVector extends visual_1.VisualUniforms {
        get doit() {
            const { fill_color } = this;
            if (fill_color.is_Scalar() && fill_color.value == 0) {
                return false;
            }
            const { fill_alpha } = this;
            if (fill_alpha.is_Scalar() && fill_alpha.value == 0) {
                return false;
            }
            return true;
        }
        v_doit(i) {
            if (this.fill_color.get(i) == 0) {
                return false;
            }
            if (this.fill_alpha.get(i) == 0) {
                return false;
            }
            return true;
        }
        apply(ctx, i, rule) {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
                ctx.fill(rule);
            }
            return doit;
        }
        values(i) {
            return {
                color: this.fill_color.get(i),
                alpha: this.fill_alpha.get(i),
            };
        }
        set_vectorize(ctx, i) {
            const color = this.fill_color.get(i);
            const alpha = this.fill_alpha.get(i);
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
        }
    }
    exports.FillVector = FillVector;
    FillVector.__name__ = "FillVector";
    Fill.prototype.type = "fill";
    Fill.prototype.attrs = Object.keys(mixins.Fill);
    FillScalar.prototype.type = "fill";
    FillScalar.prototype.attrs = Object.keys(mixins.FillScalar);
    FillVector.prototype.type = "fill";
    FillVector.prototype.attrs = Object.keys(mixins.FillVector);
},
/* core/visuals/text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(89) /* ./visual */;
    const mixins = tslib_1.__importStar(require(80) /* ../property_mixins */);
    const enums_1 = require(20) /* ../enums */;
    const color_1 = require(22) /* ../util/color */;
    const _font_cache = new Map();
    function load_font(font, obj) {
        const objs = _font_cache.get(font);
        if (objs == null) {
            const objs = new WeakSet([obj]);
            _font_cache.set(font, objs);
        }
        else if (!objs.has(obj)) {
            objs.add(obj);
        }
        else {
            return;
        }
        const { fonts } = document;
        if (!fonts.check(font)) {
            void fonts.load(font).then(() => obj.request_paint());
        }
    }
    class Text extends visual_1.VisualProperties {
        get doit() {
            const color = this.get_text_color();
            const alpha = this.get_text_alpha();
            return !(color == null || alpha == 0);
        }
        update() {
            if (!this.doit) {
                return;
            }
            const font = this.font_value();
            load_font(font, this.obj);
        }
        values() {
            return {
                color: this.get_text_color(),
                outline_color: this.get_text_outline_color(),
                alpha: this.get_text_alpha(),
                font: this.get_text_font(),
                font_size: this.get_text_font_size(),
                font_style: this.get_text_font_style(),
                align: this.get_text_align(),
                baseline: this.get_text_baseline(),
                line_height: this.get_text_line_height(),
            };
        }
        set_value(ctx) {
            const color = this.get_text_color();
            const outline_color = this.get_text_outline_color();
            const alpha = this.get_text_alpha();
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
            ctx.strokeStyle = (0, color_1.color2css)(outline_color, alpha);
            ctx.font = this.font_value();
            ctx.textAlign = this.get_text_align();
            ctx.textBaseline = this.get_text_baseline();
        }
        font_value() {
            const style = this.get_text_font_style();
            const size = this.get_text_font_size();
            const face = this.get_text_font();
            return `${style} ${size} ${face}`;
        }
        get_text_color() {
            const css_color = this._get_css_value("text-color");
            if (css_color != "") {
                return css_color;
            }
            return this.text_color.get_value();
        }
        get_text_outline_color() {
            const css_color = this._get_css_value("text-outline-color");
            if (css_color != "") {
                return css_color;
            }
            return this.text_outline_color.get_value();
        }
        get_text_alpha() {
            const css_alpha = this._get_css_value("text-alpha");
            if (css_alpha != "") {
                const alpha = Number(css_alpha);
                if (isFinite(alpha)) {
                    return alpha;
                }
            }
            return this.text_alpha.get_value();
        }
        get_text_font() {
            const css_font = this._get_css_value("text-font");
            if (css_font != "") {
                return css_font;
            }
            return this.text_font.get_value();
        }
        get_text_font_size() {
            const css_font_size = this._get_css_value("text-font-size");
            if (css_font_size != "") {
                return css_font_size;
            }
            return this.text_font_size.get_value();
        }
        get_text_font_style() {
            const css_font_style = this._get_css_value("text-font-style");
            if (enums_1.FontStyle.valid(css_font_style)) {
                return css_font_style;
            }
            return this.text_font_style.get_value();
        }
        get_text_align() {
            const css_align = this._get_css_value("text-align");
            if (enums_1.TextAlign.valid(css_align)) {
                return css_align;
            }
            return this.text_align.get_value();
        }
        get_text_baseline() {
            const css_baseline = this._get_css_value("text-baseline");
            if (enums_1.TextBaseline.valid(css_baseline)) {
                return css_baseline;
            }
            return this.text_baseline.get_value();
        }
        get_text_line_height() {
            const css_line_height = this._get_css_value("line-height");
            if (css_line_height != "") {
                const line_height = Number(css_line_height);
                if (isFinite(line_height)) {
                    return line_height;
                }
            }
            return this.text_line_height.get_value();
        }
    }
    exports.Text = Text;
    Text.__name__ = "Text";
    class TextScalar extends visual_1.VisualUniforms {
        get doit() {
            const color = this.text_color.value;
            const alpha = this.text_alpha.value;
            return !(color == 0 || alpha == 0);
        }
        update() {
            if (!this.doit) {
                return;
            }
            const font = this.font_value();
            load_font(font, this.obj);
        }
        values() {
            return {
                color: this.text_color.value,
                outline_color: this.text_outline_color.value,
                alpha: this.text_alpha.value,
                font: this.text_font.value,
                font_size: this.text_font_size.value,
                font_style: this.text_font_style.value,
                align: this.text_align.value,
                baseline: this.text_baseline.value,
                line_height: this.text_line_height.value,
            };
        }
        set_value(ctx) {
            const color = this.text_color.value;
            const alpha = this.text_alpha.value;
            const outline_color = this.text_outline_color.value;
            const font = this.font_value();
            const align = this.text_align.value;
            const baseline = this.text_baseline.value;
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
            ctx.strokeStyle = (0, color_1.color2css)(outline_color, alpha);
            ctx.font = font;
            ctx.textAlign = align;
            ctx.textBaseline = baseline;
        }
        font_value() {
            const style = this.text_font_style.value;
            const size = this.text_font_size.value;
            const face = this.text_font.value;
            return `${style} ${size} ${face}`;
        }
    }
    exports.TextScalar = TextScalar;
    TextScalar.__name__ = "TextScalar";
    class TextVector extends visual_1.VisualUniforms {
        _assert_font(i) {
            const font = this.font_value(i);
            load_font(font, this.obj);
        }
        values(i) {
            this._assert_font(i);
            return {
                color: this.text_color.get(i),
                outline_color: this.text_outline_color.get(i),
                alpha: this.text_alpha.get(i),
                font: this.text_font.get(i),
                font_size: this.text_font_size.get(i),
                font_style: this.text_font_style.get(i),
                align: this.text_align.get(i),
                baseline: this.text_baseline.get(i),
                line_height: this.text_line_height.get(i),
            };
        }
        get doit() {
            const { text_color } = this;
            if (text_color.is_Scalar() && text_color.value == 0) {
                return false;
            }
            const { text_alpha } = this;
            if (text_alpha.is_Scalar() && text_alpha.value == 0) {
                return false;
            }
            return true;
        }
        v_doit(i) {
            if (this.text_color.get(i) == 0) {
                return false;
            }
            if (this.text_alpha.get(i) == 0) {
                return false;
            }
            return true;
        }
        apply(ctx, i) {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
            }
            return doit;
        }
        set_vectorize(ctx, i) {
            this._assert_font(i);
            const color = this.text_color.get(i);
            const outline_color = this.text_outline_color.get(i);
            const alpha = this.text_alpha.get(i);
            const font = this.font_value(i);
            const align = this.text_align.get(i);
            const baseline = this.text_baseline.get(i);
            ctx.fillStyle = (0, color_1.color2css)(color, alpha);
            ctx.strokeStyle = (0, color_1.color2css)(outline_color, alpha);
            ctx.font = font;
            ctx.textAlign = align;
            ctx.textBaseline = baseline;
        }
        font_value(i) {
            const style = this.text_font_style.get(i);
            const size = this.text_font_size.get(i);
            const face = this.text_font.get(i);
            return `${style} ${size} ${face}`;
        }
    }
    exports.TextVector = TextVector;
    TextVector.__name__ = "TextVector";
    Text.prototype.type = "text";
    Text.prototype.attrs = Object.keys(mixins.Text);
    TextScalar.prototype.type = "text";
    TextScalar.prototype.attrs = Object.keys(mixins.TextScalar);
    TextVector.prototype.type = "text";
    TextVector.prototype.attrs = Object.keys(mixins.TextVector);
},
/* core/visuals/hatch.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(89) /* ./visual */;
    const patterns_1 = require(93) /* ./patterns */;
    const p = tslib_1.__importStar(require(18) /* ../properties */);
    const mixins = tslib_1.__importStar(require(80) /* ../property_mixins */);
    const object_1 = require(9) /* ../util/object */;
    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.get_hatch_color();
            const alpha = this.get_hatch_alpha();
            const scale = this.get_hatch_scale();
            const pattern = this.get_hatch_pattern();
            const weight = this.get_hatch_weight();
            const finalize = (image) => {
                this._hatch_image = image;
            };
            const textures = (0, object_1.dict)(this.get_hatch_extra());
            const texture = textures.get(pattern);
            if (texture != null) {
                const image = texture.get_pattern(color, alpha, scale, weight);
                if (image instanceof Promise) {
                    const { _update_iteration } = this;
                    void image.then((image) => {
                        if (this._update_iteration == _update_iteration) {
                            finalize(image);
                            this.obj.request_paint();
                        }
                    });
                }
                else {
                    finalize(image);
                }
            }
            else {
                const layer = this.obj.canvas.create_layer();
                const image = (0, patterns_1.get_pattern)(layer, pattern, color, alpha, scale, weight);
                finalize(image);
            }
        }
        get doit() {
            const color = this.get_hatch_color();
            const alpha = this.get_hatch_alpha();
            const pattern = this.get_hatch_pattern();
            return !(color == null || alpha == 0 || pattern == " " || pattern == "blank" || pattern == null);
        }
        apply(ctx, rule) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.layer.undo_transform(() => ctx.fill(rule));
            }
            return doit;
        }
        set_value(ctx) {
            const pattern = this.pattern(ctx);
            ctx.fillStyle = pattern ?? "transparent";
        }
        pattern(ctx) {
            const image = this._hatch_image;
            if (image == null) {
                return null;
            }
            else {
                return ctx.createPattern(image, this.repetition());
            }
        }
        repetition() {
            const pattern = this.get_hatch_pattern();
            const textures = (0, object_1.dict)(this.get_hatch_extra());
            const texture = textures.get(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";
                }
            }
        }
        get_hatch_color() {
            const css_color = this._get_css_value("hatch-color");
            if (css_color != "") {
                return css_color;
            }
            return this.hatch_color.get_value();
        }
        get_hatch_alpha() {
            const css_alpha = this._get_css_value("hatch-alpha");
            if (css_alpha != "") {
                const alpha = Number(css_alpha);
                if (isFinite(alpha)) {
                    return alpha;
                }
            }
            return this.hatch_alpha.get_value();
        }
        get_hatch_scale() {
            const css_scale = this._get_css_value("hatch-scale");
            if (css_scale != "") {
                const scale = Number(css_scale);
                if (isFinite(scale)) {
                    return scale;
                }
            }
            return this.hatch_scale.get_value();
        }
        get_hatch_pattern() {
            const css_pattern = this._get_css_value("hatch-pattern");
            if (css_pattern != "") {
                if (css_pattern == "none") {
                    return null;
                }
                else {
                    return css_pattern;
                }
            }
            return this.hatch_pattern.get_value();
        }
        get_hatch_weight() {
            const css_weight = this._get_css_value("hatch-weight");
            if (css_weight != "") {
                const weight = Number(css_weight);
                if (isFinite(weight)) {
                    return weight;
                }
            }
            return this.hatch_weight.get_value();
        }
        get_hatch_extra() {
            return this.hatch_extra.get_value();
        }
    }
    exports.Hatch = Hatch;
    Hatch.__name__ = "Hatch";
    class HatchScalar extends visual_1.VisualUniforms {
        constructor() {
            super(...arguments);
            this._static_doit = false;
            this._update_iteration = 0;
        }
        _compute_static_doit() {
            const color = this.hatch_color.value;
            const alpha = this.hatch_alpha.value;
            const pattern = this.hatch_pattern.value;
            return !(color == 0 || alpha == 0 || pattern == " " || pattern == "blank" || pattern == null);
        }
        update() {
            this._update_iteration++;
            const n = this.hatch_color.length;
            this._hatch_image = new p.UniformScalar(null, n);
            this._static_doit = this._compute_static_doit();
            if (!this._static_doit) {
                return;
            }
            const color = this.hatch_color.value;
            const alpha = this.hatch_alpha.value;
            const scale = this.hatch_scale.value;
            const pattern = this.hatch_pattern.value;
            const weight = this.hatch_weight.value;
            const finalize = (image) => {
                this._hatch_image = new p.UniformScalar(image, n);
            };
            const textures = (0, object_1.dict)(this.hatch_extra.value);
            const texture = textures.get(pattern);
            if (texture != null) {
                const image = texture.get_pattern(color, alpha, scale, weight);
                if (image instanceof Promise) {
                    const { _update_iteration } = this;
                    void image.then((image) => {
                        if (this._update_iteration == _update_iteration) {
                            finalize(image);
                            this.obj.request_paint();
                        }
                    });
                }
                else {
                    finalize(image);
                }
            }
            else {
                const layer = this.obj.canvas.create_layer();
                const image = (0, patterns_1.get_pattern)(layer, pattern, color, alpha, scale, weight);
                finalize(image);
            }
        }
        get doit() {
            return this._static_doit;
        }
        apply(ctx, rule) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
                ctx.layer.undo_transform(() => ctx.fill(rule));
            }
            return doit;
        }
        set_value(ctx) {
            ctx.fillStyle = this.pattern(ctx) ?? "transparent";
        }
        pattern(ctx) {
            const image = this._hatch_image.value;
            if (image == null) {
                return null;
            }
            else {
                return ctx.createPattern(image, this.repetition());
            }
        }
        repetition() {
            const pattern = this.hatch_pattern.value;
            if (pattern != null) {
                const textures = (0, object_1.dict)(this.hatch_extra.value);
                const texture = textures.get(pattern);
                if (texture != null) {
                    switch (texture.repetition) {
                        case "repeat": return "repeat";
                        case "repeat_x": return "repeat-x";
                        case "repeat_y": return "repeat-y";
                        case "no_repeat": return "no-repeat";
                    }
                }
            }
            return "repeat";
        }
    }
    exports.HatchScalar = HatchScalar;
    HatchScalar.__name__ = "HatchScalar";
    class HatchVector extends visual_1.VisualUniforms {
        constructor() {
            super(...arguments);
            this._static_doit = false;
            this._update_iteration = 0;
        }
        _compute_static_doit() {
            const { hatch_color } = this;
            if (hatch_color.is_Scalar() && hatch_color.value == 0) {
                return false;
            }
            const { hatch_alpha } = this;
            if (hatch_alpha.is_Scalar() && hatch_alpha.value == 0) {
                return false;
            }
            const { hatch_pattern } = this;
            if (hatch_pattern.is_Scalar()) {
                const pattern = hatch_pattern.value;
                if (pattern == " " || pattern == "blank" || pattern == null) {
                    return false;
                }
            }
            return true;
        }
        update() {
            this._update_iteration++;
            const n = this.hatch_color.length;
            this._hatch_image = new p.UniformScalar(null, n);
            this._static_doit = this._compute_static_doit();
            if (!this._static_doit) {
                return;
            }
            const resolve_image = (pattern, color, alpha, scale, weight, finalize) => {
                const textures = (0, object_1.dict)(this.hatch_extra.value);
                const texture = textures.get(pattern);
                if (texture != null) {
                    const image = texture.get_pattern(color, alpha, scale, weight);
                    if (image instanceof Promise) {
                        const { _update_iteration } = this;
                        void image.then((image) => {
                            if (this._update_iteration == _update_iteration) {
                                finalize(image);
                                this.obj.request_paint();
                            }
                        });
                    }
                    else {
                        finalize(image);
                    }
                }
                else {
                    const layer = this.obj.canvas.create_layer();
                    const image = (0, patterns_1.get_pattern)(layer, pattern, color, alpha, scale, weight);
                    finalize(image);
                }
            };
            if (this.hatch_color.is_Scalar() &&
                this.hatch_alpha.is_Scalar() &&
                this.hatch_scale.is_Scalar() &&
                this.hatch_pattern.is_Scalar() &&
                this.hatch_weight.is_Scalar()) {
                const color = this.hatch_color.value;
                const alpha = this.hatch_alpha.value;
                const scale = this.hatch_scale.value;
                const pattern = this.hatch_pattern.value;
                const weight = this.hatch_weight.value;
                resolve_image(pattern, color, alpha, scale, weight, (image) => {
                    this._hatch_image = new p.UniformScalar(image, n);
                });
            }
            else {
                const images = new Array(n);
                images.fill(null);
                this._hatch_image = new p.UniformVector(images);
                for (let i = 0; i < n; i++) {
                    const color = this.hatch_color.get(i);
                    const alpha = this.hatch_alpha.get(i);
                    const scale = this.hatch_scale.get(i);
                    const pattern = this.hatch_pattern.get(i);
                    const weight = this.hatch_weight.get(i);
                    resolve_image(pattern, color, alpha, scale, weight, (image) => {
                        images[i] = image;
                    });
                }
            }
        }
        get doit() {
            return this._static_doit;
        }
        v_doit(i) {
            if (!this.doit) {
                return false;
            }
            if (this.hatch_color.get(i) == 0) {
                return false;
            }
            if (this.hatch_alpha.get(i) == 0) {
                return false;
            }
            const pattern = this.hatch_pattern.get(i);
            if (pattern == " " || pattern == "blank" || pattern == null) {
                return false;
            }
            return true;
        }
        apply(ctx, i, rule) {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
                ctx.layer.undo_transform(() => ctx.fill(rule));
            }
            return doit;
        }
        set_vectorize(ctx, i) {
            ctx.fillStyle = this.pattern(ctx, i) ?? "transparent";
        }
        pattern(ctx, i) {
            const image = this._hatch_image.get(i);
            if (image == null) {
                return null;
            }
            else {
                return ctx.createPattern(image, this.repetition(i));
            }
        }
        repetition(i) {
            const pattern = this.hatch_pattern.get(i);
            if (pattern != null) {
                const textures = (0, object_1.dict)(this.hatch_extra.value);
                const texture = textures.get(pattern);
                if (texture != null) {
                    switch (texture.repetition) {
                        case "repeat": return "repeat";
                        case "repeat_x": return "repeat-x";
                        case "repeat_y": return "repeat-y";
                        case "no_repeat": return "no-repeat";
                    }
                }
            }
            return "repeat";
        }
    }
    exports.HatchVector = HatchVector;
    HatchVector.__name__ = "HatchVector";
    Hatch.prototype.type = "hatch";
    Hatch.prototype.attrs = Object.keys(mixins.Hatch);
    HatchScalar.prototype.type = "hatch";
    HatchScalar.prototype.attrs = Object.keys(mixins.HatchScalar);
    HatchVector.prototype.type = "hatch";
    HatchVector.prototype.attrs = Object.keys(mixins.HatchVector);
},
/* core/visuals/patterns.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.get_pattern = get_pattern;
    const logging_1 = require(19) /* ../logging */;
    const color_1 = require(22) /* ../util/color */;
    function _horz(ctx, h, h2) {
        ctx.moveTo(0, h2 + 0.5);
        ctx.lineTo(h, h2 + 0.5);
        ctx.stroke();
    }
    function _vert(ctx, h, h2) {
        ctx.moveTo(h2 + 0.5, 0);
        ctx.lineTo(h2 + 0.5, h);
        ctx.stroke();
    }
    function _x(ctx, h) {
        ctx.moveTo(0, h);
        ctx.lineTo(h, 0);
        ctx.stroke();
        ctx.moveTo(0, 0);
        ctx.lineTo(h, h);
        ctx.stroke();
    }
    exports.hatch_aliases = {
        " ": "blank",
        ".": "dot",
        o: "ring",
        "-": "horizontal_line",
        "|": "vertical_line",
        "+": "cross",
        "\"": "horizontal_dash",
        ":": "vertical_dash",
        "@": "spiral",
        "/": "right_diagonal_line",
        "\\": "left_diagonal_line",
        x: "diagonal_cross",
        ",": "right_diagonal_dash",
        "`": "left_diagonal_dash",
        v: "horizontal_wave",
        ">": "vertical_wave",
        "*": "criss_cross",
    };
    function get_pattern(layer, pattern, color, alpha, scale, weight) {
        layer.resize(scale, scale);
        layer.prepare();
        create_hatch_canvas(layer.ctx, pattern, color, alpha, scale, weight);
        return layer.canvas;
    }
    function create_hatch_canvas(ctx, hatch_pattern, hatch_color, hatch_alpha, hatch_scale, hatch_weight) {
        const h = hatch_scale;
        const h2 = h / 2;
        const h4 = h2 / 2;
        const color = (0, color_1.color2css)(hatch_color, hatch_alpha);
        ctx.strokeStyle = color;
        ctx.fillStyle = color;
        ctx.lineCap = "square";
        ctx.lineWidth = hatch_weight;
        switch (exports.hatch_aliases[hatch_pattern] ?? hatch_pattern) {
            // we should not need these if code conditions on hatch.doit, but
            // include them here just for completeness
            case "blank":
                break;
            case "dot":
                ctx.arc(h2, h2, h2 / 2, 0, 2 * Math.PI, true);
                ctx.fill();
                break;
            case "ring":
                ctx.arc(h2, h2, h2 / 2, 0, 2 * Math.PI, true);
                ctx.stroke();
                break;
            case "horizontal_line":
                _horz(ctx, h, h2);
                break;
            case "vertical_line":
                _vert(ctx, h, h2);
                break;
            case "cross":
                _horz(ctx, h, h2);
                _vert(ctx, h, h2);
                break;
            case "horizontal_dash":
                _horz(ctx, h2, h2);
                break;
            case "vertical_dash":
                _vert(ctx, h2, h2);
                break;
            case "spiral": {
                const h30 = h / 30;
                ctx.moveTo(h2, h2);
                for (let i = 0; i < 360; i++) {
                    const angle = 0.1 * i;
                    const x = h2 + (h30 * angle) * Math.cos(angle);
                    const y = h2 + (h30 * angle) * Math.sin(angle);
                    ctx.lineTo(x, y);
                }
                ctx.stroke();
                break;
            }
            case "right_diagonal_line":
                ctx.moveTo(-h4 + 0.5, h);
                ctx.lineTo(h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(h4 + 0.5, h);
                ctx.lineTo(3 * h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(3 * h4 + 0.5, h);
                ctx.lineTo(5 * h4 + 0.5, 0);
                ctx.stroke();
                break;
            case "left_diagonal_line":
                ctx.moveTo(h4 + 0.5, h);
                ctx.lineTo(-h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(3 * h4 + 0.5, h);
                ctx.lineTo(h4 + 0.5, 0);
                ctx.stroke();
                ctx.moveTo(5 * h4 + 0.5, h);
                ctx.lineTo(3 * h4 + 0.5, 0);
                ctx.stroke();
                break;
            case "diagonal_cross":
                _x(ctx, h);
                break;
            case "right_diagonal_dash":
                ctx.moveTo(h4 + 0.5, 3 * h4 + 0.5);
                ctx.lineTo(3 * h4 + 0.5, h4 + 0.5);
                ctx.stroke();
                break;
            case "left_diagonal_dash":
                ctx.moveTo(h4 + 0.5, h4 + 0.5);
                ctx.lineTo(3 * h4 + 0.5, 3 * h4 + 0.5);
                ctx.stroke();
                break;
            case "horizontal_wave":
                ctx.moveTo(0, h4);
                ctx.lineTo(h2, 3 * h4);
                ctx.lineTo(h, h4);
                ctx.stroke();
                break;
            case "vertical_wave":
                ctx.moveTo(h4, 0);
                ctx.lineTo(3 * h4, h2);
                ctx.lineTo(h4, h);
                ctx.stroke();
                break;
            case "criss_cross":
                _x(ctx, h);
                _horz(ctx, h, h2);
                _vert(ctx, h, h2);
                break;
            default:
                logging_1.logger.warn(`unknown hatch pattern: ${hatch_pattern}`);
        }
    }
},
/* core/visuals/image.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const visual_1 = require(89) /* ./visual */;
    const mixins = tslib_1.__importStar(require(80) /* ../property_mixins */);
    class Image extends visual_1.VisualProperties {
        get doit() {
            const alpha = this.global_alpha.get_value();
            return !(alpha == 0);
        }
        apply(ctx) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
            }
            return doit;
        }
        values() {
            return {
                global_alpha: this.global_alpha.get_value(),
            };
        }
        set_value(ctx) {
            const alpha = this.global_alpha.get_value();
            ctx.globalAlpha = alpha;
        }
    }
    exports.Image = Image;
    Image.__name__ = "Image";
    class ImageScalar extends visual_1.VisualUniforms {
        get doit() {
            const alpha = this.global_alpha.value;
            return !(alpha == 0);
        }
        apply(ctx) {
            const { doit } = this;
            if (doit) {
                this.set_value(ctx);
            }
            return doit;
        }
        values() {
            return {
                global_alpha: this.global_alpha.value,
            };
        }
        set_value(ctx) {
            const alpha = this.global_alpha.value;
            ctx.globalAlpha = alpha;
        }
    }
    exports.ImageScalar = ImageScalar;
    ImageScalar.__name__ = "ImageScalar";
    class ImageVector extends visual_1.VisualUniforms {
        get doit() {
            const { global_alpha } = this;
            if (global_alpha.is_Scalar() && global_alpha.value == 0) {
                return false;
            }
            return true;
        }
        v_doit(i) {
            if (this.global_alpha.get(i) == 0) {
                return false;
            }
            return true;
        }
        apply(ctx, i) {
            const doit = this.v_doit(i);
            if (doit) {
                this.set_vectorize(ctx, i);
            }
            return doit;
        }
        values(i) {
            return {
                alpha: this.global_alpha.get(i),
            };
        }
        set_vectorize(ctx, i) {
            const alpha = this.global_alpha.get(i);
            ctx.globalAlpha = alpha;
        }
    }
    exports.ImageVector = ImageVector;
    ImageVector.__name__ = "ImageVector";
    Image.prototype.type = "image";
    Image.prototype.attrs = Object.keys(mixins.Image);
    ImageScalar.prototype.type = "image";
    ImageScalar.prototype.attrs = Object.keys(mixins.ImageScalar);
    ImageVector.prototype.type = "image";
    ImageVector.prototype.attrs = Object.keys(mixins.ImageVector);
},
/* models/coordinates/coordinate_mapping.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const scale_1 = require(96) /* ../scales/scale */;
    const linear_scale_1 = require(101) /* ../scales/linear_scale */;
    const log_scale_1 = require(103) /* ../scales/log_scale */;
    const categorical_scale_1 = require(104) /* ../scales/categorical_scale */;
    const composite_scale_1 = require(105) /* ../scales/composite_scale */;
    const range_1 = require(98) /* ../ranges/range */;
    const data_range1d_1 = require(106) /* ../ranges/data_range1d */;
    const factor_range_1 = require(109) /* ../ranges/factor_range */;
    class CoordinateTransform {
        constructor(x_scale, y_scale) {
            this.x_scale = x_scale;
            this.y_scale = y_scale;
            this.x_source = this.x_scale.source_range;
            this.y_source = this.y_scale.source_range;
            this.ranges = [this.x_source, this.y_source];
            this.scales = [this.x_scale, this.y_scale];
        }
        map_to_screen(xs, ys) {
            const sxs = this.x_scale.v_compute(xs);
            const sys = this.y_scale.v_compute(ys);
            return [sxs, sys];
        }
        map_from_screen(sxs, sys) {
            const xs = this.x_scale.v_invert(sxs);
            const ys = this.y_scale.v_invert(sys);
            return [xs, ys];
        }
    }
    exports.CoordinateTransform = CoordinateTransform;
    CoordinateTransform.__name__ = "CoordinateTransform";
    class CoordinateMapping extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        get x_ranges() {
            return new Map([["default", this.x_source]]);
        }
        get y_ranges() {
            return new Map([["default", this.y_source]]);
        }
        _get_scale(range, scale, target) {
            const factor_range = range instanceof factor_range_1.FactorRange;
            const categorical_scale = scale instanceof categorical_scale_1.CategoricalScale;
            if (factor_range != categorical_scale) {
                throw new Error(`Range ${range.type} is incompatible is Scale ${scale.type}`);
            }
            if (scale instanceof log_scale_1.LogScale && range instanceof data_range1d_1.DataRange1d) {
                range.scale_hint = "log";
            }
            const derived_scale = scale.clone();
            derived_scale.setv({ source_range: range, target_range: target });
            return derived_scale;
        }
        get_transform(frame) {
            const { x_source, x_scale, x_target } = this;
            const x_source_scale = this._get_scale(x_source, x_scale, x_target);
            const { y_source, y_scale, y_target } = this;
            const y_source_scale = this._get_scale(y_source, y_scale, y_target);
            const xscale = new composite_scale_1.CompositeScale({
                source_scale: x_source_scale, source_range: x_source_scale.source_range,
                target_scale: frame.x_scale, target_range: frame.x_target,
            });
            const yscale = new composite_scale_1.CompositeScale({
                source_scale: y_source_scale, source_range: y_source_scale.source_range,
                target_scale: frame.y_scale, target_range: frame.y_target,
            });
            return new CoordinateTransform(xscale, yscale);
        }
    }
    exports.CoordinateMapping = CoordinateMapping;
    _a = CoordinateMapping;
    CoordinateMapping.__name__ = "CoordinateMapping";
    (() => {
        _a.define(({ Ref }) => ({
            x_source: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
            y_source: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
            x_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
            y_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
            x_target: [Ref(range_1.Range)],
            y_target: [Ref(range_1.Range)],
        }));
    })();
},
/* models/scales/scale.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const transform_1 = require(97) /* ../transforms/transform */;
    const range_1 = require(98) /* ../ranges/range */;
    const range1d_1 = require(99) /* ../ranges/range1d */;
    const types_1 = require(24) /* ../../core/types */;
    class Scale extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        compute(x) {
            return this.s_compute(x);
        }
        v_compute(xs) {
            const result = new types_1.ScreenArray(xs.length);
            const { s_compute } = this;
            for (let i = 0; i < xs.length; i++) {
                result[i] = s_compute(xs[i]);
            }
            return result;
        }
        invert(sx) {
            return this.s_invert(sx);
        }
        v_invert(sxs) {
            const result = new Float64Array(sxs.length);
            const { s_invert } = this;
            for (let i = 0; i < sxs.length; i++) {
                result[i] = s_invert(sxs[i]);
            }
            return result;
        }
        r_compute(x0, x1) {
            const { s_compute } = this;
            if (this.target_range.is_reversed) {
                return [s_compute(x1), s_compute(x0)];
            }
            else {
                return [s_compute(x0), s_compute(x1)];
            }
        }
        r_invert(sx0, sx1) {
            const { s_invert } = this;
            if (this.target_range.is_reversed) {
                return [s_invert(sx1), s_invert(sx0)];
            }
            else {
                return [s_invert(sx0), s_invert(sx1)];
            }
        }
    }
    exports.Scale = Scale;
    _a = Scale;
    Scale.__name__ = "Scale";
    (() => {
        _a.internal(({ Ref }) => ({
            source_range: [Ref(range_1.Range)],
            target_range: [Ref(range1d_1.Range1d)],
        }));
    })();
},
/* models/transforms/transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(51) /* ../../model */;
    class Transform extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Transform = Transform;
    Transform.__name__ = "Transform";
},
/* models/ranges/range.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const Bounds = (0, kinds_1.Nullable)((0, kinds_1.Or)((0, kinds_1.Tuple)((0, kinds_1.Nullable)(kinds_1.Float), (0, kinds_1.Nullable)(kinds_1.Float)), kinds_1.Auto));
    class Range extends model_1.Model {
        constructor(attrs) {
            super(attrs);
            this.have_updated_interactively = false;
            /** @internal */
            this.frames = new Set();
        }
        get computed_bounds() {
            return this._computed_bounds;
        }
        get is_reversed() {
            return this.start > this.end;
        }
        get is_valid() {
            return isFinite(this.min) && isFinite(this.max);
        }
        get interval() {
            return [this.start, this.end];
        }
        get span() {
            return Math.abs(this.end - this.start);
        }
        get linked_plots() {
            return new Set((0, iterator_1.map)(this.frames, (frame) => frame.parent));
        }
    }
    exports.Range = Range;
    _a = Range;
    Range.__name__ = "Range";
    (() => {
        _a.define(({ Float, Nullable }) => ({
            bounds: [Bounds, null, {
                    on_update(bounds, obj) {
                        const [lower, upper] = bounds == "auto" || bounds == null ? [null, null] : bounds;
                        obj._computed_bounds = [lower ?? -Infinity, upper ?? Infinity];
                    },
                }],
            min_interval: [Nullable(Float), null],
            max_interval: [Nullable(Float), null],
        }));
    })();
},
/* models/ranges/range1d.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const numerical_range_1 = require(100) /* ./numerical_range */;
    class Range1d extends numerical_range_1.NumericalRange {
        constructor(attrs) {
            super(attrs);
        }
        _set_auto_bounds() {
            if (this.bounds == "auto") {
                const min = Math.min(this._reset_start, this._reset_end);
                const max = Math.max(this._reset_start, this._reset_end);
                this._computed_bounds = [min, max];
            }
        }
        initialize() {
            super.initialize();
            this._set_auto_bounds();
        }
        get min() {
            return Math.min(this.start, this.end);
        }
        get max() {
            return Math.max(this.start, this.end);
        }
        reset() {
            this._set_auto_bounds();
            const { _reset_start, _reset_end } = this;
            if (this.start != _reset_start || this.end != _reset_end) {
                this.setv({ start: _reset_start, end: _reset_end });
            }
            else {
                this.change.emit();
            }
        }
        map(fn) {
            return new _a({ start: fn(this.start), end: fn(this.end) });
        }
        widen(v) {
            let { start, end } = this;
            if (this.is_reversed) {
                start += v;
                end -= v;
            }
            else {
                start -= v;
                end += v;
            }
            return new _a({ start, end });
        }
    }
    exports.Range1d = Range1d;
    _a = Range1d;
    Range1d.__name__ = "Range1d";
    (() => {
        _a.define(({ Float, Nullable }) => ({
            reset_start: [Nullable(Float), null, {
                    on_update(reset_start, self) {
                        self._reset_start = reset_start ?? self.start;
                    },
                }],
            reset_end: [Nullable(Float), null, {
                    on_update(reset_end, self) {
                        self._reset_end = reset_end ?? self.end;
                    },
                }],
        }));
        _a.override({
            start: 0,
            end: 1,
        });
    })();
},
/* models/ranges/numerical_range.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const range_1 = require(98) /* ./range */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const math_1 = require(11) /* ../../core/util/math */;
    class NumericalRange extends range_1.Range {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.NumericalRange = NumericalRange;
    _a = NumericalRange;
    NumericalRange.__name__ = "NumericalRange";
    (() => {
        _a.define(({ Float }) => ({
            start: [Float, p.unset, {
                    convert(value, obj) {
                        const [lower, upper] = obj.computed_bounds;
                        return (0, math_1.clamp)(value, lower, upper);
                    },
                }],
            end: [Float, p.unset, {
                    convert(value, obj) {
                        const [lower, upper] = obj.computed_bounds;
                        return (0, math_1.clamp)(value, lower, upper);
                    },
                }],
        }));
    })();
},
/* models/scales/linear_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_scale_1 = require(102) /* ./continuous_scale */;
    class LinearScale extends continuous_scale_1.ContinuousScale {
        constructor(attrs) {
            super(attrs);
        }
        get s_compute() {
            const [factor, offset] = this._linear_compute_state();
            return (x) => factor * x + offset;
        }
        get s_invert() {
            const [factor, offset] = this._linear_compute_state();
            return (sx) => (sx - offset) / factor;
        }
        /*protected*/ _linear_compute_state() {
            //
            //  (t1 - t0)       (t1 - t0)
            //  --------- * x - --------- * s0 + t0
            //  (s1 - s0)       (s1 - s0)
            //
            // [  factor  ]     [    offset    ]
            //
            const source_start = this.source_range.start;
            const source_end = this.source_range.end;
            const target_start = this.target_range.start;
            const target_end = this.target_range.end;
            const factor = (target_end - target_start) / (source_end - source_start);
            const offset = -(factor * source_start) + target_start;
            return [factor, offset];
        }
    }
    exports.LinearScale = LinearScale;
    LinearScale.__name__ = "LinearScale";
},
/* models/scales/continuous_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const scale_1 = require(96) /* ./scale */;
    class ContinuousScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ContinuousScale = ContinuousScale;
    ContinuousScale.__name__ = "ContinuousScale";
},
/* models/scales/log_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_scale_1 = require(102) /* ./continuous_scale */;
    class LogScale extends continuous_scale_1.ContinuousScale {
        constructor(attrs) {
            super(attrs);
        }
        get s_compute() {
            const [factor, offset, inter_factor, inter_offset] = this._compute_state();
            return (x) => {
                if (inter_factor == 0) {
                    return 0;
                }
                else {
                    const _x = (Math.log(x) - inter_offset) / inter_factor;
                    return isFinite(_x) ? _x * factor + offset : NaN;
                }
            };
        }
        get s_invert() {
            const [factor, offset, inter_factor, inter_offset] = this._compute_state();
            return (xprime) => {
                const value = (xprime - offset) / factor;
                return Math.exp(inter_factor * value + inter_offset);
            };
        }
        _get_safe_factor(orig_start, orig_end) {
            let start = orig_start < 0 ? 0 : orig_start;
            let end = orig_end < 0 ? 0 : orig_end;
            if (start == end) {
                if (start == 0) {
                    [start, end] = [1, 10];
                }
                else {
                    const log_val = Math.log10(start);
                    start = 10 ** Math.floor(log_val);
                    if (Math.ceil(log_val) != Math.floor(log_val)) {
                        end = 10 ** Math.ceil(log_val);
                    }
                    else {
                        end = 10 ** (Math.ceil(log_val) + 1);
                    }
                }
            }
            return [start, end];
        }
        /*protected*/ _compute_state() {
            const source_start = this.source_range.start;
            const source_end = this.source_range.end;
            const target_start = this.target_range.start;
            const target_end = this.target_range.end;
            const screen_range = target_end - target_start;
            const [start, end] = this._get_safe_factor(source_start, source_end);
            let inter_factor;
            let inter_offset;
            if (start == 0) {
                inter_factor = Math.log(end);
                inter_offset = 0;
            }
            else {
                inter_factor = Math.log(end / start);
                inter_offset = Math.log(start);
            }
            const factor = screen_range;
            const offset = target_start;
            return [factor, offset, inter_factor, inter_offset];
        }
    }
    exports.LogScale = LogScale;
    LogScale.__name__ = "LogScale";
},
/* models/scales/categorical_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const scale_1 = require(96) /* ./scale */;
    const linear_scale_1 = require(101) /* ./linear_scale */;
    const { _linear_compute_state } = linear_scale_1.LinearScale.prototype;
    class CategoricalScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
        get s_compute() {
            const [factor, offset] = _linear_compute_state.call(this);
            const range = this.source_range;
            return (x) => factor * range.synthetic(x) + offset;
        }
        get s_invert() {
            const [factor, offset] = _linear_compute_state.call(this);
            return (sx) => (sx - offset) / factor;
        }
    }
    exports.CategoricalScale = CategoricalScale;
    CategoricalScale.__name__ = "CategoricalScale";
},
/* models/scales/composite_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const scale_1 = require(96) /* ../scales/scale */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    class CompositeScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
        get s_compute() {
            const source_compute = this.source_scale.s_compute;
            const target_compute = this.target_scale.s_compute;
            return (x) => target_compute(source_compute(x));
        }
        get s_invert() {
            const source_invert = this.source_scale.s_invert;
            const target_invert = this.target_scale.s_invert;
            return (sx) => source_invert(target_invert(sx));
        }
        compute(x) {
            return this.s_compute(x);
        }
        v_compute(xs) {
            const { s_compute } = this;
            return (0, arrayable_1.map)(xs, s_compute); // XXX
        }
        invert(sx) {
            return this.s_invert(sx);
        }
        v_invert(sxs) {
            const { s_invert } = this;
            return (0, arrayable_1.map)(sxs, s_invert); // XXX
        }
    }
    exports.CompositeScale = CompositeScale;
    _a = CompositeScale;
    CompositeScale.__name__ = "CompositeScale";
    (() => {
        _a.define(({ Ref }) => ({
            source_scale: [Ref(scale_1.Scale)],
            target_scale: [Ref(scale_1.Scale)],
        }));
    })();
},
/* models/ranges/data_range1d.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    exports.is_auto_ranged = is_auto_ranged;
    const tslib_1 = require(1) /* tslib */;
    const data_range_1 = require(107) /* ./data_range */;
    const enums_1 = require(20) /* ../../core/enums */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const math_1 = require(11) /* ../../core/util/math */;
    const logging_1 = require(19) /* ../../core/logging */;
    const bbox = tslib_1.__importStar(require(64) /* ../../core/util/bbox */);
    const util_1 = require(108) /* ../util */;
    exports.auto_ranged = Symbol("auto_ranged");
    function is_auto_ranged(r) {
        return exports.auto_ranged in r;
    }
    class DataRange1d extends data_range_1.DataRange {
        constructor(attrs) {
            super(attrs);
            this.have_updated_interactively = false;
        }
        initialize() {
            super.initialize();
            this._initial_start = isNaN(this.start) ? null : this.start;
            this._initial_end = isNaN(this.end) ? null : this.end;
            this._initial_range_padding = this.range_padding;
            this._initial_range_padding_units = this.range_padding_units;
            this._initial_follow = this.follow;
            this._initial_follow_interval = this.follow_interval;
            this._initial_default_span = this.default_span;
            this._plot_bounds = new Map();
        }
        get min() {
            return Math.min(this.start, this.end);
        }
        get max() {
            return Math.max(this.start, this.end);
        }
        computed_renderers() {
            // TODO (bev) check that renderers actually configured with this range
            const { renderers } = this;
            const all_renderers = (0, iterator_1.flat_map)(this.linked_plots, (plot) => plot.auto_ranged_renderers.map((r) => r.model));
            return (0, util_1.compute_renderers)(renderers.length == 0 ? "auto" : renderers, [...all_renderers]);
        }
        /*protected*/ _compute_plot_bounds(renderers, bounds) {
            let result = bbox.empty();
            for (const r of renderers) {
                const rect = bounds.get(r);
                if (rect != null && (r.visible || !this.only_visible)) {
                    result = bbox.union(result, rect);
                }
            }
            return result;
        }
        adjust_bounds_for_aspect(bounds, ratio) {
            const result = bbox.empty();
            let width = bounds.x1 - bounds.x0;
            if (width <= 0) {
                width = 1.0;
            }
            let height = bounds.y1 - bounds.y0;
            if (height <= 0) {
                height = 1.0;
            }
            const xcenter = 0.5 * (bounds.x1 + bounds.x0);
            const ycenter = 0.5 * (bounds.y1 + bounds.y0);
            if (width < ratio * height) {
                width = ratio * height;
            }
            else {
                height = width / ratio;
            }
            result.x1 = xcenter + 0.5 * width;
            result.x0 = xcenter - 0.5 * width;
            result.y1 = ycenter + 0.5 * height;
            result.y0 = ycenter - 0.5 * height;
            return result;
        }
        /*protected*/ _compute_min_max(plot_bounds, dimension) {
            let overall = bbox.empty();
            for (const [plot, rect] of plot_bounds) {
                if (plot.model.visible) {
                    overall = bbox.union(overall, rect);
                }
            }
            let min, max;
            if (dimension == 0) {
                [min, max] = [overall.x0, overall.x1];
            }
            else {
                [min, max] = [overall.y0, overall.y1];
            }
            return [min, max];
        }
        /*protected*/ _compute_range(min, max) {
            const { range_padding } = this;
            const min_interval = this.min_interval ?? 0;
            const max_interval = this.max_interval ?? Infinity;
            let start, end;
            if (this._initial_start != null) {
                min = this._initial_start;
            }
            if (this._initial_end != null) {
                max = this._initial_end;
            }
            if (this.scale_hint == "log") {
                if (isNaN(min) || !isFinite(min) || min <= 0) {
                    if (isNaN(max) || !isFinite(max) || max <= 0) {
                        min = 0.1;
                    }
                    else {
                        min = max / 100;
                    }
                    logging_1.logger.warn(`could not determine minimum data value for log axis, DataRange1d using value ${min}`);
                }
                if (isNaN(max) || !isFinite(max) || max <= 0) {
                    if (isNaN(min) || !isFinite(min) || min <= 0) {
                        max = 10;
                    }
                    else {
                        max = min * 100;
                    }
                    logging_1.logger.warn(`could not determine maximum data value for log axis, DataRange1d using value ${max}`);
                }
                let center, span;
                if (max == min) {
                    span = this.default_span + 0.001;
                    center = Math.log10(min);
                }
                else {
                    let log_min, log_max;
                    if (this.range_padding_units == "percent") {
                        log_min = Math.log10(min);
                        log_max = Math.log10(max);
                        span = (log_max - log_min) * (1 + range_padding);
                    }
                    else {
                        log_min = Math.log10(min - range_padding);
                        log_max = Math.log10(max + range_padding);
                        span = log_max - log_min;
                    }
                    center = (log_min + log_max) / 2.0;
                }
                span = (0, math_1.clamp)(span, min_interval, max_interval);
                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;
                    }
                }
                span = (0, math_1.clamp)(span, min_interval, max_interval);
                const center = (max + min) / 2.0;
                start = center - span / 2.0;
                end = center + span / 2.0;
            }
            let follow_sign = +1;
            if (this.flipped) {
                [start, end] = [end, start];
                follow_sign = -1;
            }
            const follow_interval = this.follow_interval;
            if (follow_interval != null && Math.abs(start - end) > follow_interval) {
                if (this.follow == "start") {
                    end = start + follow_sign * follow_interval;
                }
                else if (this.follow == "end") {
                    start = end - follow_sign * follow_interval;
                }
            }
            return [start, end];
        }
        update(bounds, dimension, plot, ratio) {
            if (this.have_updated_interactively) {
                return;
            }
            const renderers = this.computed_renderers();
            // update the raw data bounds for all renderers we care about
            let total_bounds = this._compute_plot_bounds(renderers, bounds);
            if (ratio != null) {
                total_bounds = this.adjust_bounds_for_aspect(total_bounds, ratio);
            }
            this._plot_bounds.set(plot, total_bounds);
            // compute the min/mix for our specified dimension
            const [min, max] = this._compute_min_max(this._plot_bounds.entries(), dimension);
            // derive start, end from bounds and data range config
            let [start, end] = this._compute_range(min, max);
            if (this._initial_start != null) {
                if (this.scale_hint == "log") {
                    if (this._initial_start > 0) {
                        start = this._initial_start;
                    }
                }
                else {
                    start = this._initial_start;
                }
            }
            if (this._initial_end != null) {
                if (this.scale_hint == "log") {
                    if (this._initial_end > 0) {
                        end = this._initial_end;
                    }
                }
                else {
                    end = this._initial_end;
                }
            }
            let needs_emit = false;
            if (this.bounds == "auto") {
                this._computed_bounds = [start, end];
                needs_emit = true;
            }
            // only trigger updates when there are changes
            const [_start, _end] = [this.start, this.end];
            if (start != _start || end != _end) {
                const new_range = {};
                if (start != _start) {
                    new_range.start = start;
                }
                if (end != _end) {
                    new_range.end = end;
                }
                this.setv(new_range);
                needs_emit = false;
            }
            if (needs_emit) {
                this.change.emit();
            }
        }
        reset() {
            this.have_updated_interactively = false;
            // change events silenced as PlotView.update_dataranges triggers property callbacks
            this.setv({
                range_padding: this._initial_range_padding,
                range_padding_units: this._initial_range_padding_units,
                follow: this._initial_follow,
                follow_interval: this._initial_follow_interval,
                default_span: this._initial_default_span,
            }, { silent: true });
            this.change.emit();
        }
    }
    exports.DataRange1d = DataRange1d;
    _a = DataRange1d;
    DataRange1d.__name__ = "DataRange1d";
    (() => {
        _a.define(({ Bool, Float, Nullable }) => ({
            range_padding: [Float, 0.1],
            range_padding_units: [enums_1.PaddingUnits, "percent"],
            flipped: [Bool, false],
            follow: [Nullable(enums_1.StartEnd), null],
            follow_interval: [Nullable(Float), null],
            default_span: [Float, 2.0],
            only_visible: [Bool, false],
        }));
        _a.internal(({ Enum }) => ({
            scale_hint: [Enum("log", "auto"), "auto"],
        }));
    })();
},
/* models/ranges/data_range.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const numerical_range_1 = require(100) /* ./numerical_range */;
    class DataRange extends numerical_range_1.NumericalRange {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DataRange = DataRange;
    _a = DataRange;
    DataRange.__name__ = "DataRange";
    (() => {
        _a.define(({ List, AnyRef, Or, Auto }) => ({
            renderers: [Or(List(AnyRef()), Auto), []],
        }));
        _a.override({
            start: NaN,
            end: NaN,
        });
    })();
},
/* models/util.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.compute_renderers = compute_renderers;
    function compute_renderers(renderers, all_renderers) {
        return renderers == "auto" ? all_renderers : renderers ?? [];
    }
},
/* models/ranges/factor_range.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    exports.map_one_level = map_one_level;
    exports.map_two_levels = map_two_levels;
    exports.map_three_levels = map_three_levels;
    const tslib_1 = require(1) /* tslib */;
    const range_1 = require(98) /* ./range */;
    const enums_1 = require(20) /* ../../core/enums */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const signaling_1 = require(15) /* ../../core/signaling */;
    const types_1 = require(24) /* ../../core/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const types_2 = require(8) /* ../../core/util/types */;
    exports.Factor = (0, kinds_1.Or)(kinds_1.Str, (0, kinds_1.Tuple)(kinds_1.Str, kinds_1.Str), (0, kinds_1.Tuple)(kinds_1.Str, kinds_1.Str, kinds_1.Str));
    exports.FactorSeq = (0, kinds_1.Or)((0, kinds_1.List)(kinds_1.Str), (0, kinds_1.List)((0, kinds_1.Tuple)(kinds_1.Str, kinds_1.Str)), (0, kinds_1.List)((0, kinds_1.Tuple)(kinds_1.Str, kinds_1.Str, kinds_1.Str)));
    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)) {
                throw new Error(`duplicate factor or subfactor: ${factor}`);
            }
            mapping.set(factor, { value: 0.5 + i * (1 + padding) + offset });
        }
        const inner_padding = (factors.length - 1) * padding;
        return { mapping, inner_padding };
    }
    function map_two_levels(factors, outer_pad, factor_pad, offset = 0) {
        const mapping = new Map();
        const tops = new Map();
        for (const [f0, f1] of factors) {
            const top = tops.get(f0) ?? [];
            tops.set(f0, [...top, f1]);
        }
        let suboffset = offset;
        let total_subpad = 0;
        for (const [f0, top] of tops) {
            const n = top.length;
            const sub = map_one_level(top, factor_pad, suboffset);
            total_subpad += sub.inner_padding;
            const subtot = (0, array_1.sum)(top.map((f1) => sub.mapping.get(f1).value));
            mapping.set(f0, { value: subtot / n, mapping: sub.mapping });
            suboffset += n + outer_pad + sub.inner_padding;
        }
        const inner_padding = (tops.size - 1) * outer_pad + total_subpad;
        return { mapping, tops: [...mapping.keys()], inner_padding };
    }
    function map_three_levels(factors, outer_pad, inner_pad, factor_pad, offset = 0) {
        const mapping = new Map();
        const tops = new Map();
        for (const [f0, f1, f2] of factors) {
            const top = tops.get(f0) ?? [];
            tops.set(f0, [...top, [f1, f2]]);
        }
        let suboffset = offset;
        let total_subpad = 0;
        for (const [f0, top] of tops) {
            const n = top.length;
            const sub = map_two_levels(top, inner_pad, factor_pad, suboffset);
            total_subpad += sub.inner_padding;
            const subtot = (0, array_1.sum)(top.map(([f1]) => sub.mapping.get(f1).value));
            mapping.set(f0, { value: subtot / n, mapping: sub.mapping });
            suboffset += n + outer_pad + sub.inner_padding;
        }
        const mids = [];
        for (const [f0, L2] of mapping) {
            for (const f1 of L2.mapping.keys()) {
                mids.push([f0, f1]);
            }
        }
        const inner_padding = (tops.size - 1) * outer_pad + total_subpad;
        return { mapping, tops: [...mapping.keys()], mids, inner_padding };
    }
    const is_l1 = (x) => (0, types_2.isString)(x);
    const is_l2 = (x) => (0, types_2.isArray)(x) && x.length == 2 && (0, types_2.isString)(x[0]) && (0, types_2.isString)(x[1]);
    const is_l3 = (x) => (0, types_2.isArray)(x) && x.length == 3 && (0, types_2.isString)(x[0]) && (0, types_2.isString)(x[1]) && (0, types_2.isString)(x[2]);
    class FactorMapper {
        constructor({ levels, mapping, tops = null, mids = null, inner_padding }) {
            this.levels = levels;
            this.mapping = mapping;
            this.tops = tops;
            this.mids = mids;
            this.inner_padding = inner_padding;
        }
        static compute_levels(factors) {
            if ((0, array_1.every)(factors, is_l1)) {
                return 1;
            }
            if ((0, array_1.every)(factors, is_l2)) {
                return 2;
            }
            if ((0, array_1.every)(factors, is_l3)) {
                return 3;
            }
            throw TypeError("factor levels are inconsistent");
        }
        static for(range) {
            switch (this.compute_levels(range.factors)) {
                case 1: {
                    return new L1FactorMapper(range);
                }
                case 2: {
                    return new L2FactorMapper(range);
                }
                case 3: {
                    return new L3FactorMapper(range);
                }
            }
        }
        map(x) {
            if ((0, types_2.isNumber)(x)) {
                return x;
            }
            const [boxed, offset] = (() => {
                if ((0, types_2.isString)(x)) {
                    return [[x], 0];
                }
                const last = x[x.length - 1];
                if ((0, types_2.isNumber)(last)) {
                    return [x.slice(0, -1), last];
                }
                return [x, 0];
            })();
            if (boxed.length > this.levels) {
                throw new Error(`Attempted to map ${boxed.length} levels of factors with an L${this.levels}FactorMap`);
            }
            return this.lookup_value(boxed) + offset;
        }
        lookup_value(x) {
            return this.lookup_entry(x)?.value ?? NaN;
        }
    }
    exports.FactorMapper = FactorMapper;
    FactorMapper.__name__ = "FactorMapper";
    class L1FactorMapper extends FactorMapper {
        constructor(range) {
            const { factors, factor_padding } = range;
            const spec = map_one_level(factors, factor_padding);
            super({ levels: 1, ...spec });
        }
        lookup_entry(x) {
            const [f0] = x;
            return this.mapping.get(f0) ?? null;
        }
    }
    L1FactorMapper.__name__ = "L1FactorMapper";
    class L2FactorMapper extends FactorMapper {
        constructor(range) {
            const { factors, group_padding, factor_padding } = range;
            const spec = map_two_levels(factors, group_padding, factor_padding);
            super({ levels: 2, ...spec });
        }
        lookup_entry(x) {
            if (x.length == 1) {
                const [f0] = x;
                return this.mapping.get(f0) ?? null;
            }
            else {
                const [f0, f1] = x;
                return this.mapping.get(f0)?.mapping.get(f1) ?? null;
            }
        }
    }
    L2FactorMapper.__name__ = "L2FactorMapper";
    class L3FactorMapper extends FactorMapper {
        constructor(range) {
            const { factors, group_padding, subgroup_padding, factor_padding } = range;
            const spec = map_three_levels(factors, group_padding, subgroup_padding, factor_padding);
            super({ levels: 3, ...spec });
        }
        lookup_entry(x) {
            if (x.length == 1) {
                const [f0] = x;
                return this.mapping.get(f0) ?? null;
            }
            else if (x.length == 2) {
                const [f0, f1] = x;
                return this.mapping.get(f0)?.mapping.get(f1) ?? null;
            }
            else {
                const [f0, f1, f2] = x;
                return this.mapping.get(f0)?.mapping.get(f1)?.mapping.get(f2) ?? null;
            }
        }
    }
    L3FactorMapper.__name__ = "L3FactorMapper";
    class FactorRange extends range_1.Range {
        constructor(attrs) {
            super(attrs);
            this.invalidate_synthetic = new signaling_1.Signal0(this, "invalidate_synthetic");
        }
        get min() {
            return this.start;
        }
        get max() {
            return this.end;
        }
        initialize() {
            super.initialize();
            this.configure();
        }
        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.configure();
            this.invalidate_synthetic.emit();
        }
        /** Convert a categorical factor into a synthetic coordinate. */
        synthetic(x) {
            return this.mapper.map(x);
        }
        /** Convert an array of categorical factors into synthetic coordinates. */
        v_synthetic(xs) {
            return types_1.ScreenArray.from(xs, (x) => this.synthetic(x));
        }
        /** Convert a synthetic coordinate into a categorical factor. */
        factor(x) {
            for (const f of this.factors) {
                const v = this.mapper.map(f);
                if (x >= (v - 0.5) && x < (v + 0.5)) {
                    return f;
                }
            }
            return null;
        }
        compute_bounds(inner_padding) {
            const interval = this.factors.length + inner_padding;
            const padding = (() => {
                switch (this.range_padding_units) {
                    case "percent": {
                        return interval * this.range_padding / 2;
                    }
                    case "absolute": {
                        return this.range_padding;
                    }
                }
            })();
            return [-padding, interval + padding];
        }
        configure() {
            this.mapper = FactorMapper.for(this);
            const [start, end] = this.compute_bounds(this.mapper.inner_padding);
            this.setv({ start, end }, { silent: true });
            if (this.bounds == "auto") {
                this._computed_bounds = [start, end];
            }
        }
    }
    exports.FactorRange = FactorRange;
    _a = FactorRange;
    FactorRange.__name__ = "FactorRange";
    (() => {
        _a.define(({ Float }) => ({
            factors: [exports.FactorSeq, []],
            factor_padding: [Float, 0],
            subgroup_padding: [Float, 0.8],
            group_padding: [Float, 1.4],
            range_padding: [Float, 0],
            range_padding_units: [enums_1.PaddingUnits, "percent"],
            start: [Float, p.unset, { readonly: true }],
            end: [Float, p.unset, { readonly: true }],
        }));
    })();
},
/* models/ui/menus/menu.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(111) /* ../ui_element */;
    const menu_item_1 = require(117) /* ./menu_item */;
    const action_item_1 = require(118) /* ./action_item */;
    const checkable_item_1 = require(120) /* ./checkable_item */;
    const divider_item_1 = require(121) /* ./divider_item */;
    const dom_1 = require(63) /* ../../../core/dom */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const build_views_1 = require(56) /* ../../../core/build_views */;
    const array_1 = require(10) /* ../../../core/util/array */;
    const callbacks_1 = require(50) /* ../../../core/util/callbacks */;
    const menus__css_1 = tslib_1.__importStar(require(122) /* ../../../styles/menus_.css */), menus = menus__css_1;
    const icons_css_1 = tslib_1.__importDefault(require(123) /* ../../../styles/icons.css */);
    class MenuView extends ui_element_1.UIElementView {
        constructor() {
            super(...arguments);
            this._menu_views = new Map();
            this._open = false;
            this._item_click = (item) => {
                if (!item.disabled) {
                    const { action } = item;
                    if (action != null) {
                        void (0, callbacks_1.execute)(action, this.model, { item });
                    }
                    this.hide();
                }
            };
            this._on_mousedown = (event) => {
                if (event.composedPath().includes(this.el)) {
                    return;
                }
                if (this.prevent_hide?.(event) ?? false) {
                    return;
                }
                this.hide();
            };
            this._on_keydown = (event) => {
                if (event.key == "Escape") {
                    this.hide();
                }
            };
            this._on_blur = () => {
                this.hide();
            };
        }
        *children() {
            yield* super.children();
            yield* this._menu_views.values();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const menus = this.model.items
                .map((item) => item instanceof action_item_1.ActionItem ? item.menu : null)
                .filter((item) => item != null);
            await (0, build_views_1.build_views)(this._menu_views, menus, { parent: this });
        }
        get is_open() {
            return this._open;
        }
        remove() {
            this._unlisten();
            (0, build_views_1.remove_views)(this._menu_views);
            super.remove();
        }
        _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);
        }
        stylesheets() {
            return [...super.stylesheets(), menus__css_1.default, icons_css_1.default];
        }
        render() {
            super.render();
            const items = (() => {
                const { reversed, items } = this.model;
                return reversed ? (0, array_1.reversed)(items) : items;
            })();
            for (const item of items) {
                if (item instanceof divider_item_1.DividerItem) {
                    const item_el = (0, dom_1.div)({ class: menus.divider });
                    this.shadow_el.append(item_el);
                }
                else if (item instanceof action_item_1.ActionItem) {
                    const check_el = (0, dom_1.div)({ class: menus.check });
                    const icon_el = (0, dom_1.div)({ class: menus.icon });
                    const label_el = (0, dom_1.div)({ class: menus.label }, item.label);
                    const shortcut_el = (0, dom_1.div)({ class: menus.shortcut }, item.shortcut);
                    const chevron_el = (0, dom_1.div)({ class: menus.chevron });
                    const { icon } = item;
                    if (icon != null) {
                        if (icon.startsWith("data:image")) {
                            const url = `url("${encodeURI(icon)}")`;
                            icon_el.style.backgroundImage = url;
                        }
                        else if (icon.startsWith("--")) {
                            icon_el.style.backgroundImage = `var(${icon})`;
                        }
                        else if (icon.startsWith(".")) {
                            const cls = icon.substring(1);
                            icon_el.classList.add(cls);
                        }
                        else if (enums_1.ToolIcon.valid(icon)) {
                            const cls = `bk-tool-icon-${icon.replace(/_/g, "-")}`;
                            icon_el.classList.add(cls);
                        }
                    }
                    const item_el = (0, dom_1.div)({ class: menus.item, title: item.tooltip, tabIndex: 0 }, check_el, icon_el, label_el, shortcut_el, chevron_el);
                    item_el.classList.toggle(menus.menu, item.menu != null);
                    item_el.classList.toggle(menus.disabled, item.disabled);
                    if (item instanceof checkable_item_1.CheckableItem) {
                        item_el.classList.add(menus.checkable);
                        item_el.classList.toggle(menus.checked, item.checked);
                    }
                    item_el.addEventListener("click", () => {
                        this._item_click(item);
                    });
                    item_el.addEventListener("keydown", (event) => {
                        if (event.key == "Enter") {
                            this._item_click(item);
                        }
                    });
                    const { menu } = item;
                    if (menu != null) {
                        item_el.addEventListener("pointerenter", () => {
                            const menu_view = this._menu_views.get(menu);
                            menu_view._show_submenu(item_el);
                        });
                        item_el.addEventListener("pointerleave", () => {
                            const menu_view = this._menu_views.get(menu);
                            menu_view.hide();
                        });
                    }
                    this.shadow_el.append(item_el);
                }
            }
        }
        _show_submenu(target) {
            if (this.model.items.length == 0) {
                this.hide();
                return;
            }
            this.render();
            target.append(this.el);
            const { style } = this.el;
            style.left = "100%";
            style.top = "0";
            this._listen();
            this._open = true;
        }
        show(at) {
            if (this.model.items.length == 0) {
                this.hide();
                return;
            }
            const { parent } = this;
            if (parent == null) {
                // TODO position: fixed
                this.hide();
                return;
            }
            this.render();
            const target = parent.el.shadowRoot ?? parent.el;
            target.append(this.el);
            const { style } = this.el;
            style.left = (0, dom_1.px)(at.x);
            style.top = (0, dom_1.px)(at.y);
            this._listen();
            this._open = true;
        }
        hide() {
            if (this._open) {
                this._open = false;
                this._unlisten();
                this.el.remove();
            }
        }
    }
    exports.MenuView = MenuView;
    MenuView.__name__ = "MenuView";
    class Menu extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Menu = Menu;
    _a = Menu;
    Menu.__name__ = "Menu";
    (() => {
        _a.prototype.default_view = MenuView;
        _a.define(({ Bool, List, Ref }) => ({
            items: [List(Ref(menu_item_1.MenuItem)), []],
            reversed: [Bool, false],
        }));
    })();
},
/* models/ui/ui_element.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const styled_element_1 = require(84) /* ./styled_element */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const dom_1 = require(63) /* ../../core/dom */;
    const canvas_1 = require(112) /* ../../core/util/canvas */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const types_1 = require(8) /* ../../core/util/types */;
    const defer_1 = require(16) /* ../../core/util/defer */;
    const ui_css_1 = tslib_1.__importDefault(require(116) /* ../../styles/ui.css */);
    const { round, floor } = Math;
    class UIElementView extends styled_element_1.StyledElementView {
        constructor() {
            super(...arguments);
            this._display = new dom_1.InlineStyleSheet();
            this._bbox = new bbox_1.BBox();
            this._context_menu = null;
            this._resized = false;
            this._is_displayed = false;
        }
        *_stylesheets() {
            yield* super._stylesheets();
            yield this._display;
        }
        stylesheets() {
            return [...super.stylesheets(), ui_css_1.default];
        }
        update_style() {
            this.style.clear();
        }
        box_sizing() {
            return {
                width_policy: "auto", height_policy: "auto",
                width: null, height: null,
                aspect_ratio: null,
            };
        }
        get bbox() {
            return this._bbox;
        }
        update_bbox() {
            return this._update_bbox();
        }
        _update_bbox() {
            const displayed = (() => {
                // Consider using Element.checkVisibility() in the future.
                // https://w3c.github.io/csswg-drafts/cssom-view-1/#dom-element-checkvisibility
                if (!this.el.isConnected) {
                    return false;
                }
                else if (this.el.offsetParent != null) {
                    return true;
                }
                else {
                    const { position, display } = getComputedStyle(this.el);
                    return position == "fixed" && display != "none";
                }
            })();
            const bbox = !displayed ? new bbox_1.BBox() : (() => {
                const self = this.el.getBoundingClientRect();
                const { left, top } = (() => {
                    if (this.parent != null) {
                        const parent = this.parent.el.getBoundingClientRect();
                        return {
                            left: self.left - parent.left,
                            top: self.top - parent.top,
                        };
                    }
                    else {
                        return { left: 0, top: 0 };
                    }
                })();
                return new bbox_1.BBox({
                    left: round(left),
                    top: round(top),
                    width: floor(self.width),
                    height: floor(self.height),
                });
            })();
            const changed = !this._bbox.equals(bbox);
            this._bbox = bbox;
            this._is_displayed = displayed;
            return changed;
        }
        initialize() {
            super.initialize();
            this._resize_observer = new ResizeObserver((_entries) => this.after_resize());
            this._resize_observer.observe(this.el, { box: "border-box" });
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { context_menu } = this.model;
            if (context_menu != null) {
                this._context_menu = await (0, build_views_1.build_view)(context_menu, { parent: this });
            }
        }
        connect_signals() {
            super.connect_signals();
            const { visible } = this.model.properties;
            this.on_change(visible, () => this._update_visible());
            this.el.addEventListener("contextmenu", (event) => this.show_context_menu(event));
        }
        get_context_menu(_xy) {
            return this._context_menu;
        }
        show_context_menu(event) {
            if (!event.shiftKey) {
                const rect = this.el.getBoundingClientRect();
                const x = event.x - rect.x;
                const y = event.y - rect.y;
                const context_menu = this.get_context_menu({ x, y });
                if (context_menu != null) {
                    event.stopPropagation();
                    event.preventDefault();
                    context_menu.show({ x, y });
                }
            }
        }
        remove() {
            this._resize_observer.disconnect();
            this._context_menu?.remove();
            super.remove();
        }
        _after_resize() { }
        after_resize() {
            this._resized = true;
            if (this.update_bbox()) {
                this._after_resize();
            }
            this.finish();
        }
        render() {
            super.render();
            this._apply_visible();
        }
        _after_render() {
            this.update_style();
            this.update_bbox();
        }
        after_render() {
            super.after_render();
            this._after_render();
            if (!this._has_finished) {
                // If not displayed, then after_resize() will not be called.
                if (!this.is_displayed) {
                    this.force_finished();
                }
                else {
                    // In case after_resize() wasn't called (see regression test for issue
                    // #9113), then wait one macro task and consider this view finished.
                    void (0, defer_1.defer)().then(() => {
                        if (!this._resized) {
                            this.finish();
                        }
                    });
                }
            }
        }
        get is_displayed() {
            return this._is_displayed;
        }
        _apply_visible() {
            if (this.model.visible) {
                this._display.clear();
            }
            else {
                // in case `display` element style was set, use `!important` to work around this
                this._display.replace(":host { display: none !important; }");
            }
        }
        _update_visible() {
            this._apply_visible();
        }
        export(type = "auto", hidpi = true) {
            const output_backend = type == "auto" || type == "png" ? "canvas" : "svg";
            const canvas = new canvas_1.CanvasLayer(output_backend, hidpi);
            const { width, height } = this.bbox;
            canvas.resize(width, height);
            return canvas;
        }
        resolve_symbol(node) {
            const value = this.bbox.resolve(node.symbol);
            const { offset } = node;
            if ((0, types_1.isNumber)(value)) {
                return value + offset;
            }
            else {
                const { x, y } = value;
                return { x: x + offset, y: y + offset };
            }
        }
    }
    exports.UIElementView = UIElementView;
    UIElementView.__name__ = "UIElementView";
    class UIElement extends styled_element_1.StyledElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.UIElement = UIElement;
    _a = UIElement;
    UIElement.__name__ = "UIElement";
    (() => {
        _a.define(({ Bool, AnyRef, Nullable }) => ({
            visible: [Bool, true],
            context_menu: [Nullable(AnyRef()), null],
        }));
    })();
},
/* core/util/canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const svg_1 = require(113) /* ./svg */;
    const bbox_1 = require(64) /* ./bbox */;
    const dom_1 = require(63) /* ../dom */;
    class CanvasLayer {
        get canvas() {
            return this._canvas;
        }
        get ctx() {
            return this._ctx;
        }
        get el() {
            return this._el;
        }
        constructor(backend, hidpi) {
            this.pixel_ratio = 1;
            this.bbox = new bbox_1.BBox();
            this.backend = backend;
            this.hidpi = hidpi;
            switch (backend) {
                case "webgl":
                case "canvas": {
                    this._el = this._canvas = (0, dom_1.canvas)({ class: "bk-layer" });
                    const ctx = this.canvas.getContext("2d");
                    if (ctx == null) {
                        throw new Error("unable to obtain 2D rendering context");
                    }
                    this._ctx = ctx;
                    if (hidpi) {
                        this.pixel_ratio = devicePixelRatio;
                    }
                    break;
                }
                case "svg": {
                    const ctx = new svg_1.SVGRenderingContext2D();
                    this._ctx = ctx;
                    this._canvas = ctx.get_svg();
                    this._el = (0, dom_1.div)({ class: "bk-layer" });
                    const shadow_el = this._el.attachShadow({ mode: "open" });
                    shadow_el.appendChild(this._canvas);
                    break;
                }
            }
            this._ctx.layer = this;
        }
        resize(width, height) {
            if (this.bbox.width == width && this.bbox.height == height) {
                return;
            }
            this.bbox = new bbox_1.BBox({ left: 0, top: 0, width, height });
            const { target } = this;
            target.width = width * this.pixel_ratio;
            target.height = height * this.pixel_ratio;
        }
        get target() {
            return this._ctx instanceof svg_1.SVGRenderingContext2D ? this._ctx : this.canvas;
        }
        undo_transform(fn) {
            const { ctx } = this;
            const current_transform = ctx.getTransform();
            ctx.resetTransform();
            try {
                fn(ctx);
            }
            finally {
                ctx.setTransform(current_transform);
            }
        }
        prepare() {
            const { ctx, hidpi, pixel_ratio } = this;
            ctx.save();
            if (hidpi) {
                ctx.scale(pixel_ratio, pixel_ratio);
                ctx.translate(0.5, 0.5);
            }
            this.clear();
        }
        clear() {
            const { x, y, width, height } = this.bbox;
            this.ctx.clearRect(x, y, width, height);
        }
        finish() {
            this.ctx.restore();
        }
        to_blob() {
            const { _canvas } = this;
            if (_canvas instanceof HTMLCanvasElement) {
                return new Promise((resolve, reject) => {
                    _canvas.toBlob((blob) => blob != null ? resolve(blob) : reject(), "image/png");
                });
            }
            else {
                const ctx = this._ctx;
                const svg = ctx.get_serialized_svg(true);
                const blob = new Blob([svg], { type: "image/svg+xml" });
                return Promise.resolve(blob);
            }
        }
    }
    exports.CanvasLayer = CanvasLayer;
    CanvasLayer.__name__ = "CanvasLayer";
},
/* core/util/svg.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    /**
     * Based on https://github.com/gliffy/canvas2svg
     */
    const affine_1 = require(114) /* ./affine */;
    const types_1 = require(8) /* ./types */;
    const object_1 = require(9) /* ./object */;
    const random_1 = require(115) /* ./random */;
    const math_1 = require(11) /* ./math */;
    const dom_1 = require(63) /* ../dom */;
    // helper function to map named to numbered entities
    function createNamedToNumberedLookup(input, radix) {
        const lookup = new Map();
        const items = input.split(",");
        radix = radix ?? 10;
        // Map from named to numbered entities.
        for (let i = 0; i < items.length; i += 2) {
            const entity = `&${items[i + 1]};`;
            const base10 = parseInt(items[i], radix);
            lookup.set(entity, `&#${base10};`);
        }
        // FF and IE need to create a regex from hex values ie &nbsp; == \xa0
        lookup.set("\\xa0", "&#160;");
        return lookup;
    }
    // helper function to map canvas-textAlign to svg-textAnchor
    function getTextAnchor(textAlign) {
        // TODO: support rtl languages
        const mapping = { left: "start", right: "end", center: "middle", start: "start", end: "end" };
        return textAlign in mapping ? mapping[textAlign] : mapping.start;
    }
    // helper function to map canvas-textBaseline to svg-dominantBaseline
    function getDominantBaseline(textBaseline) {
        // INFO: not supported in all browsers
        const mapping = { alphabetic: "alphabetic", hanging: "hanging", top: "text-before-edge", bottom: "text-after-edge", middle: "central" };
        return textBaseline in mapping ? mapping[textBaseline] : mapping.alphabetic;
    }
    // Unpack entities lookup where the numbers are in radix 32 to reduce the size
    // entity mapping courtesy of tinymce
    const namedEntities = createNamedToNumberedLookup("50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy," +
        "5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute," +
        "5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34," +
        "5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil," +
        "68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde," +
        "6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute," +
        "6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml," +
        "75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc," +
        "7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash," +
        "7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta," +
        "sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu," +
        "st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi," +
        "t9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota," +
        "tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau," +
        "u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip," +
        "81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym," +
        "8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr," +
        "8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod," +
        "8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup," +
        "8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4," +
        "nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob," +
        "rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0," +
        "Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm," +
        "80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger," +
        "811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro", 32);
    // Some basic mappings for attributes and default values.
    const STYLES = {
        strokeStyle: {
            svgAttr: "stroke", // corresponding svg attribute
            canvas: "#000000", // canvas default
            svg: "none", // svg default
            apply: "stroke", // apply on stroke() or fill()
        },
        fillStyle: {
            svgAttr: "fill",
            canvas: "#000000",
            svg: null, // svg default is black, but we need to special case this to handle canvas stroke without fill
            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",
        },
        shadowColor: {
            canvas: "#000000",
        },
        shadowOffsetX: {
            canvas: 0,
        },
        shadowOffsetY: {
            canvas: 0,
        },
        shadowBlur: {
            canvas: 0,
        },
        lineDash: {
            svgAttr: "stroke-dasharray",
            canvas: [],
            svg: null,
            apply: "stroke",
        },
        lineDashOffset: {
            svgAttr: "stroke-dashoffset",
            canvas: 0,
            svg: 0,
            apply: "stroke",
        },
        direction: {
            canvas: "inherit",
        },
        font: {
            // font converts to multiple svg attributes, there is custom logic for this
            canvas: "10px sans-serif",
        },
        fontKerning: {
            canvas: "auto",
        },
        fontStretch: {
            canvas: "normal",
        },
        fontVariantCaps: {
            canvas: "normal",
        },
        letterSpacing: {
            canvas: "0px",
        },
        textAlign: {
            canvas: "start",
        },
        textBaseline: {
            canvas: "alphabetic",
        },
        textRendering: {
            canvas: "auto",
        },
        wordSpacing: {
            canvas: "0px",
        },
    };
    function is_VideoFrame(image) {
        return typeof VideoFrame !== "undefined" && image instanceof VideoFrame;
    }
    function width_height(image) {
        if (is_VideoFrame(image)) {
            return [image.codedWidth, image.codedHeight]; // TODO not sure if this makes any sense
        }
        else {
            function to_number(val) {
                return (0, types_1.isNumber)(val) ? val : val.baseVal.value;
            }
            const { width, height } = image;
            return [to_number(width), to_number(height)];
        }
    }
    class CanvasGradient {
        constructor(gradientNode, ctx) {
            this.__root = gradientNode;
            this.__ctx = ctx;
        }
        /**
         * Adds a color stop to the gradient root
         */
        addColorStop(offset, color) {
            if (this.__root.nodeName === "linearGradient" &&
                this.__root.getAttribute("x1") === this.__root.getAttribute("x2") &&
                this.__root.getAttribute("y1") === this.__root.getAttribute("y2")) {
                return;
            }
            if (this.__root.nodeName === "radialGradient" &&
                this.__root.getAttribute("cx") === this.__root.getAttribute("fx") &&
                this.__root.getAttribute("cy") === this.__root.getAttribute("fy") &&
                this.__root.getAttribute("r") === this.__root.getAttribute("r0")) {
                return;
            }
            const stop = this.__ctx.__createElement("stop");
            stop.setAttribute("offset", `${offset}`);
            if (color.indexOf("rgba") !== -1) {
                // separate alpha value, since webkit can't handle it
                const regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi;
                const matches = regex.exec(color);
                const [, r, g, b, a] = matches;
                stop.setAttribute("stop-color", `rgb(${r},${g},${b})`);
                stop.setAttribute("stop-opacity", a);
            }
            else {
                stop.setAttribute("stop-color", color);
            }
            this.__root.appendChild(stop);
        }
    }
    CanvasGradient.__name__ = "CanvasGradient";
    class CanvasPattern {
        constructor(pattern, ctx) {
            this.__root = pattern;
            this.__ctx = ctx;
        }
        setTransform(_transform) {
            throw new Error("not implemented");
        }
    }
    CanvasPattern.__name__ = "CanvasPattern";
    class SVGRenderingContext2D {
        get canvas() {
            // XXX: point back to this instance
            return this;
        }
        get width() {
            return this._width;
        }
        set width(width) {
            this._width = width;
            this.__root.setAttribute("width", `${width}`);
        }
        get height() {
            return this._height;
        }
        set height(height) {
            this._height = height;
            this.__root.setAttribute("height", `${height}`);
        }
        constructor(options) {
            this.__currentDefaultPath = "";
            this.__currentPosition = null;
            this.globalAlpha = 1.0;
            this._transform = new affine_1.AffineTransform();
            this._clip_path = null;
            this.__document = options?.document ?? document;
            // allow passing in an existing context to wrap around
            // if a context is passed in, we know a canvas already exist
            if (options?.ctx != null) {
                this.__ctx = options.ctx;
            }
            else {
                this.__canvas = this.__document.createElement("canvas");
                this.__ctx = this.__canvas.getContext("2d");
            }
            this.reset();
            // the root svg element
            this.__root = this.__document.createElementNS("http://www.w3.org/2000/svg", "svg");
            this.__root.setAttribute("version", "1.1");
            this.__root.setAttribute("xmlns", "http://www.w3.org/2000/svg");
            this.__currentElement = this.__root;
            this.width = options?.width ?? 500;
            this.height = options?.height ?? 500;
            // make sure we don't generate the same ids in defs
            this.__ids = new Set();
            // defs tag
            this.__defs = this.__document.createElementNS("http://www.w3.org/2000/svg", "defs");
            this.__root.appendChild(this.__defs);
        }
        // helper function that generates a random string
        _random_string() {
            const chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
            let str;
            do {
                str = SVGRenderingContext2D.__random.choices(12, chars).join("");
            } while (this.__ids.has(str));
            return str;
        }
        /**
         * Creates the specified svg element
         */
        __createElement(elementName, properties = {}, resetFill = false) {
            const element = this.__document.createElementNS("http://www.w3.org/2000/svg", elementName);
            if (resetFill) {
                // if fill or stroke is not specified, the svg element should not display. By default SVG's fill is black.
                element.setAttribute("fill", "none");
                element.setAttribute("stroke", "none");
            }
            const keys = Object.keys(properties);
            for (const key of keys) {
                element.setAttribute(key, `${properties[key]}`);
            }
            return element;
        }
        /**
         * Applies default canvas styles to the context
         */
        __setDefaultStyles() {
            // default 2d canvas context properties see:http://www.w3.org/TR/2dcontext/
            for (const [key, val] of (0, object_1.typed_entries)(STYLES)) {
                this[key] = val.canvas;
            }
        }
        /**
         * Applies styles on restore
         */
        __applyStyleState(style_state) {
            for (const [key, val] of (0, object_1.typed_entries)(style_state)) {
                this[key] = val;
            }
        }
        /**
         * Gets the current style state
         */
        __getStyleState() {
            const style_state = {};
            for (const [key, _val] of (0, object_1.typed_entries)(STYLES)) {
                style_state[key] = this[key];
            }
            return style_state;
        }
        /**
         * Apples the current styles to the current SVG element. On "ctx.fill" or "ctx.stroke"
         */
        __applyStyleToCurrentElement(type) {
            const currentElement = this.__currentElement;
            /*
            const currentStyleGroup = this.__currentElementsToStyle
            if (currentStyleGroup != null) {
              currentElement.setAttribute(type, "")
              currentElement = currentStyleGroup.element
              for (const node of currentStyleGroup.children) {
                node.setAttribute(type, "")
              }
            }
            */
            for (const [key, style] of (0, object_1.typed_entries)(STYLES)) {
                const value = this[key];
                if (style.apply != null && style.apply.includes(type)) {
                    if (value instanceof CanvasPattern) {
                        for (const def of [...value.__ctx.__defs.childNodes]) {
                            if (def instanceof Element) {
                                const id = def.getAttribute("id");
                                this.__ids.add(id);
                                this.__defs.appendChild(def);
                            }
                        }
                        const id = value.__root.getAttribute("id");
                        currentElement.setAttribute(style.apply, `url(#${id})`);
                    }
                    else if (value instanceof CanvasGradient) {
                        const id = value.__root.getAttribute("id");
                        currentElement.setAttribute(style.apply, `url(#${id})`);
                    }
                    else if (style.svg !== value) {
                        if ((style.svgAttr === "stroke" || style.svgAttr === "fill") && (0, types_1.isString)(value) && value.indexOf("rgba") !== -1) {
                            // separate alpha value, since illustrator can't handle it
                            const regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi;
                            const matches = regex.exec(value);
                            const [, r, g, b, a] = matches;
                            currentElement.setAttribute(style.svgAttr, `rgb(${r},${g},${b})`);
                            const opacity = parseFloat(a) * this.globalAlpha;
                            currentElement.setAttribute(`${style.svgAttr}-opacity`, `${opacity}`);
                        }
                        else {
                            let attr = style.svgAttr;
                            if (key === "globalAlpha") {
                                attr = `${type}-${style.svgAttr}`;
                                if (currentElement.getAttribute(attr) != null) {
                                    // fill-opacity or stroke-opacity has already been set by stroke or fill.
                                    continue;
                                }
                            }
                            // otherwise only update attribute if right type, and not svg default
                            currentElement.setAttribute(attr, `${value}`);
                        }
                    }
                }
            }
        }
        /**
          * Returns the serialized value of the svg so far
          * @param fixNamedEntities - Standalone SVG doesn't support named entities, which document.createTextNode encodes.
          *                           If true, we attempt to find all named entities and encode it as a numeric entity.
          * @return serialized svg
          */
        get_serialized_svg(fixNamedEntities = false) {
            let serialized = new XMLSerializer().serializeToString(this.__root);
            if (fixNamedEntities) {
                // loop over each named entity and replace with the proper equivalent.
                for (const [key, value] of namedEntities) {
                    const regexp = new RegExp(key, "gi");
                    if (regexp.test(serialized)) {
                        serialized = serialized.replace(regexp, value);
                    }
                }
            }
            return serialized;
        }
        get_svg() {
            return this.__root;
        }
        /**
          * Will generate a group tag.
          */
        save() {
            this.__stack.push({
                transform: this._transform,
                clip_path: this._clip_path,
                attributes: this.__getStyleState(),
            });
            this._transform = this._transform.clone();
        }
        /**
          * Sets current element to parent, or just root if already root
          */
        restore() {
            if (this.__stack.length == 0) {
                return;
            }
            const { transform, clip_path, attributes } = this.__stack.pop();
            this._transform = transform;
            this._clip_path = clip_path;
            this.__applyStyleState(attributes);
        }
        isContextLost() {
            return false;
        }
        reset() {
            this.__setDefaultStyles();
            this.__stack = [];
        }
        _apply_transform(element, transform = this._transform) {
            if (!transform.is_identity) {
                element.setAttribute("transform", transform.toString());
            }
        }
        /**
          *  scales the current element
          */
        scale(x, y) {
            if (!isFinite(x) || (y != null && !isFinite(y))) {
                return;
            }
            this._transform.scale(x, y ?? x);
        }
        /**
          * rotates the current element
          */
        rotate(angle) {
            if (!isFinite(angle)) {
                return;
            }
            this._transform.rotate(angle);
        }
        /**
          * translates the current element
          */
        translate(x, y) {
            if (!isFinite(x + y)) {
                return;
            }
            this._transform.translate(x, y);
        }
        /**
          * applies a transform to the current element
          */
        transform(a, b, c, d, e, f) {
            if (!isFinite(a + b + c + d + e + f)) {
                return;
            }
            this._transform.transform(a, b, c, d, e, f);
        }
        /**
          * Create a new Path Element
          */
        beginPath() {
            // Note that there is only one current default path, it is not part of the drawing state.
            // See also: https://html.spec.whatwg.org/multipage/scripting.html#current-default-path
            this.__currentDefaultPath = "";
            this.__currentPosition = null;
            this.__init_element();
        }
        __init_element() {
            const path = this.__createElement("path", {}, true);
            this.__root.appendChild(path);
            this.__currentElement = path;
        }
        /**
          * Helper function to apply currentDefaultPath to current path element
          */
        __applyCurrentDefaultPath() {
            const currentElement = this.__currentElement;
            if (currentElement.nodeName === "path") {
                currentElement.setAttribute("d", this.__currentDefaultPath);
            }
            else {
                console.error("Attempted to apply path command to node", currentElement.nodeName);
            }
        }
        /**
          * Helper function to add path command
          */
        __addPathCommand(x, y, path) {
            const separator = this.__currentDefaultPath == "" ? "" : " ";
            this.__currentDefaultPath += separator + path;
            this.__currentPosition = { x, y };
        }
        get _hasCurrentDefaultPath() {
            return this.__currentDefaultPath != "";
        }
        /**
          * Adds the move command to the current path element,
          * if the currentPathElement is not empty create a new path element
          */
        moveTo(x, y) {
            if (!isFinite(x + y)) {
                return;
            }
            const currentElement = this.__currentElement;
            if (currentElement.nodeName !== "path") {
                this.beginPath();
            }
            // creates a new subpath with the given point
            const [tx, ty] = this._transform.apply(x, y);
            this.__addPathCommand(tx, ty, `M ${tx} ${ty}`);
        }
        /**
          * Closes the current path
          */
        closePath() {
            if (this._hasCurrentDefaultPath) {
                this.__addPathCommand(NaN, NaN, "Z");
            }
        }
        /**
          * Adds a line to command
          */
        lineTo(x, y) {
            if (!isFinite(x + y)) {
                return;
            }
            if (!this._hasCurrentDefaultPath) {
                this.moveTo(x, y);
            }
            else {
                const [tx, ty] = this._transform.apply(x, y);
                this.__addPathCommand(tx, ty, `L ${tx} ${ty}`);
            }
        }
        /**
          * Add a bezier command
          */
        bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
            if (!isFinite(cp1x + cp1y + cp2x + cp2y + x + y)) {
                return;
            }
            const [tx, ty] = this._transform.apply(x, y);
            const [tcp1x, tcp1y] = this._transform.apply(cp1x, cp1y);
            const [tcp2x, tcp2y] = this._transform.apply(cp2x, cp2y);
            this.__addPathCommand(tx, ty, `C ${tcp1x} ${tcp1y} ${tcp2x} ${tcp2y} ${tx} ${ty}`);
        }
        /**
          * Adds a quadratic curve to command
          */
        quadraticCurveTo(cpx, cpy, x, y) {
            if (!isFinite(cpx + cpy + x + y)) {
                return;
            }
            const [tx, ty] = this._transform.apply(x, y);
            const [tcpx, tcpy] = this._transform.apply(cpx, cpy);
            this.__addPathCommand(tx, ty, `Q ${tcpx} ${tcpy} ${tx} ${ty}`);
        }
        /**
          * Adds the arcTo to the current path
          *
          * @see http://www.w3.org/TR/2015/WD-2dcontext-20150514/#dom-context-2d-arcto
          */
        arcTo(x1, y1, x2, y2, radius) {
            if (!isFinite(x1 + y1 + x2 + y2 + radius)) {
                return;
            }
            // Let the point (x0, y0) be the last point in the subpath.
            if (this.__currentPosition == null) {
                return;
            }
            // Issue #12699.
            // this.__currentPosition has already been transformed using this._transform.
            // Arguments to this function have not been transformed, so to compare the two need
            // to inverse transform this.__currentPosition.
            const inverse = this._transform.inverse();
            const [x0, y0] = inverse.apply(this.__currentPosition.x, this.__currentPosition.y);
            // Negative values for radius must cause the implementation to throw an IndexSizeError exception.
            if (radius < 0) {
                throw new Error(`IndexSizeError: The radius provided (${radius}) is negative.`);
            }
            // If the point (x0, y0) is equal to the point (x1, y1),
            // or if the point (x1, y1) is equal to the point (x2, y2),
            // or if the radius radius is zero,
            // then the method must add the point (x1, y1) to the subpath,
            // and connect that point to the previous point (x0, y0) by a straight line.
            if (((x0 === x1) && (y0 === y1)) || ((x1 === x2) && (y1 === y2)) || (radius === 0)) {
                this.lineTo(x1, y1);
                return;
            }
            function normalize([x, y]) {
                const len = Math.sqrt(x ** 2 + y ** 2);
                return [x / len, y / len];
            }
            // Otherwise, if the points (x0, y0), (x1, y1), and (x2, y2) all lie on a single straight line,
            // then the method must add the point (x1, y1) to the subpath,
            // and connect that point to the previous point (x0, y0) by a straight line.
            const unit_vec_p1_p0 = normalize([x0 - x1, y0 - y1]);
            const unit_vec_p1_p2 = normalize([x2 - x1, y2 - y1]);
            if (unit_vec_p1_p0[0] * unit_vec_p1_p2[1] === unit_vec_p1_p0[1] * unit_vec_p1_p2[0]) {
                this.lineTo(x1, y1);
                return;
            }
            // Otherwise, let The Arc be the shortest arc given by circumference of the circle that has radius radius,
            // and that has one point tangent to the half-infinite line that crosses the point (x0, y0) and ends at the point (x1, y1),
            // and that has a different point tangent to the half-infinite line that ends at the point (x1, y1), and crosses the point (x2, y2).
            // The points at which this circle touches these two lines are called the start and end tangent points respectively.
            // note that both vectors are unit vectors, so the length is 1
            const cos = (unit_vec_p1_p0[0] * unit_vec_p1_p2[0] + unit_vec_p1_p0[1] * unit_vec_p1_p2[1]);
            const theta = Math.acos(Math.abs(cos));
            // Calculate origin
            const unit_vec_p1_origin = normalize([
                unit_vec_p1_p0[0] + unit_vec_p1_p2[0],
                unit_vec_p1_p0[1] + unit_vec_p1_p2[1],
            ]);
            const len_p1_origin = radius / Math.sin(theta / 2);
            const x = x1 + len_p1_origin * unit_vec_p1_origin[0];
            const y = y1 + len_p1_origin * unit_vec_p1_origin[1];
            // Calculate start angle and end angle
            // rotate 90deg clockwise (note that y axis points to its down)
            const unit_vec_origin_start_tangent = [
                -unit_vec_p1_p0[1],
                unit_vec_p1_p0[0],
            ];
            // rotate 90deg counter clockwise (note that y axis points to its down)
            const unit_vec_origin_end_tangent = [
                unit_vec_p1_p2[1],
                -unit_vec_p1_p2[0],
            ];
            function getAngle(vector) {
                // get angle (clockwise) between vector and (1, 0)
                const x = vector[0];
                const y = vector[1];
                if (y >= 0) { // note that y axis points to its down
                    return Math.acos(x);
                }
                else {
                    return -Math.acos(x);
                }
            }
            const startAngle = getAngle(unit_vec_origin_start_tangent);
            const endAngle = getAngle(unit_vec_origin_end_tangent);
            // Connect the point (x0, y0) to the start tangent point by a straight line
            this.lineTo(x + unit_vec_origin_start_tangent[0] * radius, y + unit_vec_origin_start_tangent[1] * radius);
            // Connect the start tangent point to the end tangent point by arc
            // and adding the end tangent point to the subpath.
            this.arc(x, y, radius, startAngle, endAngle);
        }
        /**
          * Sets the stroke property on the current element
          */
        stroke() {
            if (this.__currentElement.nodeName === "path") {
                this.__currentElement.setAttribute("paint-order", "fill");
            }
            this.__applyCurrentDefaultPath();
            this.__applyStyleToCurrentElement("stroke");
            if (this._clip_path != null) {
                this.__currentElement.setAttribute("clip-path", this._clip_path);
            }
        }
        fill(path_or_fill_rule, fill_rule) {
            let path = null;
            if (path_or_fill_rule instanceof Path2D) {
                path = path_or_fill_rule;
            }
            else if (fill_rule == null) {
                fill_rule = path_or_fill_rule;
            }
            else {
                throw new Error("invalid arguments");
            }
            if (path != null) {
                throw new Error("not implemented");
            }
            // XXX: hack (?) to allow fill and hatch visuals on same canvas path
            if (this.__currentElement.getAttribute("fill") != "none") {
                this.__init_element();
            }
            if (this.__currentElement.nodeName === "path") {
                this.__currentElement.setAttribute("paint-order", "stroke");
            }
            this.__applyCurrentDefaultPath();
            this.__applyStyleToCurrentElement("fill");
            if (fill_rule != null) {
                this.__currentElement.setAttribute("fill-rule", fill_rule);
            }
            if (this._clip_path != null) {
                this.__currentElement.setAttribute("clip-path", this._clip_path);
            }
        }
        /**
          *  Adds a rectangle to the path.
          */
        rect(x, y, width, height) {
            if (!isFinite(x + y + width + height)) {
                return;
            }
            this.moveTo(x, y);
            this.lineTo(x + width, y);
            this.lineTo(x + width, y + height);
            this.lineTo(x, y + height);
            this.lineTo(x, y);
            this.closePath();
        }
        /**
          * adds a rectangle element
          */
        fillRect(x, y, width, height) {
            if (!isFinite(x + y + width + height)) {
                return;
            }
            this.beginPath();
            this.rect(x, y, width, height);
            this.fill();
        }
        /**
          * Draws a rectangle with no fill
          * @param x
          * @param y
          * @param width
          * @param height
          */
        strokeRect(x, y, width, height) {
            if (!isFinite(x + y + width + height)) {
                return;
            }
            this.beginPath();
            this.rect(x, y, width, height);
            this.stroke();
        }
        /**
          * Clear entire canvas:
          * 1. save current transforms
          * 2. remove all the childNodes of the root g element
          */
        __clearCanvas() {
            (0, dom_1.empty)(this.__defs);
            (0, dom_1.empty)(this.__root);
            this.__root.appendChild(this.__defs);
            this.__currentElement = this.__root;
        }
        /**
          * "Clears" a canvas by just drawing a white rectangle in the current group.
          */
        clearRect(x, y, width, height) {
            if (!isFinite(x + y + width + height)) {
                return;
            }
            if (x === 0 && y === 0 && width === this.width && height === this.height) {
                this.__clearCanvas();
                return;
            }
            const rect = this.__createElement("rect", { x, y, width, height, fill: "#FFFFFF" }, true);
            this._apply_transform(rect);
            this.__root.appendChild(rect);
        }
        roundRect(_x, _y, _w, _h, _radii) {
            throw new Error("not implemented");
        }
        /**
          * Adds a linear gradient to a defs tag.
          * Returns a canvas gradient object that has a reference to it's parent def
          */
        createLinearGradient(x1, y1, x2, y2) {
            if (!isFinite(x1 + y1 + x2 + y2)) {
                throw new Error("The provided double value is non-finite");
            }
            const [tx1, ty1] = this._transform.apply(x1, y1);
            const [tx2, ty2] = this._transform.apply(x2, y2);
            const grad = this.__createElement("linearGradient", {
                id: this._random_string(),
                x1: `${tx1}px`,
                x2: `${tx2}px`,
                y1: `${ty1}px`,
                y2: `${ty2}px`,
                gradientUnits: "userSpaceOnUse",
            }, false);
            this.__defs.appendChild(grad);
            return new CanvasGradient(grad, this);
        }
        /**
          * Adds a radial gradient to a defs tag.
          * Returns a canvas gradient object that has a reference to it's parent def
          */
        createRadialGradient(x0, y0, r0, x1, y1, r1) {
            if (!isFinite(x0 + y0 + r0 + x1 + y1 + r1)) {
                throw new Error("The provided double value is non-finite");
            }
            const [tx0, ty0] = this._transform.apply(x0, y0);
            const [tx1, ty1] = this._transform.apply(x1, y1);
            const grad = this.__createElement("radialGradient", {
                id: this._random_string(),
                cx: `${tx1}px`,
                cy: `${ty1}px`,
                r: `${r1}px`,
                r0: `${r0}px`,
                fx: `${tx0}px`,
                fy: `${ty0}px`,
                gradientUnits: "userSpaceOnUse",
            }, false);
            this.__defs.appendChild(grad);
            return new CanvasGradient(grad, this);
        }
        createConicGradient(_start_angle, _x, _y) {
            throw Error("not implemented");
        }
        /**
          * Parses the font string and returns svg mapping
          */
        __parseFont() {
            const regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\'\"\sa-z0-9]+?)\s*$/i;
            const [, style, decoration, weight, size, , family] = regex.exec(this.font); // XXX: RegExpExecArray is incorrecdt
            const data = {
                style: style ?? "normal",
                size: size ?? "10px",
                family: family ?? "sans-serif",
                weight: weight ?? "normal",
                decoration: decoration ?? "normal",
            };
            return data;
        }
        /**
          * Fills or strokes text
          */
        __applyText(text, x, y, action) {
            const font = this.__parseFont();
            const text_el = this.__createElement("text", {
                "font-family": font.family,
                "font-size": font.size,
                "font-style": font.style,
                "font-weight": font.weight,
                "text-decoration": font.decoration,
                x,
                y,
                "text-anchor": getTextAnchor(this.textAlign),
                "dominant-baseline": getDominantBaseline(this.textBaseline),
            }, true);
            text_el.appendChild(this.__document.createTextNode(text));
            this._apply_transform(text_el);
            this.__currentElement = text_el;
            this.__applyStyleToCurrentElement(action);
            const el = (() => {
                if (this._clip_path != null) {
                    const g = this.__createElement("g");
                    g.setAttribute("clip-path", this._clip_path);
                    g.appendChild(text_el);
                    return g;
                }
                else {
                    return text_el;
                }
            })();
            this.__root.appendChild(el);
        }
        /**
          * Creates a text element, in position x,y
          */
        fillText(text, x, y) {
            if (!isFinite(x + y)) {
                return;
            }
            this.__applyText(text, x, y, "fill");
        }
        /**
          * Strokes text
          */
        strokeText(text, x, y) {
            if (!isFinite(x + y)) {
                return;
            }
            this.__applyText(text, x, y, "stroke");
        }
        /**
          * No need to implement this for svg.
          */
        measureText(text) {
            this.__ctx.font = this.font;
            return this.__ctx.measureText(text);
        }
        arc(x, y, radius, start_angle, end_angle, counterclockwise = false) {
            this.ellipse(x, y, radius, radius, 0, start_angle, end_angle, counterclockwise);
        }
        ellipse(x, y, radius_x, radius_y, rotation, start_angle, end_angle, counterclockwise = false) {
            if (!isFinite(x + y + radius_x + radius_y + rotation + start_angle + end_angle)) {
                return;
            }
            if (radius_x < 0 || radius_y < 0) {
                throw new DOMException("IndexSizeError, radius can't be negative");
            }
            const initial_diff = counterclockwise ? end_angle - start_angle : start_angle - end_angle;
            start_angle = start_angle % (2 * Math.PI);
            end_angle = end_angle % (2 * Math.PI);
            const transform = new affine_1.AffineTransform().translate(x, y).rotate(rotation);
            const dx = radius_x * Math.cos(start_angle);
            const dy = radius_y * Math.sin(start_angle);
            const [start_x, start_y] = transform.apply(dx, dy);
            this.lineTo(start_x, start_y);
            // Canvas ellipse defines rotation in radians and SVG elliptical arc is defined in degrees
            const rotation_in_degrees = rotation * 180 / Math.PI;
            const sweep_flag = counterclockwise ? 0 : 1;
            /**
             * Check if need to draw full ellipse (issue #11475). When testing if angular difference is
             * equal to an integer multiple of 2*pi radians, need to account for float64 to float32 rounding
             * error on both the start and end angles, hence the factor of 2. Do not assume full circle if
             * start and end angles are close, but test here depends on combination of sign of angular
             * difference and wedge direction (clockwise/counterclockwise) to obtain the same results as on
             * canvas.
             */
            if (Math.abs(start_angle - end_angle) < 2 * math_1.float32_epsilon &&
                !(Math.abs(initial_diff) < 2 * math_1.float32_epsilon && initial_diff < 0)) {
                // Draw full ellipse. SVG elliptical arc cannot do this, so instead use two semi ellipses.
                const [tstart_x, tstart_y] = this._transform.apply(start_x, start_y);
                const dx = radius_x * Math.cos(start_angle + Math.PI);
                const dy = radius_y * Math.sin(start_angle + Math.PI);
                const [mid_x, mid_y] = transform.apply(dx, dy);
                const [tmid_x, tmid_y] = this._transform.apply(mid_x, mid_y);
                this.__addPathCommand(tstart_x, tstart_y, `A ${radius_x} ${radius_y} ${rotation_in_degrees} 0 ${sweep_flag} ${tmid_x} ${tmid_y} A ${radius_x} ${radius_y} ${rotation_in_degrees} 0 ${sweep_flag} ${tstart_x} ${tstart_y}`);
            }
            else {
                // Draw partial ellipse only.
                const dx = radius_x * Math.cos(end_angle);
                const dy = radius_y * Math.sin(end_angle);
                const [end_x, end_y] = transform.apply(dx, dy);
                let diff = end_angle - start_angle;
                // https://github.com/gliffy/canvas2svg/issues/4
                if (diff < 0) {
                    diff += 2 * Math.PI;
                }
                const large_arc_flag = (counterclockwise !== diff > Math.PI) ? 1 : 0; // imitation xor
                const [tend_x, tend_y] = this._transform.apply(end_x, end_y);
                this.__addPathCommand(tend_x, tend_y, `A ${radius_x} ${radius_y} ${rotation_in_degrees} ${large_arc_flag} ${sweep_flag} ${tend_x} ${tend_y}`);
            }
        }
        clip(path_or_fill_rule, fill_rule) {
            let path = null;
            if (path_or_fill_rule instanceof Path2D) {
                path = path_or_fill_rule;
            }
            else if (fill_rule == null) {
                fill_rule = path_or_fill_rule;
            }
            else {
                throw new Error("invalid arguments");
            }
            if (path != null) {
                throw new Error("not implemented");
            }
            const clip_path = this.__createElement("clipPath");
            const id = this._random_string();
            this.__applyCurrentDefaultPath();
            if (fill_rule != null) {
                this.__currentElement.setAttribute("clip-rule", fill_rule);
            }
            clip_path.setAttribute("id", id);
            clip_path.appendChild(this.__currentElement);
            this.__defs.appendChild(clip_path);
            this._clip_path = `url(#${id})`;
        }
        /**
          * Draws a canvas, image or mock context to this canvas.
          * Note that all svg dom manipulation uses node.childNodes rather than node.children for IE support.
          * http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-drawimage
          */
        drawImage(image, ...args) {
            let dx, dy;
            let dw, dh;
            let sx, sy;
            let sw, sh;
            if (args.length == 2) {
                [dx, dy] = args;
                if (!isFinite(dx + dy)) {
                    return;
                }
                sx = 0;
                sy = 0;
                const [w, h] = width_height(image);
                dw = sw = w;
                dh = sh = h;
            }
            else if (args.length == 4) {
                [dx, dy, dw, dh] = args;
                if (!isFinite(dx + dy + dw + dh)) {
                    return;
                }
                sx = 0;
                sy = 0;
                const [w, h] = width_height(image);
                sw = w;
                sh = h;
            }
            else if (args.length === 8) {
                [sx, sy, sw, sh, dx, dy, dw, dh] = args;
                if (!isFinite(sx + sy + sw + sh + dx + dy + dw + dh)) {
                    return;
                }
            }
            else {
                throw new Error(`Inavlid number of arguments passed to drawImage: ${arguments.length}`);
            }
            // parent, svg, defs, group, currentElement, svgImage, canvas, context, id
            const parent = this.__root;
            const transform = this._transform.clone().translate(dx, dy);
            if (image instanceof SVGRenderingContext2D || image instanceof SVGSVGElement) {
                // In the future we may want to clone nodes instead.
                // also I'm currently ignoring dw, dh, sw, sh, sx, sy for a mock context.
                const svg_node = image instanceof SVGSVGElement ? image : image.get_svg();
                const svg = svg_node.cloneNode(true);
                let scope;
                if (transform.is_identity && this.globalAlpha == 1.0 && this._clip_path == null) {
                    scope = parent;
                }
                else {
                    scope = this.__createElement("g");
                    if (!transform.is_identity) {
                        this._apply_transform(scope, transform);
                    }
                    if (this.globalAlpha != 1.0) {
                        scope.setAttribute("opacity", `${this.globalAlpha}`);
                    }
                    if (this._clip_path != null) {
                        scope.setAttribute("clip-path", this._clip_path);
                    }
                    parent.appendChild(scope);
                }
                for (const child of [...svg.childNodes]) {
                    if (child instanceof SVGDefsElement) {
                        for (const def of [...child.childNodes]) {
                            if (def instanceof Element) {
                                const id = def.getAttribute("id");
                                this.__ids.add(id);
                                this.__defs.appendChild(def.cloneNode(true));
                            }
                        }
                    }
                    else {
                        scope.appendChild(child.cloneNode(true));
                    }
                }
            }
            else if (image instanceof HTMLImageElement || image instanceof SVGImageElement) {
                const svgImage = this.__createElement("image");
                svgImage.setAttribute("width", `${dw}`);
                svgImage.setAttribute("height", `${dh}`);
                svgImage.setAttribute("preserveAspectRatio", "none");
                if (this.globalAlpha != 1.0) {
                    svgImage.setAttribute("opacity", `${this.globalAlpha}`);
                }
                if (sx != 0 || sy != 0 || sw !== image.width || sh !== image.height) {
                    // crop the image using a temporary canvas
                    const canvas = this.__document.createElement("canvas");
                    canvas.width = dw;
                    canvas.height = dh;
                    const context = canvas.getContext("2d");
                    context.drawImage(image, sx, sy, sw, sh, 0, 0, dw, dh);
                    image = canvas;
                }
                this._apply_transform(svgImage, transform);
                const url = image instanceof HTMLCanvasElement ? image.toDataURL() : image.getAttribute("src");
                svgImage.setAttribute("href", url);
                if (this._clip_path != null) {
                    const scope = this.__createElement("g");
                    scope.setAttribute("clip-path", this._clip_path);
                    scope.appendChild(svgImage);
                    parent.appendChild(scope);
                }
                else {
                    parent.appendChild(svgImage);
                }
            }
            else if (image instanceof HTMLCanvasElement) {
                const svgImage = this.__createElement("image");
                svgImage.setAttribute("width", `${dw}`);
                svgImage.setAttribute("height", `${dh}`);
                svgImage.setAttribute("preserveAspectRatio", "none");
                if (this.globalAlpha != 1.0) {
                    svgImage.setAttribute("opacity", `${this.globalAlpha}`);
                }
                // draw canvas onto temporary canvas so that smoothing can be handled
                const canvas = this.__document.createElement("canvas");
                canvas.width = dw;
                canvas.height = dh;
                const context = canvas.getContext("2d");
                context.imageSmoothingEnabled = false;
                context.drawImage(image, sx, sy, sw, sh, 0, 0, dw, dh);
                image = canvas;
                this._apply_transform(svgImage, transform);
                svgImage.setAttribute("href", image.toDataURL());
                if (this._clip_path != null) {
                    const scope = this.__createElement("g");
                    scope.setAttribute("clip-path", this._clip_path);
                    scope.appendChild(svgImage);
                    parent.appendChild(scope);
                }
                else {
                    parent.appendChild(svgImage);
                }
            }
        }
        /**
          * Generates a pattern tag
          */
        createPattern(image, _repetition) {
            const pattern = this.__document.createElementNS("http://www.w3.org/2000/svg", "pattern");
            const id = this._random_string();
            const [width, height] = width_height(image);
            pattern.setAttribute("id", id);
            pattern.setAttribute("width", `${width}`);
            pattern.setAttribute("height", `${height}`);
            pattern.setAttribute("patternUnits", "userSpaceOnUse");
            if (image instanceof HTMLCanvasElement || image instanceof HTMLImageElement || image instanceof SVGImageElement) {
                const img = this.__document.createElementNS("http://www.w3.org/2000/svg", "image");
                const url = image instanceof HTMLCanvasElement ? image.toDataURL() : image.getAttribute("src");
                img.setAttribute("href", url);
                pattern.appendChild(img);
                this.__defs.appendChild(pattern);
            }
            else if (image instanceof SVGRenderingContext2D) {
                for (const child of [...image.__root.childNodes]) {
                    if (!(child instanceof SVGDefsElement)) {
                        pattern.appendChild(child.cloneNode(true));
                    }
                }
                //pattern.appendChild(image.__root.childNodes[1])
                this.__defs.appendChild(pattern);
            }
            else if (image instanceof SVGSVGElement) {
                for (const child of [...image.childNodes]) {
                    if (!(child instanceof SVGDefsElement)) {
                        pattern.appendChild(child.cloneNode(true));
                    }
                }
                //pattern.appendChild(image.__root.childNodes[1])
                this.__defs.appendChild(pattern);
            }
            else {
                throw new Error("unsupported");
            }
            return new CanvasPattern(pattern, this);
        }
        getLineDash() {
            const { lineDash } = this;
            if ((0, types_1.isString)(lineDash)) {
                return lineDash.split(",").map((v) => parseInt(v));
            }
            else if (lineDash == null) {
                return [];
            }
            else {
                return lineDash;
            }
        }
        setLineDash(segments) {
            if (segments.length > 0) {
                this.lineDash = segments.join(",");
            }
            else {
                this.lineDash = null;
            }
        }
        getTransform() {
            return this._transform.to_DOMMatrix();
        }
        setTransform(...args) {
            let matrix;
            if ((0, types_1.isNumber)(args[0])) {
                matrix = new DOMMatrix(args);
            }
            else if (args[0] instanceof DOMMatrix) {
                matrix = args[0];
            }
            else {
                matrix = new DOMMatrix(Object.values(args[0] == null));
            }
            this._transform = affine_1.AffineTransform.from_DOMMatrix(matrix);
        }
        resetTransform() {
            this._transform = new affine_1.AffineTransform();
        }
        isPointInPath(..._args) {
            throw new Error("not implemented");
        }
        isPointInStroke(..._args) {
            throw new Error("not implemented");
        }
        createImageData(..._args) {
            throw new Error("not implemented");
        }
        getImageData(_sx, _sy, _sw, _sh) {
            throw new Error("not implemented");
        }
        putImageData(..._args) {
            throw new Error("not implemented");
        }
        drawFocusIfNeeded(..._args) {
            throw new Error("not implemented");
        }
        scrollPathIntoView(..._args) {
            throw new Error("not implemented");
        }
    }
    exports.SVGRenderingContext2D = SVGRenderingContext2D;
    SVGRenderingContext2D.__name__ = "SVGRenderingContext2D";
    //__currentElementsToStyle: {element: SVGElement, children: SVGElement[]} | null = null
    SVGRenderingContext2D.__random = random_1.random;
},
/* core/util/affine.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.rotate_around = rotate_around;
    const eq_1 = require(26) /* ./eq */;
    const { sin, cos } = Math;
    class AffineTransform {
        constructor(a = 1, b = 0, c = 0, d = 1, e = 0, f = 0) {
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
            this.e = e;
            this.f = f;
        }
        toString() {
            const { a, b, c, d, e, f } = this;
            return `matrix(${a}, ${b}, ${c}, ${d}, ${e}, ${f})`;
        }
        static from_DOMMatrix(matrix) {
            const { a, b, c, d, e, f } = matrix;
            return new AffineTransform(a, b, c, d, e, f);
        }
        to_DOMMatrix() {
            const { a, b, c, d, e, f } = this;
            return new DOMMatrix([a, b, c, d, e, f]);
        }
        clone() {
            const { a, b, c, d, e, f } = this;
            return new AffineTransform(a, b, c, d, e, f);
        }
        [eq_1.equals](that, cmp) {
            return (cmp.eq(this.a, that.a) &&
                cmp.eq(this.b, that.b) &&
                cmp.eq(this.c, that.c) &&
                cmp.eq(this.d, that.d) &&
                cmp.eq(this.e, that.e) &&
                cmp.eq(this.f, that.f));
        }
        reset() {
            this.a = 1;
            this.b = 0;
            this.c = 0;
            this.d = 1;
            this.e = 0;
            this.f = 0;
        }
        get is_identity() {
            const { a, b, c, d, e, f } = this;
            return a == 1 && b == 0 && c == 0 && d == 1 && e == 0 && f == 0;
        }
        apply_point(p) {
            const [x, y] = this.apply(p.x, p.y);
            return { x, y };
        }
        apply_rect(rect) {
            const p0 = this.apply_point(rect.p0);
            const p1 = this.apply_point(rect.p1);
            const p2 = this.apply_point(rect.p2);
            const p3 = this.apply_point(rect.p3);
            return { p0, p1, p2, p3 };
        }
        apply(x, y) {
            const { a, b, c, d, e, f } = this;
            return [
                a * x + c * y + e,
                b * x + d * y + f,
            ];
        }
        iv_apply(xs, ys) {
            const { a, b, c, d, e, f } = this;
            const n = xs.length;
            for (let i = 0; i < n; i++) {
                const x = xs[i];
                const y = ys[i];
                xs[i] = a * x + c * y + e;
                ys[i] = b * x + d * y + f;
            }
        }
        transform(A, B, C, D, E, F) {
            const { a, b, c, d, e, f } = this;
            this.a = a * A + c * B;
            this.c = a * C + c * D;
            this.e = a * E + c * F + e;
            this.b = b * A + d * B;
            this.d = b * C + d * D;
            this.f = b * E + d * F + f;
            return this;
        }
        translate(tx, ty) {
            return this.transform(1, 0, 0, 1, tx, ty);
        }
        scale(cx, cy) {
            return this.transform(cx, 0, 0, cy, 0, 0);
        }
        skew(sx, sy) {
            return this.transform(1, sy, sx, 1, 0, 0);
        }
        rotate(angle) {
            if (angle == 0) {
                return this;
            }
            const s = sin(angle);
            const c = cos(angle);
            return this.transform(c, s, -s, c, 0, 0);
        }
        rotate_ccw(angle) {
            return this.rotate(-angle);
        }
        rotate_around(x, y, angle) {
            this.translate(x, y);
            this.rotate(angle);
            this.translate(-x, -y);
            return this;
        }
        translate_x(tx) {
            return this.translate(tx, 0);
        }
        translate_y(ty) {
            return this.translate(0, ty);
        }
        flip() {
            return this.scale(-1, -1);
        }
        flip_x() {
            return this.scale(1, -1);
        }
        flip_y() {
            return this.scale(-1, 1);
        }
        inverse() {
            return AffineTransform.from_DOMMatrix(this.to_DOMMatrix().inverse());
        }
    }
    exports.AffineTransform = AffineTransform;
    AffineTransform.__name__ = "AffineTransform";
    function rotate_around(point, center, angle) {
        if (angle == 0) {
            return point;
        }
        else {
            const tr = new AffineTransform();
            tr.rotate_around(center.x, center.y, angle);
            const [x, y] = tr.apply(point.x, point.y);
            return { x, y };
        }
    }
},
/* core/util/random.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const { PI, log, sin, cos, sqrt, floor } = Math;
    exports.MAX_INT32 = 2147483647;
    class AbstractRandom {
        float() {
            return (this.integer() - 1) / (exports.MAX_INT32 - 1);
        }
        floats(n, a = 0, b = 1) {
            const result = new Array(n);
            for (let i = 0; i < n; i++) {
                result[i] = a + this.float() * (b - a);
            }
            return result;
        }
        choices(n, items) {
            const k = items.length;
            const result = new Array(n);
            for (let i = 0; i < n; i++) {
                result[i] = items[this.integer() % k];
            }
            return result;
        }
        uniform(loc, scale) {
            return loc + (this.float() - 0.5) * scale;
        }
        uniforms(loc, scale, size) {
            return Float64Array.from({ length: size }, () => this.uniform(loc, scale));
        }
        normal(loc, scale) {
            return this.normals(loc, scale, 1)[0];
        }
        normals(loc, scale, size) {
            const [mu, sigma] = [loc, scale];
            const array = new Float64Array(size);
            for (let i = 0; i < size; i += 2) {
                // Box-Muller transform from uniform to normal distribution.
                const u = this.float();
                const v = this.float();
                const common = sqrt(-2.0 * log(u));
                array[i] = mu + sigma * (common * cos(2.0 * PI * v));
                if (i + 1 < size) {
                    array[i + 1] = mu + sigma * (common * sin(2.0 * PI * v));
                }
            }
            return array;
        }
    }
    exports.AbstractRandom = AbstractRandom;
    AbstractRandom.__name__ = "AbstractRandom";
    class SystemRandom extends AbstractRandom {
        integer() {
            return floor(Math.random() * exports.MAX_INT32);
        }
    }
    exports.SystemRandom = SystemRandom;
    SystemRandom.__name__ = "SystemRandom";
    // Park-Miller LCG
    class LCGRandom extends AbstractRandom {
        constructor(seed) {
            super();
            this._seed = seed % exports.MAX_INT32;
            if (this._seed <= 0) {
                this._seed += exports.MAX_INT32 - 1;
            }
        }
        integer() {
            this._seed = (48271 * this._seed) % exports.MAX_INT32;
            return this._seed;
        }
    }
    exports.LCGRandom = LCGRandom;
    LCGRandom.__name__ = "LCGRandom";
    class Random extends LCGRandom {
    } // for compatibility
    exports.Random = Random;
    Random.__name__ = "Random";
    exports.random = new Random(Date.now());
},
/* styles/ui.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{position:relative;}`;
},
/* models/ui/menus/menu_item.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(51) /* ../../../model */;
    class MenuItem extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MenuItem = MenuItem;
    MenuItem.__name__ = "MenuItem";
},
/* models/ui/menus/action_item.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const menu_item_1 = require(117) /* ./menu_item */;
    const callback_1 = require(119) /* ../../callbacks/callback */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const kinds_1 = require(21) /* ../../../core/kinds */;
    const IconLike = (0, kinds_1.Or)(enums_1.ToolIcon, (0, kinds_1.Regex)(/^--/), (0, kinds_1.Regex)(/^\./), (0, kinds_1.Regex)(/^data:image/));
    class ActionItem extends menu_item_1.MenuItem {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ActionItem = ActionItem;
    _a = ActionItem;
    ActionItem.__name__ = "ActionItem";
    (() => {
        _a.define(({ Bool, Str, Nullable, AnyRef, Ref, Func }) => ({
            icon: [Nullable(IconLike), null],
            label: [Str],
            tooltip: [Nullable(Str), null],
            shortcut: [Nullable(Str), null],
            menu: [Nullable(AnyRef()), null],
            disabled: [Bool, false],
            action: [Nullable((0, kinds_1.Or)(Ref(callback_1.Callback), Func())), null],
        }));
    })();
},
/* models/callbacks/callback.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(51) /* ../../model */;
    class Callback extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Callback = Callback;
    Callback.__name__ = "Callback";
},
/* models/ui/menus/checkable_item.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const action_item_1 = require(118) /* ./action_item */;
    class CheckableItem extends action_item_1.ActionItem {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.CheckableItem = CheckableItem;
    _a = CheckableItem;
    CheckableItem.__name__ = "CheckableItem";
    (() => {
        _a.define(({ Bool }) => ({
            checked: [Bool, false],
        }));
    })();
},
/* models/ui/menus/divider_item.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const menu_item_1 = require(117) /* ./menu_item */;
    class DividerItem extends menu_item_1.MenuItem {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DividerItem = DividerItem;
    DividerItem.__name__ = "DividerItem";
},
/* styles/menus_.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.item = "bk-item";
    exports.divider = "bk-divider";
    exports.check = "bk-check";
    exports.icon = "bk-icon";
    exports.label = "bk-label";
    exports.shortcut = "bk-shortcut";
    exports.chevron = "bk-chevron";
    exports.disabled = "bk-disabled";
    exports.menu = "bk-menu";
    exports.checkable = "bk-checkable";
    exports.checked = "bk-checked";
    exports.default = `:host{position:absolute;display:inline-grid;grid-template-columns:repeat(5, max-content);grid-template-rows:auto;user-select:none;-webkit-user-select:none;cursor:pointer;width:auto;height:auto;z-index:var(--bokeh-top-level);font-size:var(--font-size);background-color:#fff;border:1px solid #ccc;border-radius:var(--border-radius);box-shadow:2px 4px 8px rgba(0, 0, 0, 0.175);}.bk-item,.bk-divider{position:relative;display:grid;grid-template-columns:subgrid;grid-column:span 5;align-items:center;}.bk-check{grid-column:1;}.bk-icon{grid-column:2;}.bk-label{grid-column:3;}.bk-shortcut{grid-column:4;}.bk-chevron{grid-column:5;}.bk-divider{cursor:default;overflow:hidden;background-color:#e5e5e5;height:1px;margin:1px 5px;}.bk-item{padding:0.5em;}.bk-item:hover{background-color:#f9f9f9;}.bk-item:focus,.bk-item:focus-visible{outline:1px dotted var(--active-tool-highlight);outline-offset:-1px;}.bk-item::-moz-focus-inner{border:0;}.bk-item.bk-disabled{color:gray;}.bk-item.bk-disabled .bk-icon{color:var(--bokeh-icon-color-disabled);}.bk-item:first-of-type{border-top-left-radius:var(--border-radius);border-top-right-radius:var(--border-radius);}.bk-item:last-of-type{border-bottom-left-radius:var(--border-radius);border-bottom-right-radius:var(--border-radius);}.bk-icon{position:relative;width:16px;height:16px;mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;background-size:100% 100%;background-origin:border-box;background-position:center center;background-repeat:no-repeat;}.bk-label{padding:0 0.5em;}.bk-shortcut{text-align:right;font-size:90%;color:gray;}.bk-chevron{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-caret-right);-webkit-mask-image:var(--bokeh-icon-caret-right);mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;width:12px;height:12px;}.bk-item:not(.bk-menu) .bk-chevron{display:none;}.bk-item.bk-checkable .bk-check{width:16px;height:16px;}.bk-item.bk-checkable.bk-checked .bk-check{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-check);-webkit-mask-image:var(--bokeh-icon-check);mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;}`;
},
/* styles/icons.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.tool_icon_square_check = exports.tool_icon_square = exports.tool_icon_check = exports.tool_icon_text_align_right = exports.tool_icon_text_align_center = exports.tool_icon_text_align_left = exports.tool_icon_italic = exports.tool_icon_bold = exports.tool_icon_delete = exports.tool_icon_pointer = exports.tool_icon_unpin = exports.tool_icon_pin = exports.tool_icon_maximize = exports.tool_icon_minimize = exports.tool_icon_arrow_up_from_bar = exports.tool_icon_arrow_down_to_bar = exports.tool_icon_y_grip = exports.tool_icon_x_grip = exports.tool_icon_see_off = exports.tool_icon_see_on = exports.tool_icon_caret_right = exports.tool_icon_caret_left = exports.tool_icon_caret_down = exports.tool_icon_caret_up = exports.tool_icon_chevron_right = exports.tool_icon_chevron_left = void 0;
    exports.tool_icon_copy = "bk-tool-icon-copy";
    exports.tool_icon_open = "bk-tool-icon-open";
    exports.tool_icon_replace_mode = "bk-tool-icon-replace-mode";
    exports.tool_icon_toggle_mode = "bk-tool-icon-toggle-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_xor_mode = "bk-tool-icon-xor-mode";
    exports.tool_icon_invert_selection = "bk-tool-icon-invert-selection";
    exports.tool_icon_clear_selection = "bk-tool-icon-clear-selection";
    exports.tool_icon_box_select = "bk-tool-icon-box-select";
    exports.tool_icon_x_box_select = "bk-tool-icon-x-box-select";
    exports.tool_icon_y_box_select = "bk-tool-icon-y-box-select";
    exports.tool_icon_box_zoom = "bk-tool-icon-box-zoom";
    exports.tool_icon_x_box_zoom = "bk-tool-icon-x-box-zoom";
    exports.tool_icon_y_box_zoom = "bk-tool-icon-y-box-zoom";
    exports.tool_icon_auto_box_zoom = "bk-tool-icon-auto-box-zoom";
    exports.tool_icon_zoom_in = "bk-tool-icon-zoom-in";
    exports.tool_icon_zoom_out = "bk-tool-icon-zoom-out";
    exports.tool_icon_help = "bk-tool-icon-help";
    exports.tool_icon_hover = "bk-tool-icon-hover";
    exports.tool_icon_crosshair = "bk-tool-icon-crosshair";
    exports.tool_icon_lasso_select = "bk-tool-icon-lasso-select";
    exports.tool_icon_pan = "bk-tool-icon-pan";
    exports.tool_icon_x_pan = "bk-tool-icon-x-pan";
    exports.tool_icon_y_pan = "bk-tool-icon-y-pan";
    exports.tool_icon_pan_left = "bk-tool-icon-pan-left";
    exports.tool_icon_pan_right = "bk-tool-icon-pan-right";
    exports.tool_icon_pan_up = "bk-tool-icon-pan-up";
    exports.tool_icon_pan_down = "bk-tool-icon-pan-down";
    exports.tool_icon_range = "bk-tool-icon-range";
    exports.tool_icon_polygon_select = "bk-tool-icon-polygon-select";
    exports.tool_icon_redo = "bk-tool-icon-redo";
    exports.tool_icon_reset = "bk-tool-icon-reset";
    exports.tool_icon_save = "bk-tool-icon-save";
    exports.tool_icon_tap_select = "bk-tool-icon-tap-select";
    exports.tool_icon_undo = "bk-tool-icon-undo";
    exports.tool_icon_wheel_pan = "bk-tool-icon-wheel-pan";
    exports.tool_icon_wheel_zoom = "bk-tool-icon-wheel-zoom";
    exports.tool_icon_box_edit = "bk-tool-icon-box-edit";
    exports.tool_icon_freehand_draw = "bk-tool-icon-freehand-draw";
    exports.tool_icon_poly_draw = "bk-tool-icon-poly-draw";
    exports.tool_icon_point_draw = "bk-tool-icon-point-draw";
    exports.tool_icon_poly_edit = "bk-tool-icon-poly-edit";
    exports.tool_icon_line_edit = "bk-tool-icon-line-edit";
    exports.tool_icon_settings = "bk-tool-icon-settings";
    exports.tool_icon_unknown = "bk-tool-icon-unknown";
    exports.tool_icon_fullscreen = "bk-tool-icon-fullscreen";
    exports.tool_icon_chevron_up = "bk-tool-icon-chevron-up";
    exports.tool_icon_chevron_down = "bk-tool-icon-chevron-down";
    exports.tool_icon_chevron_left = "bk-tool-icon-chevron-left";
    exports.tool_icon_chevron_right = "bk-tool-icon-chevron-right";
    exports.tool_icon_caret_up = "bk-tool-icon-caret-up";
    exports.tool_icon_caret_down = "bk-tool-icon-caret-down";
    exports.tool_icon_caret_left = "bk-tool-icon-caret-left";
    exports.tool_icon_caret_right = "bk-tool-icon-caret-right";
    exports.tool_icon_see_on = "bk-tool-icon-see-on";
    exports.tool_icon_see_off = "bk-tool-icon-see-off";
    exports.tool_icon_x_grip = "bk-tool-icon-x-grip";
    exports.tool_icon_y_grip = "bk-tool-icon-y-grip";
    exports.tool_icon_arrow_down_to_bar = "bk-tool-icon-arrow-down-to-bar";
    exports.tool_icon_arrow_up_from_bar = "bk-tool-icon-arrow-up-from-bar";
    exports.tool_icon_minimize = "bk-tool-icon-minimize";
    exports.tool_icon_maximize = "bk-tool-icon-maximize";
    exports.tool_icon_pin = "bk-tool-icon-pin";
    exports.tool_icon_unpin = "bk-tool-icon-unpin";
    exports.tool_icon_pointer = "bk-tool-icon-pointer";
    exports.tool_icon_delete = "bk-tool-icon-delete";
    exports.tool_icon_bold = "bk-tool-icon-bold";
    exports.tool_icon_italic = "bk-tool-icon-italic";
    exports.tool_icon_text_align_left = "bk-tool-icon-text-align-left";
    exports.tool_icon_text_align_center = "bk-tool-icon-text-align-center";
    exports.tool_icon_text_align_right = "bk-tool-icon-text-align-right";
    exports.tool_icon_check = "bk-tool-icon-check";
    exports.tool_icon_square = "bk-tool-icon-square";
    exports.tool_icon_square_check = "bk-tool-icon-square-check";
    exports.default = `:host{--bokeh-icon-color:#a1a6a9;--bokeh-icon-color-disabled:#d4d9db;}.bk-tool-icon-copy{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-copy);-webkit-mask-image:var(--bokeh-icon-copy);}.bk-tool-icon-open{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-open);-webkit-mask-image:var(--bokeh-icon-open);}.bk-tool-icon-replace-mode{background-image:var(--bokeh-icon-replace-mode, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxokK3gniQAAAHpJREFUWMNjXLhsJcNAAiaGAQajDhhwB7DgEP+PxmeksvjgDwFcLmYkUh2hkBj8IcBIZXsYh1w2/I8v3sgAOM0bLYhGc8GgrwuICgldfQO88pcvXvg/aOuCUQeM5oLRuoCFCJcTbOMh5XOiW0JDNhdQS3y0IBp1ABwAAF8KGrhC1Eg6AAAAAElFTkSuQmCC"));}.bk-tool-icon-toggle-mode{background-image:var(--bokeh-icon-toggle-mode, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADP3pUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHja7ZZbsiMnDIbfWUWWgCRAYjlcq2YHWX5+6HYf2+OpiieepxyoRrRQC6EPsN34+8d0f6GwZ3YhqqWckkcJOWQu6Jg/Stkt+bDbXfgcwvuD3l0DDJVAyvFq6bS/6elycIiCXrxzZO0cqI8DOZz+7cnROZGsiFYU/XSUT0fCxwCdDsqxLJ+y6f0S6jhkv63EjsetRvRY+s3J83tQZK9HKIV5CIlHK3IGIOsJTgo6abfCh7rAVNEGuUWChLzK01UyIpor1PDS6IHK1aPXevdMK/BpIk9JTpd8qXcUX1PZqb+bOdjZ40d9tsOV80/ZX8+c3eZeM1ZRQkKq07mo21J2D3YVU6ypzcFf8oonwoXumlENu7qBWvfNV9RGmRi4JgXqVGjS2LJRQ4iBh2NdJ4Uby1aaKGduYEeLmgSarJKli4Fo29iD8BUL7Wmzb27PZpi5E0yZ4IzwydvVvfvBnOsoEHm7coW4cPoXB1pplNXCDERonkmNO8G3+lwWVwHBuLK8jkhGYuvhokb6uglkgxYYRsjjuJD20wFShKkjgiEBAVAjiZTIK7MSIZEGQAWh4wBxBQGKkTuC5CCSwMZ4TY1PlLYpR4baQY/LDCQiTpyCTZYCWCFE7B8Nhj1UosQQY0xRo8UcS5IUUkwpaVqXYlHR4DRqUlXTrMXEgkVLpmaWrWTOgksz5pQ1W865FMxZ4Lng6wKDUipXqaFGV1PVajXX0rB9WmixpabNWm6lc5eO+6Onrt167mXQwFYaYcSRhg4beZSJrTbFzTDjTFOnzTzLRe3E+lN9gxqd1HiTWoZ6UYNW9eaC1nUSFzMAw68IgbguBNjQvJh5oxB4kVvMfGacisgIMi5mnRYxEAyDOE66sXN8EF3k/hM3p+GBG/8uObfQvUnuZ26vqPX1M9Q2seMUrqR6wekbOVlhQ0T4sVsdfy/ds+J35bejb0ffjv5vjkYtqzdcSF8vL/o10x+NqJZRMNcSp9aVxL7srv+Spw0E/kL9O+/uI+EgGveRcCDdR8JBFO4j4dh29H44e3+sbXLXd78YWPvnrTW7D5yOb0fvOsL/kOz+AVNjw+bixfXWAAABhGlDQ1BJQ0MgcHJvZmlsZQAAeJx9kT1Iw0AcxV9TtSIVRTuIOGSoThZERRy1CkWoEGqFVh1MLv0QmjQkKS6OgmvBwY/FqoOLs64OroIg+AHi7OCk6CIl/i8ptIjx4Lgf7+497t4BQq3ENKttDNB020wl4mImuyKGXtGBIPoQRq/MLGNWkpLwHV/3CPD1Lsaz/M/9ObrVnMWAgEg8wwzTJl4nntq0Dc77xBFWlFXic+JRky5I/Mh1xeM3zgWXBZ4ZMdOpOeIIsVhoYaWFWdHUiCeJo6qmU76Q8VjlvMVZK1VY4578heGcvrzEdZpDSGABi5AgQkEFGyjBRoxWnRQLKdqP+/gHXb9ELoVcG2DkmEcZGmTXD/4Hv7u18hPjXlI4DrS/OM7HMBDaBepVx/k+dpz6CRB8Bq70pr9cA6Y/Sa82tegR0LMNXFw3NWUPuNwBBp4M2ZRdKUhTyOeB9zP6pizQfwt0rXq9NfZx+gCkqavkDXBwCIwUKHvN592drb39e6bR3w/9qXJ4zBnVPwAADRppVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+Cjx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDQuNC4wLUV4aXYyIj4KIDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+CiAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIgogICAgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIKICAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIKICAgIHhtbG5zOkdJTVA9Imh0dHA6Ly93d3cuZ2ltcC5vcmcveG1wLyIKICAgIHhtbG5zOnRpZmY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vdGlmZi8xLjAvIgogICAgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIgogICB4bXBNTTpEb2N1bWVudElEPSJnaW1wOmRvY2lkOmdpbXA6MjFjNTkwNzMtOTc1Zi00ZjAxLTljMDktYzY2NWY3NTBhMDA2IgogICB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjdhODY1NGM1LTZiYTktNDkwMi1iZWNmLTAyMGE3Y2I1MTI5NCIKICAgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOmNmNDY3MmE2LTRjN2ItNDAwYi04N2U4LWExMjFjY2ZlZjI1YSIKICAgZGM6Rm9ybWF0PSJpbWFnZS9wbmciCiAgIEdJTVA6QVBJPSIyLjAiCiAgIEdJTVA6UGxhdGZvcm09IkxpbnV4IgogICBHSU1QOlRpbWVTdGFtcD0iMTcxNzQzODY2NDU5OTYwMiIKICAgR0lNUDpWZXJzaW9uPSIyLjEwLjMwIgogICB0aWZmOk9yaWVudGF0aW9uPSIxIgogICB4bXA6Q3JlYXRvclRvb2w9IkdJTVAgMi4xMCI+CiAgIDx4bXBNTTpIaXN0b3J5PgogICAgPHJkZjpTZXE+CiAgICAgPHJkZjpsaQogICAgICBzdEV2dDphY3Rpb249InNhdmVkIgogICAgICBzdEV2dDpjaGFuZ2VkPSIvIgogICAgICBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjAyOTk4NWE4LThlMjItNGI2NS1hNTQwLTE3MWI2NjU3YTYxOCIKICAgICAgc3RFdnQ6c29mdHdhcmVBZ2VudD0iR2ltcCAyLjEwIChMaW51eCkiCiAgICAgIHN0RXZ0OndoZW49IjIwMjQtMDYtMDNUMjA6MTc6NDQrMDI6MDAiLz4KICAgIDwvcmRmOlNlcT4KICAgPC94bXBNTTpIaXN0b3J5PgogIDwvcmRmOkRlc2NyaXB0aW9uPgogPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgIAo8P3hwYWNrZXQgZW5kPSJ3Ij8+rdIyIAAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB+gGAxIRLNWVUewAAAB9SURBVFjDY2AYBaNggAEjNsGFy1b+R+bHR4UzUlMcGTANymBZuGzlf3TX08o8ptFUOJoGBtrxTNS2HFd+p7kDyLF80KYZkiyhieXEWkas5VTLBciVDLXinOREiGwhNRIcCzmaBiSlj9YFw7Y9wEJK8Uppm3C0RTQKRgE2AAByVIRiIg+g0AAAAABJRU5ErkJggg=="));}.bk-tool-icon-append-mode{background-image:var(--bokeh-icon-append-mode, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxkZWD04WwAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAoUlEQVRYw+1WQQ6AIAwrhO8Y/bIXEz9jIMSDr8ETCUEPQzA4pMeFLKNbu4l5WR0CDOMEALBGIzMuQIBEZQjPgP9JLjwTfBjY9sO9lZsFA9IafZng3BlIyVefgd8XQFZBAWe8jfNxwsDhir6rzoCiPiy1K+J8/FRQemv2XfAdFcQ9znU4Viqg9ta1qYJ+D1BnAIBrkgGVOrXNqUA9rbyZm/AEzFh4jEeY/soAAAAASUVORK5CYII="));}.bk-tool-icon-intersect-mode{background-image:var(--bokeh-icon-intersect-mode, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxkrkOpp2wAAAPhJREFUWMPtV1EKwjAMTUavI3oawR/vtn5srJdREfzwMvHHQlcT2mpdMzFfWxiP5r2+JMN+mAiCOB72CABgR1cln4oOGocJnuMTSxWk8jMm7OggYkYXA9gPE3uyd8NXHONJ+eYMdE/NqCJmEZ5ZqlJJ4sUksKN7cYSaPoCZFWR1QI+Xm1fBACU63Cw22x0AAJxudwrffVwvZ+JmQdAHZkw0d4EpAMCw8k87pMdbnwtizQumJYv3nwV6XOA1qbUT/oQLUJgFRbsiNwFVucBIlyR3p0tdMp+XmFjfLKi1LatyAXtCRjPWBdL3Ke3VuACJKFfDr/xFN2fgAR/Go0qaLlmEAAAAAElFTkSuQmCC"));}.bk-tool-icon-subtract-mode{background-image:var(--bokeh-icon-subtract-mode, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUFFxgsF5XNOQAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAABFUlEQVRYw9VWUQqDMAxNpWfxQxD1MoP97G7zQ5mH2RTZYLtM9lWoMbXtxLXNX4OG9r28l4hrd0PQoqxqAACYpxH25C/nkwCHyCBwSPoS09k1T5Fo+4EiExcC4v584xGFmyIXHBLRISAVZyZufUPVa4rcrwmPDgr93ylo+2GliLRUYHK6th/o/6r7nfLpqaCsagEA8Hh9FmcNKeRmgeYDC+SCq0B6FFi8/BcV6BdR9cL3gCv3ijPKOacsn3rBEcjmaVxpfGcg4wHxzgJJnc6241Hn23DERFRAu1bNcWa3Q0uXi62XR6sCaWoSejbtdLYmU3kTEunNgj0bUbQqYG/IcMaqwPS9jftoVCAQ0ZVDJwf0zQdH4AsyW6fpQu4YegAAAABJRU5ErkJggg=="));}.bk-tool-icon-xor-mode{background-image:var(--bokeh-icon-xor-mode, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAQAAADZc7J/AAAAAmJLR0QA/4ePzL8AAACXSURBVEjH3VXBCcAwCDxLxgl0oM7nQEL3sa9ASLQIqS3UT4SIOfXOECsAADsAwb1/ECbbsGilvdKfli9OgmUEdGo8uKb0QIZ6PUvrwfcJzCn0zGtM9fx1BKzzFMTgvRf3jBZGs1TnxeVNwUIxxsqrWmBNYmJptewBBuZMwas3uiP+sA+8i8i2rpSlRg7+FaxZCHpFpu/EC1y3NtihGuwKAAAAAElFTkSuQmCC"));}.bk-tool-icon-invert-selection{background-image:var(--bokeh-icon-invert-selection, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAQAAADZc7J/AAAAAmJLR0QA/4ePzL8AAAC2SURBVEjH7VVJEoQwCGysPMeqPCjv40FU+R/moCbMmEWNenFygUug6aYTmhRdZwBeX8ClVJboCRDN5SN4zc8gkBaCtaONKZ+vB0JEcT0HtmvtBALS+rnatAEAF/KcCroThXKZRAP0J3IUT25bpG33m1TwBCCqQOY9IKtCDsVkiOxQQdR6we2dlR+ws7FMYQObKsgJFUyB8Wtev2W+hYB1dtoxFa4mMaJQqb6PDRmPeIH+X1t/gQ8PhzjuVbw+wwAAAABJRU5ErkJggg=="));}.bk-tool-icon-clear-selection{background-image:var(--bokeh-icon-clear-selection, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AUGEhcuan3d3wAAAoRJREFUWMPtlzFP3EAQhd+b3TNSzg0N5TWXLkJQUUaKhIQ4fgP/g5ArrriE/I3opEgRrZtIVJR0FJQ010SioUmEZHtnUpwN9gWHGA5BJCy58MraffvmfZ41v3z9hqe8BE98vQh4cgG+Ydzmnrng8efvQJNi/uN7dznx/B3ggtfhf4ehNdUttRzBDIm/2VTiiWCG1HK0nc+3UWtq8BQIiEEakEQOADBIA4QCQmBqoHBhFNR27ikQSmGdYCdTqCpEHMDZmEKRWUBEv1gBDg5SzRJnpopILWICgWuRYflLamuzxB2BmtYqSRIka5VWU8QduXO+1hRc5YZu5GAwmP2ZJzND0IBu5HCV2+NQcAhAVRsnC2IbPzPdSjzd6to6VtfWkXi6YLaVWr7xoAwkfpb8MnC3SH7rKSMBe4M0jA/OTicFIbtCGRIyNbURhcf3ErCd6YwA1m0HgAxhw1NGQnlXBHG4kylVlSJuH0RfIP2CkL2I/qS1gIAAQiBl1QwFggIHtyxgrxK5PgyfC0JWKoT0HLh8LwoietB4TYKaIl7yeNURxB05UtMxDOcVQlZIrlRKdK6m47gjR/fuBRQihyLArtNeJD50Izcx2Eczu7iFkIug4VM3cpOr3MKDekFED0fWUHv9Zq0kpLnridjhY3XDg7NTN0jDrhO3X7O9Wg7wwyANu4mnayNg3gmbu0tCNoUyBNGv2l4rB9EXynA7082FOxAQLhU6rQVO9T2AvWowFToNCJcPORGxIRcnpjZSKATSU9NxvOQnAPArDSaQoUKnNI4iufkGtD4P3EHIcWZhz4HLceSOyrR3Izf5memPAL2cX3yhAkonysZVaWLBkd9dw1Ivv2a/AYPkK+ty1U1DAAAAAElFTkSuQmCC"));}.bk-tool-icon-box-select{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-box-select);-webkit-mask-image:var(--bokeh-icon-box-select);}.bk-tool-icon-x-box-select{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-x-box-select);-webkit-mask-image:var(--bokeh-icon-x-box-select);}.bk-tool-icon-y-box-select{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-y-box-select);-webkit-mask-image:var(--bokeh-icon-y-box-select);}.bk-tool-icon-box-zoom{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-box-zoom);-webkit-mask-image:var(--bokeh-icon-box-zoom);}.bk-tool-icon-x-box-zoom{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-x-box-zoom);-webkit-mask-image:var(--bokeh-icon-x-box-zoom);}.bk-tool-icon-y-box-zoom{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-y-box-zoom);-webkit-mask-image:var(--bokeh-icon-y-box-zoom);}.bk-tool-icon-auto-box-zoom{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-auto-box-zoom);-webkit-mask-image:var(--bokeh-icon-auto-box-zoom);}.bk-tool-icon-zoom-in{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-zoom-in);-webkit-mask-image:var(--bokeh-icon-zoom-in);}.bk-tool-icon-zoom-out{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-zoom-out);-webkit-mask-image:var(--bokeh-icon-zoom-out);}.bk-tool-icon-help{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-help);-webkit-mask-image:var(--bokeh-icon-help);}.bk-tool-icon-hover{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-hover);-webkit-mask-image:var(--bokeh-icon-hover);}.bk-tool-icon-crosshair{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-crosshair);-webkit-mask-image:var(--bokeh-icon-crosshair);}.bk-tool-icon-lasso-select{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-lasso-select);-webkit-mask-image:var(--bokeh-icon-lasso-select);}.bk-tool-icon-pan{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-pan);-webkit-mask-image:var(--bokeh-icon-pan);}.bk-tool-icon-x-pan{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-x-pan);-webkit-mask-image:var(--bokeh-icon-x-pan);}.bk-tool-icon-y-pan{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-y-pan);-webkit-mask-image:var(--bokeh-icon-y-pan);}.bk-tool-icon-pan-left{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-pan-left);-webkit-mask-image:var(--bokeh-icon-pan-left);}.bk-tool-icon-pan-right{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-pan-right);-webkit-mask-image:var(--bokeh-icon-pan-right);}.bk-tool-icon-pan-up{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-pan-up);-webkit-mask-image:var(--bokeh-icon-pan-up);}.bk-tool-icon-pan-down{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-pan-down);-webkit-mask-image:var(--bokeh-icon-pan-down);}.bk-tool-icon-range{background-image:var(--bokeh-icon-range, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAABCJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICAgICAgICAgIHhtbG5zOmV4aWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vZXhpZi8xLjAvIgogICAgICAgICAgICB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iCiAgICAgICAgICAgIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyI+CiAgICAgICAgIDx0aWZmOlJlc29sdXRpb25Vbml0PjI8L3RpZmY6UmVzb2x1dGlvblVuaXQ+CiAgICAgICAgIDx0aWZmOkNvbXByZXNzaW9uPjU8L3RpZmY6Q29tcHJlc3Npb24+CiAgICAgICAgIDx0aWZmOlhSZXNvbHV0aW9uPjcyPC90aWZmOlhSZXNvbHV0aW9uPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk9yaWVudGF0aW9uPgogICAgICAgICA8dGlmZjpZUmVzb2x1dGlvbj43MjwvdGlmZjpZUmVzb2x1dGlvbj4KICAgICAgICAgPGV4aWY6UGl4ZWxYRGltZW5zaW9uPjMyPC9leGlmOlBpeGVsWERpbWVuc2lvbj4KICAgICAgICAgPGV4aWY6Q29sb3JTcGFjZT4xPC9leGlmOkNvbG9yU3BhY2U+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj4zMjwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAgICAgICAgIDxkYzpzdWJqZWN0PgogICAgICAgICAgICA8cmRmOkJhZy8+CiAgICAgICAgIDwvZGM6c3ViamVjdD4KICAgICAgICAgPHhtcDpNb2RpZnlEYXRlPjIwMTgtMDQtMjhUMTQ6MDQ6NDk8L3htcDpNb2RpZnlEYXRlPgogICAgICAgICA8eG1wOkNyZWF0b3JUb29sPlBpeGVsbWF0b3IgMy43PC94bXA6Q3JlYXRvclRvb2w+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgrsrWBhAAAD60lEQVRYCcVWv2scRxSemZ097SHbSeWkcYwwclDhzr1Q5T6QE1LghP6BGNIYJGRWNlaZItiFK1mr+JAu4HQu0kjpU8sgF3ITAsaFg0hOvt2Zyfvmdsa7a610Unx44Zgf773vvfneezPHNzrbhn3CT3xC3wPXYOC8LDzqdi8YY/gwh4BeknS/2th6dr2kf94AOp3OFyWgMyziOPbMDxV9FTtJnl1ut795Xd0/YQ0/vtYQwMT1KXWCfr2IjOWwtNehwN4xL9ykTrm6Pzl58yLn3J+mKh9mXbT3uRjGEDph+O8/TjfP5dBp7Ha7AX7O3o5nZeD/0E/OGyXntDgzA0X6qmCnrVutVlrUWV9f/3xo+pwhGDhvEPHOjoxnZjJggXmMHzBQ7NGNp9vxk61fr0HR7e/u7pZzCGHlc7qwBYYTT7tJYSx1AQzppyFPft5apta9w7SKcn0b7P7+/jCsDQ5mbc0dCmIJGDN0ehdcjsmkm6A6KUeKFOTE11PLxrC7Ukqh3ylL2fT0NAP9q6ur6rRCJJYsbKB0JsbCKMuy+xREePDyxQPCz+Crlw062QcA5wBOOt1l6vIl2WiI9F1fN6Q+BBqit6hEC4Hk08GQJMn4myjSP7RavVxgdaVUh/3U6HCMsPr9pYnJKRziHtWQ+un58+hGs6nsjQSjpuTyKGN3CX+FBwHXSiEVgjP+O8X6N12kIePES+GzTKAkGbNp8yJsGUMVzz8jPKReiyAQRimy5/cjye5RpF8utFp/+nwmT7d/NMzcFkS7yjJNGDaPURQxIQThEQy0SyF4l5WJYYhBa816vZ6dU7A6CAhbZVow/pDe0O9hVOoCi13r4BgBAvJHqMSQL2vE/iH6IAXEwgrRVUmBoRRwnwJQT98xEeVeSUyB4dJ5nwJBKdCFFGRmUCcu7rwIYypCTblaChuNBhWODrman5ub+4v0rMNBt8z6Ezh7GksJQpCbm79cMQE7QBFm/X6f0rjWnv8WRYg/QdbUpwDAEBy8vPyA8rNGzg3a8MiElwiM7dAtRqNoNptjGPM1laVxP9umWEMGLOKhKUOJDtBwDmzsw9fC/CzHr9SGuCTi2LbbKvVtmqXpCjMihBFa79Wrt5fGx9PDzc3fmu32Lf8qFliwU9emKhBSp+kRKn/hu9k1COEDbFdt/BoKWOAkuEbdVYyoIXv8+I/QK9dMHEb1Knb7MHOv8LFFOsjzCVHWOD7Ltn+MXCRF4729vWMDK+p8rLkvwjLg4N4v741m5YuwCI9CvHp1Ha8gFdBoPnQAkGsYYGxxcfEI7QQlFCTGUXwjAz4tWF+EpymOWu7fglE7qsOvrYE6g4+9/x/vhRbMdLOCFgAAAABJRU5ErkJggg=="));}.bk-tool-icon-polygon-select{background-image:var(--bokeh-icon-polygon-select, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEjc1OfiVKAAAAe1JREFUWMPt1r9rU1EUB/DPK0XbqphFHETo4OCiFhwF0V1KHbRSROLqon+AUMVRRFBwEbRFMBiV+mMW/wIxi5OD1kERRVKRJHUwLvfBTZrU5OWBGXLgQu7Jfe98z/ec7z0vKa88b2q1BDtRHdAPBaylm1NzsxsOjPnPNt6WSWprbft+/c3I3zOAjhT1Y4+fvcjEQJIXnVECSa+AhqIHqlHH5lWCZoe+Gk4GRgDG86j9SAUdlDBSQaZhlOkuHyoVdJmsw98D1S5fM4NYM1LCpqM+Lwa240oLgmZzpVZvzKT75VLZcqksSZKWlQeAy/iORVwIvh31xvotvK7VG3Px4aWHj3Jl4C2uYSvq+Bn8v6LLbaVWb9zsBiKLCvbiNG7gLm7jAYqbPHMJMziZ9lsKoh8GtqCEVVzHftwJn+TFHp4/hg8BSCYVfMOZoPEv2NZGdy9WCGUr9toDR3E2/H4V6nwRe/BmgN65H1ZhvMuB3XiKIyFoGefwO6ysVkUlrNUNsyAK/jli533Q+Y8cJFvAeXyMS1CI/jiMr/gUtD2LQwMGr4R3p7bY3oQHQ5b38CT4D2AXXg6YcQXHpyYnlqKsi5iOAVSwL9zd7zJ09r+Cpwq72omFMazjT9Dnibym0dTkRDUKrrgwH7MwXVyYB38BstaGDfLUTsgAAAAASUVORK5CYII="));}.bk-tool-icon-redo{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-redo);-webkit-mask-image:var(--bokeh-icon-redo);}.bk-tool-icon-reset{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-reset);-webkit-mask-image:var(--bokeh-icon-reset);}.bk-tool-icon-save{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-save);-webkit-mask-image:var(--bokeh-icon-save);}.bk-tool-icon-tap-select{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-tap-select);-webkit-mask-image:var(--bokeh-icon-tap-select);}.bk-tool-icon-undo{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-undo);-webkit-mask-image:var(--bokeh-icon-undo);}.bk-tool-icon-wheel-pan{background-image:var(--bokeh-icon-wheel-pan, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEgswOmEYWAAABddJREFUWMO9l09oXNcVxn/n3vc0fzRjj2RHyIZ6ERuy6CarxJtS0pQSCsXNpqGFWK5tTHAwyqIGN7VdEts1LV04BEoxdlJnUbfNogtDCYWQRZOSxtAUCoFiJY0pWJVUjeTKM9LMe+9+Xcyb8ZMychuofeHCffeee7/vnXvOuefYlV/+mv932//tb91z/Y2rvxmMHQ+4FcEfOIGN4A+UwDDwoQScc7vM7AIwB8yZ2QXn3K77Ab6OgJnVgeOSbkqaBiaACUnTkm4Cx3OZzwf+qzcRQup1zNZ9RwDe+0YI4YKZTUn6zCGSMLOfAF/03r+QZdnyfwO+ePEiI6N1nPMgMDMkETLRbd2mXG8gCbd9YiIKIUxLKoLfBN7I+80+CUlTIYTp7RMT0b3Af37p8kh5y9gZcy4Fzt+5szqSaxkzUR7dwtrKMmaGW242d0t6vrD/He/90865o865o977p4F3Ctp4frnZ3L0Z+OryUrVSrZ0z8ZxhHjhcq1XPrS43q/0flDlK9XpPA2ma7gMeyvfPx3H8TJZlH4YQWiGEVpZlH8Zx/Awwn8s8lKbpvmq1ahvB641SXNk6dhLskNA2MIBtwKHK1vGTW8bKMRbAMgyPqWeETxUM8VSSJAv52JmZA0iSZMHMThWwnipXKp8hsLLcSaIR92oU8xjSayCQXotiHotG3Ku3m+0EOQwPQCDggMf7BzQajSs5eAk4B5zLx4O1vD2eJMmAQKliscgASJMw21pansFs1swQ/DNLmUmTMNuXX+taXHTDaj5OW612R1JZ0nFJJ/J+XFJ5aWmpA6S5bHV8fHsPHFU6q3pJCjtFxtrKMuXRLUUXXxdrRLazFOtUolZlsGhmACsgnHPTwJnCnjP5HMBKLotzxsTE9rgDL0t6LoriKsDIaB31ZEK+JxQJRHFUBR2NqLw8OTkZR0OC0ntm9k1JWU7OA4vD/mZ+YfElsANmNEKi75vztzB5M8uAr+bx48me88g757PQ1U5zNg52YH7hX8l6f+4Fi3c3BqHNmkI4YQOV2MGCNu9qHPYCewfzbrC+XSGcWEcgTRKA3wFfyzdDz5d+D3x9CIcfA4eBbQS9LscskgfLnHNPAnslvS/pbZDHLLPADpx9N9fqpSIBH8cxWZY9m6bpb4Ev5fN/iKLo2TRNgdx/eo8Wk5O7Ts/N/SOSdMjHdj4kmgkIEJLJzPZKetvMTkIvFLsR25Ml2gfuF5M7vnA66sdooJYkCSGERe/9VAjhzRxoKk3Tvg3U8nulVqvx8cyNpER2umM+SdOkbc5B8JhpqBdIgTRR24h+lpKen731aRIN7thscH9Zlv0d2F8YD2TIX7F2uw3A7ZWV1a0TYz9ca8cJZHRbuRuaDfUCw9/qJHamPOKToAwHtHN6lMvlSkH2o7wDMDo6WuGuQbbn5+YAKNcb3J5fSvrhtTY+vsOPuD1IOyRhMOkj9kSx29HfXB5RUnS964NT2+3vbGbxG9auO2cDNuV6A8NTb5TitBuOpQkfYD2vwOxgmvBB2g3Hto5X42EJyVsFlztbKpXGNgqVSqUxSWcLU2+tdToa9hasLjfPYlwGa+bTi8Dl1dvNsyvNtQQL9MO2w+HM7BqwlAtPdrvdq9773WAVsIr3fne3270KTOYyS2Z2bbXdHhogKmPj7YWF+VOSXs/v/9KdO+0fVBrjbRkgB/KIDBnYu9f/7D+ZmfmRxPd6qwB8YmZXcq1MAQ/nJhTM+OnDe/a8+PGNG9lm19V/D1Qw7HXZlcRa69+U6w38l5/4ipxzf5X0CPBILjcGPJH34pVcc8692FxcXLlXRnTwwH7+9P4f8aWe3fY59LIqo1NMyQBCCHNmdgx4BegUWefjDvCKmR0LIcz9L8nokSNH+PRvH4HC3YQ098pSbevg24qlmZmNmtmjkg4D3+j/tZldkvQXSa3PW5ptlpL3ZaIN99OS9F7+IgKUgSyEkNyv2nHT7DZX0dr9rpjua2l2r4rogRAYVqZvnPsPqVnpEXjEaB4AAAAASUVORK5CYII="));}.bk-tool-icon-wheel-zoom{background-image:var(--bokeh-icon-wheel-zoom, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEgskILvMJQAABTtJREFUWMPdl1+MXVUVxn/fPvf2zrSFmUKnoBCUdjRoVaIxEpO2JhilMYBCtBQS2hejpg1Uo2NUrIFAoyGmtiE+GHwQGtvQJhqDmKYRBv+URFsFDNCSptH60DJTO3dKnX/33rM/H7rvsDu9M20fDMaVnGTvtb69z7fWXmvtc/TEzqd4OyXwNsv/FwFJQVI/sA14SZKRLOlPkr5TrVYXHz70quYkEEK4TtI2YAgYkrQthHDdhV5uuw+43/ZrwCbgRttgY/tjtrc0m83X3/f+D6ydnJhYcB4BSZcBA7aP2d4ELAGW2N5k+xgwkDB0IH19CGGH7R8B1aQeAf4KvAw0ku4K2zu7uru3ApdPEyiKohd4TNKjtjt5h6RHgccSNrddbvuHtm9Jqoak7xVF8WFgdavV+pSk5cCObNmXgK++85prCj3z28HKqZMnH7D9YAY4BvwujT8BvCuL1INX9vVt+dfwcCvNb7f9q2RuSfrGvWu/sL2Nf3LX7pzvj4ENSGBPVarVd4fRkZFltjdmoMGiKO4IIWwIIWwoiuIOYDDzeOPoyMiyFLkum7WJCMDztrcrTTrIRuAQZ6NcK1utL4dWq/VZoC8BhqvV6l1lWb4YYxyLMY6VZflitVq9CxhOmL60hhCKeYiV7WMKIXw9jT1HpXw3c+bOAKzOjJubzebJrKQCQLPZPClpc7bP6rMYKtjXth2OMf7tIkr11Wz8oQDc1Fb09vY+kQw1YAuwJY2nbUluAnCWpKkaFl6IQIzxivaR2SYA89sJVK/Xp2x32R6w/a30DNjuqtfrU0ArYecDCEqgLqm94T0dEm9mBG7PxkdDlkBnkhebgIezNQ8nHcCZPL9ijE1Jf/bZZoPtzbavmqNZLbf9tSxq+yoduuJ+SZ+zXSZyBXCqU+d8fvC5yRUrV+0G2j3g2hDCLyXd/+Su3QdnvP/zCuH72LWsgf2k0oHlH2c2odlkxcpVEdgr6aDtjyb8x20/J+mA7T9I6rL9SWA5dne2/GdXLl58qNJh398An85yTMA+4DOz8Dgu6Zu2dwJXJ91ltm8Gbp7Fgb+EEB4aHhpq5CEtACqVyr3AC0AlPS8k3TSmQ2YPhhBuS/1/LpmS9JTtNTHGfwBU2uUALARotVqniqJYH2Pck85pfavVaufAwnQvnHc0McaDKVptebN94QAnJB0EdtjekydyZXqjs/0ZgLIs/w6sy8bnYGYJ63pgERKC05JutT1kOwITwL9tvzlzUQUYB+Zjs2DBgu6xsbGJZHstByZbezregcBXeCsEz1bnzXt5anLyzLq71zDLxTRdVgemdx0fv2e2w5thO5DbiqL4oKT3ZKpnpyYnz+SY2ZpTAPZmJfdIrVZbNBNUq9UW2X4kU+2dcf53Aj1pj2PA7y/6m1DS00A9za9uNBq7iqJYBuoGdRdFsazRaOzKSqye1rTbaa/tlbYrqXQP2X4FIA9/J1l39xrC0v7+w5IeB8XkwS1lWe6TGJAYKMty31tfO4qSHl/a3384I3CDpI+kzC4lnRfrue6GytEjR8oQwlY73gC0L4qlth/q0M1/LYWtR48cKQF6enrC6dOnVwGLEpnxnp7en4+O1i/tszzGOCTpPmB7ahb57QUwBWyXdF+McWg6MScmuoA8OX8xOlpvXGz422XYTsB/SnpA0h7bX5R0WzI9HUL4qe2XbI+dk3xl+V7gxoztD5jRI+YK/zkEEokx2/uB/RdzIfUtueqVN04cXwF8G3iHY3z9Urw/j8ClyhsnjrcS2Vv/J/8NLxT+/zqBTkcxU/cfEkyEAu3kmjAAAAAASUVORK5CYII="));}.bk-tool-icon-box-edit{background-image:var(--bokeh-icon-box-edit, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEg4QfHjM1QAAAGRJREFUWMNjXLhsJcNAAiaGAQYsDAwM/+lsJ+OgCwGsLqMB+D8o08CoA0YdMOqAUQewDFQdMBoFIyoN/B/U7YFRB7DQIc7xyo9GwbBMA4xDqhxgISH1klXbDYk0QOseEeOgDgEAIS0JQleje6IAAAAASUVORK5CYII="));}.bk-tool-icon-freehand-draw{background-image:var(--bokeh-icon-freehand-draw, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADTElEQVRYCeWWTWwMYRjH/88721X1lZJIGxJxcEE4OOiBgzjXWh8TJKR76kWacOBGxdEJIdk4VChZI/phidRBHMRRIr7DSUiaSCRFRM3u88gz+o7Z6bBTdjmYZPf9eJ55fv/5zzvvDPC/H9QsA66Olo9Ga+/MdR+Ljm2/KQIULsz9FqItGdOfJKLhApLgVkiSCGODjWit7QpKWy+TNrFeXvzKVUT8NiTVaIgDcbiCFJ7GiT8WkARXAdYBK0Lbhi/CenArRNskuM7/tgNp4ArQ42dwjf3WY5gWTqC7O/NbNn2Xkfw/YwdSw/We14HP2IEZwX+y9cZ9SH0LmgFP7UCz4KkENBNeV0Cz4b8U8DfgKiDxMWwUXETqLvJpCQpXZfawbzS7t9v5pL19cHBwfja7YA0y/lyCM0+E5hv5+piZXwKYcF23as+37bTXsQVqgkL0p/34fHR7DcBtbetFsBmGDwMOJCggYG55yw7dMlk6DuC1Bdu2RsCU9TYWQq2IoGbsreZ5NzvEqfSBsIsIy8OTbcdgiRHeh4o8AFAEwDakbY2AaCCpH7V9aGhoUUUy3UyVbkPYFuYLDlUZH8XBpwxkK0Dbgxg5HcVi0ent7a0RULMIozaHBSMfF9b2SzdutFcFB2FkwMIJOG6qfteXOa1nHZ48tyefuwyfT9s6wtzZ3t7eZse2DR2I228TtHXzuWCx9g8MtK5cuHCZTH4tiHEOa4xFngvTyS8f35d6enomiCi4/foEXBkZaQuukChL4FYA2Whd7YcC4gEdW3CpdL3LtGAVCVYJywEyTpAuJKeMOKXZs/Bw947C50KhUFOG4cwz35cjWNBlHGeD53n3xsfHP/T19U1qciggar8Fa4I3PHobIotBWBtc2hSiChyZxVzM53Pv7FVH6Tp3uVy+g0r1ImD2GjIrQGYIxjnfuXTZGICS5k/bBwJoubwEFX4TLah9EXomJGMA3za+f9913Yl4TnzsDQ+vE6YTZOjHh4ngibstt1pzQwd04F0bPStEBpXqRoBeQ/AKghfBnOEKgS+Q7z91Xfdz/HGKg8Ox7z8iYD9z6wqTkZFgnvhMGP9VZ2or1XVkPM9z0mytSfVsHa1RLBZbLoyNzUnK+ydz3wC6I9x+lwbngwAAAABJRU5ErkJggg=="));}.bk-tool-icon-poly-draw{background-image:var(--bokeh-icon-poly-draw, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEjglo9eZgwAAAc5JREFUWMPt1zFrU1EUB/DfS4OmVTGDIChCP4BgnQXRxVHqIJUupp9AB8VBQcRBQUXIB9DWQoMRiXZzcnQSA34A7aAuHSJKkgo2LvfBrU3aJnlYkBy4vHcP557zP/9z3r33JdXa647N0kHSZd5Nn0rSxc8G3cXp85sMcnZZ8vge3osZ+l3vB8CWFA0iL14t79h210swAjACMAIwAjACkB90D/8/GchI9ve4nPwTBh5E9ws7OepzGWb9EddSn51Op9ZstadSg4VK1UKlKkmSDSMLALewiuNh/hVJq71Wxttmqz0dG88vPc+MgWP4grvYG3SLOBrZFFFrttqPe4HIDxh4GSei+98iSlusuYopXEAjBtEPA3tQwUpwluAbDm4TPJUz+BTW9l2Ce6G7L0X/Bw8D3T/7SKKIDzHg7QCcxjvcQAEtXAnrrg/RP0/DKPbqgcN4iVOR7gcO4dcQgRuoh7HSqwlP4n20m63jJu5n8MkWMYfP3UowhzdR8FU8w9iQwevBdyq3/27CMRzAE5yLuvsRLg+ZcR1nJ8YL81HWJUzGAPaFZwe/Q5MdyYDyNHgjzO90YyGHtVDncuiJchaHw8R4oREFV5qdiVmYLM3OgD9k5209/atmIAAAAABJRU5ErkJggg=="));}.bk-tool-icon-point-draw{background-image:var(--bokeh-icon-point-draw, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEMEiERGWPELgAAA4RJREFUWMO1lr1uG1cQhb9ztdRSP7AF1QxgwKlcuZSqRC9gWUUUINWqTh5AnaFOnVPEteQmRuhCURqWsSqqc9IolREXdEvQBElxtdw7KURSFEVKu4w8wAKLxdw9Z+bMnRmZGXfZ29//II8th4WwGVNyIoQLYB5vxA9Caq04iUd9A+7ZlsNC2I7TdSd2hZXMJKlnTqp9jtl/GBaqoyQ0noFKpUIzBicYYc+DEFpxkglc4oVJa5gvDn8v1xV2irG3FM4NSVwjUKlUaMcpJhCGmSEJQ6QGD8M5WnHCd8+f3QCXpPLx8WNwv0j6Bm9FMK7FJ3WBE+R/2t7c/GBmFvSBrzRTCsyTDjXrxUgEMtpxynJYmJoBJ4VAybwVARgvL7Oik0okCodnKpVKX7P0leiVMb0VvbJT+upznK4vh0GIeQwwQStJkHQD3MwsCALTJRG7Qrdrj5m/djgYaIa0hlkRdJk26XEgC9txurccBtVW3IudBImmZuACUP+ZlIDBt9FKcubYNTcAH/X0RYM1E7utJPlqe+uZzPxUcEkiSS4sTT95n15Mud0xWC0o2PAWOCdK3KYZlFxfM+tHOcnMzNr1es18ug+cgsVjP4yBU/Ppfrter1m/+l0+zYygML1xRVHU7TSb1cSzBzoBzszsH+AMdJJ49jrNZjWKou6wBnwOzcyndBpNbuueURR1Dw8Pq35p9cc5p/Dy9Dypt7jXrtdGwQECS9NPhr6Gq6txUzNigE6zydLK6lTw12/KT4FGFEUfJX2YJNONq5tVs4ODA7sD/DnwJ/BoADZuE3tHFs12dna6d4C/BI6AlbyzI8ii2TTw12/KK33gb2cdXsNZoAntbZC2SeO4c9592k/5eNQbiwvFd1kJuFGwLJr1wSPg/SwpvyFBHufOeXcFeAlE97U/uCxOY+P3b+Bn4B3Q+L8EdJfD4a+/AbC4UBzPxiPg3wlHZquB28Cn2IuR9x3gr3uV4DbwfvSDOvi4uFA8BDZmIRHkjHpS9Ht9iRqd8+5G3g05mAGcQbsdiX5QJ428G7Kygo8XYdb1/K4NWVmjzkNge2sz84bs+ELmpDDLtqWsNZBXgvmw8CTtpWVMT7x5YWBjLARnwZfKQNYN2U2LPvrh+5nBt7c2M2/It9bArCTKR8eZN+SJ13AScPnoODeRdqNenH+wul5w2gUr2WUjMFAt8bZ/0axX/wNnv4H8vTFb1QAAAABJRU5ErkJggg=="));}.bk-tool-icon-poly-edit{background-image:var(--bokeh-icon-poly-edit, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gELFi46qJmxxAAABV9JREFUWMOdl19vFFUYxn9n9u9sCyylUIzWUoMQBAWCMdEEIt6xIRQSLIEKtvHe6AcA4yeQb7CAUNJy0daLeomJN8SEULAC2kBBapBKoLvbmdl/c14vdmY7u91tF95kknPOnHmf95znPc97Ro2OTeBbdjFDT3c32ZxVHUOE9kSMB0/m6ExuoJn1H+ur6Y+OTfD50SMN5168OgrAlyf7CfuD+z7+iDs3p8hkLUQ0iFQ/yFl5Nm/qonfHVva+s32Zw9GxCYILsZ08tpNfBhbs+1YN4OH9+7huGdECSBVfqUosbsllfmauBqiR+cCNwOr7AEo8pPHJnymXykhg5fUWjoQpl0vVvhZhbSzGoUOHqgBlt6B6uruj2Zy1E9jo0fhfeyL2x4Mnc8VErK0KUEOB64JSyptfG4RSytsJjUJVxw2lsFy3urL9nx1Qd25ObctkrVMi+jQivd7U2ZyV/3Hzpq7h3h1b/7p9Y0o8v8rwAbTWrGpSocN/FGDlbAI0Rl23PCBan0Ok158H9Ipwzi25A/Mzc9Gl/BYx/E4kYqC1NKRARNAaDCNUM27Z+Zr+ouXs0q4+LSLBHPYCFkTkC6uU39kwCdsS7WRKmaYUiAhdnZ3MPX2K4+QjQI+C94A93rMzm8ltMwyDeDzWjMZeEb2pYQDdW3vITU2jtUZ5QThOPgm8C7wP7J15OPsBsB3oWpGnVWisCeDS1VHj4vBI92+/3tgB7Ab2AruAXiDBK5oIOkhtkEYRNRuJhObrd8Dl9ewf4D5wG7hVLpen29vb5wzD+BrkbBMaL3d1dk5nsrnlFDTTFWAWmAZueWD3gCemGde2k2fw1Al1YXhEvjozoO49eczdqekrWmsc2zlrmvEKOGoW1GUjFLqSk2KpJrCLwyMCPAP+BO54QL8DM6YZX/ClsP9YnwKkXnIBP4jdIpJRpdJTCYdMwwi98KU0Hjc/dDILNyUcwTCWdOSMJ0TRmBktGRhLugu0xyLk7CIqVNm+0bGJptl1YXikD0grpY4Rjc4a8Fbgdab/6OGbAJeCUuyJnnHmZH9pbSyGuBXV8NUwlUpR1EWyixmSyTWEwqGlJ2Swbo2JXbAAfgDGgGQA9I1A9t1tlq0AxrXxn0ilUpw4fhQqYkH/sT41OTnJJwf2s6FjI5mshdYa7bqVR2uezr9MJmJt14FvGrh/O9D+e6UkM/xyCuCqEKCYnJyUTKFQrZDHjxzGshwWLQcRsOz8Hi85P23id0ug/XilAMLBmm4tPGdoaKjSH5+oAGrhwvBI9SjZTn4QSK9yenoD7dlrExPoJlXW8G8ytpNHxRKk02lGxsdRKFwXLNvx5yY94HQLGhGk4LFCYQSqaE0AwWM1eOoEbR0dKBSW7bC4mKuffxs4D/wCLKwQQPAUzIkslfp6cVomROWSolh0GjldAM4nzDi2k9/i5UAzC9aKfwNJ3zgJg9YEvN6+C7SHgKm69+sD7RfNnKTTaZRPQfAut4oFV//IS7gkcB34VlVo8kGzphlfB+DU+TfNGBpZtRastvrvARJmfMF28ge9sc2B9/PNnCilMIDwK6y8/ow/Ai4kvILTljAXvDvEvrqKSUs60KolzPjBxspavQD2tKqCAGF/Ba+xE/Wbilu54wZV8NEKF5fXzQHl/bh4hUsE0WAXSlDMYcQSrQXgCmsTseXHsJkNnjqBFGwKJaHsKlxtUHYVhbLCzr1kaOA4bcn1y1Swmb+iLpJKpVrfgdpfsiVVCYcgluwgnU7jEgJ4s5UkLFtWYyHyEg0/N1q1tmQH+YXnAMFr97Nmv3p+0QsHQRsF8qpBOE5+rb9Nkaj50tVQKjqh4OU3GNL/1/So3vuUgbAAAAAASUVORK5CYII="));}.bk-tool-icon-line-edit{background-image:var(--bokeh-icon-line-edit, url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAG/3pUWHRSYXcgcHJvZmlsZSB0eXBlIGV4aWYAAHjarVdpknSpDfzPKXwEJBDLccQW4Rv4+E4BtXR198znCdeLLijgQUoppWg3//Pv5f6FDwefXJRcUk3J4xNrrKzoFH8+pyUf9/f+8J3C7y/j7jnBGApow/mZ5l2vGJfXCzne8fZ13OV+9yl3ozvx2DDYyXbauCDvRoHPON3frl5Imt7MuX8hH0seiz9/xwxnDMFgYMczUPD7m89J4fwp/iK+OVRbiMf6gm8K4bv/3NN1Pzjw2fvwn+93PLzccTZ6mJU+/HTHSX723/bSOyLi58n8jmiqz/798+a/tUZZax7rNCKOakzXqIcpu4eFDe483kh4Mv4E/byfiqd49R2OHzC1Od/woxLD44siDVJaNHfbqQNi5MkZLXPnsMdKyFy5gwwCHXhocXahhhEK+OhgLmCYn1hon1vtPBxWcPIgrGTCZrR5fHvc58A/fb5stJaFOZEvT18BF1t8AYYxZ99YBUJoXZ/K9i+50/jPjxEbwKBsNxcYqL6dLZrQK7bC5jl4cVga/Ql5yuNuABfhbAEYCmDAJwpCiXxmzkTwYwE/CuQcIjcwQOKEB1ByDCGBnMJ2Nt7JtNey8BmGvIAICSlkUFODgqwYJSbkW0EIqZMgUUSSZClSRVNIMUlKKSfTKc0hxyw55ZxLrllLKLFISSWXUmrRyjVAxsTVVHMttVZVHKpRsZdivWKgcQstNmmp5VZabdoRPj126annXnrtOniEAQlwI408yqhDJ02E0oxTZpp5llmnLsTaCisuWWnlVVZd+mTtsvqVtU/m/po1uqzxJsrW5RdrGM75sQWZnIhxBsY4EhjPxgACmo0zXyhGNuaMM185uBCEgVKMnEHGGBiMk1gWPbl7Mfcrbw7e/V9545+Yc0bd/4M5Z9S9Mfedtx9YG7rlNmyCLAvhUyhkQPrNhvO5AJFnrZIR0plaLL5liQYdDi5TubaIokFDkmoFEB8CzxZVxemssDqthPhUblPgW1iQU5g6XwNwyVI7bUFRm035iNziMkgWvEso2SXnsJfveR0Y4SlVF8YWC1pVQhJiQa8JwDvlMNIxAfq3F7GDObHU1LlhzlZaWwNp6BvACxAgInGXlllMGZCpEnZHrGA6GM2718xuFcz7YdUQxzEEfjdWz4GlkcwaonT0pgA6mB25grPILtnSMhuCpsGhmMU6uJbixJs4lbKHqh+wos1jW2rchyGRCIvN9MXu+KAmMSfAlIKVvi/tybhCPJZCu2Ow9pLdyo427+X2ovMBmKNu8PA0zgl3fS0PB1DWWkVYB47bkyiJHhkFPzTzCjzn4Dq1mqoIWzCmcDGsHQmQAQdEHsixK1IXESd5rLU7THVJNV8obHS8sZeN0G5Jdt5pQTVKCCbgK1hItTS8o92iEZpuWJ/oC2r/0+zTmhvFXoaMVKRe27altDtid6OvG1hENVwBnC61KKugNoemOiPCCNb3GoHAZOFuDxxPsD+07nbSPcr/o1Zmc4jARhotrA5F5ZcjP9rPk90vR8A+k028A+8+5wKlHVID542sMzMCuXktkRzUCpE+xCBZywjNcJITx0II9x5948CekBl4XaC5OCX2nCyObdwN3HwQh5DWL/BBEkhDYHn/vpXNgZkVTZs8rj+HO8JFC6qvDVhgAEQSYCDyC86rMhG1WPzAVB9ZldDWG6EzDcFiqJBDvFS8mXDv3SK2LPoguVB2kwUx7UL5KqZWiEzocsbvSjNnaYDNtcYJuA5cDcsrvHd6yCxGjqvl9+wh3Qh8Kc9py8sNW8ncU8qwxdPj1qIGfrPqlXeoS4/JLa/LwRLTCtxuSoZUT+2Su6kXW3QNacYQbId6NUKVbROpviybFSPQQL9lhB2MamEnFyB9Y+hrG1+xBg+L0QG2TZdTdlcsBdq9oHdt9Bu5/IM9+Nfh1AwrSqlboTA6Bgq568A7UfbaMrZjoQZhQphofvNw93+bN+5X7FYKBgLmRid+tSdV6c02A4R0cHwKobmoMt5+6WI9XNISFIywpf6RMd5/a91vE78FzVHIFmxud4woyJx76OMTCa4yhgN3iJO2VfRPFMv9sYTxFzU+1eWeYS52pwOoSJldZY6koib4P1O427rbeUrNZfu44hWjz5ZSuu/vKPpimoXbLkfxWSPetvxDWG5jQSaZCxA3ad+p6rlttDhK+YwwK1LHVe0drDtorc5vnQ1247g58vewDtU7L3DRwrG4dhCUDRKKOtYr2dXHtpt+33d1WZmfkAHdl7Q8ENF+CNgB+nOw29n5F7SeNo/ckbu4laLTCdqJLHjmhJbKzmrCEX7zULrhefuHmu0V/1nbP1pnb6FaT7sOxn4pvWkfrYhYtCeJ4Xv+kOXrroIs1eHWXN1/AfzaY94ms5vaAAABg2lDQ1BJQ0MgcHJvZmlsZQAAeJx9kT1Iw0AcxV/TSkUqDnYQUchQnSyIijhqFYpQIdQKrTqYXPoFTRqSFBdHwbXg4Mdi1cHFWVcHV0EQ/ABxcnRSdJES/5cUWsR4cNyPd/ced+8AoVFhmhUaBzTdNtPJhJjNrYrhV4QwjAgGIMrMMuYkKQXf8XWPAF/v4jzL/9yfo1fNWwwIiMSzzDBt4g3i6U3b4LxPHGUlWSU+Jx4z6YLEj1xXPH7jXHRZ4JlRM5OeJ44Si8UOVjqYlUyNeIo4pmo65QtZj1XOW5y1So217slfGMnrK8tcpzmEJBaxBAkiFNRQRgU24rTqpFhI037Cxz/o+iVyKeQqg5FjAVVokF0/+B/87tYqTE54SZEE0PXiOB8jQHgXaNYd5/vYcZonQPAZuNLb/moDmPkkvd7WYkdA3zZwcd3WlD3gcgcYeDJkU3alIE2hUADez+ibckD/LdCz5vXW2sfpA5ChrlI3wMEhMFqk7HWfd3d39vbvmVZ/P2aecqIM1FFZAAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH5AQdDBkQmV+argAABM5JREFUWMOtl9trHFUcxz9n9jYzm7Tb9JIWGtqUllLwVgRBQWl90S6lTaGmF6E2/4H+A4r+A0offdlWodL4kEZw9bG+iC9iKqLF0os0EBq02dtcdmdnfj7szGZ2M5vulv5g4JwzZ873+7ufUfMLi0RSa1TZNzVFrW511xBhzMxx79EyOwrbGSSzZ073zOcXFnlv5lTi3mvfzAPwwYVZ0tHiq6+/xu+/LlGtWYgEINL9oG657N41yfSRgxw9cHjDgfMLi8QVsR0X23E3gMXnkXQJ3L9zB99vI4EA0sVXqsPF93xW7y73ACVJBJwE1j8HUBIi3Sz/QNtrIzHN+yWdSdNue915IMKWXI4TJ050Adp+U+2bmkrV6tZeYAXwEJExMyf3Hi0rM5fvAvS4wPdBKRW6vZeEUiq0RIBCddddpymu0+rRbPvEzkPVmmWLBA1EdGAbYNctt7V712QwfeSgd/uXJQnPVVoEEAQBTxXpuEMELNtNNFW1WrsrQdBCRImQEeE/wBUh53v+7tW7y5n1+BZRIoJSioXvy3itdgclURSZTBrP87AdV57G1TT0d4GPgC+Bw8Ca7bifATsTgzBvjlH1qgNdICJM7tjB8soKw4jtuD+Gw3c229e1wF+P/uHPpT86rhBBRHActwAcAl4EjgIvAYcFJnlOoq5dv6EBU8AR4OUQ6AVgGjATwuC5YUdZ4A+z+1mBTUM/AKwqpZSIpPfu2VP7+/6DYEMMPE9N83lzq23ZWwxDd4GaQnmgUloqperSCpKC8HGCXz8G7NANU8CWUKPzsUDbyLPVyjYC39e0VMZx3Ccoha4b4lQqbUlnsBqNWCXpEMgKfA38DNSBcdPQr4zlMtTtFiqlulmQmJv9ks2idUZGZMjZmZMAfBUvxWHR0y5dmPV2FcbPG9ncFdPQS3nTuAJQLBZpBS1qjSqFwjipdGr9SWlsHTewm9ZmnngMKAaV9nBd+/bmdxSLRc6dnemm3+yZ06pcLvPGW2+yfWIn1ZpFEAQEvt95goCV1TXMXH4zAt4woaRF7RTAVylAUS6Xpdpsdjvk2VMnsSyHhuVEZTh+xgywBhwLfZIdKRfj7dWqPGFubq7T428ukslkaHttLNsZ9P3nwIfh+DhwS4EO9DA0zByBCE2n1fPxpQuznSCaX1js9nFp2pjbtqGhobQ0jUY9CbgALERah3IM+El1rNqTaqaph5W1uYGAFrfA5YvnyE9MoFBYtjMI/BXgQR/4pqVDZL3V9/cYrX+x7SnsXh/H5TLwW2iBQbVLNgn65CDsrSPOIJOXwmdQ4fRHrZilUqmXwNXrNzbbfxv4ArgFVBLeJ95oDEMHwHHcvvUcRqEwuBf0SSUEB9gfxsAgAkO1kcj/WvwKPaR8EhvPAUvRtdIMtR1FtBH37w8DEeChaehXw/xfAnzHcVOjEkhHrIe0Qlz7T8PuWLEd9+2w9KphgUUgQJ7JAgAPDT13NTrJyOYqIilrlEwQv/NPMTSByxfPIU37eCqtq2zWmPYDjbavaLYVdn2NuffPjqRJK2hRLBaHzoK+X7L1QE+nIFeYoFQqkTVMaTn2UOe1LWtwEJqGzqgRnS9M4Fb+3XBJGfSrFzW9dBw0icioJBzHzUXdMJM18APwWo6Kmy1O6X+V8UHDotBqogAAAABJRU5ErkJggg=="));}.bk-tool-icon-settings{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-settings);-webkit-mask-image:var(--bokeh-icon-settings);}.bk-tool-icon-unknown{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-unknown);-webkit-mask-image:var(--bokeh-icon-unknown);}.bk-tool-icon-fullscreen{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-fullscreen);-webkit-mask-image:var(--bokeh-icon-fullscreen);}.bk-tool-icon-chevron-up{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-up);-webkit-mask-image:var(--bokeh-icon-chevron-up);}.bk-tool-icon-chevron-down{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-down);-webkit-mask-image:var(--bokeh-icon-chevron-down);}.bk-tool-icon-chevron-left{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-left);-webkit-mask-image:var(--bokeh-icon-chevron-left);}.bk-tool-icon-chevron-right{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-right);-webkit-mask-image:var(--bokeh-icon-chevron-right);}.bk-tool-icon-caret-up{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-caret-up);-webkit-mask-image:var(--bokeh-icon-caret-up);}.bk-tool-icon-caret-down{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-caret-down);-webkit-mask-image:var(--bokeh-icon-caret-down);}.bk-tool-icon-caret-left{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-caret-left);-webkit-mask-image:var(--bokeh-icon-caret-left);}.bk-tool-icon-caret-right{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-caret-right);-webkit-mask-image:var(--bokeh-icon-caret-right);}.bk-tool-icon-see-on{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-see-on);-webkit-mask-image:var(--bokeh-icon-see-on);}.bk-tool-icon-see-off{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-see-off);-webkit-mask-image:var(--bokeh-icon-see-off);}.bk-tool-icon-x-grip{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-y-grip);-webkit-mask-image:var(--bokeh-icon-y-grip);}.bk-tool-icon-y-grip{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-y-grip);-webkit-mask-image:var(--bokeh-icon-y-grip);}.bk-tool-icon-arrow-down-to-bar{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-arrow-down-to-bar);-webkit-mask-image:var(--bokeh-icon-arrow-down-to-bar);}.bk-tool-icon-arrow-up-from-bar{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-arrow-up-from-bar);-webkit-mask-image:var(--bokeh-icon-arrow-up-from-bar);}.bk-tool-icon-minimize{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-minimize);-webkit-mask-image:var(--bokeh-icon-minimize);}.bk-tool-icon-maximize{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-maximize);-webkit-mask-image:var(--bokeh-icon-maximize);}.bk-tool-icon-pin{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-pin);-webkit-mask-image:var(--bokeh-icon-pin);}.bk-tool-icon-unpin{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-unpin);-webkit-mask-image:var(--bokeh-icon-unpin);}.bk-tool-icon-pointer{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-hand-pointing);-webkit-mask-image:var(--bokeh-icon-hand-pointing);}.bk-tool-icon-delete{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-trash);-webkit-mask-image:var(--bokeh-icon-trash);}.bk-tool-icon-bold{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-bold);-webkit-mask-image:var(--bokeh-icon-bold);}.bk-tool-icon-italic{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-italic);-webkit-mask-image:var(--bokeh-icon-italic);}.bk-tool-icon-text-align-left{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-text-align-left);-webkit-mask-image:var(--bokeh-icon-text-align-left);}.bk-tool-icon-text-align-center{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-text-align-center);-webkit-mask-image:var(--bokeh-icon-text-align-center);}.bk-tool-icon-text-align-right{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-text-align-right);-webkit-mask-image:var(--bokeh-icon-text-align-right);}.bk-tool-icon-check{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-check);-webkit-mask-image:var(--bokeh-icon-check);}.bk-tool-icon-square{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-square);-webkit-mask-image:var(--bokeh-icon-square);}.bk-tool-icon-square-check{background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-square-check);-webkit-mask-image:var(--bokeh-icon-square-check);}:host{--bokeh-icon-question-mark:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M8%208a3.5%203%200%200%201%203.5%20-3h1a3.5%203%200%200%201%203.5%203a3%203%200%200%201%20-2%203a3%204%200%200%200%20-2%204%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2212%22%20y1%3D%2219%22%20x2%3D%2212%22%20y2%3D%2219.01%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-help:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%229%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2212%22%20y1%3D%2217%22%20x2%3D%2212%22%20y2%3D%2217.01%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2013.5a1.5%201.5%200%200%201%201%20-1.5a2.6%202.6%200%201%200%20-3%20-4%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-x:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%206l-12%2012%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%206l12%2012%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-settings:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M10.325%204.317c.426%20-1.756%202.924%20-1.756%203.35%200a1.724%201.724%200%200%200%202.573%201.066c1.543%20-.94%203.31%20.826%202.37%202.37a1.724%201.724%200%200%200%201.065%202.572c1.756%20.426%201.756%202.924%200%203.35a1.724%201.724%200%200%200%20-1.066%202.573c.94%201.543%20-.826%203.31%20-2.37%202.37a1.724%201.724%200%200%200%20-2.572%201.065c-.426%201.756%20-2.924%201.756%20-3.35%200a1.724%201.724%200%200%200%20-2.573%20-1.066c-1.543%20.94%20-3.31%20-.826%20-2.37%20-2.37a1.724%201.724%200%200%200%20-1.065%20-2.572c-1.756%20-.426%20-1.756%20-2.924%200%20-3.35a1.724%201.724%200%200%200%201.066%20-2.573c-.94%20-1.543%20.826%20-3.31%202.37%20-2.37c1%20.608%202.296%20.07%202.572%20-1.065z%22%3E%3C%2Fpath%3E%0A%20%20%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%223%22%3E%3C%2Fcircle%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-unknown:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M14%203v4a1%201%200%200%200%201%201h4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M17%2021h-10a2%202%200%200%201%20-2%20-2v-14a2%202%200%200%201%202%20-2h7l5%205v11a2%202%200%200%201%20-2%202z%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2017v.01%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2014a1.5%201.5%200%201%200%20-1.14%20-2.474%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-fullscreen:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Crect%20x%3D%223%22%20y%3D%2216%22%20width%3D%225%22%20height%3D%225%22%20rx%3D%221%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2012v-6a2%202%200%200%201%202%20-2h12a2%202%200%200%201%202%202v12a2%202%200%200%201%20-2%202h-6%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%208h4v4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M16%208l-5%205%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-save:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%2017v2a2%202%200%200%200%202%202h12a2%202%200%200%200%202%20-2v-2%22%20%2F%3E%0A%20%20%3Cpolyline%20points%3D%227%2011%2012%2016%2017%2011%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2212%22%20y1%3D%224%22%20x2%3D%2212%22%20y2%3D%2216%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-copy:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Crect%20x%3D%228%22%20y%3D%228%22%20width%3D%2212%22%20height%3D%2212%22%20rx%3D%222%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M16%208v-2a2%202%200%200%200%20-2%20-2h-8a2%202%200%200%200%20-2%202v8a2%202%200%200%200%202%202h2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-open:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M9%204h3l2%202h5a2%202%200%200%201%202%202v7a2%202%200%200%201%20-2%202h-10a2%202%200%200%201%20-2%20-2v-9a2%202%200%200%201%202%20-2%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M17%2017v2a2%202%200%200%201%20-2%202h-10a2%202%200%200%201%20-2%20-2v-9a2%202%200%200%201%202%20-2h2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-tap-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cline%20x1%3D%223%22%20y1%3D%2212%22%20x2%3D%226%22%20y2%3D%2212%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2212%22%20y1%3D%223%22%20x2%3D%2212%22%20y2%3D%226%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%227.8%22%20y1%3D%227.8%22%20x2%3D%225.6%22%20y2%3D%225.6%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2216.2%22%20y1%3D%227.8%22%20x2%3D%2218.4%22%20y2%3D%225.6%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%227.8%22%20y1%3D%2216.2%22%20x2%3D%225.6%22%20y2%3D%2218.4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012l9%203l-4%202l-2%204l-3%20-9%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-lasso-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4.028%2013.252c-.657%20-.972%20-1.028%20-2.078%20-1.028%20-3.252c0%20-3.866%204.03%20-7%209%20-7s9%203.134%209%207s-4.03%207%20-9%207c-1.913%200%20-3.686%20-.464%20-5.144%20-1.255%22%20%2F%3E%0A%20%20%3Ccircle%20cx%3D%225%22%20cy%3D%2215%22%20r%3D%222%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M5%2017c0%201.42%20.316%202.805%201%204%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pan:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%209l3%203l-3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%209l-3%203l3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9%2018l3%203l3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%206l-3%20-3l-3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012h9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2012h9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012v9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%203v9%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-x-pan:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%209l3%203l-3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%209l-3%203l3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012h9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2012h9%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-y-pan:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M9%2018l3%203l3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%206l-3%20-3l-3%203%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2012v9%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%203v9%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pan-left:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M20%2015h-8v3.586a1%201%200%200%201%20-1.707%20.707l-6.586%20-6.586a1%201%200%200%201%200%20-1.414l6.586%20-6.586a1%201%200%200%201%201.707%20.707v3.586h8a1%201%200%200%201%201%201v4a1%201%200%200%201%20-1%201z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pan-right:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%209h8v-3.586a1%201%200%200%201%201.707%20-.707l6.586%206.586a1%201%200%200%201%200%201.414l-6.586%206.586a1%201%200%200%201%20-1.707%20-.707v-3.586h-8a1%201%200%200%201%20-1%20-1v-4a1%201%200%200%201%201%20-1z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pan-up:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M9%2020v-8h-3.586a1%201%200%200%201%20-.707%20-1.707l6.586%20-6.586a1%201%200%200%201%201.414%200l6.586%206.586a1%201%200%200%201%20-.707%201.707h-3.586v8a1%201%200%200%201%20-1%201h-4a1%201%200%200%201%20-1%20-1z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pan-down:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M15%204v8h3.586a1%201%200%200%201%20.707%201.707l-6.586%206.586a1%201%200%200%201%20-1.414%200l-6.586%20-6.586a1%201%200%200%201%20.707%20-1.707h3.586v-8a1%201%200%200%201%201%20-1h4a1%201%200%200%201%201%201z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-box-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%206v-1a1%201%200%200%201%201%20-1h1m5%200h2m5%200h1a1%201%200%200%201%201%201v1m0%205v2m0%205v1a1%201%200%200%201%20-1%201h-1m-5%200h-2m-5%200h-1a1%201%200%200%201%20-1%20-1v-1m0%20-5v-2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-x-box-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M17%2013l-4%204%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M13%2013l4%204%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%206v-1a1%201%200%200%201%201%20-1h1m5%200h2m5%200h1a1%201%200%200%201%201%201v1m0%205v2m0%205v1a1%201%200%200%201%20-1%201h-1m-5%200h-2m-5%200h-1a1%201%200%200%201%20-1%20-1v-1m0%20-5v-2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-y-box-select:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M13%2013l2%202l2%20-2%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%2015v2.5%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%206v-1a1%201%200%200%201%201%20-1h1m5%200h2m5%200h1a1%201%200%200%201%201%201v1m0%205v2m0%205v1a1%201%200%200%201%20-1%201h-1m-5%200h-2m-5%200h-1a1%201%200%200%201%20-1%20-1v-1m0%20-5v-2%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-box-zoom:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2215%22%20cy%3D%2215%22%20r%3D%225%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2022l-3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018h-1a2%202%200%200%201%20-2%20-2v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2011v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%206v-1a2%202%200%200%201%202%20-2h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%203h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%203h1a2%202%200%200%201%202%202v1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-x-box-zoom:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M17%2013l-4%204%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M13%2013l4%204%22%20%2F%3E%0A%20%20%3Ccircle%20cx%3D%2215%22%20cy%3D%2215%22%20r%3D%225%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2022l-3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018h-1a2%202%200%200%201%20-2%20-2v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2011v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%206v-1a2%202%200%200%201%202%20-2h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%203h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%203h1a2%202%200%200%201%202%202v1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-y-box-zoom:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M13%2013l2%202l2%20-2%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%2015v2.5%22%20%2F%3E%0A%20%20%3Ccircle%20cx%3D%2215%22%20cy%3D%2215%22%20r%3D%225%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2022l-3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018h-1a2%202%200%200%201%20-2%20-2v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2011v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%206v-1a2%202%200%200%201%202%20-2h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%203h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%203h1a2%202%200%200%201%202%202v1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-auto-box-zoom:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2215%22%20cy%3D%2215%22%20r%3D%225%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2022l-3%20-3%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018h-1a2%202%200%200%201%20-2%20-2v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%2011v-1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M3%206v-1a2%202%200%200%201%202%20-2h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%203h1%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%203h1a2%202%200%200%201%202%202v1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-zoom-in:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2210%22%20cy%3D%2210%22%20r%3D%227%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%227%22%20y1%3D%2210%22%20x2%3D%2213%22%20y2%3D%2210%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2210%22%20y1%3D%227%22%20x2%3D%2210%22%20y2%3D%2213%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2221%22%20y1%3D%2221%22%20x2%3D%2215%22%20y2%3D%2215%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-zoom-out:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2210%22%20cy%3D%2210%22%20r%3D%227%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%227%22%20y1%3D%2210%22%20x2%3D%2213%22%20y2%3D%2210%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%2221%22%20y1%3D%2221%22%20x2%3D%2215%22%20y2%3D%2215%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-undo:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M9%2013l-4%20-4l4%20-4m-4%204h11a4%204%200%200%201%200%208h-1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-redo:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M15%2013l4%20-4l-4%20-4m4%204h-11a4%204%200%200%200%200%208h1%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-reset:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M20%2011a8.1%208.1%200%200%200%20-15.5%20-2m-.5%20-4v4h4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2013a8.1%208.1%200%200%200%2015.5%202m.5%204v-4h-4%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-hover:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M12%2020l-3%20-3h-2a3%203%200%200%201%20-3%20-3v-6a3%203%200%200%201%203%20-3h10a3%203%200%200%201%203%203v6a3%203%200%200%201%20-3%203h-2l-3%203%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%228%22%20y1%3D%229%22%20x2%3D%2216%22%20y2%3D%229%22%20%2F%3E%0A%20%20%3Cline%20x1%3D%228%22%20y1%3D%2213%22%20x2%3D%2214%22%20y2%3D%2213%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-crosshair:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%229%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M20%2012h-4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2012h4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%2020v-4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M12%204v4%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-chevron-up:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpolyline%20points%3D%226%2015%2012%209%2018%2015%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-chevron-down:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-chevron-left:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpolyline%20points%3D%2215%206%209%2012%2015%2018%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-chevron-right:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpolyline%20points%3D%229%206%2015%2012%209%2018%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-caret-up:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22currentColor%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%2015l-6%20-6l-6%206h12%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-caret-down:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22currentColor%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%2015l-6%20-6l-6%206h12%22%20transform%3D%22rotate(180%2012%2012)%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-caret-left:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22currentColor%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%2015l-6%20-6l-6%206h12%22%20transform%3D%22rotate(270%2012%2012)%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-caret-right:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22currentColor%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M18%2015l-6%20-6l-6%206h12%22%20transform%3D%22rotate(90%2012%2012)%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-see-on:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%222%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M22%2012c-2.667%204.667%20-6%207%20-10%207s-7.333%20-2.333%20-10%20-7c2.667%20-4.667%206%20-7%2010%20-7s7.333%202.333%2010%207%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-see-off:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cline%20x1%3D%223%22%20y1%3D%223%22%20x2%3D%2221%22%20y2%3D%2221%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10.584%2010.587a2%202%200%200%200%202.828%202.83%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9.363%205.365a9.466%209.466%200%200%201%202.637%20-.365c4%200%207.333%202.333%2010%207c-.778%201.361%20-1.612%202.524%20-2.503%203.488m-2.14%201.861c-1.631%201.1%20-3.415%201.651%20-5.357%201.651c-4%200%20-7.333%20-2.333%20-10%20-7c1.369%20-2.395%202.913%20-4.175%204.632%20-5.341%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-cursor-rotate:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%3E%0A%20%20%3Cg%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%20%20%3Cg%20stroke-width%3D%224%22%20stroke%3D%22white%22%3E%0A%20%20%20%20%20%20%3Cpath%20d%3D%22M9%204.55a8%208%200%200%201%206%2014.9m0%20-4.45v5h5%22%20%2F%3E%0A%20%20%20%20%3C%2Fg%3E%0A%20%20%20%20%3Cg%20stroke-width%3D%222%22%20stroke%3D%22black%22%3E%0A%20%20%20%20%20%20%3Cpath%20d%3D%22M9%204.55a8%208%200%200%201%206%2014.9m0%20-4.45v5h5%22%20%2F%3E%0A%20%20%20%20%3C%2Fg%3E%0A%20%20%3C%2Fg%3E%0A%3C%2Fsvg%3E%0A") 12 12, auto;--bokeh-icon-x-grip:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M5%209m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M5%2015m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%209m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%2015m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M19%209m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M19%2015m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-y-grip:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M9%205m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M9%2012m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M9%2019m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M15%205m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M15%2012m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M15%2019m-1%200a1%201%200%201%200%202%200a1%201%200%201%200%20-2%200%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-arrow-down-to-bar:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%2020l16%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%2014l0%20-10%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%2014l4%20-4%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%2014l-4%20-4%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-arrow-up-from-bar:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M12%204l0%2010%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%204l4%204%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M12%204l-4%204%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M4%2020l16%200%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-minimize:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M15%2019v-2a2%202%200%200%201%202%20-2h2%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M15%205v2a2%202%200%200%200%202%202h2%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M5%2015h2a2%202%200%200%201%202%202v2%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M5%209h2a2%202%200%200%200%202%20-2v-2%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-maximize:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%208v-2a2%202%200%200%201%202%20-2h2%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M4%2016v2a2%202%200%200%200%202%202h2%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M16%204h2a2%202%200%200%201%202%202v2%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M16%2020h2a2%202%200%200%200%202%20-2v-2%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-pin:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M15%204.5l-4%204l-4%201.5l-1.5%201.5l7%207l1.5%20-1.5l1.5%20-4l4%20-4%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9%2015l-4.5%204.5%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M14.5%204l5.5%205.5%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-unpin:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M3%203l18%2018%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M15%204.5l-3.249%203.249m-2.57%201.433l-2.181%20.818l-1.5%201.5l7%207l1.5%20-1.5l.82%20-2.186m1.43%20-2.563l3.25%20-3.251%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9%2015l-4.5%204.5%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M14.5%204l5.5%205.5%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-hand-pointing:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M8%2013v-8.5a1.5%201.5%200%200%201%203%200v7.5%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M11%2011.5v-2a1.5%201.5%200%201%201%203%200v2.5%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M14%2010.5a1.5%201.5%200%200%201%203%200v1.5%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M17%2011.5a1.5%201.5%200%200%201%203%200v4.5a6%206%200%200%201%20-6%206h-2h.208a6%206%200%200%201%20-5.012%20-2.7a69.74%2069.74%200%200%201%20-.196%20-.3c-.312%20-.479%20-1.407%20-2.388%20-3.286%20-5.728a1.5%201.5%200%200%201%20.536%20-2.022a1.867%201.867%200%200%201%202.28%20.28l1.47%201.47%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-trash:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%207l16%200%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M10%2011l0%206%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M14%2011l0%206%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M5%207l1%2012a2%202%200%200%200%202%202h8a2%202%200%200%200%202%20-2l1%20-12%22%3E%3C%2Fpath%3E%0A%20%20%3Cpath%20d%3D%22M9%207v-3a1%201%200%200%201%201%20-1h4a1%201%200%200%201%201%201v3%22%3E%3C%2Fpath%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-bold:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M7%205h6a3.5%203.5%200%200%201%200%207h-6z%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M13%2012h1a3.5%203.5%200%200%201%200%207h-7v-7%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-italic:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M11%205l6%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M7%2019l6%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M14%205l-4%2014%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-text-align-left:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%206l16%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2012l10%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M4%2018l14%200%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-text-align-center:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%206l16%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M8%2012l8%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018l12%200%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-text-align-right:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M4%206l16%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M10%2012l10%200%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M6%2018l14%200%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-check:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M5%2012l5%205l10%20-10%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-square:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M3%203m0%202a2%202%200%200%201%202%20-2h14a2%202%200%200%201%202%202v14a2%202%200%200%201%20-2%202h-14a2%202%200%200%201%20-2%20-2z%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");--bokeh-icon-square-check:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20stroke-width%3D%222%22%20stroke%3D%22currentColor%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%0A%20%20%3Cpath%20d%3D%22M3%203m0%202a2%202%200%200%201%202%20-2h14a2%202%200%200%201%202%202v14a2%202%200%200%201%20-2%202h-14a2%202%200%200%201%20-2%20-2z%22%20%2F%3E%0A%20%20%3Cpath%20d%3D%22M9%2012l2%202l4%20-4%22%20%2F%3E%0A%3C%2Fsvg%3E%0A");}`;
},
/* models/renderers/renderer_group.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    class RendererGroup extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.RendererGroup = RendererGroup;
    _a = RendererGroup;
    RendererGroup.__name__ = "RendererGroup";
    (() => {
        _a.define(({ Bool }) => ({
            visible: [Bool, true],
        }));
    })();
},
/* models/dom/dom_node.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_view_1 = require(57) /* ../../core/dom_view */;
    const model_1 = require(51) /* ../../model */;
    class DOMNodeView extends dom_view_1.DOMView {
    }
    exports.DOMNodeView = DOMNodeView;
    DOMNodeView.__name__ = "DOMNodeView";
    class DOMNode extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DOMNode = DOMNode;
    DOMNode.__name__ = "DOMNode";
    DOMNode.__module__ = "bokeh.models.dom";
},
/* models/annotations/arrow.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(127) /* ./data_annotation */;
    const arrow_head_1 = require(168) /* ./arrow_head */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const enums_1 = require(20) /* ../../core/enums */;
    const types_1 = require(24) /* ../../core/types */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const types_2 = require(24) /* ../../core/types */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const math_1 = require(11) /* ../../core/util/math */;
    class ArrowView extends data_annotation_1.DataAnnotationView {
        *children() {
            yield* super.children();
            const { start, end } = this;
            if (start != null) {
                yield start;
            }
            if (end != null) {
                yield end;
            }
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { start, end } = this.model;
            if (start != null) {
                this.start = await (0, build_views_1.build_view)(start, { parent: this });
            }
            if (end != null) {
                this.end = await (0, build_views_1.build_view)(end, { parent: this });
            }
        }
        set_data(source) {
            super.set_data(source);
            const indices = types_2.Indices.all_set(this._x_start.length);
            this.start?.set_data(source, indices);
            this.end?.set_data(source, indices);
        }
        remove() {
            this.start?.remove();
            this.end?.remove();
            super.remove();
        }
        map_data() {
            const { frame } = this.plot_view;
            const [sx_start, sy_start] = (() => {
                switch (this.model.start_units) {
                    case "canvas": {
                        return [
                            new types_1.ScreenArray(this._x_start),
                            new types_1.ScreenArray(this._y_start),
                        ];
                    }
                    case "screen": {
                        return [
                            frame.bbox.xview.v_compute(this._x_start),
                            frame.bbox.yview.v_compute(this._y_start),
                        ];
                    }
                    case "data": {
                        return [
                            this.coordinates.x_scale.v_compute(this._x_start),
                            this.coordinates.y_scale.v_compute(this._y_start),
                        ];
                    }
                }
            })();
            const [sx_end, sy_end] = (() => {
                switch (this.model.end_units) {
                    case "canvas": {
                        return [
                            new types_1.ScreenArray(this._x_end),
                            new types_1.ScreenArray(this._y_end),
                        ];
                    }
                    case "screen": {
                        return [
                            frame.bbox.xview.v_compute(this._x_end),
                            frame.bbox.yview.v_compute(this._y_end),
                        ];
                    }
                    case "data": {
                        return [
                            this.coordinates.x_scale.v_compute(this._x_end),
                            this.coordinates.y_scale.v_compute(this._y_end),
                        ];
                    }
                }
            })();
            this._sx_start = sx_start;
            this._sy_start = sy_start;
            this._sx_end = sx_end;
            this._sy_end = sy_end;
            const n = sx_start.length;
            const angles = this._angles = new types_1.ScreenArray(n);
            for (let i = 0; i < n; i++) {
                // arrow head runs orthogonal to arrow body (???)
                angles[i] = Math.PI / 2 + (0, math_1.atan2)([sx_start[i], sy_start[i]], [sx_end[i], sy_end[i]]);
            }
        }
        _paint_data(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.paint(ctx, i);
                    ctx.restore();
                }
                if (start != null) {
                    ctx.save();
                    ctx.translate(_sx_start[i], _sy_start[i]);
                    ctx.rotate(_angles[i] + Math.PI);
                    start.paint(ctx, i);
                    ctx.restore();
                }
                if (!this.visuals.line.doit) {
                    continue;
                }
                ctx.save();
                if (start != null || end != null) {
                    ctx.beginPath();
                    ctx.rect(x, y, width, height);
                    if (end != null) {
                        ctx.save();
                        ctx.translate(_sx_end[i], _sy_end[i]);
                        ctx.rotate(_angles[i]);
                        end.clip(ctx, i);
                        ctx.restore();
                    }
                    if (start != null) {
                        ctx.save();
                        ctx.translate(_sx_start[i], _sy_start[i]);
                        ctx.rotate(_angles[i] + Math.PI);
                        start.clip(ctx, i);
                        ctx.restore();
                    }
                    ctx.closePath();
                    ctx.clip();
                }
                ctx.beginPath();
                ctx.moveTo(_sx_start[i], _sy_start[i]);
                ctx.lineTo(_sx_end[i], _sy_end[i]);
                this.visuals.line.apply(ctx, i);
                ctx.restore();
            }
        }
    }
    exports.ArrowView = ArrowView;
    ArrowView.__name__ = "ArrowView";
    class Arrow extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Arrow = Arrow;
    _a = Arrow;
    Arrow.__name__ = "Arrow";
    (() => {
        _a.prototype.default_view = ArrowView;
        _a.mixins(property_mixins_1.LineVector);
        _a.define(({ Ref, Nullable }) => ({
            x_start: [p.XCoordinateSpec, { field: "x_start" }],
            y_start: [p.YCoordinateSpec, { field: "y_start" }],
            start_units: [enums_1.CoordinateUnits, "data"],
            start: [Nullable(Ref(arrow_head_1.ArrowHead)), null],
            x_end: [p.XCoordinateSpec, { field: "x_end" }],
            y_end: [p.YCoordinateSpec, { field: "y_end" }],
            end_units: [enums_1.CoordinateUnits, "data"],
            end: [Nullable(Ref(arrow_head_1.ArrowHead)), () => new arrow_head_1.OpenHead()],
        }));
    })();
},
/* models/annotations/data_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(81) /* ./annotation */;
    const columnar_data_source_1 = require(128) /* ../sources/columnar_data_source */;
    const column_data_source_1 = require(133) /* ../sources/column_data_source */;
    const projections_1 = require(134) /* ../../core/util/projections */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class DataAnnotationView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this._initial_set_data = false;
        }
        connect_signals() {
            super.connect_signals();
            const update = () => {
                this.set_data(this.model.source);
                this._rerender();
            };
            this.connect(this.model.change, update);
            this.connect(this.model.source.streaming, update);
            this.connect(this.model.source.patching, update);
            this.connect(this.model.source.change, update);
        }
        _rerender() {
            this.request_paint();
        }
        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();
            }
        }
        _paint() {
            if (!this._initial_set_data) {
                this.set_data(this.model.source);
                this._initial_set_data = true;
            }
            this.map_data();
            this._paint_data(this.layer.ctx);
        }
    }
    exports.DataAnnotationView = DataAnnotationView;
    DataAnnotationView.__name__ = "DataAnnotationView";
    class DataAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DataAnnotation = DataAnnotation;
    _a = DataAnnotation;
    DataAnnotation.__name__ = "DataAnnotation";
    (() => {
        _a.define(({ Ref }) => ({
            source: [Ref(columnar_data_source_1.ColumnarDataSource), () => new column_data_source_1.ColumnDataSource()],
        }));
    })();
},
/* models/sources/columnar_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const logging_1 = require(19) /* ../../core/logging */;
    const selection_manager_1 = require(129) /* ../../core/selection_manager */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const array_1 = require(10) /* ../../core/util/array */;
    const ndarray_1 = require(30) /* ../../core/util/ndarray */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const interaction_policy_1 = require(131) /* ../selections/interaction_policy */;
    const selection_1 = require(130) /* ../selections/selection */;
    const data_source_1 = require(132) /* ./data_source */;
    class ColumnarDataSource extends data_source_1.DataSource {
        get_array(key) {
            const data = (0, object_1.dict)(this.data);
            let column = data.get(key);
            if (column == null) {
                data.set(key, column = []);
            }
            else if (!(0, types_1.isArray)(column)) {
                data.set(key, column = Array.from(column));
            }
            return column;
        }
        constructor(attrs) {
            super(attrs);
            this.selection_manager = new selection_manager_1.SelectionManager(this);
        }
        initialize() {
            super.initialize();
            this._select = new signaling_1.Signal0(this, "select");
            this.inspect = new signaling_1.Signal(this, "inspect");
        }
        get inferred_defaults() {
            const defaults = new Map();
            for (const [name, array] of (0, object_1.entries)(this.data)) {
                const value = (() => {
                    if ((0, ndarray_1.is_NDArray)(array)) {
                        switch (array.dtype) {
                            case "bool":
                                return false;
                            case "uint8":
                            case "int8":
                            case "uint16":
                            case "int16":
                            case "uint32":
                            case "int32":
                            case "float32":
                            case "float64":
                                return 0;
                            case "object":
                                return null;
                        }
                    }
                    else if ((0, types_1.isArray)(array) && array.length != 0) {
                        const [item] = array;
                        if (item === null) {
                            return null;
                        }
                        else if ((0, types_1.isBoolean)(item)) {
                            return false;
                        }
                        else if ((0, types_1.isNumber)(item)) {
                            return 0;
                        }
                        else if ((0, types_1.isString)(item)) {
                            return "";
                        }
                        else if ((0, types_1.isArray)(item)) {
                            return [];
                        }
                    }
                    return undefined;
                })();
                if (value !== undefined) {
                    defaults.set(name, value);
                }
            }
            return defaults;
        }
        get(name) {
            const column = this.get_column(name);
            (0, assert_1.assert)(column != null, `unknown column '${name}' in ${this}`);
            return column;
        }
        set(name, column) {
            (0, object_1.dict)(this.data).set(name, column);
        }
        get_column(name) {
            const data = (0, object_1.dict)(this.data);
            return data.get(name) ?? null;
        }
        columns() {
            // return the column names in this data source
            return (0, object_1.keys)(this.data);
        }
        get_length(soft = true) {
            const lengths = (0, array_1.uniq)((0, object_1.values)(this.data).map((v) => (0, ndarray_1.is_NDArray)(v) ? v.shape[0] : v.length));
            switch (lengths.length) {
                case 0: {
                    return null; // XXX: don't guess, treat on case-by-case basis
                }
                case 1: {
                    return lengths[0];
                }
                default: {
                    const msg = "data source has columns of inconsistent lengths";
                    if (soft) {
                        logging_1.logger.warn(msg);
                        return lengths.sort()[0];
                    }
                    else {
                        throw new Error(msg);
                    }
                }
            }
        }
        get length() {
            return this.get_length() ?? 0;
        }
        clear() {
            const data = (0, object_1.clone)(this.data);
            const proxy = (0, object_1.dict)(data);
            for (const [name, column] of proxy) {
                const empty = new column.constructor(0);
                proxy.set(name, empty);
            }
            this.data = data;
        }
        stream(new_data, rollover, { sync } = {}) {
            this.stream_to(this.properties.data, new_data, rollover, { sync });
        }
        patch(patches, { sync } = {}) {
            this.patch_to(this.properties.data, patches, { sync });
        }
    }
    exports.ColumnarDataSource = ColumnarDataSource;
    _a = ColumnarDataSource;
    ColumnarDataSource.__name__ = "ColumnarDataSource";
    (() => {
        _a.define(({ Ref, Dict, Unknown }) => ({
            default_values: [Dict(Unknown), {}],
            selection_policy: [Ref(interaction_policy_1.SelectionPolicy), () => new interaction_policy_1.UnionRenderers()],
        }));
        _a.internal(({ AnyRef }) => ({
            inspected: [AnyRef(), () => new selection_1.Selection()],
        }));
    })();
},
/* core/selection_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selection_1 = require(130) /* ../models/selections/selection */;
    // XXX: this is needed to cut circular dependency between this, models/renderers/* and models/sources/*
    function is_GlyphRendererView(renderer_view) {
        return renderer_view.model.type == "GlyphRenderer";
    }
    function is_GraphRendererView(renderer_view) {
        return renderer_view.model.type == "GraphRenderer";
    }
    class SelectionManager {
        constructor(source) {
            this.inspectors = new Map();
            this.source = source;
        }
        select(renderer_views, geometry, final, mode = "replace") {
            // divide renderers into glyph_renderers or graph_renderers
            const glyph_renderer_views = [];
            const graph_renderer_views = [];
            for (const r of renderer_views) {
                if (is_GlyphRendererView(r)) {
                    glyph_renderer_views.push(r);
                }
                else if (is_GraphRendererView(r)) {
                    graph_renderer_views.push(r);
                }
            }
            let did_hit = false;
            // graph renderer case
            for (const r of graph_renderer_views) {
                const hit_test_result = r.model.selection_policy.hit_test(geometry, r);
                did_hit = did_hit || r.model.selection_policy.do_selection(hit_test_result, r.model, final, mode);
            }
            // glyph renderers
            if (glyph_renderer_views.length > 0) {
                const hit_test_result = this.source.selection_policy.hit_test(geometry, glyph_renderer_views);
                did_hit = did_hit || this.source.selection_policy.do_selection(hit_test_result, this.source, final, mode);
            }
            return did_hit;
        }
        inspect(renderer_view, geometry) {
            let did_hit = false;
            if (is_GlyphRendererView(renderer_view)) {
                const hit_test_result = renderer_view.hit_test(geometry);
                if (hit_test_result != null) {
                    did_hit = !hit_test_result.is_empty();
                    const inspection = this.get_or_create_inspector(renderer_view.model);
                    inspection.update(hit_test_result, true, "replace");
                    this.source.setv({ inspected: inspection }, { silent: true });
                    this.source.inspect.emit([renderer_view.model, { geometry }]);
                }
            }
            else if (is_GraphRendererView(renderer_view)) {
                const hit_test_result = renderer_view.model.inspection_policy.hit_test(geometry, renderer_view);
                did_hit = renderer_view.model.inspection_policy.do_inspection(hit_test_result, geometry, renderer_view, false, "replace");
            }
            return did_hit;
        }
        invert(rview) {
            const n = this.source.get_length();
            if (n == null) {
                return;
            }
            this.source.selected.invert(n);
            if (rview != null) {
                this.get_or_create_inspector(rview.model).invert(n);
            }
        }
        clear(rview) {
            this.source.selected.clear();
            if (rview != null) {
                this.get_or_create_inspector(rview.model).clear();
            }
        }
        get_or_create_inspector(renderer) {
            let selection = this.inspectors.get(renderer);
            if (selection == null) {
                selection = new selection_1.Selection();
                this.inspectors.set(renderer, selection);
            }
            return selection;
        }
    }
    exports.SelectionManager = SelectionManager;
    SelectionManager.__name__ = "SelectionManager";
},
/* models/selections/selection.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    exports.OpaqueIndices = (0, kinds_1.Arrayable)(kinds_1.Int);
    exports.MultiIndices = (0, kinds_1.Mapping)(kinds_1.Int, exports.OpaqueIndices);
    class Selection extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        get_view() {
            return this.view;
        }
        get selected_glyph() {
            return this.selected_glyphs.length > 0 ? this.selected_glyphs[0] : null;
        }
        add_to_selected_glyphs(glyph) {
            this.selected_glyphs.push(glyph);
        }
        update(selection, _final = true, mode = "replace") {
            switch (mode) {
                case "replace": {
                    this.update_through_replacement(selection);
                    break;
                }
                case "toggle": {
                    this.update_through_toggle(selection);
                    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;
                }
                case "xor": {
                    this.update_through_symmetric_difference(selection);
                    break;
                }
            }
        }
        // TODO `size` wouldn't be needed if `indices` was an instance of
        // `Indices` class, instead of an array of numbers. Then also we
        // could just call `.invert()` on the class.
        invert(size) {
            const indices = new Set(this.indices);
            const inversion = [];
            for (let i = 0; i < size; i++) {
                if (!indices.has(i)) {
                    inversion.push(i);
                }
            }
            this.indices = inversion;
            // this.line_indices
            // this.multiline_indices
            // this.image_indices
        }
        clear() {
            this.indices = [];
            this.line_indices = [];
            this.multiline_indices = new Map();
            this.image_indices = [];
            this.view = null;
            this.selected_glyphs = [];
        }
        map(mapper) {
            return new _a({
                ...this.attributes,
                indices: (0, arrayable_1.map)(this.indices, mapper),
                // NOTE: line_indices don't support subset indexing
                multiline_indices: new Map((0, arrayable_1.map)([...this.multiline_indices.entries()], ([index, line_indices]) => [mapper(index), line_indices])),
                image_indices: this.image_indices.map((image_index) => ({ ...image_index, index: mapper(image_index.index) })),
            });
        }
        is_empty() {
            return this.indices.length == 0 && this.line_indices.length == 0 && this.image_indices.length == 0;
        }
        _union_image_indices(...collection) {
            const is = new Map();
            const js = new Map();
            const result = [];
            for (const indices of collection) {
                for (const image_index of indices) {
                    const { index, i, j } = image_index;
                    const iis = is.get(index);
                    const ijs = js.get(index);
                    if (iis != null && ijs != null) {
                        if (!iis.has(i) || !ijs.has(j)) {
                            result.push(image_index);
                            iis.add(i);
                            ijs.add(j);
                        }
                    }
                    else {
                        result.push(image_index);
                        is.set(index, new Set([i]));
                        js.set(index, new Set([j]));
                    }
                }
            }
            return result;
        }
        update_through_replacement(other) {
            this.indices = other.indices;
            this.line_indices = other.line_indices;
            this.multiline_indices = other.multiline_indices;
            this.image_indices = other.image_indices;
            this.view = other.view;
            this.selected_glyphs = other.selected_glyphs;
        }
        update_through_toggle(other) {
            // note the order of arguments when comparing with update_through_subtraction()
            this.indices = (0, array_1.difference)(other.indices, this.indices);
            // TODO: think through and fix any logic below
            this.selected_glyphs = (0, array_1.union)(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = (0, array_1.union)(other.line_indices, this.line_indices);
            this.image_indices = this._union_image_indices(this.image_indices, other.image_indices); // TODO
            this.view = other.view;
            this.multiline_indices = (0, object_1.merge)(other.multiline_indices, this.multiline_indices);
        }
        update_through_union(other) {
            this.indices = (0, array_1.union)(this.indices, other.indices);
            this.selected_glyphs = (0, array_1.union)(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = (0, array_1.union)(other.line_indices, this.line_indices);
            this.image_indices = this._union_image_indices(this.image_indices, other.image_indices); // TODO
            this.view = other.view;
            this.multiline_indices = (0, object_1.merge)(other.multiline_indices, this.multiline_indices);
        }
        update_through_intersection(other) {
            this.indices = (0, array_1.intersection)(this.indices, other.indices);
            // TODO: think through and fix any logic below
            this.selected_glyphs = (0, array_1.union)(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = (0, array_1.union)(other.line_indices, this.line_indices);
            this.image_indices = this._union_image_indices(this.image_indices, other.image_indices); // TODO
            this.view = other.view;
            this.multiline_indices = (0, object_1.merge)(other.multiline_indices, this.multiline_indices);
        }
        update_through_subtraction(other) {
            this.indices = (0, array_1.difference)(this.indices, other.indices);
            // TODO: think through and fix any logic below
            this.selected_glyphs = (0, array_1.union)(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = (0, array_1.union)(other.line_indices, this.line_indices);
            this.image_indices = this._union_image_indices(this.image_indices, other.image_indices); // TODO
            this.view = other.view;
            this.multiline_indices = (0, object_1.merge)(other.multiline_indices, this.multiline_indices);
        }
        update_through_symmetric_difference(other) {
            this.indices = (0, array_1.symmetric_difference)(this.indices, other.indices);
            // TODO: think through and fix any logic below
            this.selected_glyphs = (0, array_1.union)(other.selected_glyphs, this.selected_glyphs);
            this.line_indices = (0, array_1.union)(other.line_indices, this.line_indices);
            this.image_indices = this._union_image_indices(this.image_indices, other.image_indices); // TODO
            this.view = other.view;
            this.multiline_indices = (0, object_1.merge)(other.multiline_indices, this.multiline_indices);
        }
    }
    exports.Selection = Selection;
    _a = Selection;
    Selection.__name__ = "Selection";
    (() => {
        _a.define(({ Int, List, Struct }) => ({
            indices: [exports.OpaqueIndices, []],
            line_indices: [exports.OpaqueIndices, []],
            multiline_indices: [exports.MultiIndices, new Map()],
            image_indices: [List(Struct({ index: Int, i: Int, j: Int, flat_index: Int })), []],
        }));
        _a.internal(({ List, AnyRef, Nullable }) => ({
            selected_glyphs: [List(AnyRef()), []],
            view: [Nullable(AnyRef()), null],
        }));
    })();
},
/* models/selections/interaction_policy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(51) /* ../../model */;
    class SelectionPolicy extends model_1.Model {
        do_selection(hit_test_result, source, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            else {
                source.selected.update(hit_test_result, final, mode);
                source._select.emit();
                return !source.selected.is_empty();
            }
        }
    }
    exports.SelectionPolicy = SelectionPolicy;
    SelectionPolicy.__name__ = "SelectionPolicy";
    class IntersectRenderers extends SelectionPolicy {
        hit_test(geometry, renderer_views) {
            const hit_test_result_renderers = [];
            for (const r of renderer_views) {
                const result = r.hit_test(geometry);
                if (result != null) {
                    hit_test_result_renderers.push(result);
                }
            }
            if (hit_test_result_renderers.length > 0) {
                const hit_test_result = hit_test_result_renderers[0];
                for (const hit_test_result_other of hit_test_result_renderers) {
                    hit_test_result.update_through_intersection(hit_test_result_other);
                }
                return hit_test_result;
            }
            else {
                return null;
            }
        }
    }
    exports.IntersectRenderers = IntersectRenderers;
    IntersectRenderers.__name__ = "IntersectRenderers";
    class UnionRenderers extends SelectionPolicy {
        hit_test(geometry, renderer_views) {
            const hit_test_result_renderers = [];
            for (const r of renderer_views) {
                const result = r.hit_test(geometry);
                if (result != null) {
                    hit_test_result_renderers.push(result);
                }
            }
            if (hit_test_result_renderers.length > 0) {
                const hit_test_result = hit_test_result_renderers[0];
                for (const hit_test_result_other of hit_test_result_renderers) {
                    hit_test_result.update_through_union(hit_test_result_other);
                }
                return hit_test_result;
            }
            else {
                return null;
            }
        }
    }
    exports.UnionRenderers = UnionRenderers;
    UnionRenderers.__name__ = "UnionRenderers";
},
/* models/sources/data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const selection_1 = require(130) /* ../selections/selection */;
    class DataSource extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DataSource = DataSource;
    _a = DataSource;
    DataSource.__name__ = "DataSource";
    (() => {
        _a.define(({ Ref }) => ({
            selected: [Ref(selection_1.Selection), () => new selection_1.Selection(), { readonly: true }],
        }));
    })();
},
/* models/sources/column_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const columnar_data_source_1 = require(128) /* ./columnar_data_source */;
    class ColumnDataSource extends columnar_data_source_1.ColumnarDataSource {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ColumnDataSource = ColumnDataSource;
    _a = ColumnDataSource;
    ColumnDataSource.__name__ = "ColumnDataSource";
    (() => {
        _a.define(({ Unknown, Dict, Arrayable }) => ({
            data: [Dict(Arrayable(Unknown)), {}],
        }));
    })();
},
/* core/util/projections.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.clip_mercator = clip_mercator;
    exports.in_bounds = in_bounds;
    exports.project_xy = project_xy;
    exports.project_xsys = project_xsys;
    const tslib_1 = require(1) /* tslib */;
    const core_1 = tslib_1.__importDefault(require(135) /* proj4/lib/core */);
    const Proj_1 = tslib_1.__importDefault(require(136) /* proj4/lib/Proj */);
    const types_1 = require(24) /* ../types */;
    const mercator = new Proj_1.default("GOOGLE");
    const wgs84 = new Proj_1.default("WGS84");
    const _wgs84_mercator = (0, core_1.default)(wgs84, mercator);
    exports.wgs84_mercator = {
        compute(x, y) {
            if (isFinite(x) && isFinite(y)) {
                return _wgs84_mercator.forward([x, y]);
            }
            else {
                return [NaN, NaN];
            }
        },
        invert(merc_x, merc_y) {
            if (isFinite(merc_x) && isFinite(merc_y)) {
                return _wgs84_mercator.inverse([merc_x, merc_y]);
            }
            else {
                return [NaN, NaN];
            }
        },
    };
    const mercator_bounds = {
        lon: [-20026376.39, 20026376.39],
        lat: [-20048966.10, 20048966.10],
    };
    const latlon_bounds = {
        lon: [-180, 180],
        lat: [-85.06, 85.06],
    };
    const { min, max } = Math;
    function clip_mercator(low, high, dimension) {
        const [vmin, vmax] = mercator_bounds[dimension];
        return [max(low, vmin), min(high, vmax)];
    }
    function in_bounds(value, dimension) {
        const [min, max] = latlon_bounds[dimension];
        return min < value && value < max;
    }
    (function (inplace) {
        function project_xy(x, y, merc_x, merc_y) {
            const n = min(x.length, y.length);
            merc_x = merc_x ?? x;
            merc_y = 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 ?? xs;
            merc_ys = merc_ys ?? ys;
            for (let i = 0; i < n; i++) {
                project_xy(xs[i], ys[i], merc_xs[i], merc_ys[i]);
            }
        }
        inplace.project_xsys = project_xsys;
    })(exports.inplace || (exports.inplace = {}));
    function project_xy(x, y) {
        const n = min(x.length, y.length);
        const ArrayType = (0, types_1.infer_type)(x, y);
        const merc_x = new ArrayType(n);
        const merc_y = new ArrayType(n);
        exports.inplace.project_xy(x, y, merc_x, merc_y);
        return [merc_x, merc_y];
    }
    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];
    }
},
/* proj4/lib/core.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const Proj_1 = tslib_1.__importDefault(require(136) /* ./Proj */);
    const transform_1 = tslib_1.__importDefault(require(162) /* ./transform */);
    var wgs84 = (0, Proj_1.default)('WGS84');
    function transformer(from, to, coords, enforceAxis) {
        var transformedArray, out, keys;
        if (Array.isArray(coords)) {
            transformedArray = (0, transform_1.default)(from, to, coords, enforceAxis) || { x: NaN, y: NaN };
            if (coords.length > 2) {
                if ((typeof from.name !== 'undefined' && from.name === 'geocent') || (typeof to.name !== 'undefined' && to.name === 'geocent')) {
                    if (typeof transformedArray.z === 'number') {
                        return [transformedArray.x, transformedArray.y, transformedArray.z].concat(coords.splice(3));
                    }
                    else {
                        return [transformedArray.x, transformedArray.y, coords[2]].concat(coords.splice(3));
                    }
                }
                else {
                    return [transformedArray.x, transformedArray.y].concat(coords.splice(2));
                }
            }
            else {
                return [transformedArray.x, transformedArray.y];
            }
        }
        else {
            out = (0, transform_1.default)(from, to, coords, enforceAxis);
            keys = Object.keys(coords);
            if (keys.length === 2) {
                return out;
            }
            keys.forEach(function (key) {
                if ((typeof from.name !== 'undefined' && from.name === 'geocent') || (typeof to.name !== 'undefined' && to.name === 'geocent')) {
                    if (key === 'x' || key === 'y' || key === 'z') {
                        return;
                    }
                }
                else {
                    if (key === 'x' || key === 'y') {
                        return;
                    }
                }
                out[key] = coords[key];
            });
            return out;
        }
    }
    function checkProj(item) {
        if (item instanceof Proj_1.default) {
            return item;
        }
        if (item.oProj) {
            return item.oProj;
        }
        return (0, Proj_1.default)(item);
    }
    function proj4(fromProj, toProj, coord) {
        fromProj = checkProj(fromProj);
        var single = false;
        var obj;
        if (typeof toProj === 'undefined') {
            toProj = fromProj;
            fromProj = wgs84;
            single = true;
        }
        else if (typeof toProj.x !== 'undefined' || Array.isArray(toProj)) {
            coord = toProj;
            toProj = fromProj;
            fromProj = wgs84;
            single = true;
        }
        toProj = checkProj(toProj);
        if (coord) {
            return transformer(fromProj, toProj, coord);
        }
        else {
            obj = {
                forward: function (coords, enforceAxis) {
                    return transformer(fromProj, toProj, coords, enforceAxis);
                },
                inverse: function (coords, enforceAxis) {
                    return transformer(toProj, fromProj, coords, enforceAxis);
                }
            };
            if (single) {
                obj.oProj = toProj;
            }
            return obj;
        }
    }
    exports.default = proj4;
},
/* proj4/lib/Proj.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const parseCode_1 = tslib_1.__importDefault(require(137) /* ./parseCode */);
    const extend_1 = tslib_1.__importDefault(require(148) /* ./extend */);
    const projections_1 = tslib_1.__importDefault(require(149) /* ./projections */);
    const deriveConstants_1 = require(157) /* ./deriveConstants */;
    const Datum_1 = tslib_1.__importDefault(require(159) /* ./constants/Datum */);
    const datum_1 = tslib_1.__importDefault(require(160) /* ./datum */);
    const match_1 = tslib_1.__importDefault(require(144) /* ./match */);
    const nadgrid_1 = require(161) /* ./nadgrid */;
    function Projection(srsCode, callback) {
        if (!(this instanceof Projection)) {
            return new Projection(srsCode);
        }
        callback = callback || function (error) {
            if (error) {
                throw error;
            }
        };
        var json = (0, parseCode_1.default)(srsCode);
        if (typeof json !== 'object') {
            callback(srsCode);
            return;
        }
        var ourProj = Projection.projections.get(json.projName);
        if (!ourProj) {
            callback(srsCode);
            return;
        }
        if (json.datumCode && json.datumCode !== 'none') {
            var datumDef = (0, match_1.default)(Datum_1.default, json.datumCode);
            if (datumDef) {
                json.datum_params = json.datum_params || (datumDef.towgs84 ? datumDef.towgs84.split(',') : null);
                json.ellps = datumDef.ellipse;
                json.datumName = datumDef.datumName ? datumDef.datumName : json.datumCode;
            }
        }
        json.k0 = json.k0 || 1.0;
        json.axis = json.axis || 'enu';
        json.ellps = json.ellps || 'wgs84';
        json.lat1 = json.lat1 || json.lat0; // Lambert_Conformal_Conic_1SP, for example, needs this
        var sphere_ = (0, deriveConstants_1.sphere)(json.a, json.b, json.rf, json.ellps, json.sphere);
        var ecc = (0, deriveConstants_1.eccentricity)(sphere_.a, sphere_.b, sphere_.rf, json.R_A);
        var nadgrids = (0, nadgrid_1.getNadgrids)(json.nadgrids);
        var datumObj = json.datum || (0, datum_1.default)(json.datumCode, json.datum_params, sphere_.a, sphere_.b, ecc.es, ecc.ep2, nadgrids);
        (0, extend_1.default)(this, json); // transfer everything over from the projection because we don't know what we'll need
        (0, extend_1.default)(this, ourProj); // transfer all the methods from the projection
        // copy the 4 things over we calculated in deriveConstants.sphere
        this.a = sphere_.a;
        this.b = sphere_.b;
        this.rf = sphere_.rf;
        this.sphere = sphere_.sphere;
        // copy the 3 things we calculated in deriveConstants.eccentricity
        this.es = ecc.es;
        this.e = ecc.e;
        this.ep2 = ecc.ep2;
        // add in the datum object
        this.datum = datumObj;
        // init the projection
        this.init();
        // legecy callback from back in the day when it went to spatialreference.org
        callback(null, this);
    }
    Projection.projections = projections_1.default;
    Projection.projections.start();
    exports.default = Projection;
},
/* proj4/lib/parseCode.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const defs_1 = tslib_1.__importDefault(require(138) /* ./defs */);
    const wkt_parser_1 = tslib_1.__importDefault(require(145) /* wkt-parser */);
    const projString_1 = tslib_1.__importDefault(require(140) /* ./projString */);
    const match_1 = tslib_1.__importDefault(require(144) /* ./match */);
    function testObj(code) {
        return typeof code === 'string';
    }
    function testDef(code) {
        return code in defs_1.default;
    }
    var codeWords = ['PROJECTEDCRS', 'PROJCRS', 'GEOGCS', 'GEOCCS', 'PROJCS', 'LOCAL_CS', 'GEODCRS', 'GEODETICCRS', 'GEODETICDATUM', 'ENGCRS', 'ENGINEERINGCRS'];
    function testWKT(code) {
        return codeWords.some(function (word) {
            return code.indexOf(word) > -1;
        });
    }
    var codes = ['3857', '900913', '3785', '102113'];
    function checkMercator(item) {
        var auth = (0, match_1.default)(item, 'authority');
        if (!auth) {
            return;
        }
        var code = (0, match_1.default)(auth, 'epsg');
        return code && codes.indexOf(code) > -1;
    }
    function checkProjStr(item) {
        var ext = (0, match_1.default)(item, 'extension');
        if (!ext) {
            return;
        }
        return (0, match_1.default)(ext, 'proj4');
    }
    function testProj(code) {
        return code[0] === '+';
    }
    function parse(code) {
        if (testObj(code)) {
            //check to see if this is a WKT string
            if (testDef(code)) {
                return defs_1.default[code];
            }
            if (testWKT(code)) {
                var out = (0, wkt_parser_1.default)(code);
                // test of spetial case, due to this being a very common and often malformed
                if (checkMercator(out)) {
                    return defs_1.default['EPSG:3857'];
                }
                var maybeProjStr = checkProjStr(out);
                if (maybeProjStr) {
                    return (0, projString_1.default)(maybeProjStr);
                }
                return out;
            }
            if (testProj(code)) {
                return (0, projString_1.default)(code);
            }
        }
        else {
            return code;
        }
    }
    exports.default = parse;
},
/* proj4/lib/defs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const global_1 = tslib_1.__importDefault(require(139) /* ./global */);
    const projString_1 = tslib_1.__importDefault(require(140) /* ./projString */);
    const wkt_parser_1 = tslib_1.__importDefault(require(145) /* wkt-parser */);
    function defs(name) {
        /*global console*/
        var that = this;
        if (arguments.length === 2) {
            var def = arguments[1];
            if (typeof def === 'string') {
                if (def.charAt(0) === '+') {
                    defs[name] = (0, projString_1.default)(arguments[1]);
                }
                else {
                    defs[name] = (0, wkt_parser_1.default)(arguments[1]);
                }
            }
            else {
                defs[name] = def;
            }
        }
        else if (arguments.length === 1) {
            if (Array.isArray(name)) {
                return name.map(function (v) {
                    if (Array.isArray(v)) {
                        defs.apply(that, v);
                    }
                    else {
                        defs(v);
                    }
                });
            }
            else if (typeof name === 'string') {
                if (name in defs) {
                    return defs[name];
                }
            }
            else if ('EPSG' in name) {
                defs['EPSG:' + name.EPSG] = name;
            }
            else if ('ESRI' in name) {
                defs['ESRI:' + name.ESRI] = name;
            }
            else if ('IAU2000' in name) {
                defs['IAU2000:' + name.IAU2000] = name;
            }
            else {
                console.log(name);
            }
            return;
        }
    }
    (0, global_1.default)(defs);
    exports.default = defs;
},
/* proj4/lib/global.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    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'];
    }
},
/* proj4/lib/projString.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(141) /* ./constants/values */;
    const PrimeMeridian_1 = tslib_1.__importDefault(require(142) /* ./constants/PrimeMeridian */);
    const units_1 = tslib_1.__importDefault(require(143) /* ./constants/units */);
    const match_1 = tslib_1.__importDefault(require(144) /* ./match */);
    function default_1(defData) {
        var self = {};
        var paramObj = defData.split('+').map(function (v) {
            return v.trim();
        }).filter(function (a) {
            return a;
        }).reduce(function (p, a) {
            var split = a.split('=');
            split.push(true);
            p[split[0].toLowerCase()] = split[1];
            return p;
        }, {});
        var paramName, paramVal, paramOutname;
        var params = {
            proj: 'projName',
            datum: 'datumCode',
            rf: function (v) {
                self.rf = parseFloat(v);
            },
            lat_0: function (v) {
                self.lat0 = v * values_1.D2R;
            },
            lat_1: function (v) {
                self.lat1 = v * values_1.D2R;
            },
            lat_2: function (v) {
                self.lat2 = v * values_1.D2R;
            },
            lat_ts: function (v) {
                self.lat_ts = v * values_1.D2R;
            },
            lon_0: function (v) {
                self.long0 = v * values_1.D2R;
            },
            lon_1: function (v) {
                self.long1 = v * values_1.D2R;
            },
            lon_2: function (v) {
                self.long2 = v * values_1.D2R;
            },
            alpha: function (v) {
                self.alpha = parseFloat(v) * values_1.D2R;
            },
            gamma: function (v) {
                self.rectified_grid_angle = parseFloat(v);
            },
            lonc: function (v) {
                self.longc = v * values_1.D2R;
            },
            x_0: function (v) {
                self.x0 = parseFloat(v);
            },
            y_0: function (v) {
                self.y0 = parseFloat(v);
            },
            k_0: function (v) {
                self.k0 = parseFloat(v);
            },
            k: function (v) {
                self.k0 = parseFloat(v);
            },
            a: function (v) {
                self.a = parseFloat(v);
            },
            b: function (v) {
                self.b = parseFloat(v);
            },
            r: function (v) {
                self.a = self.b = parseFloat(v);
            },
            r_a: function () {
                self.R_A = true;
            },
            zone: function (v) {
                self.zone = parseInt(v, 10);
            },
            south: function () {
                self.utmSouth = true;
            },
            towgs84: function (v) {
                self.datum_params = v.split(",").map(function (a) {
                    return parseFloat(a);
                });
            },
            to_meter: function (v) {
                self.to_meter = parseFloat(v);
            },
            units: function (v) {
                self.units = v;
                var unit = (0, match_1.default)(units_1.default, v);
                if (unit) {
                    self.to_meter = unit.to_meter;
                }
            },
            from_greenwich: function (v) {
                self.from_greenwich = v * values_1.D2R;
            },
            pm: function (v) {
                var pm = (0, match_1.default)(PrimeMeridian_1.default, v);
                self.from_greenwich = (pm ? pm : parseFloat(v)) * values_1.D2R;
            },
            nadgrids: function (v) {
                if (v === '@null') {
                    self.datumCode = 'none';
                }
                else {
                    self.nadgrids = v;
                }
            },
            axis: function (v) {
                var legalAxis = "ewnsud";
                if (v.length === 3 && legalAxis.indexOf(v.substr(0, 1)) !== -1 && legalAxis.indexOf(v.substr(1, 1)) !== -1 && legalAxis.indexOf(v.substr(2, 1)) !== -1) {
                    self.axis = v;
                }
            },
            approx: function () {
                self.approx = true;
            }
        };
        for (paramName in paramObj) {
            paramVal = paramObj[paramName];
            if (paramName in params) {
                paramOutname = params[paramName];
                if (typeof paramOutname === 'function') {
                    paramOutname(paramVal);
                }
                else {
                    self[paramOutname] = paramVal;
                }
            }
            else {
                self[paramName] = paramVal;
            }
        }
        if (typeof self.datumCode === 'string' && self.datumCode !== "WGS84") {
            self.datumCode = self.datumCode.toLowerCase();
        }
        return self;
    }
},
/* proj4/lib/constants/values.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.PJD_3PARAM = 1;
    exports.PJD_7PARAM = 2;
    exports.PJD_GRIDSHIFT = 3;
    exports.PJD_WGS84 = 4; // WGS84 or equivalent
    exports.PJD_NODATUM = 5; // WGS84 or equivalent
    exports.SRS_WGS84_SEMIMAJOR = 6378137.0; // only used in grid shift transforms
    exports.SRS_WGS84_SEMIMINOR = 6356752.314; // only used in grid shift transforms
    exports.SRS_WGS84_ESQUARED = 0.0066943799901413165; // only used in grid shift transforms
    exports.SEC_TO_RAD = 4.84813681109535993589914102357e-6;
    exports.HALF_PI = Math.PI / 2;
    // ellipoid pj_set_ell.c
    exports.SIXTH = 0.1666666666666666667;
    /* 1/6 */
    exports.RA4 = 0.04722222222222222222;
    /* 17/360 */
    exports.RA6 = 0.02215608465608465608;
    exports.EPSLN = 1.0e-10;
    // you'd think you could use Number.EPSILON above but that makes
    // Mollweide get into an infinate loop.
    exports.D2R = 0.01745329251994329577;
    exports.R2D = 57.29577951308232088;
    exports.FORTPI = Math.PI / 4;
    exports.TWO_PI = Math.PI * 2;
    // SPI is slightly greater than Math.PI, so values that exceed the -180..180
    // degree range by a tiny amount don't get wrapped. This prevents points that
    // have drifted from their original location along the 180th meridian (due to
    // floating point error) from changing their sign.
    exports.SPI = 3.14159265359;
},
/* proj4/lib/constants/PrimeMeridian.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var exports$1 = {};
    exports.default = exports$1;
    exports$1.greenwich = 0.0; //"0dE",
    exports$1.lisbon = -9.131906111111; //"9d07'54.862\"W",
    exports$1.paris = 2.337229166667; //"2d20'14.025\"E",
    exports$1.bogota = -74.080916666667; //"74d04'51.3\"W",
    exports$1.madrid = -3.687938888889; //"3d41'16.58\"W",
    exports$1.rome = 12.452333333333; //"12d27'8.4\"E",
    exports$1.bern = 7.439583333333; //"7d26'22.5\"E",
    exports$1.jakarta = 106.807719444444; //"106d48'27.79\"E",
    exports$1.ferro = -17.666666666667; //"17d40'W",
    exports$1.brussels = 4.367975; //"4d22'4.71\"E",
    exports$1.stockholm = 18.058277777778; //"18d3'29.8\"E",
    exports$1.athens = 23.7163375; //"23d42'58.815\"E",
    exports$1.oslo = 10.722916666667; //"10d43'22.5\"E"
},
/* proj4/lib/constants/units.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = {
        ft: { to_meter: 0.3048 },
        'us-ft': { to_meter: 1200 / 3937 }
    };
},
/* proj4/lib/match.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = match;
    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];
            }
        }
    }
},
/* wkt-parser/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const tslib_1 = require(1) /* tslib */;
    var D2R = 0.01745329251994329577;
    const parser_1 = tslib_1.__importDefault(require(146) /* ./parser */);
    const process_1 = require(147) /* ./process */;
    function rename(obj, params) {
        var outName = params[0];
        var inName = params[1];
        if (!(outName in obj) && (inName in obj)) {
            obj[outName] = obj[inName];
            if (params.length === 3) {
                obj[outName] = params[2](obj[outName]);
            }
        }
    }
    function d2r(input) {
        return input * D2R;
    }
    function cleanWKT(wkt) {
        if (wkt.type === 'GEOGCS') {
            wkt.projName = 'longlat';
        }
        else if (wkt.type === 'LOCAL_CS') {
            wkt.projName = 'identity';
            wkt.local = true;
        }
        else {
            if (typeof wkt.PROJECTION === 'object') {
                wkt.projName = Object.keys(wkt.PROJECTION)[0];
            }
            else {
                wkt.projName = wkt.PROJECTION;
            }
        }
        if (wkt.AXIS) {
            var axisOrder = '';
            for (var i = 0, ii = wkt.AXIS.length; i < ii; ++i) {
                var axis = [wkt.AXIS[i][0].toLowerCase(), wkt.AXIS[i][1].toLowerCase()];
                if (axis[0].indexOf('north') !== -1 || ((axis[0] === 'y' || axis[0] === 'lat') && axis[1] === 'north')) {
                    axisOrder += 'n';
                }
                else if (axis[0].indexOf('south') !== -1 || ((axis[0] === 'y' || axis[0] === 'lat') && axis[1] === 'south')) {
                    axisOrder += 's';
                }
                else if (axis[0].indexOf('east') !== -1 || ((axis[0] === 'x' || axis[0] === 'lon') && axis[1] === 'east')) {
                    axisOrder += 'e';
                }
                else if (axis[0].indexOf('west') !== -1 || ((axis[0] === 'x' || axis[0] === 'lon') && axis[1] === 'west')) {
                    axisOrder += 'w';
                }
            }
            if (axisOrder.length === 2) {
                axisOrder += 'u';
            }
            if (axisOrder.length === 3) {
                wkt.axis = axisOrder;
            }
        }
        if (wkt.UNIT) {
            wkt.units = wkt.UNIT.name.toLowerCase();
            if (wkt.units === 'metre') {
                wkt.units = 'meter';
            }
            if (wkt.UNIT.convert) {
                if (wkt.type === 'GEOGCS') {
                    if (wkt.DATUM && wkt.DATUM.SPHEROID) {
                        wkt.to_meter = wkt.UNIT.convert * wkt.DATUM.SPHEROID.a;
                    }
                }
                else {
                    wkt.to_meter = wkt.UNIT.convert;
                }
            }
        }
        var geogcs = wkt.GEOGCS;
        if (wkt.type === 'GEOGCS') {
            geogcs = wkt;
        }
        if (geogcs) {
            //if(wkt.GEOGCS.PRIMEM&&wkt.GEOGCS.PRIMEM.convert){
            //  wkt.from_greenwich=wkt.GEOGCS.PRIMEM.convert*D2R;
            //}
            if (geogcs.DATUM) {
                wkt.datumCode = geogcs.DATUM.name.toLowerCase();
            }
            else {
                wkt.datumCode = geogcs.name.toLowerCase();
            }
            if (wkt.datumCode.slice(0, 2) === 'd_') {
                wkt.datumCode = wkt.datumCode.slice(2);
            }
            if (wkt.datumCode === 'new_zealand_geodetic_datum_1949' || wkt.datumCode === 'new_zealand_1949') {
                wkt.datumCode = 'nzgd49';
            }
            if (wkt.datumCode === 'wgs_1984' || wkt.datumCode === 'world_geodetic_system_1984') {
                if (wkt.PROJECTION === 'Mercator_Auxiliary_Sphere') {
                    wkt.sphere = true;
                }
                wkt.datumCode = 'wgs84';
            }
            if (wkt.datumCode.slice(-6) === '_ferro') {
                wkt.datumCode = wkt.datumCode.slice(0, -6);
            }
            if (wkt.datumCode.slice(-8) === '_jakarta') {
                wkt.datumCode = wkt.datumCode.slice(0, -8);
            }
            if (~wkt.datumCode.indexOf('belge')) {
                wkt.datumCode = 'rnb72';
            }
            if (geogcs.DATUM && geogcs.DATUM.SPHEROID) {
                wkt.ellps = geogcs.DATUM.SPHEROID.name.replace('_19', '').replace(/[Cc]larke\_18/, 'clrk');
                if (wkt.ellps.toLowerCase().slice(0, 13) === 'international') {
                    wkt.ellps = 'intl';
                }
                wkt.a = geogcs.DATUM.SPHEROID.a;
                wkt.rf = parseFloat(geogcs.DATUM.SPHEROID.rf, 10);
            }
            if (geogcs.DATUM && geogcs.DATUM.TOWGS84) {
                wkt.datum_params = geogcs.DATUM.TOWGS84;
            }
            if (~wkt.datumCode.indexOf('osgb_1936')) {
                wkt.datumCode = 'osgb36';
            }
            if (~wkt.datumCode.indexOf('osni_1952')) {
                wkt.datumCode = 'osni52';
            }
            if (~wkt.datumCode.indexOf('tm65')
                || ~wkt.datumCode.indexOf('geodetic_datum_of_1965')) {
                wkt.datumCode = 'ire65';
            }
            if (wkt.datumCode === 'ch1903+') {
                wkt.datumCode = 'ch1903';
            }
            if (~wkt.datumCode.indexOf('israel')) {
                wkt.datumCode = 'isr93';
            }
        }
        if (wkt.b && !isFinite(wkt.b)) {
            wkt.b = wkt.a;
        }
        function toMeter(input) {
            var ratio = wkt.to_meter || 1;
            return input * ratio;
        }
        var renamer = function (a) {
            return rename(wkt, a);
        };
        var list = [
            ['standard_parallel_1', 'Standard_Parallel_1'],
            ['standard_parallel_1', 'Latitude of 1st standard parallel'],
            ['standard_parallel_2', 'Standard_Parallel_2'],
            ['standard_parallel_2', 'Latitude of 2nd standard parallel'],
            ['false_easting', 'False_Easting'],
            ['false_easting', 'False easting'],
            ['false-easting', 'Easting at false origin'],
            ['false_northing', 'False_Northing'],
            ['false_northing', 'False northing'],
            ['false_northing', 'Northing at false origin'],
            ['central_meridian', 'Central_Meridian'],
            ['central_meridian', 'Longitude of natural origin'],
            ['central_meridian', 'Longitude of false origin'],
            ['latitude_of_origin', 'Latitude_Of_Origin'],
            ['latitude_of_origin', 'Central_Parallel'],
            ['latitude_of_origin', 'Latitude of natural origin'],
            ['latitude_of_origin', 'Latitude of false origin'],
            ['scale_factor', 'Scale_Factor'],
            ['k0', 'scale_factor'],
            ['latitude_of_center', 'Latitude_Of_Center'],
            ['latitude_of_center', 'Latitude_of_center'],
            ['lat0', 'latitude_of_center', d2r],
            ['longitude_of_center', 'Longitude_Of_Center'],
            ['longitude_of_center', 'Longitude_of_center'],
            ['longc', 'longitude_of_center', d2r],
            ['x0', 'false_easting', toMeter],
            ['y0', 'false_northing', toMeter],
            ['long0', 'central_meridian', d2r],
            ['lat0', 'latitude_of_origin', d2r],
            ['lat0', 'standard_parallel_1', d2r],
            ['lat1', 'standard_parallel_1', d2r],
            ['lat2', 'standard_parallel_2', d2r],
            ['azimuth', 'Azimuth'],
            ['alpha', 'azimuth', d2r],
            ['srsCode', 'name']
        ];
        list.forEach(renamer);
        if (!wkt.long0 && wkt.longc && (wkt.projName === 'Albers_Conic_Equal_Area' || wkt.projName === 'Lambert_Azimuthal_Equal_Area')) {
            wkt.long0 = wkt.longc;
        }
        if (!wkt.lat_ts && wkt.lat1 && (wkt.projName === 'Stereographic_South_Pole' || wkt.projName === 'Polar Stereographic (variant B)')) {
            wkt.lat0 = d2r(wkt.lat1 > 0 ? 90 : -90);
            wkt.lat_ts = wkt.lat1;
        }
        else if (!wkt.lat_ts && wkt.lat0 && wkt.projName === 'Polar_Stereographic') {
            wkt.lat_ts = wkt.lat0;
            wkt.lat0 = d2r(wkt.lat0 > 0 ? 90 : -90);
        }
    }
    function default_1(wkt) {
        var lisp = (0, parser_1.default)(wkt);
        var type = lisp.shift();
        var name = lisp.shift();
        lisp.unshift(['name', name]);
        lisp.unshift(['type', type]);
        var obj = {};
        (0, process_1.sExpr)(lisp, obj);
        cleanWKT(obj);
        return obj;
    }
},
/* 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();
    exports.sExpr = sExpr;
    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);
        }
    }
},
/* proj4/lib/extend.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    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;
    }
},
/* proj4/lib/projections.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.add = add;
    exports.get = get;
    exports.start = start;
    const tslib_1 = require(1) /* tslib */;
    const merc_1 = tslib_1.__importDefault(require(150) /* ./projections/merc */);
    const longlat_1 = tslib_1.__importDefault(require(156) /* ./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;
    }
    function get(name) {
        if (!name) {
            return false;
        }
        var n = name.toLowerCase();
        if (typeof names[n] !== 'undefined' && projStore[names[n]]) {
            return projStore[names[n]];
        }
    }
    function start() {
        projs.forEach(add);
    }
    exports.default = {
        start: start,
        add: add,
        get: get
    };
},
/* proj4/lib/projections/merc.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = forward;
    exports.inverse = inverse;
    const tslib_1 = require(1) /* tslib */;
    const msfnz_1 = tslib_1.__importDefault(require(151) /* ../common/msfnz */);
    const adjust_lon_1 = tslib_1.__importDefault(require(152) /* ../common/adjust_lon */);
    const tsfnz_1 = tslib_1.__importDefault(require(154) /* ../common/tsfnz */);
    const phi2z_1 = tslib_1.__importDefault(require(155) /* ../common/phi2z */);
    const values_1 = require(141) /* ../constants/values */;
    function init() {
        var con = this.b / this.a;
        this.es = 1 - con * con;
        if (!('x0' in this)) {
            this.x0 = 0;
        }
        if (!('y0' in this)) {
            this.y0 = 0;
        }
        this.e = Math.sqrt(this.es);
        if (this.lat_ts) {
            if (this.sphere) {
                this.k0 = Math.cos(this.lat_ts);
            }
            else {
                this.k0 = (0, msfnz_1.default)(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));
            }
        }
        else {
            if (!this.k0) {
                if (this.k) {
                    this.k0 = this.k;
                }
                else {
                    this.k0 = 1;
                }
            }
        }
    }
    /* Mercator forward equations--mapping lat,long to x,y
      --------------------------------------------------*/
    function forward(p) {
        var lon = p.x;
        var lat = p.y;
        // convert to radians
        if (lat * values_1.R2D > 90 && lat * values_1.R2D < -90 && lon * values_1.R2D > 180 && lon * values_1.R2D < -180) {
            return null;
        }
        var x, y;
        if (Math.abs(Math.abs(lat) - values_1.HALF_PI) <= values_1.EPSLN) {
            return null;
        }
        else {
            if (this.sphere) {
                x = this.x0 + this.a * this.k0 * (0, adjust_lon_1.default)(lon - this.long0);
                y = this.y0 + this.a * this.k0 * Math.log(Math.tan(values_1.FORTPI + 0.5 * lat));
            }
            else {
                var sinphi = Math.sin(lat);
                var ts = (0, tsfnz_1.default)(this.e, lat, sinphi);
                x = this.x0 + this.a * this.k0 * (0, adjust_lon_1.default)(lon - this.long0);
                y = this.y0 - this.a * this.k0 * Math.log(ts);
            }
            p.x = x;
            p.y = y;
            return p;
        }
    }
    /* Mercator inverse equations--mapping x,y to lat/long
      --------------------------------------------------*/
    function inverse(p) {
        var x = p.x - this.x0;
        var y = p.y - this.y0;
        var lon, lat;
        if (this.sphere) {
            lat = values_1.HALF_PI - 2 * Math.atan(Math.exp(-y / (this.a * this.k0)));
        }
        else {
            var ts = Math.exp(-y / (this.a * this.k0));
            lat = (0, phi2z_1.default)(this.e, ts);
            if (lat === -9999) {
                return null;
            }
        }
        lon = (0, adjust_lon_1.default)(this.long0 + x / (this.a * this.k0));
        p.x = lon;
        p.y = lat;
        return p;
    }
    exports.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();
    exports.default = default_1;
    function default_1(eccent, sinphi, cosphi) {
        var con = eccent * sinphi;
        return cosphi / (Math.sqrt(1 - con * con));
    }
},
/* proj4/lib/common/adjust_lon.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(141) /* ../constants/values */;
    const sign_1 = tslib_1.__importDefault(require(153) /* ./sign */);
    function default_1(x) {
        return (Math.abs(x) <= values_1.SPI) ? x : (x - ((0, sign_1.default)(x) * values_1.TWO_PI));
    }
},
/* proj4/lib/common/sign.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(x) {
        return x < 0 ? -1 : 1;
    }
},
/* proj4/lib/common/tsfnz.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const values_1 = require(141) /* ../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);
    }
},
/* proj4/lib/common/phi2z.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    const values_1 = require(141) /* ../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;
    }
},
/* proj4/lib/projections/longlat.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.init = init;
    exports.forward = identity;
    exports.inverse = identity;
    function init() {
        //no-op for longlat
    }
    function identity(pt) {
        return pt;
    }
    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();
    exports.eccentricity = eccentricity;
    exports.sphere = sphere;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(141) /* ./constants/values */;
    const Ellipsoid_1 = tslib_1.__importStar(require(158) /* ./constants/Ellipsoid */);
    const match_1 = tslib_1.__importDefault(require(144) /* ./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
        };
    }
    function sphere(a, b, rf, ellps, sphere) {
        if (!a) { // do we have an ellipsoid?
            var ellipse = (0, match_1.default)(Ellipsoid_1.default, ellps);
            if (!ellipse) {
                ellipse = Ellipsoid_1.WGS84;
            }
            a = ellipse.a;
            b = ellipse.b;
            rf = ellipse.rf;
        }
        if (rf && !b) {
            b = (1.0 - 1.0 / rf) * a;
        }
        if (rf === 0 || Math.abs(a - b) < values_1.EPSLN) {
            sphere = true;
            b = a;
        }
        return {
            a: a,
            b: b,
            rf: rf,
            sphere: sphere
        };
    }
},
/* proj4/lib/constants/Ellipsoid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var exports$1 = {};
    exports.default = exports$1;
    exports$1.MERIT = {
        a: 6378137.0,
        rf: 298.257,
        ellipseName: "MERIT 1983"
    };
    exports$1.SGS85 = {
        a: 6378136.0,
        rf: 298.257,
        ellipseName: "Soviet Geodetic System 85"
    };
    exports$1.GRS80 = {
        a: 6378137.0,
        rf: 298.257222101,
        ellipseName: "GRS 1980(IUGG, 1980)"
    };
    exports$1.IAU76 = {
        a: 6378140.0,
        rf: 298.257,
        ellipseName: "IAU 1976"
    };
    exports$1.airy = {
        a: 6377563.396,
        b: 6356256.910,
        ellipseName: "Airy 1830"
    };
    exports$1.APL4 = {
        a: 6378137,
        rf: 298.25,
        ellipseName: "Appl. Physics. 1965"
    };
    exports$1.NWL9D = {
        a: 6378145.0,
        rf: 298.25,
        ellipseName: "Naval Weapons Lab., 1965"
    };
    exports$1.mod_airy = {
        a: 6377340.189,
        b: 6356034.446,
        ellipseName: "Modified Airy"
    };
    exports$1.andrae = {
        a: 6377104.43,
        rf: 300.0,
        ellipseName: "Andrae 1876 (Den., Iclnd.)"
    };
    exports$1.aust_SA = {
        a: 6378160.0,
        rf: 298.25,
        ellipseName: "Australian Natl & S. Amer. 1969"
    };
    exports$1.GRS67 = {
        a: 6378160.0,
        rf: 298.2471674270,
        ellipseName: "GRS 67(IUGG 1967)"
    };
    exports$1.bessel = {
        a: 6377397.155,
        rf: 299.1528128,
        ellipseName: "Bessel 1841"
    };
    exports$1.bess_nam = {
        a: 6377483.865,
        rf: 299.1528128,
        ellipseName: "Bessel 1841 (Namibia)"
    };
    exports$1.clrk66 = {
        a: 6378206.4,
        b: 6356583.8,
        ellipseName: "Clarke 1866"
    };
    exports$1.clrk80 = {
        a: 6378249.145,
        rf: 293.4663,
        ellipseName: "Clarke 1880 mod."
    };
    exports$1.clrk80ign = {
        a: 6378249.2,
        b: 6356515,
        rf: 293.4660213,
        ellipseName: "Clarke 1880 (IGN)"
    };
    exports$1.clrk58 = {
        a: 6378293.645208759,
        rf: 294.2606763692654,
        ellipseName: "Clarke 1858"
    };
    exports$1.CPM = {
        a: 6375738.7,
        rf: 334.29,
        ellipseName: "Comm. des Poids et Mesures 1799"
    };
    exports$1.delmbr = {
        a: 6376428.0,
        rf: 311.5,
        ellipseName: "Delambre 1810 (Belgium)"
    };
    exports$1.engelis = {
        a: 6378136.05,
        rf: 298.2566,
        ellipseName: "Engelis 1985"
    };
    exports$1.evrst30 = {
        a: 6377276.345,
        rf: 300.8017,
        ellipseName: "Everest 1830"
    };
    exports$1.evrst48 = {
        a: 6377304.063,
        rf: 300.8017,
        ellipseName: "Everest 1948"
    };
    exports$1.evrst56 = {
        a: 6377301.243,
        rf: 300.8017,
        ellipseName: "Everest 1956"
    };
    exports$1.evrst69 = {
        a: 6377295.664,
        rf: 300.8017,
        ellipseName: "Everest 1969"
    };
    exports$1.evrstSS = {
        a: 6377298.556,
        rf: 300.8017,
        ellipseName: "Everest (Sabah & Sarawak)"
    };
    exports$1.fschr60 = {
        a: 6378166.0,
        rf: 298.3,
        ellipseName: "Fischer (Mercury Datum) 1960"
    };
    exports$1.fschr60m = {
        a: 6378155.0,
        rf: 298.3,
        ellipseName: "Fischer 1960"
    };
    exports$1.fschr68 = {
        a: 6378150.0,
        rf: 298.3,
        ellipseName: "Fischer 1968"
    };
    exports$1.helmert = {
        a: 6378200.0,
        rf: 298.3,
        ellipseName: "Helmert 1906"
    };
    exports$1.hough = {
        a: 6378270.0,
        rf: 297.0,
        ellipseName: "Hough"
    };
    exports$1.intl = {
        a: 6378388.0,
        rf: 297.0,
        ellipseName: "International 1909 (Hayford)"
    };
    exports$1.kaula = {
        a: 6378163.0,
        rf: 298.24,
        ellipseName: "Kaula 1961"
    };
    exports$1.lerch = {
        a: 6378139.0,
        rf: 298.257,
        ellipseName: "Lerch 1979"
    };
    exports$1.mprts = {
        a: 6397300.0,
        rf: 191.0,
        ellipseName: "Maupertius 1738"
    };
    exports$1.new_intl = {
        a: 6378157.5,
        b: 6356772.2,
        ellipseName: "New International 1967"
    };
    exports$1.plessis = {
        a: 6376523.0,
        rf: 6355863.0,
        ellipseName: "Plessis 1817 (France)"
    };
    exports$1.krass = {
        a: 6378245.0,
        rf: 298.3,
        ellipseName: "Krassovsky, 1942"
    };
    exports$1.SEasia = {
        a: 6378155.0,
        b: 6356773.3205,
        ellipseName: "Southeast Asia"
    };
    exports$1.walbeck = {
        a: 6376896.0,
        b: 6355834.8467,
        ellipseName: "Walbeck"
    };
    exports$1.WGS60 = {
        a: 6378165.0,
        rf: 298.3,
        ellipseName: "WGS 60"
    };
    exports$1.WGS66 = {
        a: 6378145.0,
        rf: 298.25,
        ellipseName: "WGS 66"
    };
    exports$1.WGS7 = {
        a: 6378135.0,
        rf: 298.26,
        ellipseName: "WGS 72"
    };
    exports.WGS84 = exports$1.WGS84 = {
        a: 6378137.0,
        rf: 298.257223563,
        ellipseName: "WGS 84"
    };
    exports$1.sphere = {
        a: 6370997.0,
        b: 6370997.0,
        ellipseName: "Normal Sphere (r=6370997)"
    };
},
/* proj4/lib/constants/Datum.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var exports$1 = {};
    exports.default = exports$1;
    exports$1.wgs84 = {
        towgs84: "0,0,0",
        ellipse: "WGS84",
        datumName: "WGS84"
    };
    exports$1.ch1903 = {
        towgs84: "674.374,15.056,405.346",
        ellipse: "bessel",
        datumName: "swiss"
    };
    exports$1.ggrs87 = {
        towgs84: "-199.87,74.79,246.62",
        ellipse: "GRS80",
        datumName: "Greek_Geodetic_Reference_System_1987"
    };
    exports$1.nad83 = {
        towgs84: "0,0,0",
        ellipse: "GRS80",
        datumName: "North_American_Datum_1983"
    };
    exports$1.nad27 = {
        nadgrids: "@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat",
        ellipse: "clrk66",
        datumName: "North_American_Datum_1927"
    };
    exports$1.potsdam = {
        towgs84: "598.1,73.7,418.2,0.202,0.045,-2.455,6.7",
        ellipse: "bessel",
        datumName: "Potsdam Rauenberg 1950 DHDN"
    };
    exports$1.carthage = {
        towgs84: "-263.0,6.0,431.0",
        ellipse: "clark80",
        datumName: "Carthage 1934 Tunisia"
    };
    exports$1.hermannskogel = {
        towgs84: "577.326,90.129,463.919,5.137,1.474,5.297,2.4232",
        ellipse: "bessel",
        datumName: "Hermannskogel"
    };
    exports$1.militargeographische_institut = {
        towgs84: "577.326,90.129,463.919,5.137,1.474,5.297,2.4232",
        ellipse: "bessel",
        datumName: "Militar-Geographische Institut"
    };
    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(141) /* ./constants/values */;
    function datum(datumCode, datum_params, a, b, es, ep2, nadgrids) {
        var out = {};
        if (datumCode === undefined || datumCode === 'none') {
            out.datum_type = values_1.PJD_NODATUM;
        }
        else {
            out.datum_type = values_1.PJD_WGS84;
        }
        if (datum_params) {
            out.datum_params = datum_params.map(parseFloat);
            if (out.datum_params[0] !== 0 || out.datum_params[1] !== 0 || out.datum_params[2] !== 0) {
                out.datum_type = values_1.PJD_3PARAM;
            }
            if (out.datum_params.length > 3) {
                if (out.datum_params[3] !== 0 || out.datum_params[4] !== 0 || out.datum_params[5] !== 0 || out.datum_params[6] !== 0) {
                    out.datum_type = values_1.PJD_7PARAM;
                    out.datum_params[3] *= values_1.SEC_TO_RAD;
                    out.datum_params[4] *= values_1.SEC_TO_RAD;
                    out.datum_params[5] *= values_1.SEC_TO_RAD;
                    out.datum_params[6] = (out.datum_params[6] / 1000000.0) + 1.0;
                }
            }
        }
        if (nadgrids) {
            out.datum_type = values_1.PJD_GRIDSHIFT;
            out.grids = nadgrids;
        }
        out.a = a; //datum object also uses these values
        out.b = b;
        out.es = es;
        out.ep2 = ep2;
        return out;
    }
    exports.default = datum;
},
/* proj4/lib/nadgrid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = nadgrid;
    exports.getNadgrids = getNadgrids;
    var loadedNadgrids = {};
    /**
     * Load a binary NTv2 file (.gsb) to a key that can be used in a proj string like +nadgrids=<key>. Pass the NTv2 file
     * as an ArrayBuffer.
     */
    function nadgrid(key, data) {
        var view = new DataView(data);
        var isLittleEndian = detectLittleEndian(view);
        var header = readHeader(view, isLittleEndian);
        var subgrids = readSubgrids(view, header, isLittleEndian);
        var nadgrid = { header: header, subgrids: subgrids };
        loadedNadgrids[key] = nadgrid;
        return nadgrid;
    }
    /**
     * Given a proj4 value for nadgrids, return an array of loaded grids
     */
    function getNadgrids(nadgrids) {
        // Format details: http://proj.maptools.org/gen_parms.html
        if (nadgrids === undefined) {
            return null;
        }
        var grids = nadgrids.split(',');
        return grids.map(parseNadgridString);
    }
    function parseNadgridString(value) {
        if (value.length === 0) {
            return null;
        }
        var optional = value[0] === '@';
        if (optional) {
            value = value.slice(1);
        }
        if (value === 'null') {
            return { name: 'null', mandatory: !optional, grid: null, isNull: true };
        }
        return {
            name: value,
            mandatory: !optional,
            grid: loadedNadgrids[value] || null,
            isNull: false
        };
    }
    function secondsToRadians(seconds) {
        return (seconds / 3600) * Math.PI / 180;
    }
    function detectLittleEndian(view) {
        var nFields = view.getInt32(8, false);
        if (nFields === 11) {
            return false;
        }
        nFields = view.getInt32(8, true);
        if (nFields !== 11) {
            console.warn('Failed to detect nadgrid endian-ness, defaulting to little-endian');
        }
        return true;
    }
    function readHeader(view, isLittleEndian) {
        return {
            nFields: view.getInt32(8, isLittleEndian),
            nSubgridFields: view.getInt32(24, isLittleEndian),
            nSubgrids: view.getInt32(40, isLittleEndian),
            shiftType: decodeString(view, 56, 56 + 8).trim(),
            fromSemiMajorAxis: view.getFloat64(120, isLittleEndian),
            fromSemiMinorAxis: view.getFloat64(136, isLittleEndian),
            toSemiMajorAxis: view.getFloat64(152, isLittleEndian),
            toSemiMinorAxis: view.getFloat64(168, isLittleEndian),
        };
    }
    function decodeString(view, start, end) {
        return String.fromCharCode.apply(null, new Uint8Array(view.buffer.slice(start, end)));
    }
    function readSubgrids(view, header, isLittleEndian) {
        var gridOffset = 176;
        var grids = [];
        for (var i = 0; i < header.nSubgrids; i++) {
            var subHeader = readGridHeader(view, gridOffset, isLittleEndian);
            var nodes = readGridNodes(view, gridOffset, subHeader, isLittleEndian);
            var lngColumnCount = Math.round(1 + (subHeader.upperLongitude - subHeader.lowerLongitude) / subHeader.longitudeInterval);
            var latColumnCount = Math.round(1 + (subHeader.upperLatitude - subHeader.lowerLatitude) / subHeader.latitudeInterval);
            // Proj4 operates on radians whereas the coordinates are in seconds in the grid
            grids.push({
                ll: [secondsToRadians(subHeader.lowerLongitude), secondsToRadians(subHeader.lowerLatitude)],
                del: [secondsToRadians(subHeader.longitudeInterval), secondsToRadians(subHeader.latitudeInterval)],
                lim: [lngColumnCount, latColumnCount],
                count: subHeader.gridNodeCount,
                cvs: mapNodes(nodes)
            });
            gridOffset += 176 + subHeader.gridNodeCount * 16;
        }
        return grids;
    }
    function mapNodes(nodes) {
        return nodes.map(function (r) { return [secondsToRadians(r.longitudeShift), secondsToRadians(r.latitudeShift)]; });
    }
    function readGridHeader(view, offset, isLittleEndian) {
        return {
            name: decodeString(view, offset + 8, offset + 16).trim(),
            parent: decodeString(view, offset + 24, offset + 24 + 8).trim(),
            lowerLatitude: view.getFloat64(offset + 72, isLittleEndian),
            upperLatitude: view.getFloat64(offset + 88, isLittleEndian),
            lowerLongitude: view.getFloat64(offset + 104, isLittleEndian),
            upperLongitude: view.getFloat64(offset + 120, isLittleEndian),
            latitudeInterval: view.getFloat64(offset + 136, isLittleEndian),
            longitudeInterval: view.getFloat64(offset + 152, isLittleEndian),
            gridNodeCount: view.getInt32(offset + 168, isLittleEndian)
        };
    }
    function readGridNodes(view, offset, gridHeader, isLittleEndian) {
        var nodesOffset = offset + 176;
        var gridRecordLength = 16;
        var gridShiftRecords = [];
        for (var i = 0; i < gridHeader.gridNodeCount; i++) {
            var record = {
                latitudeShift: view.getFloat32(nodesOffset + i * gridRecordLength, isLittleEndian),
                longitudeShift: view.getFloat32(nodesOffset + i * gridRecordLength + 4, isLittleEndian),
                latitudeAccuracy: view.getFloat32(nodesOffset + i * gridRecordLength + 8, isLittleEndian),
                longitudeAccuracy: view.getFloat32(nodesOffset + i * gridRecordLength + 12, isLittleEndian),
            };
            gridShiftRecords.push(record);
        }
        return gridShiftRecords;
    }
},
/* proj4/lib/transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = transform;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(141) /* ./constants/values */;
    const datum_transform_1 = tslib_1.__importDefault(require(163) /* ./datum_transform */);
    const adjust_axis_1 = tslib_1.__importDefault(require(165) /* ./adjust_axis */);
    const Proj_1 = tslib_1.__importDefault(require(136) /* ./Proj */);
    const toPoint_1 = tslib_1.__importDefault(require(166) /* ./common/toPoint */);
    const checkSanity_1 = tslib_1.__importDefault(require(167) /* ./checkSanity */);
    function checkNotWGS(source, dest) {
        return ((source.datum.datum_type === values_1.PJD_3PARAM || source.datum.datum_type === values_1.PJD_7PARAM || source.datum.datum_type === values_1.PJD_GRIDSHIFT) && dest.datumCode !== 'WGS84') ||
            ((dest.datum.datum_type === values_1.PJD_3PARAM || dest.datum.datum_type === values_1.PJD_7PARAM || dest.datum.datum_type === values_1.PJD_GRIDSHIFT) && source.datumCode !== 'WGS84');
    }
    function transform(source, dest, point, enforceAxis) {
        var wgs84;
        if (Array.isArray(point)) {
            point = (0, toPoint_1.default)(point);
        }
        else {
            // Clone the point object so inputs don't get modified
            point = {
                x: point.x,
                y: point.y,
                z: point.z,
                m: point.m
            };
        }
        var hasZ = point.z !== undefined;
        (0, checkSanity_1.default)(point);
        // Workaround for datum shifts towgs84, if either source or destination projection is not wgs84
        if (source.datum && dest.datum && checkNotWGS(source, dest)) {
            wgs84 = new Proj_1.default('WGS84');
            point = transform(source, wgs84, point, enforceAxis);
            source = wgs84;
        }
        // DGR, 2010/11/12
        if (enforceAxis && source.axis !== 'enu') {
            point = (0, adjust_axis_1.default)(source, false, point);
        }
        // Transform source points to long/lat, if they aren't already.
        if (source.projName === 'longlat') {
            point = {
                x: point.x * values_1.D2R,
                y: point.y * values_1.D2R,
                z: point.z || 0
            };
        }
        else {
            if (source.to_meter) {
                point = {
                    x: point.x * source.to_meter,
                    y: point.y * source.to_meter,
                    z: point.z || 0
                };
            }
            point = source.inverse(point); // Convert Cartesian to longlat
            if (!point) {
                return;
            }
        }
        // Adjust for the prime meridian if necessary
        if (source.from_greenwich) {
            point.x += source.from_greenwich;
        }
        // Convert datums if needed, and if possible.
        point = (0, datum_transform_1.default)(source.datum, dest.datum, point);
        if (!point) {
            return;
        }
        // Adjust for the prime meridian if necessary
        if (dest.from_greenwich) {
            point = {
                x: point.x - dest.from_greenwich,
                y: point.y,
                z: point.z || 0
            };
        }
        if (dest.projName === 'longlat') {
            // convert radians to decimal degrees
            point = {
                x: point.x * values_1.R2D,
                y: point.y * values_1.R2D,
                z: point.z || 0
            };
        }
        else { // else project
            point = dest.forward(point);
            if (dest.to_meter) {
                point = {
                    x: point.x / dest.to_meter,
                    y: point.y / dest.to_meter,
                    z: point.z || 0
                };
            }
        }
        // DGR, 2010/11/12
        if (enforceAxis && dest.axis !== 'enu') {
            return (0, adjust_axis_1.default)(dest, true, point);
        }
        if (point && !hasZ) {
            delete point.z;
        }
        return point;
    }
},
/* proj4/lib/datum_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    exports.applyGridShift = applyGridShift;
    const tslib_1 = require(1) /* tslib */;
    const values_1 = require(141) /* ./constants/values */;
    const datumUtils_1 = require(164) /* ./datumUtils */;
    const adjust_lon_1 = tslib_1.__importDefault(require(152) /* ./common/adjust_lon */);
    function checkParams(type) {
        return (type === values_1.PJD_3PARAM || type === values_1.PJD_7PARAM);
    }
    function default_1(source, dest, point) {
        // Short cut if the datums are identical.
        if ((0, datumUtils_1.compareDatums)(source, dest)) {
            return point; // in this case, zero is sucess,
            // whereas cs_compare_datums returns 1 to indicate TRUE
            // confusing, should fix this
        }
        // Explicitly skip datum transform by setting 'datum=none' as parameter for either source or dest
        if (source.datum_type === values_1.PJD_NODATUM || dest.datum_type === values_1.PJD_NODATUM) {
            return point;
        }
        // If this datum requires grid shifts, then apply it to geodetic coordinates.
        var source_a = source.a;
        var source_es = source.es;
        if (source.datum_type === values_1.PJD_GRIDSHIFT) {
            var gridShiftCode = applyGridShift(source, false, point);
            if (gridShiftCode !== 0) {
                return undefined;
            }
            source_a = values_1.SRS_WGS84_SEMIMAJOR;
            source_es = values_1.SRS_WGS84_ESQUARED;
        }
        var dest_a = dest.a;
        var dest_b = dest.b;
        var dest_es = dest.es;
        if (dest.datum_type === values_1.PJD_GRIDSHIFT) {
            dest_a = values_1.SRS_WGS84_SEMIMAJOR;
            dest_b = values_1.SRS_WGS84_SEMIMINOR;
            dest_es = values_1.SRS_WGS84_ESQUARED;
        }
        // Do we need to go through geocentric coordinates?
        if (source_es === dest_es && source_a === dest_a && !checkParams(source.datum_type) && !checkParams(dest.datum_type)) {
            return point;
        }
        // Convert to geocentric coordinates.
        point = (0, datumUtils_1.geodeticToGeocentric)(point, source_es, source_a);
        // Convert between datums
        if (checkParams(source.datum_type)) {
            point = (0, datumUtils_1.geocentricToWgs84)(point, source.datum_type, source.datum_params);
        }
        if (checkParams(dest.datum_type)) {
            point = (0, datumUtils_1.geocentricFromWgs84)(point, dest.datum_type, dest.datum_params);
        }
        point = (0, datumUtils_1.geocentricToGeodetic)(point, dest_es, dest_a, dest_b);
        if (dest.datum_type === values_1.PJD_GRIDSHIFT) {
            var destGridShiftResult = applyGridShift(dest, true, point);
            if (destGridShiftResult !== 0) {
                return undefined;
            }
        }
        return point;
    }
    function applyGridShift(source, inverse, point) {
        if (source.grids === null || source.grids.length === 0) {
            console.log('Grid shift grids not found');
            return -1;
        }
        var input = { x: -point.x, y: point.y };
        var output = { x: Number.NaN, y: Number.NaN };
        var onlyMandatoryGrids = false;
        var attemptedGrids = [];
        outer: for (var i = 0; i < source.grids.length; i++) {
            var grid = source.grids[i];
            attemptedGrids.push(grid.name);
            if (grid.isNull) {
                output = input;
                break;
            }
            onlyMandatoryGrids = grid.mandatory;
            if (grid.grid === null) {
                if (grid.mandatory) {
                    console.log("Unable to find mandatory grid '" + grid.name + "'");
                    return -1;
                }
                continue;
            }
            var subgrids = grid.grid.subgrids;
            for (var j = 0, jj = subgrids.length; j < jj; j++) {
                var subgrid = subgrids[j];
                // skip tables that don't match our point at all
                var epsilon = (Math.abs(subgrid.del[1]) + Math.abs(subgrid.del[0])) / 10000.0;
                var minX = subgrid.ll[0] - epsilon;
                var minY = subgrid.ll[1] - epsilon;
                var maxX = subgrid.ll[0] + (subgrid.lim[0] - 1) * subgrid.del[0] + epsilon;
                var maxY = subgrid.ll[1] + (subgrid.lim[1] - 1) * subgrid.del[1] + epsilon;
                if (minY > input.y || minX > input.x || maxY < input.y || maxX < input.x) {
                    continue;
                }
                output = applySubgridShift(input, inverse, subgrid);
                if (!isNaN(output.x)) {
                    break outer;
                }
            }
        }
        if (isNaN(output.x)) {
            console.log("Failed to find a grid shift table for location '" +
                -input.x * values_1.R2D + " " + input.y * values_1.R2D + " tried: '" + attemptedGrids + "'");
            return -1;
        }
        point.x = -output.x;
        point.y = output.y;
        return 0;
    }
    function applySubgridShift(pin, inverse, ct) {
        var val = { x: Number.NaN, y: Number.NaN };
        if (isNaN(pin.x)) {
            return val;
        }
        var tb = { x: pin.x, y: pin.y };
        tb.x -= ct.ll[0];
        tb.y -= ct.ll[1];
        tb.x = (0, adjust_lon_1.default)(tb.x - Math.PI) + Math.PI;
        var t = nadInterpolate(tb, ct);
        if (inverse) {
            if (isNaN(t.x)) {
                return val;
            }
            t.x = tb.x - t.x;
            t.y = tb.y - t.y;
            var i = 9, tol = 1e-12;
            var dif, del;
            do {
                del = nadInterpolate(t, ct);
                if (isNaN(del.x)) {
                    console.log("Inverse grid shift iteration failed, presumably at grid edge.  Using first approximation.");
                    break;
                }
                dif = { x: tb.x - (del.x + t.x), y: tb.y - (del.y + t.y) };
                t.x += dif.x;
                t.y += dif.y;
            } while (i-- && Math.abs(dif.x) > tol && Math.abs(dif.y) > tol);
            if (i < 0) {
                console.log("Inverse grid shift iterator failed to converge.");
                return val;
            }
            val.x = (0, adjust_lon_1.default)(t.x + ct.ll[0]);
            val.y = t.y + ct.ll[1];
        }
        else {
            if (!isNaN(t.x)) {
                val.x = pin.x + t.x;
                val.y = pin.y + t.y;
            }
        }
        return val;
    }
    function nadInterpolate(pin, ct) {
        var t = { x: pin.x / ct.del[0], y: pin.y / ct.del[1] };
        var indx = { x: Math.floor(t.x), y: Math.floor(t.y) };
        var frct = { x: t.x - 1.0 * indx.x, y: t.y - 1.0 * indx.y };
        var val = { x: Number.NaN, y: Number.NaN };
        var inx;
        if (indx.x < 0 || indx.x >= ct.lim[0]) {
            return val;
        }
        if (indx.y < 0 || indx.y >= ct.lim[1]) {
            return val;
        }
        inx = (indx.y * ct.lim[0]) + indx.x;
        var f00 = { x: ct.cvs[inx][0], y: ct.cvs[inx][1] };
        inx++;
        var f10 = { x: ct.cvs[inx][0], y: ct.cvs[inx][1] };
        inx += ct.lim[0];
        var f11 = { x: ct.cvs[inx][0], y: ct.cvs[inx][1] };
        inx--;
        var f01 = { x: ct.cvs[inx][0], y: ct.cvs[inx][1] };
        var m11 = frct.x * frct.y, m10 = frct.x * (1.0 - frct.y), m00 = (1.0 - frct.x) * (1.0 - frct.y), m01 = (1.0 - frct.x) * frct.y;
        val.x = (m00 * f00.x + m10 * f10.x + m01 * f01.x + m11 * f11.x);
        val.y = (m00 * f00.y + m10 * f10.y + m01 * f01.y + m11 * f11.y);
        return val;
    }
},
/* proj4/lib/datumUtils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.compareDatums = compareDatums;
    exports.geodeticToGeocentric = geodeticToGeocentric;
    exports.geocentricToGeodetic = geocentricToGeodetic;
    exports.geocentricToWgs84 = geocentricToWgs84;
    exports.geocentricFromWgs84 = geocentricFromWgs84;
    const values_1 = require(141) /* ./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()
    /*
     * 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()
    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()
    /****************************************************************/
    // 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
    /****************************************************************/
    // 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()
    }
},
/* proj4/lib/adjust_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    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;
    }
},
/* proj4/lib/common/toPoint.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    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;
    }
},
/* proj4/lib/checkSanity.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = default_1;
    function default_1(point) {
        checkCoord(point.x);
        checkCoord(point.y);
    }
    function checkCoord(num) {
        if (typeof Number.isFinite === 'function') {
            if (Number.isFinite(num)) {
                return;
            }
            throw new TypeError('coordinates must be finite numbers');
        }
        if (typeof num !== 'number' || num !== num || !isFinite(num)) {
            throw new TypeError('coordinates must be finite numbers');
        }
    }
},
/* models/annotations/arrow_head.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c, _d, _e;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const marking_1 = require(169) /* ../graphics/marking */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class ArrowHeadView extends marking_1.MarkingView {
    }
    exports.ArrowHeadView = ArrowHeadView;
    ArrowHeadView.__name__ = "ArrowHeadView";
    class ArrowHead extends marking_1.Marking {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ArrowHead = ArrowHead;
    _a = ArrowHead;
    ArrowHead.__name__ = "ArrowHead";
    (() => {
        _a.define(() => ({
            size: [p.NumberSpec, 25],
        }));
    })();
    class OpenHeadView extends ArrowHeadView {
        clip(ctx, i) {
            this.visuals.line.set_vectorize(ctx, i);
            const size_i = this.size.get(i);
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.lineTo(0, 0);
            ctx.lineTo(0.5 * size_i, size_i);
        }
        paint(ctx, i) {
            const size_i = this.size.get(i);
            ctx.beginPath();
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0, 0);
            ctx.lineTo(-0.5 * size_i, size_i);
            this.visuals.line.apply(ctx, i);
        }
    }
    exports.OpenHeadView = OpenHeadView;
    OpenHeadView.__name__ = "OpenHeadView";
    class OpenHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.OpenHead = OpenHead;
    _b = OpenHead;
    OpenHead.__name__ = "OpenHead";
    (() => {
        _b.prototype.default_view = OpenHeadView;
        _b.mixins(property_mixins_1.LineVector);
    })();
    class NormalHeadView extends ArrowHeadView {
        clip(ctx, i) {
            this.visuals.line.set_vectorize(ctx, i);
            const size_i = this.size.get(i);
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.lineTo(0.5 * size_i, size_i);
        }
        paint(ctx, i) {
            const size_i = this.size.get(i);
            ctx.beginPath();
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0, 0);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.closePath();
            this.visuals.fill.apply(ctx, i);
            this.visuals.line.apply(ctx, i);
        }
    }
    exports.NormalHeadView = NormalHeadView;
    NormalHeadView.__name__ = "NormalHeadView";
    class NormalHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.NormalHead = NormalHead;
    _c = NormalHead;
    NormalHead.__name__ = "NormalHead";
    (() => {
        _c.prototype.default_view = NormalHeadView;
        _c.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector]);
        _c.override({
            fill_color: "black",
        });
    })();
    class VeeHeadView extends ArrowHeadView {
        clip(ctx, i) {
            this.visuals.line.set_vectorize(ctx, i);
            const size_i = this.size.get(i);
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, -2);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.lineTo(0, 0.5 * size_i);
            ctx.lineTo(0.5 * size_i, size_i);
        }
        paint(ctx, i) {
            const size_i = this.size.get(i);
            ctx.beginPath();
            ctx.moveTo(0.5 * size_i, size_i);
            ctx.lineTo(0, 0);
            ctx.lineTo(-0.5 * size_i, size_i);
            ctx.lineTo(0, 0.5 * size_i);
            ctx.closePath();
            this.visuals.fill.apply(ctx, i);
            this.visuals.line.apply(ctx, i);
        }
    }
    exports.VeeHeadView = VeeHeadView;
    VeeHeadView.__name__ = "VeeHeadView";
    class VeeHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VeeHead = VeeHead;
    _d = VeeHead;
    VeeHead.__name__ = "VeeHead";
    (() => {
        _d.prototype.default_view = VeeHeadView;
        _d.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector]);
        _d.override({
            fill_color: "black",
        });
    })();
    class TeeHeadView extends ArrowHeadView {
        paint(ctx, i) {
            const size_i = this.size.get(i);
            ctx.beginPath();
            ctx.moveTo(0.5 * size_i, 0);
            ctx.lineTo(-0.5 * size_i, 0);
            this.visuals.line.apply(ctx, i);
        }
        clip(_ctx, _i) { }
    }
    exports.TeeHeadView = TeeHeadView;
    TeeHeadView.__name__ = "TeeHeadView";
    class TeeHead extends ArrowHead {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TeeHead = TeeHead;
    _e = TeeHead;
    TeeHead.__name__ = "TeeHead";
    (() => {
        _e.prototype.default_view = TeeHeadView;
        _e.mixins(property_mixins_1.LineVector);
    })();
},
/* models/graphics/marking.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(51) /* ../../model */;
    const dom_view_1 = require(57) /* ../../core/dom_view */;
    const visuals = tslib_1.__importStar(require(87) /* ../../core/visuals */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class MarkingView extends dom_view_1.DOMComponentView {
        initialize() {
            super.initialize();
            this.visuals = new visuals.Visuals(this);
        }
        request_paint() {
            this.parent.request_paint();
        }
        get canvas() {
            return this.parent.canvas;
        }
        set_data(source, indices) {
            const self = this;
            for (const prop of this.model) {
                if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec)) {
                    continue;
                }
                const uniform = prop.uniform(source).select(indices);
                self[`${prop.attr}`] = uniform;
            }
        }
    }
    exports.MarkingView = MarkingView;
    MarkingView.__name__ = "MarkingView";
    class Marking extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Marking = Marking;
    _a = Marking;
    Marking.__name__ = "Marking";
    (() => {
        _a.define(({}) => ({}));
    })();
},
/* models/annotations/base_color_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(81) /* ./annotation */;
    const title_1 = require(171) /* ./title */;
    const cartesian_frame_1 = require(188) /* ../canvas/cartesian_frame */;
    const axis_1 = require(189) /* ../axes/axis */;
    const linear_axis_1 = require(194) /* ../axes/linear_axis */;
    const ticker_1 = require(191) /* ../tickers/ticker */;
    const tickers_1 = require(200) /* ../tickers */;
    const tick_formatter_1 = require(192) /* ../formatters/tick_formatter */;
    const formatters_1 = require(242) /* ../formatters */;
    const labeling_1 = require(193) /* ../policies/labeling */;
    const scales_1 = require(254) /* ../scales */;
    const ranges_1 = require(256) /* ../ranges */;
    const base_text_1 = require(176) /* ../text/base_text */;
    const enums_1 = require(20) /* ../../core/enums */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const layout_1 = require(257) /* ../../core/layout */;
    const alignments_1 = require(258) /* ../../core/layout/alignments */;
    const border_1 = require(260) /* ../../core/layout/border */;
    const side_panel_1 = require(173) /* ../../core/layout/side_panel */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    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 BaseColorBarView extends annotation_1.AnnotationView {
        get orientation() {
            return this._orientation;
        }
        *children() {
            yield* super.children();
            yield this._axis_view;
            yield this._title_view;
        }
        initialize() {
            super.initialize();
            const { ticker, formatter } = this.model;
            this._ticker = ticker != "auto" ? ticker : this._create_ticker();
            this._formatter = formatter != "auto" ? formatter : this._create_formatter();
            this._major_range = this._create_major_range();
            this._major_scale = this._create_major_scale();
            this._minor_range = new ranges_1.Range1d({ start: 0, end: 1 });
            this._minor_scale = new scales_1.LinearScale();
            // configure some frame, update when the layout is known
            this._frame = new cartesian_frame_1.CartesianFrame({
                x_scale: this._major_scale,
                y_scale: this._minor_scale,
                x_range: this._major_range,
                y_range: this._minor_range,
            });
            this._axis = this._create_axis();
            this._apply_axis_properties();
            this._title = new title_1.Title();
            this._apply_title_properties();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const self = this;
            const parent = {
                get parent() {
                    return self.parent;
                },
                get root() {
                    return self.root;
                },
                get frame() {
                    return self._frame_view;
                },
                get frame_view() {
                    return self._frame_view;
                },
                get canvas_view() {
                    return self.parent.canvas_view;
                },
                request_layout() {
                    // force re-layout; not ideal but ColorBar's layout doesn't fully
                    // participate in has_size_changed to detect if layout is needed
                    self.layout.dirty = true;
                    self.parent.request_layout();
                },
                request_paint() {
                    self.parent.request_paint(self);
                },
                notify_finished_after_paint() {
                    self.parent.notify_finished_after_paint();
                },
            };
            this._frame_view = await (0, build_views_1.build_view)(this._frame, { parent });
            this._axis_view = await (0, build_views_1.build_view)(this._axis, { parent });
            this._title_view = await (0, build_views_1.build_view)(this._title, { parent });
        }
        remove() {
            this._title_view.remove();
            this._axis_view.remove();
            super.remove();
        }
        _apply_axis_properties() {
            const attrs = {
                ticker: this._ticker,
                formatter: this._formatter,
                major_label_standoff: this.model.label_standoff,
                axis_line_color: null,
                major_tick_in: this.model.major_tick_in,
                major_tick_out: this.model.major_tick_out,
                minor_tick_in: this.model.minor_tick_in,
                minor_tick_out: this.model.minor_tick_out,
                major_label_overrides: this.model.major_label_overrides,
                major_label_policy: this.model.major_label_policy,
                // TODO: this needs strict typing
                ...mixins.attrs_of(this.model, "major_label_", mixins.Text, true),
                ...mixins.attrs_of(this.model, "major_tick_", mixins.Line, true),
                ...mixins.attrs_of(this.model, "minor_tick_", mixins.Line, true),
            };
            this._axis.setv(attrs);
        }
        _apply_title_properties() {
            const attrs = {
                text: this.model.title ?? "",
                standoff: this.model.title_standoff,
                // TODO: this needs strict typing
                ...mixins.attrs_of(this.model, "title_", mixins.Text, false),
            };
            this._title.setv(attrs);
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => {
                this._apply_title_properties();
                this._apply_axis_properties();
                // TODO?: this.plot_view.invalidate_layout()
            });
            this.connect(this._ticker.change, () => this.request_paint());
            this.connect(this._formatter.change, () => this.request_paint());
        }
        _update_frame() {
            const [x_scale, y_scale, x_range, y_range] = (() => {
                if (this.orientation == "horizontal") {
                    return [this._major_scale, this._minor_scale, this._major_range, this._minor_range];
                }
                else {
                    return [this._minor_scale, this._major_scale, this._minor_range, this._major_range];
                }
            })();
            this._frame.setv({ x_scale, y_scale, x_range, y_range });
        }
        update_layout() {
            const { location, width: w, height: h, padding, margin } = this.model;
            const [valign, halign] = (() => {
                if ((0, types_1.isString)(location)) {
                    switch (location) {
                        case "top_left":
                            return ["start", "start"];
                        case "top":
                        case "top_center":
                            return ["start", "center"];
                        case "top_right":
                            return ["start", "end"];
                        case "bottom_left":
                            return ["end", "start"];
                        case "bottom":
                        case "bottom_center":
                            return ["end", "center"];
                        case "bottom_right":
                            return ["end", "end"];
                        case "left":
                        case "center_left":
                            return ["center", "start"];
                        case "center":
                        case "center_center":
                            return ["center", "center"];
                        case "right":
                        case "center_right":
                            return ["center", "end"];
                    }
                }
                else {
                    return ["end", "start"];
                } // "bottom_left"
            })();
            const orientation = this._orientation = (() => {
                const { orientation } = this.model;
                if (orientation == "auto") {
                    if (this.panel != null) {
                        return this.panel.is_horizontal ? "horizontal" : "vertical";
                    }
                    else {
                        if (halign == "start" || halign == "end" || ( /*halign == "center" &&*/valign == "center")) {
                            return "vertical";
                        }
                        else {
                            return "horizontal";
                        }
                    }
                }
                else {
                    return orientation;
                }
            })();
            this._update_frame();
            const center_panel = new alignments_1.NodeLayout();
            const top_panel = new alignments_1.VStack();
            const bottom_panel = new alignments_1.VStack();
            const left_panel = new alignments_1.HStack();
            const right_panel = new alignments_1.HStack();
            center_panel.absolute = true;
            top_panel.absolute = true;
            bottom_panel.absolute = true;
            left_panel.absolute = true;
            right_panel.absolute = true;
            center_panel.on_resize((bbox) => this._frame_view.set_geometry(bbox));
            const layout = new border_1.BorderLayout();
            this._inner_layout = layout;
            layout.absolute = true;
            layout.center_panel = center_panel;
            layout.top_panel = top_panel;
            layout.bottom_panel = bottom_panel;
            layout.left_panel = left_panel;
            layout.right_panel = right_panel;
            const padding_box = { left: padding, right: padding, top: padding, bottom: padding };
            const margin_box = (() => {
                if (this.panel == null) {
                    if ((0, types_1.isString)(location)) {
                        return { left: margin, right: margin, top: margin, bottom: margin };
                    }
                    else {
                        const [left, bottom] = location;
                        return { left, right: margin, top: margin, bottom };
                    }
                }
                else {
                    /**
                     * XXX: alignment is broken in Grid, which is used to govern positioning of a ColorBar
                     * in side panels. Earlier attempts at fixing this failed and resulted in a multitude
                     * or regressions in various places in the layout. So instead of this, let's assume that
                     * the positioning is always at "start" regardless of configuration, and fix this here
                     * by manually computing "center" and "end" alignment.
                     */
                    if ((0, types_1.isString)(location)) {
                        layout.fixup_geometry = (outer, inner) => {
                            const origin = outer;
                            if (orientation == "horizontal") {
                                const { top, width, height } = outer;
                                if (halign == "end") {
                                    const { right } = this.layout.bbox;
                                    outer = new bbox_1.BBox({ right, top, width, height });
                                }
                                else if (halign == "center") {
                                    const { hcenter } = this.layout.bbox;
                                    outer = new bbox_1.BBox({ hcenter: Math.round(hcenter), top, width, height });
                                }
                            }
                            else {
                                const { left, width, height } = outer;
                                if (valign == "end") {
                                    const { bottom } = this.layout.bbox;
                                    outer = new bbox_1.BBox({ left, bottom, width, height });
                                }
                                else if (valign == "center") {
                                    const { vcenter } = this.layout.bbox;
                                    outer = new bbox_1.BBox({ left, vcenter: Math.round(vcenter), width, height });
                                }
                            }
                            if (inner != null) {
                                const dh = outer.left - origin.left;
                                const dv = outer.top - origin.top;
                                const { left, top, width, height } = inner;
                                inner = new bbox_1.BBox({ left: left + dh, top: top + dv, width, height });
                            }
                            return [outer, inner];
                        };
                        return undefined;
                    }
                    else {
                        const [left, bottom] = location;
                        layout.fixup_geometry = (outer, inner) => {
                            const origin = outer;
                            const grid = this.layout.bbox;
                            const { width, height } = outer;
                            outer = new bbox_1.BBox({ left: grid.left + left, bottom: grid.bottom - bottom, width, height });
                            if (inner != null) {
                                const dh = outer.left - origin.left;
                                const dv = outer.top - origin.top;
                                const { left, top, width, height } = inner;
                                inner = new bbox_1.BBox({ left: left + dh, top: top + dv, width, height });
                            }
                            return [outer, inner];
                        };
                        return { left, right: 0, top: 0, bottom };
                    }
                }
            })();
            layout.padding = padding_box;
            let major_policy;
            let major_size;
            let min_major_size;
            let max_major_size;
            if (this.panel != null) {
                major_policy = "max";
                major_size = undefined;
                min_major_size = undefined;
                max_major_size = undefined;
            }
            else {
                if ((orientation == "horizontal" ? w : h) == "auto") {
                    major_policy = "fixed";
                    const major_size_factor = this._get_major_size_factor();
                    if (major_size_factor != null) {
                        major_size = major_size_factor * MINOR_DIM;
                    }
                    min_major_size = { percent: MAJOR_DIM_MIN_SCALAR };
                    max_major_size = { percent: MAJOR_DIM_MAX_SCALAR };
                }
                else {
                    major_policy = "fit";
                    major_size = undefined;
                }
            }
            if (orientation == "horizontal") {
                const width = w == "auto" ? undefined : w;
                const height = h == "auto" ? MINOR_DIM : h;
                layout.set_sizing({
                    width_policy: major_policy, height_policy: "min",
                    width: major_size, min_width: min_major_size, max_width: max_major_size,
                    halign, valign, margin: margin_box,
                });
                layout.center_panel.set_sizing({ width_policy: w == "auto" ? "fit" : "fixed", height_policy: "fixed", width, height });
            }
            else {
                const width = w == "auto" ? MINOR_DIM : w;
                const height = h == "auto" ? undefined : h;
                layout.set_sizing({
                    width_policy: "min", height_policy: major_policy,
                    height: major_size, min_height: min_major_size, max_height: max_major_size,
                    halign, valign, margin: margin_box,
                });
                layout.center_panel.set_sizing({ width_policy: "fixed", height_policy: h == "auto" ? "fit" : "fixed", width, height });
            }
            top_panel.set_sizing({ width_policy: "fit", height_policy: "min" });
            bottom_panel.set_sizing({ width_policy: "fit", height_policy: "min" });
            left_panel.set_sizing({ width_policy: "min", height_policy: "fit" });
            right_panel.set_sizing({ width_policy: "min", height_policy: "fit" });
            const { _title_view } = this;
            if (orientation == "horizontal") {
                _title_view.panel = new side_panel_1.SidePanel("above");
                _title_view.update_layout();
                top_panel.children.push(_title_view.layout);
            }
            else {
                _title_view.panel = new side_panel_1.SidePanel("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.SidePanel(side);
            _axis_view.update_layout();
            if (_axis_view.layout != null) {
                stack.children.push(_axis_view.layout);
            }
            if (this.panel != null) {
                const outer = new layout_1.Grid([{ layout, row: 0, col: 0 }]);
                outer.absolute = true;
                if (orientation == "horizontal") {
                    outer.set_sizing({ width_policy: "max", height_policy: "min" });
                }
                else {
                    outer.set_sizing({ width_policy: "min", height_policy: "max" });
                }
                this.layout = outer;
            }
            else {
                this.layout = this._inner_layout;
            }
            const { visible } = this.model;
            this.layout.sizing.visible = visible;
        }
        _create_axis() {
            return new linear_axis_1.LinearAxis();
        }
        _create_formatter() {
            return new formatters_1.BasicTickFormatter();
        }
        _create_major_range() {
            return new ranges_1.Range1d({ start: 0, end: 1 });
        }
        _create_major_scale() {
            return new scales_1.LinearScale();
        }
        _create_ticker() {
            return new tickers_1.BasicTicker();
        }
        _get_major_size_factor() {
            return null;
        }
        _paint() {
            const { ctx } = this.layer;
            ctx.save();
            this._paint_bbox(ctx, this._inner_layout.bbox);
            this._paint_colors(ctx, this._inner_layout.center_panel.bbox);
            this._title_view.paint();
            this._axis_view.paint();
            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();
        }
    }
    exports.BaseColorBarView = BaseColorBarView;
    BaseColorBarView.__name__ = "BaseColorBarView";
    class BaseColorBar extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.BaseColorBar = BaseColorBar;
    _a = BaseColorBar;
    BaseColorBar.__name__ = "BaseColorBar";
    (() => {
        _a.mixins([
            ["major_label_", mixins.Text],
            ["title_", mixins.Text],
            ["major_tick_", mixins.Line],
            ["minor_tick_", mixins.Line],
            ["border_", mixins.Line],
            ["bar_", mixins.Line],
            ["background_", mixins.Fill],
        ]);
        _a.define(({ Alpha, Float, Str, Tuple, Or, Ref, Auto, Nullable }) => ({
            location: [Or(enums_1.Anchor, Tuple(Float, Float)), "top_right"],
            orientation: [Or(enums_1.Orientation, Auto), "auto"],
            title: [Nullable(Or(Str, Ref(base_text_1.BaseText))), null],
            title_standoff: [Float, 2],
            width: [Or(Float, Auto), "auto"],
            height: [Or(Float, 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: [axis_1.LabelOverrides, new Map()],
            major_label_policy: [Ref(labeling_1.LabelingPolicy), () => new labeling_1.NoOverlap()],
            label_standoff: [Float, 5],
            margin: [Float, 30],
            padding: [Float, 10],
            major_tick_in: [Float, 5],
            major_tick_out: [Float, 0],
            minor_tick_in: [Float, 0],
            minor_tick_out: [Float, 0],
        }));
        _a.override({
            background_fill_color: "#ffffff",
            background_fill_alpha: 0.95,
            bar_line_color: null,
            border_line_color: null,
            major_label_text_font_size: "11px",
            major_tick_line_color: "#ffffff",
            minor_tick_line_color: null,
            title_text_font_size: "13px",
            title_text_font_style: "italic",
        });
    })();
},
/* models/annotations/title.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const text_annotation_1 = require(172) /* ./text_annotation */;
    const enums_1 = require(20) /* ../../core/enums */;
    const resolve = tslib_1.__importStar(require(186) /* ../common/resolve */);
    class TitleView extends text_annotation_1.TextAnnotationView {
        _get_position() {
            const hmargin = this.model.offset;
            const vmargin = this.model.standoff / 2;
            const { align, vertical_align } = this.model;
            let sx, sy;
            const { bbox } = this.layout;
            switch (this.panel.side) {
                case "above":
                case "below": {
                    switch (vertical_align) {
                        case "top":
                            sy = bbox.top + vmargin;
                            break;
                        case "middle":
                            sy = bbox.vcenter;
                            break;
                        case "bottom":
                            sy = bbox.bottom - vmargin;
                            break;
                    }
                    switch (align) {
                        case "left":
                            sx = bbox.left + hmargin;
                            break;
                        case "center":
                            sx = bbox.hcenter;
                            break;
                        case "right":
                            sx = bbox.right - hmargin;
                            break;
                    }
                    break;
                }
                case "left": {
                    switch (vertical_align) {
                        case "top":
                            sx = bbox.left + vmargin;
                            break;
                        case "middle":
                            sx = bbox.hcenter;
                            break;
                        case "bottom":
                            sx = bbox.right - vmargin;
                            break;
                    }
                    switch (align) {
                        case "left":
                            sy = bbox.bottom - hmargin;
                            break;
                        case "center":
                            sy = bbox.vcenter;
                            break;
                        case "right":
                            sy = bbox.top + hmargin;
                            break;
                    }
                    break;
                }
                case "right": {
                    switch (vertical_align) {
                        case "top":
                            sx = bbox.right - vmargin;
                            break;
                        case "middle":
                            sx = bbox.hcenter;
                            break;
                        case "bottom":
                            sx = bbox.left + vmargin;
                            break;
                    }
                    switch (align) {
                        case "left":
                            sy = bbox.top + hmargin;
                            break;
                        case "center":
                            sy = bbox.vcenter;
                            break;
                        case "right":
                            sy = bbox.bottom - hmargin;
                            break;
                    }
                    break;
                }
            }
            return { sx, sy };
        }
        get anchor() {
            const { align, vertical_align } = this.model;
            return resolve.text_anchor("auto", align, vertical_align);
        }
        get origin() {
            return this._get_position();
        }
        get angle() {
            return this.panel.get_label_angle_heuristic("parallel");
        }
        _get_size() {
            const offset = (value) => {
                // 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 value == 0 ? 0 : 2 + value + this.model.standoff;
            };
            const { width, height } = super._get_size();
            if (this.panel.is_horizontal) {
                return { width, height: offset(height) };
            }
            else {
                return { width: offset(width), height };
            }
        }
    }
    exports.TitleView = TitleView;
    TitleView.__name__ = "TitleView";
    class Title extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Title = Title;
    _a = Title;
    Title.__name__ = "Title";
    (() => {
        _a.prototype.default_view = TitleView;
        _a.define(({ Float }) => ({
            vertical_align: [enums_1.VerticalAlign, "bottom"],
            align: [enums_1.TextAlign, "left"],
            offset: [Float, 0],
            standoff: [Float, 10],
        }));
        _a.override({
            text_font_size: "13px",
            text_font_style: "bold",
            text_line_height: 1.0,
        });
    })();
},
/* models/annotations/text_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(81) /* ./annotation */;
    const side_panel_1 = require(173) /* ../../core/layout/side_panel */;
    const base_text_1 = require(176) /* ../text/base_text */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const types_1 = require(8) /* ../../core/util/types */;
    const utils_1 = require(177) /* ../text/utils */;
    const kinds_1 = require(185) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(186) /* ../common/resolve */);
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const painting_1 = require(187) /* ../common/painting */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    class TextAnnotationView extends annotation_1.AnnotationView {
        *children() {
            yield* super.children();
            yield this._text_view;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._init_text();
        }
        async _init_text() {
            const { text } = this.model;
            const _text = (0, types_1.isString)(text) ? (0, utils_1.parse_delimited_string)(text) : text;
            this._text_view = await (0, build_views_1.build_view)(_text, { parent: this });
        }
        update_layout() {
            const { panel } = this;
            if (panel != null) {
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size(), false);
            }
            else {
                this.layout = undefined;
            }
        }
        connect_signals() {
            super.connect_signals();
            const { text } = this.model.properties;
            this.on_change(text, async () => {
                this._text_view.remove();
                await this._init_text();
            });
            this.connect(this.model.change, () => this.request_paint());
        }
        remove() {
            this._text_view.remove();
            super.remove();
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            if (!this._text_view.has_finished()) {
                return false;
            }
            return true;
        }
        get displayed() {
            return super.displayed && this._text_view.model.text != "" && this.visuals.text.doit;
        }
        get padding() {
            return resolve.padding(this.model.padding);
        }
        get border_radius() {
            return resolve.border_radius(this.model.border_radius);
        }
        _get_size() {
            if (!this.displayed) {
                return { width: 0, height: 0 };
            }
            const graphics = this._text_view.graphics();
            graphics.angle = this.angle;
            graphics.align = "auto";
            graphics.visuals = this.visuals.text.values();
            const size = graphics.size();
            const { padding } = this;
            const width = size.width + padding.left + padding.right;
            const height = size.height + padding.top + padding.bottom;
            return { width, height };
        }
        compute_geometry() {
            super.compute_geometry();
            const text_box = this._text_view.graphics();
            text_box.position = { sx: 0, sy: 0, x_anchor: "left", y_anchor: "top" };
            text_box.angle = 0; // needs reset because text_box is self-referential
            text_box.align = "auto";
            text_box.visuals = this.visuals.text.values();
            const size = text_box.size();
            const { sx, sy } = this.origin;
            const { anchor, padding, border_radius, angle } = this;
            const width = size.width + padding.left + padding.right;
            const height = size.height + padding.top + padding.bottom;
            this._text_box = text_box;
            this._rect = { sx, sy, width, height, angle, anchor, padding, border_radius };
        }
        _paint() {
            const { ctx } = this.layer;
            const { sx, sy, width, height, angle, anchor, padding, border_radius } = this._rect;
            const label = this._text_box;
            const dx = anchor.x * width;
            const dy = anchor.y * height;
            ctx.translate(sx, sy);
            ctx.rotate(angle);
            ctx.translate(-dx, -dy);
            const { background_fill, background_hatch, border_line, text } = this.visuals;
            if (background_fill.doit || background_hatch.doit || border_line.doit) {
                ctx.beginPath();
                const bbox = new bbox_1.BBox({ x: 0, y: 0, width, height });
                (0, painting_1.round_rect)(ctx, bbox, border_radius);
                background_fill.apply(ctx);
                background_hatch.apply(ctx);
                border_line.apply(ctx);
            }
            if (text.doit) {
                const { left, top } = padding;
                ctx.translate(left, top);
                label.paint(ctx);
                ctx.translate(-left, -top);
            }
            ctx.translate(dx, dy);
            ctx.rotate(-angle);
            ctx.translate(-sx, -sy);
        }
    }
    exports.TextAnnotationView = TextAnnotationView;
    TextAnnotationView.__name__ = "TextAnnotationView";
    class TextAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TextAnnotation = TextAnnotation;
    _a = TextAnnotation;
    TextAnnotation.__name__ = "TextAnnotation";
    (() => {
        _a.mixins([
            mixins.Text,
            ["border_", mixins.Line],
            ["background_", mixins.Fill],
            ["background_", mixins.Hatch],
        ]);
        _a.define(({ Str, Or, Ref }) => ({
            text: [Or(Str, Ref(base_text_1.BaseText)), ""],
            padding: [kinds_1.Padding, 0],
            border_radius: [kinds_1.BorderRadius, 0],
        }));
        _a.override({
            border_line_color: null,
            background_fill_color: null,
            background_hatch_color: null,
        });
    })();
},
/* core/layout/side_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(174) /* ./types */;
    const layoutable_1 = require(175) /* ./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 SidePanel {
        constructor(side, face) {
            this.side = side;
            this.face = (() => {
                if (face != null && face != "auto") {
                    return face;
                }
                else {
                    switch (this.side) {
                        case "left":
                        case "above":
                            return "front";
                        case "right":
                        case "below":
                            return "back";
                    }
                }
            })();
            this.dimension = this.side == "above" || this.side == "below" ? 0 : 1;
            this.orientation = this.dimension == 0 ? "horizontal" : "vertical";
            this.is_horizontal = this.dimension == 0;
            this.is_vertical = this.dimension == 1;
            this.normals = (() => {
                const sign = this.face == "front" ? -1 : 1;
                switch (this.side) {
                    case "left": return [sign, 0];
                    case "right": return [sign, 0];
                    case "above": return [0, sign];
                    case "below": return [0, sign];
                }
            })();
        }
        get face_adjusted_side() {
            const { side, face } = this;
            switch (side) {
                case "left":
                case "right":
                    return face == "front" ? "left" : "right";
                case "above":
                case "below":
                    return face == "front" ? "above" : "below";
            }
        }
        get_label_text_heuristics(orient) {
            const side = this.face_adjusted_side;
            if ((0, types_2.isString)(orient)) {
                return {
                    vertical_align: _vertical_align_lookup[side][orient],
                    align: _align_lookup[side][orient],
                };
            }
            else {
                return {
                    vertical_align: "center",
                    align: (orient < 0 ? _align_lookup_negative : _align_lookup_positive)[side],
                };
            }
        }
        get_label_angle_heuristic(orient) {
            if ((0, types_2.isString)(orient)) {
                const side = this.face_adjusted_side;
                return _angle_lookup[side][orient];
            }
            else {
                return -orient;
            }
        }
    }
    exports.SidePanel = SidePanel;
    SidePanel.__name__ = "SidePanel";
    class SideLayout extends layoutable_1.ContentLayoutable {
        constructor(panel, get_size, rotate = false) {
            super();
            this.panel = panel;
            this.get_size = get_size;
            this.rotate = rotate;
            if (this.panel.is_horizontal) {
                this.set_sizing({ width_policy: "max", height_policy: "fixed" });
            }
            else {
                this.set_sizing({ width_policy: "fixed", height_policy: "max" });
            }
        }
        _content_size() {
            const { width, height } = this.get_size();
            if (!this.rotate || this.panel.is_horizontal) {
                return new types_1.Sizeable({ width, height });
            }
            else {
                return new types_1.Sizeable({ width: height, height: width });
            }
        }
        has_size_changed() {
            const { width, height } = this._content_size();
            if (this.panel.is_horizontal) {
                return this.bbox.height != height;
            }
            else {
                return this.bbox.width != width;
            }
        }
    }
    exports.SideLayout = SideLayout;
    SideLayout.__name__ = "SideLayout";
},
/* core/layout/types.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const kinds_1 = require(21) /* ../kinds */;
    const { min, max } = Math;
    class Sizeable {
        constructor(size = {}) {
            this.width = size.width != null ? size.width : 0;
            this.height = size.height != null ? size.height : 0;
        }
        bounded_to({ width, height }) {
            return new Sizeable({
                width: this.width == Infinity && width != null ? width : this.width,
                height: this.height == Infinity && height != null ? height : this.height,
            });
        }
        expanded_to({ width, height }) {
            return new Sizeable({
                width: width != Infinity ? max(this.width, width) : this.width,
                height: height != Infinity ? max(this.height, height) : this.height,
            });
        }
        expand_to({ width, height }) {
            this.width = max(this.width, width);
            this.height = max(this.height, height);
        }
        narrowed_to({ width, height }) {
            return new Sizeable({
                width: min(this.width, width),
                height: min(this.height, height),
            });
        }
        narrow_to({ width, height }) {
            this.width = min(this.width, width);
            this.height = min(this.height, height);
        }
        grow_by({ left, right, top, bottom }) {
            const width = this.width + left + right;
            const height = this.height + top + bottom;
            return new Sizeable({ width, height });
        }
        shrink_by({ left, right, top, bottom }) {
            const width = max(this.width - left - right, 0);
            const height = max(this.height - top - bottom, 0);
            return new Sizeable({ width, height });
        }
        map(w_fn, h_fn) {
            return new Sizeable({
                width: w_fn(this.width),
                height: (h_fn != null ? h_fn : w_fn)(this.height),
            });
        }
    }
    exports.Sizeable = Sizeable;
    Sizeable.__name__ = "Sizeable";
    exports.SizingPolicy = (0, kinds_1.Enum)("fixed", "fit", "min", "max");
},
/* core/layout/layoutable.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(174) /* ./types */;
    const bbox_1 = require(64) /* ../util/bbox */;
    const types_2 = require(8) /* ../util/types */;
    const assert_1 = require(12) /* ../util/assert */;
    const { abs, min, max, round } = Math;
    class Layoutable {
        constructor() {
            this.absolute = false;
            this.position = { left: 0, top: 0 };
            this._bbox = new bbox_1.BBox();
            this._inner_bbox = new bbox_1.BBox();
            this._sizing = null;
            this._dirty = false;
            this._handlers = [];
        }
        *[Symbol.iterator]() { }
        get bbox() {
            return this._bbox;
        }
        get inner_bbox() {
            return this._inner_bbox;
        }
        get sizing() {
            (0, assert_1.assert)(this._sizing != null);
            return this._sizing;
        }
        set dirty(dirty) {
            this._dirty = dirty;
        }
        get dirty() {
            return this._dirty;
        }
        get visible() {
            return this.sizing.visible;
        }
        set visible(visible) {
            if (this.sizing.visible != visible) {
                this.sizing.visible = visible;
                this._dirty = true;
            }
        }
        set_sizing(sizing = {}) {
            const width_policy = sizing.width_policy ?? "fit";
            const width = sizing.width;
            const min_width = sizing.min_width;
            const max_width = sizing.max_width;
            const height_policy = sizing.height_policy ?? "fit";
            const height = sizing.height;
            const min_height = sizing.min_height;
            const max_height = sizing.max_height;
            const aspect = sizing.aspect;
            const margin = sizing.margin ?? { top: 0, right: 0, bottom: 0, left: 0 };
            const visible = sizing.visible ?? true;
            const halign = sizing.halign ?? "start";
            const valign = sizing.valign ?? "start";
            this._sizing = {
                width_policy, min_width, width, max_width,
                height_policy, min_height, height, max_height,
                aspect,
                margin,
                visible,
                halign,
                valign,
                size: { width, height },
            };
            this._init();
        }
        _init() { }
        _set_geometry(outer, inner) {
            this._bbox = outer;
            this._inner_bbox = inner;
        }
        set_geometry(outer, inner) {
            const { fixup_geometry } = this;
            if (fixup_geometry != null) {
                [outer, inner] = fixup_geometry(outer, inner);
            }
            this._set_geometry(outer, inner ?? outer);
            for (const handler of this._handlers) {
                handler(this._bbox, this._inner_bbox);
            }
        }
        on_resize(handler) {
            this._handlers.push(handler);
        }
        is_width_expanding() {
            return this.sizing.width_policy == "max";
        }
        is_height_expanding() {
            return this.sizing.height_policy == "max";
        }
        apply_aspect(viewport, { width, height }) {
            const { aspect } = this.sizing;
            if (aspect != null) {
                const { width_policy, height_policy } = this.sizing;
                const gt = (width, height) => {
                    const policies = { max: 4, fit: 3, min: 2, fixed: 1 };
                    return policies[width] > policies[height];
                };
                if (width_policy != "fixed" && height_policy != "fixed") {
                    if (width_policy == height_policy) {
                        const w_width = width;
                        const w_height = round(width / aspect);
                        const h_width = round(height * aspect);
                        const h_height = height;
                        const w_diff = abs(viewport.width - w_width) + abs(viewport.height - w_height);
                        const h_diff = abs(viewport.width - h_width) + abs(viewport.height - h_height);
                        if (w_diff <= h_diff) {
                            width = w_width;
                            height = w_height;
                        }
                        else {
                            width = h_width;
                            height = h_height;
                        }
                    }
                    else if (gt(width_policy, height_policy)) {
                        height = round(width / aspect);
                    }
                    else {
                        width = round(height * aspect);
                    }
                }
                else if (width_policy == "fixed") {
                    height = round(width / aspect);
                }
                else if (height_policy == "fixed") {
                    width = round(height * aspect);
                }
            }
            return { width, height };
        }
        measure(viewport_size) {
            if (this._sizing == null) {
                this.set_sizing();
            }
            if (!this.sizing.visible) {
                return { width: 0, height: 0 };
            }
            const exact_width = (width) => {
                return this.sizing.width_policy == "fixed" && this.sizing.width != null ? this.sizing.width : width;
            };
            const exact_height = (height) => {
                return this.sizing.height_policy == "fixed" && this.sizing.height != null ? this.sizing.height : height;
            };
            const viewport = new types_1.Sizeable(viewport_size)
                .shrink_by(this.sizing.margin)
                .map(exact_width, exact_height);
            const computed = this._measure(viewport);
            const clipped = this.clip_size(computed, viewport);
            const width = exact_width(clipped.width);
            const height = exact_height(clipped.height);
            const size = this.apply_aspect(viewport, { width, height });
            return { ...computed, ...size };
        }
        compute(viewport = {}) {
            const size_hint = this.measure({
                width: viewport.width != null && this.is_width_expanding() ? viewport.width : Infinity,
                height: viewport.height != null && this.is_height_expanding() ? viewport.height : Infinity,
            });
            const { width, height } = size_hint;
            const { left, top } = this.position;
            const outer = new bbox_1.BBox({ left, top, width, height });
            let inner = undefined;
            if (size_hint.inner != null) {
                const { left, top, right, bottom } = size_hint.inner;
                inner = new bbox_1.BBox({ left, top, right: width - right, bottom: height - bottom });
            }
            this.set_geometry(outer, inner);
        }
        get xview() {
            return this.bbox.xview;
        }
        get yview() {
            return this.bbox.yview;
        }
        clip_size(size, viewport) {
            function clip(size, vsize, min_size, max_size) {
                if (min_size == null) {
                    min_size = 0;
                }
                else if (!(0, types_2.isNumber)(min_size)) {
                    min_size = round(min_size.percent * vsize);
                }
                if (max_size == null) {
                    max_size = Infinity;
                }
                else if (!(0, types_2.isNumber)(max_size)) {
                    max_size = round(max_size.percent * vsize);
                }
                return max(min_size, min(size, max_size));
            }
            return {
                width: clip(size.width, viewport.width, this.sizing.min_width, this.sizing.max_width),
                height: clip(size.height, viewport.height, this.sizing.min_height, this.sizing.max_height),
            };
        }
        has_size_changed() {
            const { _dirty } = this;
            this._dirty = false;
            return _dirty;
        }
    }
    exports.Layoutable = Layoutable;
    Layoutable.__name__ = "Layoutable";
    class ContentLayoutable extends Layoutable {
        _measure(viewport) {
            const content_size = this._content_size();
            const bounds = viewport
                .bounded_to(this.sizing.size)
                .bounded_to(content_size);
            const width = (() => {
                switch (this.sizing.width_policy) {
                    case "fixed":
                        return this.sizing.width != null ? this.sizing.width : content_size.width;
                    case "min":
                        return content_size.width;
                    case "fit":
                        return bounds.width;
                    case "max":
                        return max(content_size.width, bounds.width);
                }
            })();
            const height = (() => {
                switch (this.sizing.height_policy) {
                    case "fixed":
                        return this.sizing.height != null ? this.sizing.height : content_size.height;
                    case "min":
                        return content_size.height;
                    case "fit":
                        return bounds.height;
                    case "max":
                        return max(content_size.height, bounds.height);
                }
            })();
            return { width, height };
        }
    }
    exports.ContentLayoutable = ContentLayoutable;
    ContentLayoutable.__name__ = "ContentLayoutable";
    class TextLayout extends ContentLayoutable {
        constructor(text) {
            super();
            this.text = text;
        }
        _content_size() {
            return new types_1.Sizeable(this.text.size());
        }
    }
    exports.TextLayout = TextLayout;
    TextLayout.__name__ = "TextLayout";
    class FixedLayout extends ContentLayoutable {
        constructor(size = {}) {
            super();
            this.size = size;
        }
        _content_size() {
            return new types_1.Sizeable(this.size);
        }
    }
    exports.FixedLayout = FixedLayout;
    FixedLayout.__name__ = "FixedLayout";
},
/* models/text/base_text.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const view_1 = require(58) /* ../../core/view */;
    class BaseTextView extends view_1.View {
    }
    exports.BaseTextView = BaseTextView;
    BaseTextView.__name__ = "BaseTextView";
    class BaseText extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.BaseText = BaseText;
    _a = BaseText;
    BaseText.__name__ = "BaseText";
    (() => {
        _a.define(({ Str }) => ({
            text: [Str],
        }));
    })();
},
/* models/text/utils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.parse_delimited_string = parse_delimited_string;
    const math_text_1 = require(178) /* ./math_text */;
    const plain_text_1 = require(184) /* ./plain_text */;
    const array_1 = require(10) /* ../../core/util/array */;
    const delimiters = [
        { start: "$$", end: "$$", inline: false },
        { start: "\\\[", end: "\\\]", inline: false },
        { start: "\\\(", end: "\\\)", inline: true },
    ];
    function add_backslash(m) {
        return m.split("").map(s => `\\${s}`).join("");
    }
    function parse_delimited_string(text) {
        const matches = [];
        for (const delim of delimiters) {
            const start = add_backslash(delim.start);
            const end = add_backslash(delim.end);
            const re = new RegExp(`${start}([^]*?)${end}`, "gm");
            for (const match of text.matchAll(re)) {
                const { index } = match;
                const [outer, inner] = match;
                matches.push({ index, outer, inner, delim });
            }
        }
        if (matches.length > 0) {
            if (matches.length == 1) {
                const [match] = matches;
                const start = match.index;
                const end = match.outer.length;
                if (start == 0 && end == text.length) {
                    const tex_string = match.inner;
                    return new math_text_1.TeX({ text: tex_string, inline: match.delim.inline });
                }
            }
            let tex_string = "";
            let end = 0;
            for (const match of (0, array_1.sort_by)(matches, (match) => match.index)) {
                const start = match.index;
                if (end <= start) {
                    tex_string += start != 0 ? `\\text{${text.slice(end, start)}}${match.inner}` : `${match.inner}`;
                    end = start + match.outer.length;
                }
            }
            tex_string += end < text.length ? `\\text{${text.slice(end)}}` : "";
            return new math_text_1.TeX({ text: tex_string, inline: false });
        }
        else {
            return new plain_text_1.PlainText({ text });
        }
    }
},
/* models/text/math_text.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c;
    __esModule();
    const object_1 = require(9) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const image_1 = require(179) /* ../../core/util/image */;
    const color_1 = require(22) /* ../../core/util/color */;
    const graphics_1 = require(180) /* ../../core/graphics */;
    const text_1 = require(181) /* ../../core/util/text */;
    const string_1 = require(40) /* ../../core/util/string */;
    const affine_1 = require(114) /* ../../core/util/affine */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const base_text_1 = require(176) /* ./base_text */;
    const providers_1 = require(182) /* ./providers */;
    /**
     * Helper class for rendering MathText into Canvas
     */
    class MathTextView extends base_text_1.BaseTextView {
        constructor() {
            super(...arguments);
            this._position = { sx: 0, sy: 0 };
            // Align does nothing, needed to maintain compatibility with TextBox,
            // to align you need to use TeX Macros.
            // http://docs.mathjax.org/en/latest/input/tex/macros/index.html?highlight=align
            this.align = "left";
            this._x_anchor = "left";
            this._y_anchor = "center";
            this._base_font_size = 13; // the same as :host's font-size (13px)
            this.font_size_scale = 1.0;
            this.svg_image = null;
        }
        graphics() {
            return this;
        }
        // Same for infer_text_height
        infer_text_height() {
            return "ascent_descent";
        }
        set base_font_size(v) {
            if (v != null) {
                this._base_font_size = v;
            }
        }
        get base_font_size() {
            return this._base_font_size;
        }
        _rect() {
            const { width, height } = this._size();
            const { x, y } = this._computed_position();
            const bbox = new bbox_1.BBox({ x, y, width, height });
            return bbox.rect;
        }
        set position(p) {
            this._position = p;
        }
        get position() {
            return this._position;
        }
        get text() {
            return this.model.text;
        }
        get provider() {
            return providers_1.default_provider;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            if (this.provider.status == "not_started") {
                await this.provider.fetch();
            }
        }
        connect_signals() {
            super.connect_signals();
            this.on_change(this.model.properties.text, () => this.load_image());
        }
        set visuals(v) {
            const color = v.color;
            const alpha = v.alpha;
            const style = v.font_style;
            let size = v.font_size;
            const face = v.font;
            const { font_size_scale, _base_font_size } = this;
            const res = (0, text_1.parse_css_font_size)(size);
            if (res != null) {
                let { value, unit } = res;
                value *= font_size_scale;
                if (unit == "em" && _base_font_size != 0) {
                    value *= _base_font_size;
                    unit = "px";
                }
                size = `${value}${unit}`;
            }
            const font = `${style} ${size} ${face}`;
            this.font = font;
            this.color = (0, color_1.color2css)(color, alpha);
            const align = v.align;
            //this._visual_align = align
            this._x_anchor = align;
            const baseline = v.baseline;
            this._y_anchor = (() => {
                switch (baseline) {
                    case "top": return "top";
                    case "middle": return "center";
                    case "bottom": return "bottom";
                    default: return "baseline";
                }
            })();
        }
        /**
         * Calculates position of element after considering
         * anchor and dimensions
         */
        _computed_position() {
            const { width, height } = this._size();
            const { sx, sy, x_anchor = this._x_anchor, y_anchor = this._y_anchor } = this.position;
            const metrics = (0, text_1.font_metrics)(this.font);
            const x = sx - (() => {
                if ((0, types_1.isNumber)(x_anchor)) {
                    return x_anchor * width;
                }
                else {
                    switch (x_anchor) {
                        case "left": return 0;
                        case "center": return 0.5 * width;
                        case "right": return width;
                    }
                }
            })();
            const y = sy - (() => {
                if ((0, types_1.isNumber)(y_anchor)) {
                    return y_anchor * height;
                }
                else {
                    switch (y_anchor) {
                        case "top":
                            if (metrics.height > height) {
                                return (height - (-this.valign - metrics.descent) - metrics.height);
                            }
                            else {
                                return 0;
                            }
                        case "center": return 0.5 * height;
                        case "bottom":
                            if (metrics.height > height) {
                                return (height + metrics.descent + this.valign);
                            }
                            else {
                                return height;
                            }
                        case "baseline": return 0.5 * height;
                    }
                }
            })();
            return { x, y };
        }
        /**
         * Uses the width, height and given angle to calculate the size
        */
        size() {
            const { width, height } = this._size();
            const { angle } = this;
            if (angle == null || angle == 0) {
                return { width, height };
            }
            else {
                const c = Math.cos(Math.abs(angle));
                const s = Math.sin(Math.abs(angle));
                return {
                    width: Math.abs(width * c + height * s),
                    height: Math.abs(width * s + height * c),
                };
            }
        }
        get_image_dimensions() {
            const fmetrics = (0, text_1.font_metrics)(this.font);
            // XXX: perhaps use getComputedStyle()?
            const svg_styles = this.svg_element.getAttribute("style")?.split(";");
            if (svg_styles != null) {
                const rules_map = new Map();
                svg_styles.forEach(property => {
                    const [rule, value] = property.split(":");
                    if (rule.trim() != "") {
                        rules_map.set(rule.trim(), value.trim());
                    }
                });
                const v_align = (0, text_1.parse_css_length)(rules_map.get("vertical-align"));
                if (v_align?.unit == "ex") {
                    this.valign = v_align.value * fmetrics.x_height;
                }
                else if (v_align?.unit == "px") {
                    this.valign = v_align.value;
                }
            }
            const ex = (() => {
                const width = this.svg_element.getAttribute("width");
                const height = this.svg_element.getAttribute("height");
                return {
                    width: width != null && width.endsWith("ex") ? parseFloat(width) : 1,
                    height: height != null && height.endsWith("ex") ? parseFloat(height) : 1,
                };
            })();
            return {
                width: fmetrics.x_height * ex.width,
                height: fmetrics.x_height * ex.height,
            };
        }
        get truncated_text() {
            return this.model.text.length > 6
                ? `${this.model.text.substring(0, 6)}...`
                : this.model.text;
        }
        _size() {
            if (this.svg_image == null) {
                if (this.provider.status == "failed" || this.provider.status == "not_started") {
                    return {
                        width: (0, graphics_1.text_width)(this.truncated_text, this.font),
                        height: (0, text_1.font_metrics)(this.font).height,
                    };
                }
                else {
                    return { width: this._base_font_size, height: this._base_font_size };
                }
            }
            const fmetrics = (0, text_1.font_metrics)(this.font);
            let { width, height } = this.get_image_dimensions();
            height = Math.max(height, fmetrics.height);
            const w_scale = this.width?.unit == "%" ? this.width.value : 1;
            const h_scale = this.height?.unit == "%" ? this.height.value : 1;
            return { width: width * w_scale, height: height * h_scale };
        }
        bbox() {
            const { p0, p1, p2, p3 } = this.rect();
            const left = Math.min(p0.x, p1.x, p2.x, p3.x);
            const top = Math.min(p0.y, p1.y, p2.y, p3.y);
            const right = Math.max(p0.x, p1.x, p2.x, p3.x);
            const bottom = Math.max(p0.y, p1.y, p2.y, p3.y);
            return new bbox_1.BBox({ left, right, top, bottom });
        }
        rect() {
            const rect = this._rect();
            const { angle } = this;
            if (angle == null || angle == 0) {
                return rect;
            }
            else {
                const { sx, sy } = this.position;
                const tr = new affine_1.AffineTransform();
                tr.translate(sx, sy);
                tr.rotate(angle);
                tr.translate(-sx, -sy);
                return tr.apply_rect(rect);
            }
        }
        paint_rect(ctx) {
            const { p0, p1, p2, p3 } = this.rect();
            ctx.save();
            ctx.strokeStyle = "red";
            ctx.lineWidth = 1;
            ctx.beginPath();
            const { round } = Math;
            ctx.moveTo(round(p0.x), round(p0.y));
            ctx.lineTo(round(p1.x), round(p1.y));
            ctx.lineTo(round(p2.x), round(p2.y));
            ctx.lineTo(round(p3.x), round(p3.y));
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        }
        paint_bbox(ctx) {
            const { x, y, width, height } = this.bbox();
            ctx.save();
            ctx.strokeStyle = "blue";
            ctx.lineWidth = 1;
            ctx.beginPath();
            const { round } = Math;
            ctx.moveTo(round(x), round(y));
            ctx.lineTo(round(x), round(y + height));
            ctx.lineTo(round(x + width), round(y + height));
            ctx.lineTo(round(x + width), round(y));
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        }
        async request_image() {
            if (this.provider.MathJax == null) {
                return;
            }
            const mathjax_element = this._process_text();
            if (mathjax_element == null) {
                this._has_finished = true;
                return;
            }
            const svg_element = mathjax_element.children[0];
            this.svg_element = svg_element;
            svg_element.setAttribute("font", this.font);
            svg_element.setAttribute("stroke", this.color);
            const svg = svg_element.outerHTML;
            const src = `data:image/svg+xml;utf-8,${encodeURIComponent(svg)}`;
            this.svg_image = await (0, image_1.load_image)(src);
        }
        async load_image() {
            await this.request_image();
            this.parent.request_layout();
        }
        /**
         * Takes a Canvas' Context2d and if the image has already
         * been loaded draws the image in it otherwise draws the model's text.
        */
        paint(ctx) {
            if (this.svg_image == null) {
                if (this.provider.status == "not_started" || this.provider.status == "loading") {
                    this.provider.ready.connect(() => this.load_image());
                }
                if (this.provider.status == "loaded") {
                    void this.load_image();
                }
            }
            ctx.save();
            const { sx, sy } = this.position;
            const { angle } = this;
            if (angle != null && angle != 0) {
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            const { x, y } = this._computed_position();
            if (this.svg_image != null) {
                const { width, height } = this.get_image_dimensions();
                ctx.drawImage(this.svg_image, x, y, width, height);
            }
            else if (this.provider.status == "failed" || this.provider.status == "not_started") {
                ctx.fillStyle = this.color;
                ctx.font = this.font;
                ctx.textAlign = "left";
                ctx.textBaseline = "alphabetic";
                ctx.fillText(this.truncated_text, x, y + (0, text_1.font_metrics)(this.font).ascent);
            }
            ctx.restore();
            if (!this._has_finished && (this.provider.status == "failed" || this.svg_image != null)) {
                this._has_finished = true;
                this.parent.notify_finished_after_paint();
            }
        }
    }
    exports.MathTextView = MathTextView;
    MathTextView.__name__ = "MathTextView";
    class MathText extends base_text_1.BaseText {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MathText = MathText;
    MathText.__name__ = "MathText";
    class AsciiView extends MathTextView {
        // TODO: Color ascii
        get styled_text() {
            return this.text;
        }
        _process_text() {
            return undefined; // TODO: this.provider.MathJax?.ascii2svg(text)
        }
        _size() {
            return {
                width: (0, graphics_1.text_width)(this.text, this.font),
                height: (0, text_1.font_metrics)(this.font).height,
            };
        }
        paint(ctx) {
            ctx.save();
            const { sx, sy } = this.position;
            const { angle } = this;
            if (angle != null && angle != 0) {
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            const { x, y } = this._computed_position();
            ctx.fillStyle = this.color;
            ctx.font = this.font;
            ctx.textAlign = "left";
            ctx.textBaseline = "alphabetic";
            ctx.fillText(this.text, x, y + (0, text_1.font_metrics)(this.font).ascent);
            ctx.restore();
            this._has_finished = true;
            this.parent.notify_finished_after_paint();
        }
    }
    exports.AsciiView = AsciiView;
    AsciiView.__name__ = "AsciiView";
    class Ascii extends MathText {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Ascii = Ascii;
    _a = Ascii;
    Ascii.__name__ = "Ascii";
    (() => {
        _a.prototype.default_view = AsciiView;
    })();
    class MathMLView extends MathTextView {
        get styled_text() {
            let styled = this.text.trim();
            let matchs = styled.match(/<math(.*?[^?])?>/s);
            if (matchs == null) {
                return this.text.trim();
            }
            styled = (0, string_1.insert_text_on_position)(styled, styled.indexOf(matchs[0]) + matchs[0].length, `<mstyle displaystyle="true" mathcolor="${(0, color_1.color2hexrgb)(this.color)}" ${this.font.includes("bold") ? 'mathvariant="bold"' : ""}>`);
            matchs = styled.match(/<\/[^>]*?math.*?>/s);
            if (matchs == null) {
                return this.text.trim();
            }
            return (0, string_1.insert_text_on_position)(styled, styled.indexOf(matchs[0]), "</mstyle>");
        }
        _process_text() {
            const fmetrics = (0, text_1.font_metrics)(this.font);
            return this.provider.MathJax?.mathml2svg(this.styled_text, {
                em: this.base_font_size,
                ex: fmetrics.x_height,
            });
        }
    }
    exports.MathMLView = MathMLView;
    MathMLView.__name__ = "MathMLView";
    class MathML extends MathText {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MathML = MathML;
    _b = MathML;
    MathML.__name__ = "MathML";
    (() => {
        _b.prototype.default_view = MathMLView;
    })();
    class TeXView extends MathTextView {
        get styled_text() {
            const [r, g, b] = (0, color_1.color2rgba)(this.color);
            return `\\color[RGB]{${r}, ${g}, ${b}} ${this.font.includes("bold") ? `\\pmb{${this.text}}` : this.text}`;
        }
        _process_text() {
            // TODO: allow plot/document level configuration of macros
            const fmetrics = (0, text_1.font_metrics)(this.font);
            return this.provider.MathJax?.tex2svg(this.styled_text, {
                display: !this.model.inline,
                em: this.base_font_size,
                ex: fmetrics.x_height,
            }, (0, object_1.to_object)(this.model.macros));
        }
    }
    exports.TeXView = TeXView;
    TeXView.__name__ = "TeXView";
    class TeX extends MathText {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TeX = TeX;
    _c = TeX;
    TeX.__name__ = "TeX";
    (() => {
        _c.prototype.default_view = TeXView;
        _c.define(({ Bool, Float, Str, Dict, Tuple, Or }) => ({
            macros: [Dict(Or(Str, Tuple(Str, Float))), {}],
            inline: [Bool, false],
        }));
    })();
},
/* core/util/image.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.load_image = load_image;
    const logging_1 = require(19) /* ../logging */;
    async function load_image(url, options) {
        return new ImageLoader(url, options).promise;
    }
    class ImageLoader {
        constructor(src, config = {}) {
            this.image = new Image();
            this._finished = false;
            const { attempts = 1, timeout = 1 } = config;
            const url = (() => {
                if (src instanceof ArrayBuffer) {
                    const blob = new Blob([src], { type: "image/png" }); // TODO mime
                    return URL.createObjectURL(blob); // TODO revoke
                }
                else {
                    return src;
                }
            })();
            this.promise = new Promise((resolve, _reject) => {
                this.image.crossOrigin = "anonymous";
                let retries = 0;
                this.image.onerror = () => {
                    if (++retries == attempts) {
                        const message = `unable to load ${url} image after ${attempts} attempts`;
                        logging_1.logger.warn(message);
                        if (this.image.crossOrigin != null) {
                            logging_1.logger.warn(`attempting to load ${url} without a cross origin policy`);
                            this.image.crossOrigin = null;
                            retries = 0;
                        }
                        else {
                            config.failed?.();
                            return; // XXX reject(new Error(message))
                        }
                    }
                    setTimeout(() => this.image.src = url, timeout);
                };
                this.image.onload = () => {
                    this._finished = true;
                    config.loaded?.(this.image);
                    resolve(this.image);
                };
                this.image.src = url;
            });
        }
        get finished() {
            return this._finished;
        }
    }
    exports.ImageLoader = ImageLoader;
    ImageLoader.__name__ = "ImageLoader";
},
/* core/graphics.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const bbox_1 = require(64) /* ./util/bbox */;
    const text_1 = require(181) /* ./util/text */;
    const array_1 = require(10) /* ./util/array */;
    const types_1 = require(8) /* ./util/types */;
    const affine_1 = require(114) /* ./util/affine */;
    const color_1 = require(22) /* ./util/color */;
    exports.text_width = (() => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        let current_font = "";
        return (text, font) => {
            if (font != current_font) {
                current_font = font;
                ctx.font = font;
            }
            return ctx.measureText(text).width;
        };
    })();
    class GraphicsBox {
        constructor() {
            this._position = { sx: 0, sy: 0 };
            this.font_size_scale = 1.0;
            this.align = "left";
            this._base_font_size = 13; // the same as :host's font-size (13px)
            this._x_anchor = "left";
            this._y_anchor = "center";
        }
        set base_font_size(v) {
            if (v != null) {
                this._base_font_size = v;
            }
        }
        get base_font_size() {
            return this._base_font_size;
        }
        set position(p) {
            this._position = p;
        }
        get position() {
            return this._position;
        }
        infer_text_height() {
            return "ascent_descent";
        }
        bbox() {
            const { p0, p1, p2, p3 } = this.rect();
            const left = Math.min(p0.x, p1.x, p2.x, p3.x);
            const top = Math.min(p0.y, p1.y, p2.y, p3.y);
            const right = Math.max(p0.x, p1.x, p2.x, p3.x);
            const bottom = Math.max(p0.y, p1.y, p2.y, p3.y);
            return new bbox_1.BBox({ left, right, top, bottom });
        }
        size() {
            const { width, height } = this._size();
            const { angle } = this;
            if (angle == null || angle == 0) {
                return { width, height };
            }
            else {
                const c = Math.cos(Math.abs(angle));
                const s = Math.sin(Math.abs(angle));
                return {
                    width: Math.abs(width * c + height * s),
                    height: Math.abs(width * s + height * c),
                };
            }
        }
        rect() {
            const rect = this._rect();
            const { angle } = this;
            if (angle == null || angle == 0) {
                return rect;
            }
            else {
                const { sx, sy } = this.position;
                const tr = new affine_1.AffineTransform();
                tr.translate(sx, sy);
                tr.rotate(angle);
                tr.translate(-sx, -sy);
                return tr.apply_rect(rect);
            }
        }
        paint_rect(ctx) {
            const { p0, p1, p2, p3 } = this.rect();
            ctx.save();
            ctx.strokeStyle = "red";
            ctx.lineWidth = 1;
            ctx.beginPath();
            const { round } = Math;
            ctx.moveTo(round(p0.x), round(p0.y));
            ctx.lineTo(round(p1.x), round(p1.y));
            ctx.lineTo(round(p2.x), round(p2.y));
            ctx.lineTo(round(p3.x), round(p3.y));
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        }
        paint_bbox(ctx) {
            const { x, y, width, height } = this.bbox();
            ctx.save();
            ctx.strokeStyle = "blue";
            ctx.lineWidth = 1;
            ctx.beginPath();
            const { round } = Math;
            ctx.moveTo(round(x), round(y));
            ctx.lineTo(round(x), round(y + height));
            ctx.lineTo(round(x + width), round(y + height));
            ctx.lineTo(round(x + width), round(y));
            ctx.closePath();
            ctx.stroke();
            ctx.restore();
        }
    }
    exports.GraphicsBox = GraphicsBox;
    GraphicsBox.__name__ = "GraphicsBox";
    class TextBox extends GraphicsBox {
        set visuals(v) {
            const color = v.color;
            const alpha = v.alpha;
            const outline_color = v.outline_color;
            const style = v.font_style;
            let size = v.font_size;
            const face = v.font;
            const { font_size_scale, base_font_size } = this;
            const res = (0, text_1.parse_css_font_size)(size);
            if (res != null) {
                let { value, unit } = res;
                value *= font_size_scale;
                if (unit == "em" && base_font_size != 0) {
                    value *= base_font_size;
                    unit = "px";
                }
                size = `${value}${unit}`;
            }
            const font = `${style} ${size} ${face}`;
            this.font = font;
            this.color = (0, color_1.color2css)(color, alpha);
            this.outline_color = (0, color_1.color2css)(outline_color, alpha);
            this.line_height = v.line_height;
            const align = v.align;
            this._visual_align = align;
            this._x_anchor = align;
            const baseline = v.baseline;
            this._y_anchor = (() => {
                switch (baseline) {
                    case "top": return "top";
                    case "middle": return "center";
                    case "bottom": return "bottom";
                    default: return "baseline";
                }
            })();
        }
        constructor({ text }) {
            super();
            //padding: Padding
            this._visual_align = "left";
            this.text = text;
        }
        infer_text_height() {
            if (this.text.includes("\n")) {
                return "ascent_descent";
            }
            else {
                function is_math_like(text) {
                    for (const c of new Set(text)) {
                        if ("0" <= c && c <= "9") {
                            continue;
                        }
                        switch (c) {
                            case ",":
                            case ".":
                            case "+":
                            case "-":
                            case "\u2212":
                            case "e":
                                continue;
                            default:
                                return false;
                        }
                    }
                    return true;
                }
                if (is_math_like(this.text)) {
                    return "cap";
                }
                else {
                    return "ascent_descent";
                }
            }
        }
        _text_line(fmetrics) {
            const metric = this.text_height_metric ?? 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() {
            const { font } = this;
            const fmetrics = (0, text_1.font_metrics)(font);
            const line_spacing = (this.line_height - 1) * fmetrics.height; // TODO: max(trailing(L[n-1]), leading(L[n]))
            const empty = this.text == "";
            const lines = this.text.split("\n");
            const nlines = lines.length;
            const widths = lines.map((line) => (0, exports.text_width)(line, font));
            const text_line = this._text_line(fmetrics);
            const text_height = text_line.height * nlines;
            /*
            const heights: number[] = []
            const ascents: number[] = []
            const descents: number[] = []
        
            for (const line of lines) {
              const metrics = [...line].map((c) => glyph_metrics(c, font))
              const max_ascent = Math.max(max(metrics.map((m) => m.ascent)), fmetrics.cap_height)
              const max_descent = max(metrics.map((m) => m.descent))
              ascents.push(max_ascent)
              descents.push(max_descent)
              heights.push(max_ascent + max_descent)
            }
        
            const text_height = sum(heights)
            */
            const w_scale = this.width?.unit == "%" ? this.width.value : 1;
            const h_scale = this.height?.unit == "%" ? this.height.value : 1;
            const width = (0, array_1.max)(widths) * w_scale;
            const height = empty ? 0 : (text_height + line_spacing * (nlines - 1)) * h_scale;
            return { width, height, metrics: fmetrics };
        }
        _computed_position(size, metrics, nlines) {
            const { width, height } = size;
            const { sx, sy, x_anchor = this._x_anchor, y_anchor = this._y_anchor } = this.position;
            const x = sx - (() => {
                if ((0, types_1.isNumber)(x_anchor)) {
                    return x_anchor * width;
                }
                else {
                    switch (x_anchor) {
                        case "left": return 0;
                        case "center": return 0.5 * width;
                        case "right": return width;
                    }
                }
            })();
            const y = sy - (() => {
                if ((0, types_1.isNumber)(y_anchor)) {
                    return y_anchor * height;
                }
                else {
                    switch (y_anchor) {
                        case "top": return 0;
                        case "center": return 0.5 * height;
                        case "bottom": return height;
                        case "baseline": {
                            if (nlines == 1) {
                                const metric = this.text_height_metric ?? 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) {
            const { font } = this;
            const fmetrics = (0, text_1.font_metrics)(font);
            const line_spacing = (this.line_height - 1) * fmetrics.height; // TODO: see above
            const lines = this.text.split("\n");
            const nlines = lines.length;
            const widths = lines.map((line) => (0, exports.text_width)(line, font));
            const text_line = this._text_line(fmetrics);
            const text_height = text_line.height * nlines;
            /*
            const heights: number[] = []
            const ascents: number[] = []
            const descents: number[] = []
        
            for (const line of lines) {
              const metrics = [...line].map((c) => glyph_metrics(c, font))
              const max_ascent = Math.max(max(metrics.map((m) => m.ascent)), fmetrics.cap_height)
              const max_descent = max(metrics.map((m) => m.descent))
              ascents.push(max_ascent)
              descents.push(max_descent)
              heights.push(max_ascent + max_descent)
            }
            */
            const w_scale = this.width?.unit == "%" ? this.width.value : 1;
            const h_scale = this.height?.unit == "%" ? this.height.value : 1;
            const width = (0, array_1.max)(widths) * w_scale;
            const height = (text_height + line_spacing * (nlines - 1)) * h_scale;
            ctx.save();
            ctx.fillStyle = this.color;
            ctx.strokeStyle = this.outline_color;
            ctx.font = this.font;
            ctx.textAlign = "left";
            ctx.textBaseline = "alphabetic";
            const { sx, sy } = this.position;
            const { align } = this;
            const { angle } = this;
            if (angle != null && angle != 0) {
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            let { x, y } = this._computed_position({ width, height }, fmetrics, nlines);
            if (align == "justify") {
                for (let i = 0; i < nlines; i++) {
                    let xij = x;
                    const line = lines[i];
                    const words = line.split(" ");
                    const nwords = words.length;
                    const word_widths = words.map((word) => (0, exports.text_width)(word, font));
                    const word_spacing = (width - (0, array_1.sum)(word_widths)) / (nwords - 1);
                    for (let j = 0; j < nwords; j++) {
                        ctx.fillText(words[j], xij, y);
                        ctx.strokeText(words[j], xij, y);
                        xij += word_widths[j] + word_spacing;
                    }
                    y += /*heights[i]*/ text_line.height + line_spacing;
                }
            }
            else {
                for (let i = 0; i < nlines; i++) {
                    const xi = x + (() => {
                        switch (align == "auto" ? this._visual_align : align) {
                            case "left": return 0;
                            case "center": return 0.5 * (width - widths[i]);
                            case "right": return width - widths[i];
                        }
                    })();
                    const linei = lines[i];
                    const yi = y + /*ascents[i]*/ text_line.ascent;
                    ctx.fillText(linei, xi, yi);
                    ctx.strokeText(linei, xi, yi);
                    y += /*heights[i]*/ text_line.height + line_spacing;
                }
            }
            ctx.restore();
        }
    }
    exports.TextBox = TextBox;
    TextBox.__name__ = "TextBox";
    class BaseExpo extends GraphicsBox {
        constructor(base, expo) {
            super();
            this.base = base;
            this.expo = expo;
        }
        get children() {
            return [this.base, this.expo];
        }
        set base_font_size(v) {
            super.base_font_size = v;
            this.base.base_font_size = v;
            this.expo.base_font_size = v;
        }
        set position(p) {
            this._position = p;
            const bs = this.base.size();
            const es = this.expo.size();
            const shift = this._shift_scale() * bs.height;
            const height = Math.max(bs.height, shift + es.height);
            this.base.position = {
                sx: 0, x_anchor: "left",
                sy: height, y_anchor: "bottom",
            };
            this.expo.position = {
                sx: bs.width, x_anchor: "left",
                sy: shift, y_anchor: "bottom",
            };
        }
        get position() {
            return this._position;
        }
        set visuals(v) {
            this.expo.font_size_scale = 0.7;
            this.base.visuals = v;
            this.expo.visuals = v;
        }
        _shift_scale() {
            if (this.base instanceof TextBox && this.base.nlines == 1) {
                const { x_height, cap_height } = (0, text_1.font_metrics)(this.base.font);
                return x_height / cap_height;
            }
            else {
                return 2 / 3;
            }
        }
        infer_text_height() {
            return this.base.infer_text_height();
        }
        _rect() {
            const bb = this.base.bbox();
            const eb = this.expo.bbox();
            const bbox = bb.union(eb);
            const { x, y } = this._computed_position();
            return bbox.translate(x, y).rect;
        }
        _size() {
            const bs = this.base.size();
            const es = this.expo.size();
            return {
                width: bs.width + es.width,
                height: Math.max(bs.height, this._shift_scale() * bs.height + es.height),
            };
        }
        paint(ctx) {
            ctx.save();
            const { angle } = this;
            if (angle != null && angle != 0) {
                const { sx, sy } = this.position;
                ctx.translate(sx, sy);
                ctx.rotate(angle);
                ctx.translate(-sx, -sy);
            }
            const { x, y } = this._computed_position();
            ctx.translate(x, y);
            this.base.paint(ctx);
            this.expo.paint(ctx);
            ctx.restore();
        }
        // paint_rect ...
        paint_bbox(ctx) {
            super.paint_bbox(ctx);
            const { x, y } = this._computed_position();
            ctx.save();
            ctx.translate(x, y);
            for (const child of this.children) {
                child.paint_bbox(ctx);
            }
            ctx.restore();
        }
        _computed_position() {
            const { width, height } = this._size();
            const { sx, sy, x_anchor = this._x_anchor, y_anchor = this._y_anchor } = this.position;
            const x = sx - (() => {
                if ((0, types_1.isNumber)(x_anchor)) {
                    return x_anchor * width;
                }
                else {
                    switch (x_anchor) {
                        case "left": return 0;
                        case "center": return 0.5 * width;
                        case "right": return width;
                    }
                }
            })();
            const y = sy - (() => {
                if ((0, types_1.isNumber)(y_anchor)) {
                    return y_anchor * height;
                }
                else {
                    switch (y_anchor) {
                        case "top": return 0;
                        case "center": return 0.5 * height;
                        case "bottom": return height;
                        case "baseline": return 0.5 * height; /* TODO */
                    }
                }
            })();
            return { x, y };
        }
    }
    exports.BaseExpo = BaseExpo;
    BaseExpo.__name__ = "BaseExpo";
    class GraphicsBoxes {
        constructor(items) {
            this.items = items;
        }
        set base_font_size(v) {
            for (const item of this.items) {
                item.base_font_size = v;
            }
        }
        get length() {
            return this.items.length;
        }
        set visuals(v) {
            for (const item of this.items) {
                item.visuals = v;
            }
            const metric_map = { x: 0, cap: 1, ascent: 2, x_descent: 3, cap_descent: 4, ascent_descent: 5 };
            const common = (0, array_1.max_by)(this.items.map((item) => item.infer_text_height()), (metric) => metric_map[metric]);
            for (const item of this.items) {
                item.text_height_metric = common;
            }
        }
        set angle(a) {
            for (const item of this.items) {
                item.angle = a;
            }
        }
        max_size() {
            let width = 0;
            let height = 0;
            for (const item of this.items) {
                const size = item.size();
                width = Math.max(width, size.width);
                height = Math.max(height, size.height);
            }
            return { width, height };
        }
    }
    exports.GraphicsBoxes = GraphicsBoxes;
    GraphicsBoxes.__name__ = "GraphicsBoxes";
},
/* core/util/text.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.font_metrics = font_metrics;
    exports.parse_css_font_size = parse_css_font_size;
    exports.parse_css_length = parse_css_length;
    const assert_1 = require(12) /* ./assert */;
    const dom_1 = require(63) /* ../dom */;
    const _offscreen_context = (() => {
        // Support Firefox ESR, etc., see https://github.com/bokeh/bokeh/issues/14006.
        const canvas_el = typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(0, 0) : (0, dom_1.canvas)({ width: 0, height: 0 });
        const ctx = canvas_el.getContext("2d");
        (0, assert_1.assert)(ctx != null, "can't obtain 2d context");
        return ctx;
    })();
    function _font_metrics(font) {
        const ctx = _offscreen_context;
        ctx.font = font;
        const cap_metrics = ctx.measureText("M");
        const x_metrics = ctx.measureText("x");
        const metrics = ctx.measureText("ÅŚg|");
        // Support Firefox ESR, etc., see https://github.com/bokeh/bokeh/issues/13969.
        const ascent = typeof metrics.fontBoundingBoxAscent !== "undefined" ? metrics.fontBoundingBoxAscent : metrics.actualBoundingBoxAscent;
        const descent = typeof metrics.fontBoundingBoxDescent !== "undefined" ? metrics.fontBoundingBoxDescent : metrics.actualBoundingBoxDescent;
        return {
            height: ascent + descent,
            ascent,
            descent,
            cap_height: cap_metrics.actualBoundingBoxAscent,
            x_height: x_metrics.actualBoundingBoxAscent,
        };
    }
    const _metrics_cache = new Map();
    function font_metrics(font) {
        let metrics = _metrics_cache.get(font);
        if (metrics == null) {
            const loaded = document.fonts.check(font);
            metrics = { font: _font_metrics(font) };
            if (loaded) {
                _metrics_cache.set(font, metrics);
            }
        }
        return metrics.font;
    }
    function parse_css_font_size(size) {
        const match = size.match(/^\s*(\d+(\.\d+)?)(\w+)\s*$/);
        if (match != null) {
            const [, value, , unit] = match;
            const number = Number(value);
            if (isFinite(number)) {
                return { value: number, unit };
            }
        }
        return null;
    }
    function parse_css_length(size) {
        const match = size.match(/^\s*(-?\d+(\.\d+)?)(\w+)\s*$/);
        if (match != null) {
            const [, value, , unit] = match;
            const number = Number(value);
            if (isFinite(number)) {
                return { value: number, unit };
            }
        }
        return null;
    }
},
/* models/text/providers.js */ function _(require, module, exports, __esModule, __esExport) {
    var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    }));
    var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    });
    var __importStar = (this && this.__importStar) || function (mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k in mod)
                if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
                    __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    };
    __esModule();
    const signaling_1 = require(15) /* ../../core/signaling */;
    const modules_1 = require(183) /* ../../core/util/modules */;
    class MathJaxProvider {
        constructor() {
            this.ready = new signaling_1.Signal0(this, "ready");
            this.status = "not_started";
        }
    }
    exports.MathJaxProvider = MathJaxProvider;
    MathJaxProvider.__name__ = "MathJaxProvider";
    class NoProvider extends MathJaxProvider {
        get MathJax() {
            return null;
        }
        async fetch() {
            this.status = "failed";
        }
    }
    exports.NoProvider = NoProvider;
    NoProvider.__name__ = "NoProvider";
    class CDNProvider extends MathJaxProvider {
        get MathJax() {
            return typeof MathJax !== "undefined" ? MathJax : null;
        }
        async fetch() {
            const script = document.createElement("script");
            script.src = "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js";
            script.onload = () => {
                this.status = "loaded";
                this.ready.emit();
            };
            script.onerror = () => {
                this.status = "failed";
            };
            this.status = "loading";
            document.head.appendChild(script);
        }
    }
    exports.CDNProvider = CDNProvider;
    CDNProvider.__name__ = "CDNProvider";
    class BundleProvider extends MathJaxProvider {
        get MathJax() {
            return this._mathjax;
        }
        async fetch() {
            this.status = "loading";
            try {
                const mathjax = await (0, modules_1.load_module)(Promise.resolve().then(() => __importStar(require(714) /* ./mathjax */)));
                this.status = mathjax == null ? "failed" : "loaded";
                this._mathjax = mathjax;
                this.ready.emit();
            }
            catch (error) {
                this.status = "failed";
            }
        }
    }
    exports.BundleProvider = BundleProvider;
    BundleProvider.__name__ = "BundleProvider";
    exports.default_provider = new BundleProvider();
},
/* core/util/modules.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.load_module = load_module;
    function is_ModuleError(error) {
        return error instanceof Error && "code" in error;
    }
    /** T is of import("some/module/path") type */
    async function load_module(module) {
        try {
            return await module;
        }
        catch (e) {
            // XXX: this exposes the underlying module system and hinders
            // interoperability with other module systems and bundlers
            if (is_ModuleError(e) && e.code === "MODULE_NOT_FOUND") {
                return null;
            }
            else {
                throw e;
            }
        }
    }
},
/* models/text/plain_text.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const base_text_1 = require(176) /* ./base_text */;
    const graphics_1 = require(180) /* ../../core/graphics */;
    class PlainTextView extends base_text_1.BaseTextView {
        initialize() {
            super.initialize();
            this._has_finished = true;
        }
        graphics() {
            return new graphics_1.TextBox({ text: this.model.text });
        }
    }
    exports.PlainTextView = PlainTextView;
    PlainTextView.__name__ = "PlainTextView";
    class PlainText extends base_text_1.BaseText {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.PlainText = PlainText;
    _a = PlainText;
    PlainText.__name__ = "PlainText";
    (() => {
        _a.prototype.default_view = PlainTextView;
    })();
},
/* models/common/kinds.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const enums = tslib_1.__importStar(require(20) /* ../../core/enums */);
    exports.Length = (0, kinds_1.NonNegative)(kinds_1.Int);
    const XY = (type) => (0, kinds_1.PartialStruct)({ x: type, y: type });
    const LRTB = (type) => (0, kinds_1.PartialStruct)({ left: type, right: type, top: type, bottom: type });
    exports.HAnchor = (0, kinds_1.Or)(enums.Align, enums.HAlign, kinds_1.Percent);
    exports.VAnchor = (0, kinds_1.Or)(enums.Align, enums.VAlign, kinds_1.Percent);
    exports.Anchor = (0, kinds_1.Or)(enums.Anchor, (0, kinds_1.Tuple)(exports.HAnchor, exports.VAnchor));
    exports.AutoAnchor = (0, kinds_1.Or)(kinds_1.Auto, enums.Anchor, (0, kinds_1.Tuple)((0, kinds_1.Or)(exports.HAnchor, kinds_1.Auto), (0, kinds_1.Or)(exports.VAnchor, kinds_1.Auto)));
    exports.TextAnchor = (0, kinds_1.Or)(exports.Anchor, kinds_1.Auto);
    exports.Padding = ((0, kinds_1.Or)(exports.Length, (0, kinds_1.Tuple)(exports.Length, exports.Length), XY(exports.Length), (0, kinds_1.Tuple)(exports.Length, exports.Length, exports.Length, exports.Length), LRTB(exports.Length)));
    exports.BorderRadius = ((0, kinds_1.Or)(exports.Length, (0, kinds_1.Tuple)(exports.Length, exports.Length, exports.Length, exports.Length), (0, kinds_1.PartialStruct)({
        top_left: exports.Length,
        top_right: exports.Length,
        bottom_right: exports.Length,
        bottom_left: exports.Length,
    })));
    exports.Index = (0, kinds_1.NonNegative)(kinds_1.Int);
    exports.Span = (0, kinds_1.NonNegative)(kinds_1.Int);
    const GridChild = (child) => (0, kinds_1.Tuple)((0, kinds_1.Ref)(child), exports.Index, exports.Index, (0, kinds_1.Opt)(exports.Span), (0, kinds_1.Opt)(exports.Span));
    exports.GridChild = GridChild;
    exports.GridSpacing = (0, kinds_1.Or)(exports.Length, (0, kinds_1.Tuple)(exports.Length, exports.Length));
    exports.TrackAlign = (0, kinds_1.Enum)("start", "center", "end", "auto");
    exports.TrackSize = kinds_1.Str;
    exports.TrackSizing = (0, kinds_1.PartialStruct)({ size: exports.TrackSize, align: exports.TrackAlign });
    exports.TrackSizingLike = (0, kinds_1.Or)(exports.TrackSize, exports.TrackSizing);
    exports.TracksSizing = (0, kinds_1.Or)(exports.TrackSizingLike, (0, kinds_1.List)(exports.TrackSizingLike), (0, kinds_1.Mapping)(kinds_1.Int, exports.TrackSizingLike));
},
/* models/common/resolve.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.normalized_anchor = normalized_anchor;
    exports.anchor = anchor;
    exports.text_anchor = text_anchor;
    exports.padding = padding;
    exports.border_radius = border_radius;
    const types_1 = require(8) /* ../../core/util/types */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    function normalized_anchor(anchor) {
        if (anchor == "auto") {
            return { x: "auto", y: "auto" };
        }
        const normalized = (() => {
            switch (anchor) {
                case "top": return "top_center";
                case "bottom": return "bottom_center";
                case "left": return "center_left";
                case "center": return "center_center";
                case "right": return "center_right";
                default: return anchor;
            }
        })();
        if ((0, types_1.isString)(normalized)) {
            const [y, x] = normalized.split("_");
            return { x, y };
        }
        else {
            const [x, y] = normalized;
            return { x, y };
        }
    }
    function anchor(anchor) {
        const { x, y } = normalized_anchor(anchor);
        const x_anchor = (() => {
            switch (x) {
                case "start":
                case "left": return 0.0;
                case "center": return 0.5;
                case "end":
                case "right": return 1.0;
                default: return x;
            }
        })();
        const y_anchor = (() => {
            switch (y) {
                case "start":
                case "top": return 0.0;
                case "center": return 0.5;
                case "end":
                case "bottom": return 1.0;
                default: return y;
            }
        })();
        return { x: x_anchor, y: y_anchor };
    }
    function text_anchor(text_anchor, align, baseline) {
        if (text_anchor != "auto") {
            return anchor(text_anchor);
        }
        else {
            const x_anchor = (() => {
                switch (align) {
                    case "left": return "start";
                    case "center": return "center";
                    case "right": return "end";
                }
            })();
            const y_anchor = (() => {
                switch (baseline) {
                    case "alphabetic":
                    case "ideographic":
                    case "hanging":
                        return "center";
                    case "top": return "start";
                    case "middle": return "center";
                    case "bottom": return "end";
                }
            })();
            return anchor([x_anchor, y_anchor]);
        }
    }
    function padding(padding) {
        if ((0, types_1.isNumber)(padding)) {
            return { left: padding, right: padding, top: padding, bottom: padding };
        }
        else if ((0, types_1.isPlainObject)(padding)) {
            if ("x" in padding || "y" in padding) {
                const { x = 0, y = 0 } = padding;
                return { left: x, right: x, top: y, bottom: y };
            }
            else if ("left" in padding || "right" in padding || "top" in padding || "bottom" in padding) {
                const { left = 0, right = 0, top = 0, bottom = 0 } = padding;
                return { left, right, top, bottom };
            }
            else {
                (0, assert_1.unreachable)(); // TODO: TypeScript 4.9
            }
        }
        else {
            if (padding.length == 2) {
                const [x = 0, y = 0] = padding;
                return { left: x, right: x, top: y, bottom: y };
            }
            else {
                const [left = 0, right = 0, top = 0, bottom = 0] = padding;
                return { left, right, top, bottom };
            }
        }
    }
    function border_radius(border_radius) {
        if ((0, types_1.isNumber)(border_radius)) {
            return {
                top_left: border_radius,
                top_right: border_radius,
                bottom_right: border_radius,
                bottom_left: border_radius,
            };
        }
        else if ((0, types_1.isPlainObject)(border_radius)) {
            return {
                top_left: border_radius.top_left ?? 0,
                top_right: border_radius.top_right ?? 0,
                bottom_right: border_radius.bottom_right ?? 0,
                bottom_left: border_radius.bottom_left ?? 0,
            };
        }
        else {
            const [top_left = 0, top_right = 0, bottom_right = 0, bottom_left = 0] = border_radius;
            return { top_left, top_right, bottom_right, bottom_left };
        }
    }
},
/* models/common/painting.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.round_rect = round_rect;
    function round_rect(ctx, bbox, border_radius) {
        /**
         * Create a path for a rect with rounded corners.
         *
         * From https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-roundrect.
         */
        let { top_left, top_right, bottom_right, bottom_left } = border_radius;
        if (top_left != 0 || top_right != 0 || bottom_right != 0 || bottom_left != 0) {
            const { left, right, top, bottom, width, height } = bbox;
            const scale = Math.min(width / (top_left + top_right), height / (top_right + bottom_right), width / (bottom_right + bottom_left), height / (top_left + bottom_left));
            if (scale < 1.0) {
                top_left *= scale;
                top_right *= scale;
                bottom_right *= scale;
                bottom_left *= scale;
            }
            ctx.moveTo(left + top_left, top);
            ctx.lineTo(right - top_right, top);
            if (top_right != 0) {
                ctx.arcTo(right, top, right, top + top_right, top_right);
            }
            ctx.lineTo(right, bottom - bottom_right);
            if (bottom_right != 0) {
                ctx.arcTo(right, bottom, right - bottom_right, bottom, bottom_right);
            }
            ctx.lineTo(left + bottom_left, bottom);
            if (bottom_left != 0) {
                ctx.arcTo(left, bottom, left, bottom - bottom_left, bottom_left);
            }
            ctx.lineTo(left, top + top_left);
            if (top_left != 0) {
                ctx.arcTo(left, top, left + top_left, top, top_left);
            }
            ctx.closePath();
        }
        else {
            const { left, top, width, height } = bbox;
            ctx.rect(left, top, width, height);
        }
    }
},
/* models/canvas/cartesian_frame.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const styled_element_1 = require(84) /* ../ui/styled_element */;
    const categorical_scale_1 = require(104) /* ../scales/categorical_scale */;
    const log_scale_1 = require(103) /* ../scales/log_scale */;
    const scale_1 = require(96) /* ../scales/scale */;
    const linear_scale_1 = require(101) /* ../scales/linear_scale */;
    const range_1 = require(98) /* ../ranges/range */;
    const range1d_1 = require(99) /* ../ranges/range1d */;
    const data_range1d_1 = require(106) /* ../ranges/data_range1d */;
    const factor_range_1 = require(109) /* ../ranges/factor_range */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const object_1 = require(9) /* ../../core/util/object */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const types_1 = require(8) /* ../../core/util/types */;
    const dom_1 = require(63) /* ../../core/dom */;
    class CartesianFrameView extends styled_element_1.StyledElementView {
        constructor() {
            super(...arguments);
            this._bbox = new bbox_1.BBox();
            this._x_ranges = new Map();
            this._y_ranges = new Map();
            this._x_scales = new Map();
            this._y_scales = new Map();
            this.position = new dom_1.InlineStyleSheet();
        }
        get bbox() {
            return this._bbox;
        }
        initialize() {
            super.initialize();
            this._configure_scales();
        }
        remove() {
            this._unregister_frame();
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            const { x_range, y_range, x_scale, y_scale, extra_x_ranges, extra_y_ranges, extra_x_scales, extra_y_scales } = this.model.properties;
            this.on_change([x_range, y_range, x_scale, y_scale, extra_x_ranges, extra_y_ranges, extra_x_scales, extra_y_scales], () => {
                this._configure_scales();
            });
        }
        _get_ranges(range, extra_ranges) {
            return new Map([...(0, object_1.entries)(extra_ranges), ["default", range]]);
        }
        _get_scales(scale, extra_scales, ranges, frame_range) {
            const in_scales = new Map([...(0, object_1.entries)(extra_scales), ["default", scale]]);
            const scales = new Map();
            for (const [name, range] of ranges) {
                const factor_range = range instanceof factor_range_1.FactorRange;
                const categorical_scale = scale instanceof categorical_scale_1.CategoricalScale;
                if (factor_range != categorical_scale) {
                    throw new Error(`'${range.type}' is incompatible '${scale.type}'`);
                }
                if (scale instanceof log_scale_1.LogScale && range instanceof data_range1d_1.DataRange1d) {
                    range.scale_hint = "log";
                }
                const base_scale = in_scales.get(name) ?? scale;
                const derived_scale = base_scale.clone();
                derived_scale.setv({ source_range: range, target_range: frame_range });
                scales.set(name, derived_scale);
            }
            return scales;
        }
        _configure_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() {
            const { x_range, y_range, extra_x_ranges, extra_y_ranges } = this.model;
            const { x_scale, y_scale, extra_x_scales, extra_y_scales } = this.model;
            (0, assert_1.assert)(x_scale.properties.source_range.is_unset && x_scale.properties.target_range.is_unset);
            (0, assert_1.assert)(y_scale.properties.source_range.is_unset && y_scale.properties.target_range.is_unset);
            this._configure_ranges();
            this._unregister_frame();
            this._x_ranges = this._get_ranges(x_range, extra_x_ranges);
            this._y_ranges = this._get_ranges(y_range, extra_y_ranges);
            this._register_frame();
            this._x_scales = this._get_scales(x_scale, extra_x_scales, this._x_ranges, this._x_target);
            this._y_scales = this._get_scales(y_scale, extra_y_scales, this._y_ranges, this._y_target);
            this._x_scale = this._x_scales.get("default");
            this._y_scale = this._y_scales.get("default");
            this.mark_finished();
        }
        _update_scales() {
            this._configure_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;
            }
        }
        _register_frame() {
            for (const range of this.ranges.values()) {
                range.frames.add(this);
            }
        }
        _unregister_frame() {
            for (const range of this.ranges.values()) {
                range.frames.delete(this);
            }
        }
        set_geometry(bbox) {
            this._bbox = bbox;
            this._update_scales();
            this._update_position();
        }
        get x_range() {
            return this.model.x_range;
        }
        get y_range() {
            return this.model.y_range;
        }
        get x_target() {
            return this._x_target;
        }
        get y_target() {
            return this._y_target;
        }
        get x_ranges() {
            return this._x_ranges;
        }
        get y_ranges() {
            return this._y_ranges;
        }
        get ranges() {
            return new Set([...this.x_ranges.values(), ...this.y_ranges.values()]);
        }
        get x_scales() {
            return this._x_scales;
        }
        get y_scales() {
            return this._y_scales;
        }
        get scales() {
            return new Set([...this.x_scales.values(), ...this.y_scales.values()]);
        }
        get x_scale() {
            return this._x_scale;
        }
        get y_scale() {
            return this._y_scale;
        }
        // TODO remove this when bbox handling is unified
        resolve_symbol(node) {
            const target = this;
            const value = target.bbox.resolve(node.symbol);
            const { offset } = node;
            if ((0, types_1.isNumber)(value)) {
                return value + offset;
            }
            else {
                const { x, y } = value;
                return { x: x + offset, y: y + offset };
            }
        }
        stylesheets() {
            return [...super.stylesheets(), this.position];
        }
        rendering_target() {
            return this.parent.canvas_view.underlays_el;
        }
        /**
         * Updates the position of the associated DOM element.
         */
        _update_position() {
            const { bbox, position } = this;
            if (bbox.is_valid) {
                position.replace(`
      :host {
        position: absolute;
        left:     ${bbox.left}px;
        top:      ${bbox.top}px;
        width:    ${bbox.width}px;
        height:   ${bbox.height}px;
      }
      `);
            }
            else {
                position.replace(`
      :host {
        display: none;
      }
      `);
            }
        }
    }
    exports.CartesianFrameView = CartesianFrameView;
    CartesianFrameView.__name__ = "CartesianFrameView";
    class CartesianFrame extends styled_element_1.StyledElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.CartesianFrame = CartesianFrame;
    _a = CartesianFrame;
    CartesianFrame.__name__ = "CartesianFrame";
    (() => {
        _a.prototype.default_view = CartesianFrameView;
        _a.define(({ Bool, Float, Dict, Ref }) => ({
            x_range: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
            y_range: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
            x_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
            y_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
            extra_x_ranges: [Dict(Ref(range_1.Range)), {}],
            extra_y_ranges: [Dict(Ref(range_1.Range)), {}],
            extra_x_scales: [Dict(Ref(scale_1.Scale)), {}],
            extra_y_scales: [Dict(Ref(scale_1.Scale)), {}],
            match_aspect: [Bool, false],
            aspect_scale: [Float, 1],
        }));
    })();
},
/* models/axes/axis.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const guide_renderer_1 = require(190) /* ../renderers/guide_renderer */;
    const ticker_1 = require(191) /* ../tickers/ticker */;
    const tick_formatter_1 = require(192) /* ../formatters/tick_formatter */;
    const labeling_1 = require(193) /* ../policies/labeling */;
    const bokeh_events_1 = require(53) /* ../../core/bokeh_events */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const types_1 = require(24) /* ../../core/types */;
    const side_panel_1 = require(173) /* ../../core/layout/side_panel */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_2 = require(8) /* ../../core/util/types */;
    const graphics_1 = require(180) /* ../../core/graphics */;
    const factor_range_1 = require(109) /* ../ranges/factor_range */;
    const base_text_1 = require(176) /* ../text/base_text */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const types_3 = require(8) /* ../../core/util/types */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const utils_1 = require(177) /* ../text/utils */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    exports.LabelOverrides = (0, kinds_1.Or)((0, kinds_1.Dict)((0, kinds_1.Or)(kinds_1.Str, (0, kinds_1.Ref)(base_text_1.BaseText))), (0, kinds_1.Mapping)((0, kinds_1.Or)(kinds_1.Str, kinds_1.Float), (0, kinds_1.Or)(kinds_1.Str, (0, kinds_1.Ref)(base_text_1.BaseText))));
    const { abs } = Math;
    class AxisView extends guide_renderer_1.GuideRendererView {
        constructor() {
            super(...arguments);
            /*private*/ this._axis_label_view = null;
            /*private*/ this._major_label_views = new Map();
        }
        get panel() {
            return this._panel;
        }
        set panel(panel) {
            this._panel = new side_panel_1.SidePanel(panel.side, this.model.face);
        }
        get bbox() {
            // TODO Fixed axes should not participate in layout at all.
            if (this.layout != null && this.model.fixed_location == null) {
                return this.layout.bbox;
            }
            else if (this.is_renderable) {
                const { extents } = this;
                const depth = Math.round(extents.tick + extents.tick_label + extents.axis_label);
                let { sx0, sy0, sx1, sy1 } = this.rule_scoords;
                const { dimension, face } = this;
                if (dimension == 0) {
                    if (face == "front") {
                        sy0 -= depth;
                    }
                    else {
                        sy1 += depth;
                    }
                }
                else {
                    if (face == "front") {
                        sx0 -= depth;
                    }
                    else {
                        sx1 += depth;
                    }
                }
                return bbox_1.BBox.from_lrtb({ left: sx0, top: sy0, right: sx1, bottom: sy1 });
            }
            else {
                return new bbox_1.BBox();
            }
        }
        *children() {
            yield* super.children();
            if (this._axis_label_view != null) {
                yield this._axis_label_view;
            }
            yield* this._major_label_views.values();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._init_axis_label();
            await this._init_major_labels();
        }
        async _init_axis_label() {
            const { axis_label } = this.model;
            if (axis_label != null) {
                const _axis_label = (0, types_3.isString)(axis_label) ? (0, utils_1.parse_delimited_string)(axis_label) : axis_label;
                this._axis_label_view = await (0, build_views_1.build_view)(_axis_label, { parent: this });
            }
            else {
                this._axis_label_view = null;
            }
        }
        async _init_major_labels() {
            for (const [label, label_text] of (0, object_1.dict)(this.model.major_label_overrides)) {
                const _label_text = (0, types_3.isString)(label_text) ? (0, utils_1.parse_delimited_string)(label_text) : label_text;
                this._major_label_views.set(label, await (0, build_views_1.build_view)(_label_text, { parent: this }));
            }
        }
        update_layout() {
            this.layout = new side_panel_1.SideLayout(this.panel, () => this.get_size(), true);
            this.layout.on_resize(() => {
                this._coordinates = undefined;
            });
        }
        get_size() {
            const { visible, fixed_location } = this.model;
            if (visible && fixed_location == null && this.is_renderable) {
                const { extents } = this;
                const height = Math.round(extents.tick + extents.tick_label + extents.axis_label);
                return { width: 0, height };
            }
            else {
                return { width: 0, height: 0 };
            }
        }
        get is_renderable() {
            const [range, cross_range] = this.ranges;
            return super.is_renderable && range.is_valid && cross_range.is_valid && range.span > 0 && cross_range.span > 0;
        }
        interactive_hit(sx, sy) {
            return this.bbox.contains(sx, sy);
        }
        on_hit(sx, sy) {
            const value = this._hit_value(sx, sy);
            if (value != null) {
                this.model.trigger_event(new bokeh_events_1.AxisClick(this.model, value));
                return true;
            }
            return false;
        }
        _paint() {
            const { tick_coords, extents } = this;
            const ctx = this.layer.ctx;
            this._draw_background(ctx, extents);
            this._draw_rule(ctx, extents);
            this._draw_major_ticks(ctx, extents, tick_coords);
            this._draw_minor_ticks(ctx, extents, tick_coords);
            this._draw_major_labels(ctx, extents, tick_coords);
            this._draw_axis_label(ctx, extents, tick_coords);
        }
        connect_signals() {
            super.connect_signals();
            const { axis_label, major_label_overrides } = this.model.properties;
            this.on_change(axis_label, async () => {
                this._axis_label_view?.remove();
                await this._init_axis_label();
            });
            this.on_change(major_label_overrides, async () => {
                for (const label_view of this._major_label_views.values()) {
                    label_view.remove();
                }
                await this._init_major_labels();
            });
            this.connect(this.model.change, () => this.plot_view.request_layout());
        }
        get needs_clip() {
            return this.model.fixed_location != null;
        }
        // drawing sub functions -----------------------------------------------------
        _draw_background(ctx, _extents) {
            if (!this.visuals.background_fill.doit) {
                return;
            }
            ctx.beginPath();
            const { x, y, width, height } = this.bbox;
            ctx.rect(x, y, width, height);
            this.visuals.background_fill.apply(ctx);
        }
        _draw_rule(ctx, _extents) {
            if (!this.visuals.axis_line.doit) {
                return;
            }
            const { sx0, sy0, sx1, sy1 } = this.rule_scoords;
            ctx.beginPath();
            ctx.moveTo(sx0, sy0);
            ctx.lineTo(sx1, sy1);
            this.visuals.axis_line.apply(ctx);
        }
        _draw_major_ticks(ctx, _extents, tick_coords) {
            const tin = this.model.major_tick_in;
            const tout = this.model.major_tick_out;
            const visuals = this.visuals.major_tick_line;
            this._draw_ticks(ctx, tick_coords.major, tin, tout, visuals);
        }
        _draw_minor_ticks(ctx, _extents, tick_coords) {
            const tin = this.model.minor_tick_in;
            const tout = this.model.minor_tick_out;
            const visuals = this.visuals.minor_tick_line;
            this._draw_ticks(ctx, tick_coords.minor, tin, tout, visuals);
        }
        _draw_major_labels(ctx, extents, tick_coords) {
            const coords = tick_coords.major;
            const labels = this.compute_labels(coords[this.dimension]);
            const orient = this.model.major_label_orientation;
            const standoff = extents.tick + this.model.major_label_standoff;
            const visuals = this.visuals.major_label_text;
            this._draw_oriented_labels(ctx, labels, coords, orient, standoff, visuals);
        }
        _axis_label_extent() {
            if (this._axis_label_view == null) {
                return 0;
            }
            const axis_label_graphics = this._axis_label_view.graphics();
            const padding = 3;
            const orient = this.model.axis_label_orientation;
            axis_label_graphics.visuals = this.visuals.axis_label_text.values();
            axis_label_graphics.angle = this.panel.get_label_angle_heuristic(orient);
            axis_label_graphics.base_font_size = this.plot_view.base_font_size;
            const size = axis_label_graphics.size();
            const extent = this.dimension == 0 ? size.height : size.width;
            const standoff = this.model.axis_label_standoff;
            return extent > 0 ? standoff + extent + padding : 0;
        }
        _draw_axis_label(ctx, extents, _tick_coords) {
            if (this._axis_label_view == null) {
                return;
            }
            const [sx, sy /* TODO, x_anchor, y_anchor*/] = (() => {
                const { bbox } = this;
                const { side, face } = this.panel;
                const [range] = this.ranges;
                const { axis_label_align } = this.model;
                switch (side) {
                    case "above":
                    case "below": {
                        const [sx, x_anchor] = (() => {
                            switch (axis_label_align) {
                                case "start": return !range.is_reversed ? [bbox.left, "left"] : [bbox.right, "right"];
                                case "center": return [bbox.hcenter, "center"];
                                case "end": return !range.is_reversed ? [bbox.right, "right"] : [bbox.left, "left"];
                            }
                        })();
                        const [sy, y_anchor] = face == "front" ? [bbox.bottom, "bottom"] : [bbox.top, "top"];
                        return [sx, sy, x_anchor, y_anchor];
                    }
                    case "left":
                    case "right": {
                        const [sy, y_anchor] = (() => {
                            switch (axis_label_align) {
                                case "start": return !range.is_reversed ? [bbox.bottom, "bottom"] : [bbox.top, "top"];
                                case "center": return [bbox.vcenter, "center"];
                                case "end": return !range.is_reversed ? [bbox.top, "top"] : [bbox.bottom, "bottom"];
                            }
                        })();
                        const [sx, x_anchor] = face == "front" ? [bbox.right, "right"] : [bbox.left, "left"];
                        return [sx, sy, x_anchor, y_anchor];
                    }
                }
            })();
            const [nx, ny] = this.normals;
            const orient = this.model.axis_label_orientation;
            const standoff = extents.tick + extents.tick_label + this.model.axis_label_standoff;
            const { vertical_align, align } = this.panel.get_label_text_heuristics(orient);
            const position = {
                sx: sx + nx * standoff,
                sy: sy + ny * standoff,
                x_anchor: align,
                y_anchor: vertical_align,
            };
            const axis_label_graphics = this._axis_label_view.graphics();
            axis_label_graphics.visuals = this.visuals.axis_label_text.values();
            axis_label_graphics.angle = this.panel.get_label_angle_heuristic(orient);
            axis_label_graphics.base_font_size = this.plot_view.base_font_size;
            axis_label_graphics.position = position;
            axis_label_graphics.align = align;
            axis_label_graphics.paint(ctx);
        }
        _draw_ticks(ctx, coords, tin, tout, visuals) {
            if (!visuals.doit) {
                return;
            }
            const [sxs, sys] = this.scoords(coords);
            const [nx, ny] = this.normals;
            const [nxin, nyin] = [nx * -tin, ny * -tin];
            const [nxout, nyout] = [nx * tout, ny * tout];
            visuals.set_value(ctx);
            ctx.beginPath();
            for (let i = 0; i < sxs.length; i++) {
                const sx0 = Math.round(sxs[i] + nxout);
                const sy0 = Math.round(sys[i] + nyout);
                const sx1 = Math.round(sxs[i] + nxin);
                const sy1 = Math.round(sys[i] + nyin);
                ctx.moveTo(sx0, sy0);
                ctx.lineTo(sx1, sy1);
            }
            ctx.stroke();
        }
        _draw_oriented_labels(ctx, labels, coords, orient, standoff, visuals) {
            if (!visuals.doit || labels.length == 0) {
                return;
            }
            const [sxs, sys] = this.scoords(coords);
            const [nx, ny] = this.normals;
            const nxd = nx * standoff;
            const nyd = ny * standoff;
            const { vertical_align, align } = this.panel.get_label_text_heuristics(orient);
            const angle = this.panel.get_label_angle_heuristic(orient);
            labels.visuals = visuals.values();
            labels.angle = angle;
            labels.base_font_size = this.plot_view.base_font_size;
            for (let i = 0; i < labels.length; i++) {
                const label = labels.items[i];
                label.position = {
                    sx: sxs[i] + nxd,
                    sy: sys[i] + nyd,
                    x_anchor: align,
                    y_anchor: vertical_align,
                };
                if (label instanceof graphics_1.TextBox) {
                    label.align = align;
                }
            }
            const n = labels.length;
            const indices = types_1.Indices.all_set(n);
            const { items } = labels;
            const bboxes = items.map((l) => l.bbox());
            const dist = (() => {
                const [range] = this.ranges;
                if (!range.is_reversed) {
                    return this.dimension == 0 ? (i, j) => bboxes[j].left - bboxes[i].right
                        : (i, j) => bboxes[i].top - bboxes[j].bottom;
                }
                else {
                    return this.dimension == 0 ? (i, j) => bboxes[i].left - bboxes[j].right
                        : (i, j) => bboxes[j].top - bboxes[i].bottom;
                }
            })();
            const { major_label_policy } = this.model;
            const selected = major_label_policy.filter(indices, bboxes, dist);
            const ids = [...selected.ones()];
            if (ids.length != 0) {
                const cbox = this.canvas.bbox;
                const correct_x = (k) => {
                    const bbox = bboxes[k];
                    if (bbox.left < 0) {
                        const offset = -bbox.left;
                        const { position } = items[k];
                        items[k].position = { ...position, sx: position.sx + offset };
                    }
                    else if (bbox.right > cbox.width) {
                        const offset = bbox.right - cbox.width;
                        const { position } = items[k];
                        items[k].position = { ...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 = { ...position, sy: position.sy + offset };
                    }
                    else if (bbox.bottom > cbox.height) {
                        const offset = bbox.bottom - cbox.height;
                        const { position } = items[k];
                        items[k].position = { ...position, sy: position.sy - offset };
                    }
                };
                const i = ids[0];
                const j = ids[ids.length - 1];
                if (this.dimension == 0) {
                    correct_x(i);
                    correct_x(j);
                }
                else {
                    correct_y(i);
                    correct_y(j);
                }
            }
            for (const i of selected) {
                const label = items[i];
                label.paint(ctx);
            }
        }
        // extents sub functions -----------------------------------------------------
        /*protected*/ _tick_extent() {
            const { major, minor } = this.tick_coords;
            const i = this.dimension;
            return Math.max(major[i].length == 0 ? 0 : this.model.major_tick_out, minor[i].length == 0 ? 0 : this.model.minor_tick_out);
        }
        _tick_label_extents() {
            const coords = this.tick_coords.major;
            const labels = this.compute_labels(coords[this.dimension]);
            const orient = this.model.major_label_orientation;
            const standoff = this.model.major_label_standoff;
            const visuals = this.visuals.major_label_text;
            return [this._oriented_labels_extent(labels, orient, standoff, visuals)];
        }
        get extents() {
            const tick_labels = this._tick_label_extents();
            return {
                tick: this._tick_extent(),
                tick_labels,
                tick_label: (0, array_1.sum)(tick_labels),
                axis_label: this._axis_label_extent(),
            };
        }
        _oriented_labels_extent(labels, orient, standoff, visuals) {
            if (labels.length == 0 || !visuals.doit) {
                return 0;
            }
            const angle = this.panel.get_label_angle_heuristic(orient);
            labels.visuals = visuals.values();
            labels.angle = angle;
            labels.base_font_size = this.plot_view.base_font_size;
            const size = labels.max_size();
            const extent = this.dimension == 0 ? size.height : size.width;
            const padding = 3;
            return extent > 0 ? standoff + extent + padding : 0;
        }
        // {{{ TODO: state
        get normals() {
            return this.panel.normals;
        }
        get dimension() {
            return this.panel.dimension;
        }
        compute_labels(ticks) {
            const labels = this.model.formatter.format_graphics(ticks, this);
            const { _major_label_views } = this;
            const visited = new Set();
            for (let i = 0; i < ticks.length; i++) {
                const override = _major_label_views.get(ticks[i]);
                if (override != null) {
                    visited.add(override);
                    labels[i] = override.graphics();
                }
            }
            // XXX: make sure unused overrides don't prevent document idle
            for (const label_view of this._major_label_views.values()) {
                if (!visited.has(label_view)) {
                    label_view._has_finished = true;
                }
            }
            return new graphics_1.GraphicsBoxes(labels);
        }
        scoords(coords) {
            /**
             * Compute screen coordinates with respect to the bbox.
             */
            const [x, y] = coords;
            const [sxs, sys] = this.coordinates.map_to_screen(x, y);
            if (this.model.fixed_location != null) {
                return [[...sxs], [...sys]];
            }
            else {
                const { bbox } = this;
                const { face } = this.panel;
                if (this.panel.is_vertical) {
                    const sx = face == "front" ? bbox.right : bbox.left;
                    return [(0, array_1.repeat)(sx, sxs.length), [...sys]];
                }
                else {
                    const sy = face == "front" ? bbox.bottom : bbox.top;
                    return [[...sxs], (0, array_1.repeat)(sy, sys.length)];
                }
            }
        }
        get ranges() {
            const i = this.dimension;
            const j = 1 - i;
            const { ranges } = this.coordinates;
            return [ranges[i], ranges[j]];
        }
        get computed_bounds() {
            const [range] = this.ranges;
            const user_bounds = this.model.bounds;
            const range_bounds = [range.min, range.max];
            if (user_bounds == "auto") {
                return [range.min, range.max];
            }
            else {
                let start;
                let end;
                const [user_start, user_end] = user_bounds;
                const [range_start, range_end] = range_bounds;
                const { min, max } = Math;
                if (abs(user_start - user_end) > abs(range_start - range_end)) {
                    start = max(min(user_start, user_end), range_start);
                    end = min(max(user_start, user_end), range_end);
                }
                else {
                    start = min(user_start, user_end);
                    end = max(user_start, user_end);
                }
                return [start, end];
            }
        }
        get rule_coords() {
            const i = this.dimension;
            const j = 1 - i;
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            const xs = new Array(2);
            const ys = new Array(2);
            const coords = [xs, ys];
            coords[i][0] = Math.max(start, range.min);
            coords[i][1] = Math.min(end, range.max);
            if (coords[i][0] > coords[i][1]) {
                coords[i][0] = coords[i][1] = NaN;
            }
            coords[j][0] = this.loc;
            coords[j][1] = this.loc;
            return coords;
        }
        get rule_scoords() {
            const [[sx0, sx1], [sy0, sy1]] = this.scoords(this.rule_coords);
            return {
                sx0: Math.round(sx0),
                sy0: Math.round(sy0),
                sx1: Math.round(sx1),
                sy1: Math.round(sy1),
            };
        }
        get tick_coords() {
            const i = this.dimension;
            const j = 1 - i;
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            const ticks = this.model.ticker.get_ticks(start, end, range, this.loc);
            const majors = ticks.major;
            const minors = ticks.minor;
            const xs = [];
            const ys = [];
            const coords = [xs, ys];
            const minor_xs = [];
            const minor_ys = [];
            const minor_coords = [minor_xs, minor_ys];
            const [range_min, range_max] = [range.min, range.max];
            for (let ii = 0; ii < majors.length; ii++) {
                if (majors[ii] < range_min || majors[ii] > range_max) {
                    continue;
                }
                coords[i].push(majors[ii]);
                coords[j].push(this.loc);
            }
            for (let ii = 0; ii < minors.length; ii++) {
                if (minors[ii] < range_min || minors[ii] > range_max) {
                    continue;
                }
                minor_coords[i].push(minors[ii]);
                minor_coords[j].push(this.loc);
            }
            return {
                major: coords,
                minor: minor_coords,
            };
        }
        get loc() {
            const { fixed_location } = this.model;
            if (fixed_location != null) {
                if ((0, types_2.isNumber)(fixed_location)) {
                    return fixed_location;
                }
                const [, cross_range] = this.ranges;
                if (cross_range instanceof factor_range_1.FactorRange) {
                    return cross_range.synthetic(fixed_location);
                }
                (0, assert_1.unreachable)();
            }
            const [, cross_range] = this.ranges;
            switch (this.panel.side) {
                case "left":
                case "below":
                    return cross_range.start;
                case "right":
                case "above":
                    return cross_range.end;
            }
        }
        get face() {
            return this.panel.face;
        }
        // }}}
        remove() {
            this._axis_label_view?.remove();
            for (const label_view of this._major_label_views.values()) {
                label_view.remove();
            }
            super.remove();
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            if (this._axis_label_view != null) {
                if (!this._axis_label_view.has_finished()) {
                    return false;
                }
            }
            for (const label_view of this._major_label_views.values()) {
                if (!label_view.has_finished()) {
                    return false;
                }
            }
            return true;
        }
    }
    exports.AxisView = AxisView;
    AxisView.__name__ = "AxisView";
    class Axis extends guide_renderer_1.GuideRenderer {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Axis = Axis;
    _a = Axis;
    Axis.__name__ = "Axis";
    (() => {
        _a.mixins([
            ["axis_", mixins.Line],
            ["major_tick_", mixins.Line],
            ["minor_tick_", mixins.Line],
            ["major_label_", mixins.Text],
            ["axis_label_", mixins.Text],
            ["background_", mixins.Fill],
        ]);
        _a.define(({ Any, Int, Float, Str, Ref, Tuple, Or, Nullable, Auto, Enum }) => ({
            dimension: [Or(Enum(0, 1), Auto), "auto"],
            face: [Or(enums_1.Face, Auto), "auto"],
            bounds: [Or(Tuple(Float, Float), Auto), "auto"],
            ticker: [Ref(ticker_1.Ticker)],
            formatter: [Ref(tick_formatter_1.TickFormatter)],
            axis_label: [Nullable(Or(Str, Ref(base_text_1.BaseText))), null],
            axis_label_standoff: [Int, 5],
            axis_label_orientation: [Or(enums_1.LabelOrientation, Float), "parallel"],
            axis_label_align: [enums_1.Align, "center"],
            major_label_standoff: [Int, 5],
            major_label_orientation: [Or(enums_1.LabelOrientation, Float), "horizontal"],
            major_label_overrides: [exports.LabelOverrides, new Map()],
            major_label_policy: [Ref(labeling_1.LabelingPolicy), () => new labeling_1.AllLabels()],
            major_tick_in: [Float, 2],
            major_tick_out: [Float, 6],
            minor_tick_in: [Float, 0],
            minor_tick_out: [Float, 4],
            fixed_location: [Nullable(Or(Float, Any)), null],
        }));
        _a.override({
            axis_line_color: "black",
            major_tick_line_color: "black",
            minor_tick_line_color: "black",
            major_label_text_font_size: "11px",
            major_label_text_align: "center", // XXX: remove
            major_label_text_baseline: "alphabetic", // XXX: remove
            axis_label_text_font_size: "13px",
            axis_label_text_font_style: "italic",
            background_fill_color: null,
        });
    })();
},
/* models/renderers/guide_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const renderer_1 = require(83) /* ./renderer */;
    class GuideRendererView extends renderer_1.RendererView {
    }
    exports.GuideRendererView = GuideRendererView;
    GuideRendererView.__name__ = "GuideRendererView";
    class GuideRenderer extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GuideRenderer = GuideRenderer;
    _a = GuideRenderer;
    GuideRenderer.__name__ = "GuideRenderer";
    (() => {
        _a.override({
            level: "guide",
        });
    })();
},
/* models/tickers/ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(51) /* ../../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(51) /* ../../model */;
    const graphics_1 = require(180) /* ../../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 ?? { loc: 0 })[0];
        }
        v_compute(tick, opts) {
            return this.doFormat(tick, opts ?? { loc: 0 });
        }
    }
    exports.TickFormatter = TickFormatter;
    TickFormatter.__name__ = "TickFormatter";
},
/* models/policies/labeling.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(40) /* ../../core/util/string */;
    const types_1 = require(8) /* ../../core/util/types */;
    const types_2 = require(24) /* ../../core/types */;
    class LabelingPolicy extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LabelingPolicy = LabelingPolicy;
    LabelingPolicy.__name__ = "LabelingPolicy";
    class AllLabels extends LabelingPolicy {
        constructor(attrs) {
            super(attrs);
        }
        filter(indices, _bboxes, _distance) {
            return indices;
        }
    }
    exports.AllLabels = AllLabels;
    AllLabels.__name__ = "AllLabels";
    class NoOverlap extends LabelingPolicy {
        constructor(attrs) {
            super(attrs);
        }
        filter(indices, _bboxes, distance) {
            const { min_distance } = this;
            let k = null;
            for (const i of indices) {
                if (k != null && distance(k, i) < min_distance) {
                    indices.unset(i);
                }
                else {
                    k = i;
                }
            }
            return indices;
        }
    }
    exports.NoOverlap = NoOverlap;
    _a = NoOverlap;
    NoOverlap.__name__ = "NoOverlap";
    (() => {
        _a.define(({ Float }) => ({
            min_distance: [Float, 5],
        }));
    })();
    class CustomLabelingPolicy extends LabelingPolicy {
        constructor(attrs) {
            super(attrs);
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        get func() {
            const code = (0, string_1.use_strict)(this.code);
            return new types_2.GeneratorFunction("indices", "bboxes", "distance", ...this.names, code);
        }
        filter(indices, bboxes, distance) {
            const obj = Object.create(null);
            const generator = this.func.call(obj, indices, bboxes, distance, ...this.values);
            let result = generator.next();
            if ((result.done ?? false) && result.value !== undefined) {
                const { value } = result;
                if (value instanceof types_2.Indices) {
                    return value;
                }
                else if (value === undefined) {
                    return indices;
                }
                else if ((0, types_1.isIterable)(value)) {
                    return types_2.Indices.from_indices(indices.size, value);
                }
                else {
                    return types_2.Indices.all_unset(indices.size);
                }
            }
            else {
                const array = [];
                do {
                    array.push(result.value);
                    result = generator.next();
                } while (!(result.done ?? false));
                return types_2.Indices.from_indices(indices.size, array);
            }
        }
    }
    exports.CustomLabelingPolicy = CustomLabelingPolicy;
    _b = CustomLabelingPolicy;
    CustomLabelingPolicy.__name__ = "CustomLabelingPolicy";
    (() => {
        _b.define(({ Unknown, Str, Dict }) => ({
            args: [Dict(Unknown), {}],
            code: [Str, ""],
        }));
    })();
},
/* models/axes/linear_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const continuous_axis_1 = require(195) /* ./continuous_axis */;
    const basic_tick_formatter_1 = require(196) /* ../formatters/basic_tick_formatter */;
    const basic_ticker_1 = require(197) /* ../tickers/basic_ticker */;
    class LinearAxisView extends continuous_axis_1.ContinuousAxisView {
    }
    exports.LinearAxisView = LinearAxisView;
    LinearAxisView.__name__ = "LinearAxisView";
    class LinearAxis extends continuous_axis_1.ContinuousAxis {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LinearAxis = LinearAxis;
    _a = LinearAxis;
    LinearAxis.__name__ = "LinearAxis";
    (() => {
        _a.prototype.default_view = LinearAxisView;
        _a.override({
            ticker: () => new basic_ticker_1.BasicTicker(),
            formatter: () => new basic_tick_formatter_1.BasicTickFormatter(),
        });
    })();
},
/* models/axes/continuous_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const axis_1 = require(189) /* ./axis */;
    class ContinuousAxisView extends axis_1.AxisView {
        _hit_value(sx, sy) {
            const [range] = this.ranges;
            const { start, end, span } = range;
            switch (this.dimension) {
                case 0: {
                    const { x0, width } = this.bbox;
                    return span * (sx - x0) / width + start;
                }
                case 1: {
                    const { y0, height } = this.bbox;
                    return end - span * (sy - y0) / height;
                }
            }
        }
    }
    exports.ContinuousAxisView = ContinuousAxisView;
    ContinuousAxisView.__name__ = "ContinuousAxisView";
    class ContinuousAxis extends axis_1.Axis {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ContinuousAxis = ContinuousAxis;
    ContinuousAxis.__name__ = "ContinuousAxis";
},
/* models/formatters/basic_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    exports.unicode_replace = unicode_replace;
    const tick_formatter_1 = require(192) /* ./tick_formatter */;
    const string_1 = require(40) /* ../../core/util/string */;
    function unicode_replace(input) {
        let output = "";
        for (const c of input) {
            if (c == "-") {
                output += "\u2212";
            }
            else {
                output += c;
            }
        }
        return output;
    }
    class BasicTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
            this.last_precision = 3;
        }
        get scientific_limit_low() {
            return 10.0 ** this.power_limit_low;
        }
        get scientific_limit_high() {
            return 10.0 ** this.power_limit_high;
        }
        _need_sci(ticks) {
            if (!this.use_scientific) {
                return false;
            }
            const { scientific_limit_high } = this;
            const { scientific_limit_low } = this;
            const zeroish = ticks.length < 2 ? 0 : Math.abs(ticks[1] - ticks[0]) / 10000;
            for (const tick of ticks) {
                const tick_abs = Math.abs(tick);
                if (tick_abs <= zeroish) {
                    continue;
                }
                if (tick_abs >= scientific_limit_high || tick_abs <= scientific_limit_low) {
                    return true;
                }
            }
            return false;
        }
        _format_with_precision(ticks, need_sci, precision) {
            if (need_sci) {
                return ticks.map((tick) => unicode_replace(tick.toExponential(precision)));
            }
            else {
                return ticks.map((tick) => unicode_replace((0, string_1.to_fixed)(tick, precision)));
            }
        }
        _auto_precision(ticks, need_sci) {
            const labels = new Array(ticks.length);
            const asc = this.last_precision <= 15;
            outer: for (let x = this.last_precision; asc ? x <= 15 : x >= 1; asc ? x++ : x--) {
                if (need_sci) {
                    labels[0] = ticks[0].toExponential(x);
                    for (let i = 1; i < ticks.length; i++) {
                        if (labels[i] == labels[i - 1]) {
                            continue outer;
                        }
                    }
                    this.last_precision = x;
                    break;
                }
                else {
                    labels[0] = (0, string_1.to_fixed)(ticks[0], x);
                    for (let i = 1; i < ticks.length; i++) {
                        labels[i] = (0, string_1.to_fixed)(ticks[i], x);
                        if (labels[i] == labels[i - 1]) {
                            continue outer;
                        }
                    }
                    this.last_precision = x;
                    break;
                }
            }
            return this.last_precision;
        }
        doFormat(ticks, _opts) {
            if (ticks.length == 0) {
                return [];
            }
            const need_sci = this._need_sci(ticks);
            const precision = this.precision == "auto" ? this._auto_precision(ticks, need_sci) : this.precision;
            return this._format_with_precision(ticks, need_sci, precision);
        }
    }
    exports.BasicTickFormatter = BasicTickFormatter;
    _a = BasicTickFormatter;
    BasicTickFormatter.__name__ = "BasicTickFormatter";
    (() => {
        _a.define(({ Bool, Int, Auto, Or }) => ({
            precision: [Or(Int, Auto), "auto"],
            use_scientific: [Bool, true],
            power_limit_high: [Int, 5],
            power_limit_low: [Int, -3],
        }));
    })();
},
/* models/tickers/basic_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const adaptive_ticker_1 = require(198) /* ./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) {
    var _a;
    __esModule();
    const continuous_ticker_1 = require(199) /* ./continuous_ticker */;
    const array_1 = require(10) /* ../../core/util/array */;
    const math_1 = require(11) /* ../../core/util/math */;
    class AdaptiveTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        get_min_interval() {
            return this.min_interval;
        }
        get_max_interval() {
            return this.max_interval ?? Infinity;
        }
        // These arguments control the range of possible intervals. The interval I
        // returned by get_interval() will be the one that most closely matches the
        // desired number of ticks, subject to the following constraints:
        // I = (M * B^N), where
        // M is a member of mantissas,
        // B is base,
        // and N is an integer;
        // and min_interval <= I <= max_interval.
        get extended_mantissas() {
            const prefix_mantissa = (0, array_1.nth)(this.mantissas, -1) / this.base;
            const suffix_mantissa = (0, array_1.nth)(this.mantissas, 0) * this.base;
            return [prefix_mantissa, ...this.mantissas, suffix_mantissa];
        }
        get base_factor() {
            return this.get_min_interval() == 0.0 ? 1.0 : this.get_min_interval();
        }
        get_interval(data_low, data_high, desired_n_ticks) {
            const data_range = data_high - data_low;
            const ideal_interval = this.get_ideal_interval(data_low, data_high, desired_n_ticks);
            const interval_exponent = Math.floor((0, math_1.log)(ideal_interval / this.base_factor, this.base));
            const ideal_magnitude = this.base ** interval_exponent * this.base_factor;
            // An untested optimization.
            //   const ideal_mantissa = ideal_interval / ideal_magnitude
            //   index = sorted_index(this.extended_mantissas, ideal_mantissa)
            //   candidate_mantissas = this.extended_mantissas[index..index + 1]
            const candidate_mantissas = this.extended_mantissas;
            const errors = candidate_mantissas.map((mantissa) => {
                return Math.abs(desired_n_ticks - (data_range / (mantissa * ideal_magnitude)));
            });
            const best_mantissa = candidate_mantissas[(0, array_1.argmin)(errors)];
            const interval = best_mantissa * ideal_magnitude;
            return (0, math_1.clamp)(interval, this.get_min_interval(), this.get_max_interval());
        }
    }
    exports.AdaptiveTicker = AdaptiveTicker;
    _a = AdaptiveTicker;
    AdaptiveTicker.__name__ = "AdaptiveTicker";
    (() => {
        _a.define(({ Float, List, Nullable }) => ({
            base: [Float, 10.0],
            mantissas: [List(Float), [1, 2, 5]],
            min_interval: [Float, 0.0],
            max_interval: [Nullable(Float), null],
        }));
    })();
},
/* models/tickers/continuous_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const ticker_1 = require(191) /* ./ticker */;
    const array_1 = require(10) /* ../../core/util/array */;
    class ContinuousTicker extends ticker_1.Ticker {
        constructor(attrs) {
            super(attrs);
        }
        get_ticks(data_low, data_high, _range, cross_loc) {
            return this.get_ticks_no_defaults(data_low, data_high, cross_loc, this.desired_num_ticks);
        }
        // The version of get_ticks() that does the work (and the version that
        // should be overridden in subclasses).
        get_ticks_no_defaults(data_low, data_high, _cross_loc, desired_n_ticks) {
            const interval = this.get_interval(data_low, data_high, desired_n_ticks);
            const start_factor = Math.floor(data_low / interval);
            const end_factor = Math.ceil(data_high / interval);
            let factors;
            if (!isFinite(start_factor) || !isFinite(end_factor)) {
                factors = [];
            }
            else {
                factors = (0, array_1.range)(start_factor, end_factor + 1);
            }
            const ticks = factors
                .map((factor) => factor * interval)
                .filter((tick) => data_low <= tick && tick <= data_high);
            const num_minor_ticks = this.num_minor_ticks;
            const minor_ticks = [];
            if (num_minor_ticks > 0 && ticks.length > 0) {
                const minor_interval = interval / num_minor_ticks;
                const minor_offsets = (0, array_1.range)(0, num_minor_ticks).map((i) => i * minor_interval);
                for (const x of minor_offsets.slice(1)) {
                    const mt = ticks[0] - x;
                    if (data_low <= mt && mt <= data_high) {
                        minor_ticks.push(mt);
                    }
                }
                for (const tick of ticks) {
                    for (const x of minor_offsets) {
                        const mt = tick + x;
                        if (data_low <= mt && mt <= data_high) {
                            minor_ticks.push(mt);
                        }
                    }
                }
            }
            return {
                major: ticks,
                minor: minor_ticks,
            };
        }
        // Returns the interval size that would produce exactly the number of
        // desired ticks.  (In general we won't use exactly this interval, because
        // we want the ticks to be round numbers.)
        get_ideal_interval(data_low, data_high, desired_n_ticks) {
            const data_range = data_high - data_low;
            return data_range / desired_n_ticks;
        }
    }
    exports.ContinuousTicker = ContinuousTicker;
    _a = ContinuousTicker;
    ContinuousTicker.__name__ = "ContinuousTicker";
    (() => {
        _a.define(({ Int }) => ({
            num_minor_ticks: [Int, 5],
            desired_num_ticks: [Int, 6],
        }));
    })();
},
/* models/tickers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var adaptive_ticker_1 = require(198) /* ./adaptive_ticker */;
    __esExport("AdaptiveTicker", adaptive_ticker_1.AdaptiveTicker);
    var basic_ticker_1 = require(197) /* ./basic_ticker */;
    __esExport("BasicTicker", basic_ticker_1.BasicTicker);
    var categorical_ticker_1 = require(201) /* ./categorical_ticker */;
    __esExport("CategoricalTicker", categorical_ticker_1.CategoricalTicker);
    var composite_ticker_1 = require(202) /* ./composite_ticker */;
    __esExport("CompositeTicker", composite_ticker_1.CompositeTicker);
    var continuous_ticker_1 = require(199) /* ./continuous_ticker */;
    __esExport("ContinuousTicker", continuous_ticker_1.ContinuousTicker);
    var customjs_ticker_1 = require(203) /* ./customjs_ticker */;
    __esExport("CustomJSTicker", customjs_ticker_1.CustomJSTicker);
    var datetime_ticker_1 = require(204) /* ./datetime_ticker */;
    __esExport("DatetimeTicker", datetime_ticker_1.DatetimeTicker);
    var days_ticker_1 = require(205) /* ./days_ticker */;
    __esExport("DaysTicker", days_ticker_1.DaysTicker);
    var fixed_ticker_1 = require(210) /* ./fixed_ticker */;
    __esExport("FixedTicker", fixed_ticker_1.FixedTicker);
    var log_ticker_1 = require(211) /* ./log_ticker */;
    __esExport("LogTicker", log_ticker_1.LogTicker);
    var mercator_ticker_1 = require(212) /* ./mercator_ticker */;
    __esExport("MercatorTicker", mercator_ticker_1.MercatorTicker);
    var months_ticker_1 = require(208) /* ./months_ticker */;
    __esExport("MonthsTicker", months_ticker_1.MonthsTicker);
    var single_interval_ticker_1 = require(206) /* ./single_interval_ticker */;
    __esExport("SingleIntervalTicker", single_interval_ticker_1.SingleIntervalTicker);
    var ticker_1 = require(191) /* ./ticker */;
    __esExport("Ticker", ticker_1.Ticker);
    var years_ticker_1 = require(209) /* ./years_ticker */;
    __esExport("YearsTicker", years_ticker_1.YearsTicker);
    var binned_ticker_1 = require(213) /* ./binned_ticker */;
    __esExport("BinnedTicker", binned_ticker_1.BinnedTicker);
},
/* models/tickers/categorical_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const ticker_1 = require(191) /* ./ticker */;
    class CategoricalTicker extends ticker_1.Ticker {
        constructor(attrs) {
            super(attrs);
        }
        get_ticks(start, end, range, _cross_loc) {
            const majors = this._collect(range.factors, range, start, end);
            const tops = this._collect(range.mapper.tops ?? [], range, start, end);
            const mids = this._collect(range.mapper.mids ?? [], 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/tickers/composite_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const continuous_ticker_1 = require(199) /* ./continuous_ticker */;
    const array_1 = require(10) /* ../../core/util/array */;
    class CompositeTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        // The tickers should be in order of increasing interval size; specifically,
        // if S comes before T, then it should be the case that
        // S.get_max_interval() < T.get_min_interval().
        // FIXME Enforce this automatically.
        get min_intervals() {
            return this.tickers.map((ticker) => ticker.get_min_interval());
        }
        get max_intervals() {
            return this.tickers.map((ticker) => ticker.get_max_interval());
        }
        get_min_interval() {
            return this.min_intervals[0];
        }
        get_max_interval() {
            return this.max_intervals[0];
        }
        get_best_ticker(data_low, data_high, desired_n_ticks) {
            const data_range = data_high - data_low;
            if (data_range == 0) {
                return this.tickers[0];
            }
            const ideal_interval = this.get_ideal_interval(data_low, data_high, desired_n_ticks);
            const ticker_ndxs = [
                (0, array_1.sorted_index)(this.min_intervals, ideal_interval) - 1,
                (0, array_1.sorted_index)(this.max_intervals, ideal_interval),
            ];
            const intervals = [
                this.min_intervals[ticker_ndxs[0]],
                this.max_intervals[ticker_ndxs[1]],
            ];
            const errors = intervals.map((interval) => {
                return Math.abs(desired_n_ticks - (data_range / interval));
            });
            let best_ticker;
            if ((0, array_1.is_empty)(errors.filter((e) => !isNaN(e)))) {
                // this can happen if the data isn't loaded yet, we just default to the first scale
                best_ticker = this.tickers[0];
            }
            else {
                const best_index = (0, array_1.argmin)(errors);
                const best_ticker_ndx = ticker_ndxs[best_index];
                best_ticker = this.tickers[best_ticker_ndx];
            }
            return best_ticker;
        }
        get_interval(data_low, data_high, desired_n_ticks) {
            const best_ticker = this.get_best_ticker(data_low, data_high, desired_n_ticks);
            return best_ticker.get_interval(data_low, data_high, desired_n_ticks);
        }
        get_ticks_no_defaults(data_low, data_high, cross_loc, desired_n_ticks) {
            const best_ticker = this.get_best_ticker(data_low, data_high, desired_n_ticks);
            return best_ticker.get_ticks_no_defaults(data_low, data_high, cross_loc, desired_n_ticks);
        }
    }
    exports.CompositeTicker = CompositeTicker;
    _a = CompositeTicker;
    CompositeTicker.__name__ = "CompositeTicker";
    (() => {
        _a.define(({ NonEmptyList, Ref }) => ({
            tickers: [NonEmptyList(Ref(continuous_ticker_1.ContinuousTicker))],
        }));
    })();
},
/* models/tickers/customjs_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const ticker_1 = require(191) /* ./ticker */;
    const factor_range_1 = require(109) /* ../ranges/factor_range */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(40) /* ../../core/util/string */;
    class CustomJSTicker extends ticker_1.Ticker {
        constructor(attrs) {
            super(attrs);
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        get_ticks(start, end, range, cross_loc) {
            const major_cb_data = { start, end, range, cross_loc };
            const major_ticks = this.major_ticks(major_cb_data);
            // CustomJSTicker for categorical axes only support a single level of major ticks
            if (range instanceof factor_range_1.FactorRange) {
                return { major: major_ticks, minor: [], tops: [], mids: [] };
            }
            const minor_cb_data = { major_ticks, ...major_cb_data };
            const minor_ticks = this.minor_ticks(minor_cb_data);
            return {
                major: major_ticks,
                minor: minor_ticks,
            };
        }
        major_ticks(cb_data) {
            if (this.major_code == "") {
                return [];
            }
            const code = (0, string_1.use_strict)(this.major_code);
            const func = new Function("cb_data", ...this.names, code);
            return func(cb_data, ...this.values);
        }
        minor_ticks(cb_data) {
            if (this.minor_code == "") {
                return [];
            }
            const code = (0, string_1.use_strict)(this.minor_code);
            const func = new Function("cb_data", ...this.names, code);
            return func(cb_data, ...this.values);
        }
    }
    exports.CustomJSTicker = CustomJSTicker;
    _a = CustomJSTicker;
    CustomJSTicker.__name__ = "CustomJSTicker";
    (() => {
        _a.define(({ Unknown, Str, Dict }) => ({
            args: [Dict(Unknown), {}],
            major_code: [Str, ""],
            minor_code: [Str, ""],
        }));
    })();
},
/* models/tickers/datetime_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const array_1 = require(10) /* ../../core/util/array */;
    const adaptive_ticker_1 = require(198) /* ./adaptive_ticker */;
    const composite_ticker_1 = require(202) /* ./composite_ticker */;
    const days_ticker_1 = require(205) /* ./days_ticker */;
    const months_ticker_1 = require(208) /* ./months_ticker */;
    const years_ticker_1 = require(209) /* ./years_ticker */;
    const util_1 = require(207) /* ./util */;
    class DatetimeTicker extends composite_ticker_1.CompositeTicker {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DatetimeTicker = DatetimeTicker;
    _a = DatetimeTicker;
    DatetimeTicker.__name__ = "DatetimeTicker";
    (() => {
        _a.override({
            num_minor_ticks: 0,
            tickers: () => [
                // Sub-second.
                new adaptive_ticker_1.AdaptiveTicker({
                    mantissas: [1, 2, 5],
                    base: 10,
                    min_interval: 0,
                    max_interval: 500 * util_1.ONE_MILLI,
                    num_minor_ticks: 0,
                }),
                // Seconds, minutes.
                new adaptive_ticker_1.AdaptiveTicker({
                    mantissas: [1, 2, 5, 10, 15, 20, 30],
                    base: 60,
                    min_interval: util_1.ONE_SECOND,
                    max_interval: 30 * util_1.ONE_MINUTE,
                    num_minor_ticks: 0,
                }),
                // Hours.
                new adaptive_ticker_1.AdaptiveTicker({
                    mantissas: [1, 2, 4, 6, 8, 12],
                    base: 24.0,
                    min_interval: util_1.ONE_HOUR,
                    max_interval: 12 * util_1.ONE_HOUR,
                    num_minor_ticks: 0,
                }),
                // Days.
                new days_ticker_1.DaysTicker({ days: (0, array_1.range)(1, 32) }),
                new days_ticker_1.DaysTicker({ days: (0, array_1.range)(1, 31, 3) }),
                new days_ticker_1.DaysTicker({ days: [1, 8, 15, 22] }),
                new days_ticker_1.DaysTicker({ days: [1, 15] }),
                // Months.
                new months_ticker_1.MonthsTicker({ months: (0, array_1.range)(0, 12, 1) }),
                new months_ticker_1.MonthsTicker({ months: (0, array_1.range)(0, 12, 2) }),
                new months_ticker_1.MonthsTicker({ months: (0, array_1.range)(0, 12, 4) }),
                new months_ticker_1.MonthsTicker({ months: (0, array_1.range)(0, 12, 6) }),
                // Years
                new years_ticker_1.YearsTicker({}),
            ],
        });
    })();
},
/* models/tickers/days_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const single_interval_ticker_1 = require(206) /* ./single_interval_ticker */;
    const util_1 = require(207) /* ./util */;
    const array_1 = require(10) /* ../../core/util/array */;
    // Given a start and end time in millis, returns the shortest array of
    // consecutive months (as Dates) that surrounds both times.
    function date_range_by_month(start_time, end_time) {
        const start_date = (0, util_1.last_month_no_later_than)(new Date(start_time));
        const end_date = (0, util_1.last_month_no_later_than)(new Date(end_time));
        // XXX This is not a reliable technique in general, but it should be
        // safe when the day of the month is 1.  (The problem case is this:
        // Mar 31 -> Apr 31, which becomes May 1.)
        end_date.setUTCMonth(end_date.getUTCMonth() + 1);
        const dates = [];
        const date = start_date;
        while (true) {
            dates.push((0, util_1.copy_date)(date));
            date.setUTCMonth(date.getUTCMonth() + 1);
            if (date > end_date) {
                break;
            }
        }
        return dates;
    }
    class DaysTicker extends single_interval_ticker_1.BaseSingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            const days = this.days;
            if (days.length > 1) {
                this.interval = (days[1] - days[0]) * util_1.ONE_DAY;
            }
            else {
                this.interval = 31 * util_1.ONE_DAY;
            }
        }
        get_ticks_no_defaults(data_low, data_high, _cross_loc, _desired_n_ticks) {
            const month_dates = date_range_by_month(data_low, data_high);
            const days = this.days;
            const days_of_month = (month_date, interval) => {
                const current_month = month_date.getUTCMonth();
                const dates = [];
                for (const day of days) {
                    const day_date = (0, util_1.copy_date)(month_date);
                    day_date.setUTCDate(day);
                    // We can't use all of the values in this.days, because they may not
                    // fall within the current month.  In fact, if, e.g., our month is 28 days
                    // and we're marking every third day, we don't want day 28 to show up
                    // because it'll be right next to the 1st of the next month.  So we
                    // make sure we have a bit of room before we include a day.
                    // TODO (bev) The above description does not exactly work because JS Date
                    // is broken and will happily consider "Feb 28 + 3*ONE_DAY" to have month "2"
                    const future_date = new Date(day_date.getTime() + (interval / 2));
                    if (future_date.getUTCMonth() == current_month) {
                        dates.push(day_date);
                    }
                }
                return dates;
            };
            const day_dates = (0, array_1.concat)(month_dates.map((date) => days_of_month(date, this.interval)));
            const all_ticks = day_dates.map((day_date) => day_date.getTime());
            const ticks_in_range = all_ticks.filter((tick) => data_low <= tick && tick <= data_high);
            return {
                major: ticks_in_range,
                minor: [],
            };
        }
    }
    exports.DaysTicker = DaysTicker;
    _a = DaysTicker;
    DaysTicker.__name__ = "DaysTicker";
    (() => {
        _a.define(({ Int, List }) => ({
            days: [List(Int), []],
        }));
        _a.override({
            num_minor_ticks: 0,
        });
    })();
},
/* models/tickers/single_interval_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const continuous_ticker_1 = require(199) /* ./continuous_ticker */;
    class BaseSingleIntervalTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        get_interval(_data_low, _data_high, _n_desired_ticks) {
            return this.interval;
        }
        get_min_interval() {
            return this.interval;
        }
        get_max_interval() {
            return this.interval;
        }
    }
    exports.BaseSingleIntervalTicker = BaseSingleIntervalTicker;
    BaseSingleIntervalTicker.__name__ = "BaseSingleIntervalTicker";
    class SingleIntervalTicker extends BaseSingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.SingleIntervalTicker = SingleIntervalTicker;
    _a = SingleIntervalTicker;
    SingleIntervalTicker.__name__ = "SingleIntervalTicker";
    (() => {
        _a.define(({ Float }) => ({
            interval: [Float],
        }));
    })();
},
/* models/tickers/util.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.copy_date = copy_date;
    exports.last_month_no_later_than = last_month_no_later_than;
    exports.last_year_no_later_than = last_year_no_later_than;
    // 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());
    }
    // 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;
    }
    // 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;
    }
},
/* models/tickers/months_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const single_interval_ticker_1 = require(206) /* ./single_interval_ticker */;
    const util_1 = require(207) /* ./util */;
    const array_1 = require(10) /* ../../core/util/array */;
    // Given a start and end time in millis, returns the shortest array of
    // consecutive years (as Dates) that surrounds both times.
    function date_range_by_year(start_time, end_time) {
        const start_date = (0, util_1.last_year_no_later_than)(new Date(start_time));
        const end_date = (0, util_1.last_year_no_later_than)(new Date(end_time));
        end_date.setUTCFullYear(end_date.getUTCFullYear() + 1);
        const dates = [];
        const date = start_date;
        while (true) {
            dates.push((0, util_1.copy_date)(date));
            date.setUTCFullYear(date.getUTCFullYear() + 1);
            if (date > end_date) {
                break;
            }
        }
        return dates;
    }
    class MonthsTicker extends single_interval_ticker_1.BaseSingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            const months = this.months;
            if (months.length > 1) {
                this.interval = (months[1] - months[0]) * util_1.ONE_MONTH;
            }
            else {
                this.interval = 12 * util_1.ONE_MONTH;
            }
        }
        get_ticks_no_defaults(data_low, data_high, _cross_loc, _desired_n_ticks) {
            const year_dates = date_range_by_year(data_low, data_high);
            const months = this.months;
            const months_of_year = (year_date) => {
                return months.map((month) => {
                    const month_date = (0, util_1.copy_date)(year_date);
                    month_date.setUTCMonth(month);
                    return month_date;
                });
            };
            const month_dates = (0, array_1.concat)(year_dates.map(months_of_year));
            const all_ticks = month_dates.map((month_date) => month_date.getTime());
            const ticks_in_range = all_ticks.filter((tick) => data_low <= tick && tick <= data_high);
            return {
                major: ticks_in_range,
                minor: [],
            };
        }
    }
    exports.MonthsTicker = MonthsTicker;
    _a = MonthsTicker;
    MonthsTicker.__name__ = "MonthsTicker";
    (() => {
        _a.define(({ Int, List }) => ({
            months: [List(Int), []],
        }));
    })();
},
/* models/tickers/years_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const basic_ticker_1 = require(197) /* ./basic_ticker */;
    const single_interval_ticker_1 = require(206) /* ./single_interval_ticker */;
    const util_1 = require(207) /* ./util */;
    class YearsTicker extends single_interval_ticker_1.BaseSingleIntervalTicker {
        constructor(attrs) {
            super(attrs);
            this.interval = util_1.ONE_YEAR;
            this.basic_ticker = new basic_ticker_1.BasicTicker({ num_minor_ticks: 0 });
        }
        get_ticks_no_defaults(data_low, data_high, cross_loc, desired_n_ticks) {
            const start_year = (0, util_1.last_year_no_later_than)(new Date(data_low)).getUTCFullYear();
            const end_year = (0, util_1.last_year_no_later_than)(new Date(data_high)).getUTCFullYear();
            const years = this.basic_ticker.get_ticks_no_defaults(start_year, end_year, cross_loc, desired_n_ticks).major;
            const all_ticks = years.map((year) => Date.UTC(year, 0, 1));
            const ticks_in_range = all_ticks.filter((tick) => data_low <= tick && tick <= data_high);
            return {
                major: ticks_in_range,
                minor: [],
            };
        }
    }
    exports.YearsTicker = YearsTicker;
    YearsTicker.__name__ = "YearsTicker";
},
/* models/tickers/fixed_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const continuous_ticker_1 = require(199) /* ./continuous_ticker */;
    class FixedTicker extends continuous_ticker_1.ContinuousTicker {
        constructor(attrs) {
            super(attrs);
        }
        get_ticks_no_defaults(_data_low, _data_high, _cross_loc, _desired_n_ticks) {
            return {
                major: [...this.ticks],
                minor: [...this.minor_ticks],
            };
        }
        // XXX: whatever, because FixedTicker needs to fulfill the interface somehow
        get_interval(_data_low, _data_high, _desired_n_ticks) {
            return 0;
        }
        get_min_interval() {
            return 0;
        }
        get_max_interval() {
            return 0;
        }
    }
    exports.FixedTicker = FixedTicker;
    _a = FixedTicker;
    FixedTicker.__name__ = "FixedTicker";
    (() => {
        _a.define(({ Float, Arrayable }) => ({
            ticks: [Arrayable(Float), []],
            minor_ticks: [Arrayable(Float), []],
        }));
    })();
},
/* models/tickers/log_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const adaptive_ticker_1 = require(198) /* ./adaptive_ticker */;
    const array_1 = require(10) /* ../../core/util/array */;
    class LogTicker extends adaptive_ticker_1.AdaptiveTicker {
        constructor(attrs) {
            super(attrs);
        }
        get_ticks_no_defaults(data_low, data_high, _cross_loc, desired_n_ticks) {
            const num_minor_ticks = this.num_minor_ticks;
            const minor_ticks = [];
            const base = this.base;
            const log_low = Math.log(data_low) / Math.log(base);
            const log_high = Math.log(data_high) / Math.log(base);
            const log_interval = log_high - log_low;
            let ticks;
            if (!isFinite(log_interval) || log_interval == 0) {
                ticks = [];
            }
            else if (log_interval < 2) { // treat as linear ticker
                const interval = this.get_interval(data_low, data_high, desired_n_ticks);
                const start_factor = Math.floor(data_low / interval);
                const end_factor = Math.ceil(data_high / interval);
                ticks = (0, array_1.range)(start_factor, end_factor + 1)
                    .filter((factor) => factor != 0)
                    .map((factor) => factor * interval)
                    .filter((tick) => data_low <= tick && tick <= data_high);
                if (num_minor_ticks > 0 && ticks.length > 0) {
                    const minor_interval = interval / num_minor_ticks;
                    const minor_offsets = (0, array_1.range)(0, num_minor_ticks).map((i) => i * minor_interval);
                    for (const x of minor_offsets.slice(1)) {
                        minor_ticks.push(ticks[0] - x);
                    }
                    for (const tick of ticks) {
                        for (const x of minor_offsets) {
                            minor_ticks.push(tick + x);
                        }
                    }
                }
            }
            else {
                const startlog = Math.ceil(log_low * 0.999999);
                const endlog = Math.floor(log_high * 1.000001);
                const interval = Math.ceil((endlog - startlog) / 9.0);
                ticks = (0, array_1.range)(startlog - 1, endlog + 1, interval)
                    .map((i) => base ** i);
                if (num_minor_ticks > 0 && ticks.length > 0) {
                    const minor_interval = base ** interval / num_minor_ticks;
                    const minor_offsets = (0, array_1.range)(1, num_minor_ticks + 1).map((i) => i * minor_interval);
                    for (const x of minor_offsets) {
                        minor_ticks.push(ticks[0] / x);
                    }
                    minor_ticks.push(ticks[0]);
                    for (const tick of ticks) {
                        for (const x of minor_offsets) {
                            minor_ticks.push(tick * x);
                        }
                    }
                }
            }
            return {
                major: ticks.filter((tick) => data_low <= tick && tick <= data_high),
                minor: minor_ticks.filter((tick) => data_low <= tick && tick <= data_high),
            };
        }
    }
    exports.LogTicker = LogTicker;
    _a = LogTicker;
    LogTicker.__name__ = "LogTicker";
    (() => {
        _a.override({
            mantissas: [1, 5],
        });
    })();
},
/* models/tickers/mercator_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const basic_ticker_1 = require(197) /* ./basic_ticker */;
    const enums_1 = require(20) /* ../../core/enums */;
    const projections_1 = require(134) /* ../../core/util/projections */;
    class MercatorTicker extends basic_ticker_1.BasicTicker {
        constructor(attrs) {
            super(attrs);
        }
        get_ticks_no_defaults(data_low, data_high, cross_loc, desired_n_ticks) {
            if (this.dimension == null) {
                throw new Error(`${this}.dimension wasn't configured`);
            }
            [data_low, data_high] = (0, projections_1.clip_mercator)(data_low, data_high, this.dimension);
            if (this.dimension == "lon") {
                return this._get_ticks_lon(data_low, data_high, cross_loc, desired_n_ticks);
            }
            else {
                return this._get_ticks_lat(data_low, data_high, cross_loc, desired_n_ticks);
            }
        }
        _get_ticks_lon(data_low, data_high, cross_loc, desired_n_ticks) {
            const [proj_low] = projections_1.wgs84_mercator.invert(data_low, cross_loc);
            const [proj_high, proj_cross_loc] = projections_1.wgs84_mercator.invert(data_high, cross_loc);
            const proj_ticks = super.get_ticks_no_defaults(proj_low, proj_high, cross_loc, desired_n_ticks);
            const major = [];
            for (const tick of proj_ticks.major) {
                if ((0, projections_1.in_bounds)(tick, "lon")) {
                    const [lon] = projections_1.wgs84_mercator.compute(tick, proj_cross_loc);
                    major.push(lon);
                }
            }
            const minor = [];
            for (const tick of proj_ticks.minor) {
                if ((0, projections_1.in_bounds)(tick, "lon")) {
                    const [lon] = projections_1.wgs84_mercator.compute(tick, proj_cross_loc);
                    minor.push(lon);
                }
            }
            return { major, minor };
        }
        _get_ticks_lat(data_low, data_high, cross_loc, desired_n_ticks) {
            const [, proj_low] = projections_1.wgs84_mercator.invert(cross_loc, data_low);
            const [proj_cross_loc, proj_high] = projections_1.wgs84_mercator.invert(cross_loc, data_high);
            const proj_ticks = super.get_ticks_no_defaults(proj_low, proj_high, cross_loc, desired_n_ticks);
            const major = [];
            for (const tick of proj_ticks.major) {
                if ((0, projections_1.in_bounds)(tick, "lat")) {
                    const [, lat] = projections_1.wgs84_mercator.compute(proj_cross_loc, tick);
                    major.push(lat);
                }
            }
            const minor = [];
            for (const tick of proj_ticks.minor) {
                if ((0, projections_1.in_bounds)(tick, "lat")) {
                    const [, lat] = projections_1.wgs84_mercator.compute(proj_cross_loc, tick);
                    minor.push(lat);
                }
            }
            return { major, minor };
        }
    }
    exports.MercatorTicker = MercatorTicker;
    _a = MercatorTicker;
    MercatorTicker.__name__ = "MercatorTicker";
    (() => {
        _a.define(({ Nullable }) => ({
            dimension: [Nullable(enums_1.LatLon), null],
        }));
    })();
},
/* models/tickers/binned_ticker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const ticker_1 = require(191) /* ./ticker */;
    const scanning_color_mapper_1 = require(214) /* ../mappers/scanning_color_mapper */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    class BinnedTicker extends ticker_1.Ticker {
        constructor(attrs) {
            super(attrs);
        }
        get_ticks(data_low, data_high, _range, _cross_loc) {
            const { binning } = this.mapper.metrics;
            const k_low = Math.max(0, (0, arrayable_1.left_edge_index)(data_low, binning));
            const k_high = Math.min((0, arrayable_1.left_edge_index)(data_high, binning) + 1, binning.length - 1);
            const _major = [];
            for (let k = k_low; k <= k_high; k++) {
                _major.push(binning[k]);
            }
            const { num_major_ticks } = this;
            const major = [];
            const n = num_major_ticks == "auto" ? _major.length : num_major_ticks;
            const step = Math.max(1, Math.floor(_major.length / n));
            for (let i = 0; i < _major.length; i += step) {
                major.push(_major[i]);
            }
            return {
                major,
                minor: [],
            };
        }
    }
    exports.BinnedTicker = BinnedTicker;
    _a = BinnedTicker;
    BinnedTicker.__name__ = "BinnedTicker";
    (() => {
        _a.define(({ Float, Ref, Or, Auto }) => ({
            mapper: [Ref(scanning_color_mapper_1.ScanningColorMapper)],
            num_major_ticks: [Or(Float, Auto), 8],
        }));
    })();
},
/* models/mappers/scanning_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_color_mapper_1 = require(215) /* ./continuous_color_mapper */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    class ScanningColorMapper extends continuous_color_mapper_1.ContinuousColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        index_to_value(index) {
            const scan_data = this._scan_data;
            return scan_data.binning[index];
        }
        value_to_index(value, palette_length) {
            const scan_data = this._scan_data;
            if (value < scan_data.binning[0]) {
                return -1;
            }
            else if (value > scan_data.binning[scan_data.binning.length - 1]) {
                return palette_length;
            }
            else {
                return (0, arrayable_1.left_edge_index)(value, scan_data.binning);
            }
        }
    }
    exports.ScanningColorMapper = ScanningColorMapper;
    ScanningColorMapper.__name__ = "ScanningColorMapper";
},
/* models/mappers/continuous_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const color_mapper_1 = require(216) /* ./color_mapper */;
    const glyph_renderer_1 = require(218) /* ../renderers/glyph_renderer */;
    const array_1 = require(10) /* ../../core/util/array */;
    const types_1 = require(8) /* ../../core/util/types */;
    class ContinuousColorMapper extends color_mapper_1.ColorMapper {
        constructor(attrs) {
            super(attrs);
            this._scan_data = null;
        }
        connect_signals() {
            super.connect_signals();
            const connect_renderers = () => {
                // TODO: if already connected this will bail. However, it won't remove old connections.
                for (const [renderer] of this.domain) {
                    this.connect(renderer.view.change, () => this.update_data());
                    this.connect(renderer.data_source.selected.change, () => this.update_data());
                }
            };
            const { high, low, high_color, low_color, palette, nan_color } = this.properties;
            this.on_change([high, low, high_color, low_color, palette, nan_color], () => this.update_data());
            this.connect(this.properties.domain.change, () => connect_renderers());
            connect_renderers();
        }
        update_data() {
            const { domain, palette } = this;
            const all_data = [...this._collect(domain)];
            this._scan_data = this.scan(all_data, palette.length);
            this.metrics_change.emit();
            this.change.emit();
        }
        get metrics() {
            if (this._scan_data == null) {
                this.update_data();
            }
            return this._scan_data;
        }
        *_collect(domain) {
            for (const [renderer, fields] of domain) {
                for (const field of (0, types_1.isArray)(fields) ? fields : [fields]) {
                    if (renderer.view.properties.indices.is_unset) {
                        continue;
                    }
                    const column = renderer.data_source.get_column(field);
                    if (column == null) {
                        continue;
                    }
                    let array = renderer.view.indices.select(column);
                    const masked = renderer.view.masked;
                    const selected = renderer.data_source.selected.indices;
                    let subset;
                    if (masked != null && selected.length > 0) {
                        subset = (0, array_1.intersection)([...masked], selected);
                    }
                    else if (masked != null) {
                        subset = [...masked];
                    }
                    else if (selected.length > 0) {
                        subset = selected;
                    }
                    if (subset != null) {
                        array = (0, array_1.map)(subset, (i) => array[i]);
                    }
                    if (array.length > 0 && !(0, types_1.isNumber)(array[0])) {
                        for (const subarray of array) {
                            yield* subarray;
                        }
                    }
                    else {
                        yield* array;
                    }
                }
            }
        }
        _v_compute(data, values, palette, colors) {
            const { nan_color } = colors;
            let { low_color, high_color } = colors;
            if (low_color == null) {
                low_color = palette[0];
            }
            if (high_color == null) {
                high_color = palette[palette.length - 1];
            }
            const { domain } = this;
            const all_data = !(0, array_1.is_empty)(domain) ? [...this._collect(domain)] : data;
            this._scan_data = this.scan(all_data, palette.length);
            this.metrics_change.emit();
            for (let i = 0, end = data.length; i < end; i++) {
                const d = data[i];
                if (isNaN(d)) {
                    values[i] = nan_color;
                }
                else {
                    values[i] = this.cmap(d, palette, low_color, high_color);
                }
            }
        }
        _colors(conv) {
            return {
                ...super._colors(conv),
                low_color: this.low_color != null ? conv(this.low_color) : undefined,
                high_color: this.high_color != null ? conv(this.high_color) : undefined,
            };
        }
        cmap(value, palette, low_color, high_color) {
            const index = this.value_to_index(value, palette.length);
            if (index < 0) {
                return low_color;
            }
            else if (index >= palette.length) {
                return high_color;
            }
            else {
                return palette[index];
            }
        }
    }
    exports.ContinuousColorMapper = ContinuousColorMapper;
    _a = ContinuousColorMapper;
    ContinuousColorMapper.__name__ = "ContinuousColorMapper";
    (() => {
        _a.define(({ Float, Str, Ref, Color, Or, Tuple, List, Nullable }) => {
            return {
                high: [Nullable(Float), null],
                low: [Nullable(Float), null],
                high_color: [Nullable(Color), null],
                low_color: [Nullable(Color), null],
                domain: [List(Tuple(Ref(glyph_renderer_1.GlyphRenderer), Or(Str, List(Str)))), []],
            };
        });
    })();
},
/* models/mappers/color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    exports._convert_color = _convert_color;
    exports._convert_palette = _convert_palette;
    const mapper_1 = require(217) /* ./mapper */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const types_1 = require(24) /* ../../core/types */;
    const color_1 = require(22) /* ../../core/util/color */;
    const platform_1 = require(27) /* ../../core/util/platform */;
    const ndarray_1 = require(30) /* ../../core/util/ndarray */;
    // export for testing
    function _convert_color(color) {
        return (0, color_1.encode_rgba)((0, color_1.color2rgba)(color));
    }
    // 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;
    }
    class ColorMapper extends mapper_1.Mapper {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this.metrics_change = new signaling_1.Signal0(this, "metrics_change");
        }
        v_compute(xs) {
            const values = new Array(xs.length);
            this._v_compute(xs, values, this.palette, this._colors((c) => c));
            return values;
        }
        get rgba_mapper() {
            const self = this;
            const palette = _convert_palette(this.palette);
            const colors = this._colors(_convert_color);
            return {
                v_compute(xs) {
                    const length_divisor = (0, ndarray_1.is_NDArray)(xs) && xs.dimension == 3 ? xs.shape[2] : 1;
                    const values = new types_1.ColorArray(xs.length / length_divisor);
                    self._v_compute_uint32(xs, values, palette, colors);
                    return new Uint8ClampedArray((0, platform_1.to_big_endian)(values).buffer);
                },
            };
        }
        _colors(conv) {
            return { nan_color: conv(this.nan_color) };
        }
        _v_compute_uint32(xs, values, palette, colors) {
            this._v_compute(xs, values, palette, colors);
        }
    }
    exports.ColorMapper = ColorMapper;
    _a = ColorMapper;
    ColorMapper.__name__ = "ColorMapper";
    (() => {
        _a.define(({ Color, List }) => ({
            palette: [List(Color)],
            nan_color: [Color, "gray"],
        }));
    })();
},
/* models/mappers/mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const transform_1 = require(97) /* ../transforms/transform */;
    class Mapper extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        compute(_x) {
            // If it's just a single value, then a mapper doesn't really make sense.
            throw new Error("mapping single values is not supported");
        }
    }
    exports.Mapper = Mapper;
    Mapper.__name__ = "Mapper";
},
/* models/renderers/glyph_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const data_renderer_1 = require(219) /* ./data_renderer */;
    const line_1 = require(220) /* ../glyphs/line */;
    const patch_1 = require(230) /* ../glyphs/patch */;
    const harea_step_1 = require(231) /* ../glyphs/harea_step */;
    const harea_1 = require(234) /* ../glyphs/harea */;
    const varea_step_1 = require(235) /* ../glyphs/varea_step */;
    const varea_1 = require(236) /* ../glyphs/varea */;
    const glyph_1 = require(222) /* ../glyphs/glyph */;
    const columnar_data_source_1 = require(128) /* ../sources/columnar_data_source */;
    const cds_view_1 = require(237) /* ../sources/cds_view */;
    const types_1 = require(24) /* ../../core/types */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const object_1 = require(9) /* ../../core/util/object */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const eq_1 = require(26) /* ../../core/util/eq */;
    const factor_range_1 = require(109) /* ../ranges/factor_range */;
    const decoration_1 = require(227) /* ../graphics/decoration */;
    const selection_defaults = {
        fill: {},
        line: {},
    };
    const decimated_defaults = {
        fill: { fill_alpha: 0.3, fill_color: "grey" },
        line: { line_alpha: 0.3, line_color: "grey" },
    };
    const nonselection_defaults = {
        fill: { fill_alpha: 0.2 },
        line: {},
    };
    const muted_defaults = {
        fill: { fill_alpha: 0.2 },
        line: {},
    };
    class GlyphRendererView extends data_renderer_1.DataRendererView {
        get glyph_view() {
            return this.glyph;
        }
        *children() {
            yield* super.children();
            yield this.cds_view;
            yield this.glyph;
            yield this.selection_glyph;
            yield this.nonselection_glyph;
            if (this.hover_glyph != null) {
                yield this.hover_glyph;
            }
            yield this.muted_glyph;
            yield this.decimated_glyph;
        }
        get data_source() {
            return this.model.properties.data_source;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.cds_view = await (0, build_views_1.build_view)(this.model.view, { parent: this });
            const base_glyph = this.model.glyph;
            this.glyph = await this.build_glyph_view(base_glyph);
            const has_fill = "fill" in this.glyph.visuals;
            const has_line = "line" in this.glyph.visuals;
            const glyph_attrs = { ...base_glyph.attributes };
            delete glyph_attrs.id;
            function mk_glyph(defaults) {
                const attrs = (0, object_1.clone)(glyph_attrs);
                if (has_fill) {
                    (0, object_1.extend)(attrs, defaults.fill);
                }
                if (has_line) {
                    (0, object_1.extend)(attrs, defaults.line);
                }
                return new base_glyph.constructor(attrs);
            }
            function glyph_from_mode(defaults, glyph) {
                if (glyph instanceof glyph_1.Glyph) {
                    return glyph;
                }
                else if (glyph == "auto") {
                    return mk_glyph(defaults);
                }
                return mk_glyph({ fill: {}, line: {} });
            }
            let { selection_glyph, nonselection_glyph, hover_glyph, muted_glyph } = this.model;
            selection_glyph = glyph_from_mode(selection_defaults, selection_glyph);
            this.selection_glyph = await this.build_glyph_view(selection_glyph);
            nonselection_glyph = glyph_from_mode(nonselection_defaults, nonselection_glyph);
            this.nonselection_glyph = await this.build_glyph_view(nonselection_glyph);
            if (hover_glyph != null) {
                this.hover_glyph = await this.build_glyph_view(hover_glyph);
            }
            muted_glyph = glyph_from_mode(muted_defaults, muted_glyph);
            this.muted_glyph = await this.build_glyph_view(muted_glyph);
            const decimated_glyph = glyph_from_mode(decimated_defaults, "auto");
            this.decimated_glyph = await this.build_glyph_view(decimated_glyph);
            this.selection_glyph.set_base(this.glyph);
            this.nonselection_glyph.set_base(this.glyph);
            this.hover_glyph?.set_base(this.glyph);
            this.muted_glyph.set_base(this.glyph);
            this.decimated_glyph.set_base(this.glyph);
            await this.set_data();
        }
        async build_glyph_view(glyph) {
            return (0, build_views_1.build_view)(glyph, { parent: this });
        }
        remove() {
            this.cds_view.remove();
            this.glyph.remove();
            this.selection_glyph.remove();
            this.nonselection_glyph.remove();
            this.hover_glyph?.remove();
            this.muted_glyph.remove();
            this.decimated_glyph.remove();
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            const render = () => this.request_paint();
            const update = () => this.update_data();
            this.connect(this.model.change, render);
            this.connect(this.glyph.model.change, update);
            this.connect(this.selection_glyph.model.change, update);
            this.connect(this.nonselection_glyph.model.change, update);
            if (this.hover_glyph != null) {
                this.connect(this.hover_glyph.model.change, update);
            }
            this.connect(this.muted_glyph.model.change, update);
            this.connect(this.decimated_glyph.model.change, update);
            this.connect(this.model.data_source.change, update);
            this.connect(this.model.data_source.streaming, update);
            this.connect(this.model.data_source.patching, (indices) => this.update_data(indices));
            this.connect(this.model.data_source.selected.change, render);
            this.connect(this.model.data_source._select, render);
            if (this.hover_glyph != null) {
                this.connect(this.model.data_source.inspect, () => {
                    // XXX: hoping for the best, assuming no in-place mutation
                    const { inspected } = this.model.data_source;
                    const current_inspected = {
                        indices: inspected.indices,
                        line_indices: inspected.line_indices,
                        multiline_indices: inspected.multiline_indices,
                        image_indices: inspected.image_indices,
                        selected_glyphs: inspected.selected_glyphs,
                    };
                    if (!(0, eq_1.is_equal)(this._previous_inspected, current_inspected)) {
                        this._previous_inspected = current_inspected;
                        render();
                    }
                });
            }
            this.connect(this.model.properties.view.change, async () => {
                this.cds_view.remove();
                this.cds_view = await (0, build_views_1.build_view)(this.model.view, { parent: this });
                await update();
            });
            this.connect(this.model.view.properties.indices.change, update);
            this.connect(this.model.view.properties.masked.change, async () => await this.set_visuals());
            this.connect(this.model.properties.visible.change, () => this.plot_view.invalidate_dataranges = true);
            const { x_ranges, y_ranges } = this.plot_view.frame;
            for (const [, range] of x_ranges) {
                if (range instanceof factor_range_1.FactorRange) {
                    this.connect(range.invalidate_synthetic, update);
                }
            }
            for (const [, range] of y_ranges) {
                if (range instanceof factor_range_1.FactorRange) {
                    this.connect(range.invalidate_synthetic, update);
                }
            }
            const { transformchange, exprchange } = this.model.glyph;
            this.connect(transformchange, update);
            this.connect(exprchange, update);
        }
        _update_masked_indices() {
            const masked = this.glyph.mask_data();
            this.model.view.masked = masked;
            return masked;
        }
        async update_data(indices) {
            await this.set_data(indices);
            this.request_paint();
        }
        // 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
        async set_data(indices) {
            const source = this.model.data_source;
            this.all_indices = this.model.view.indices;
            const { all_indices } = this;
            await this.glyph.set_data(source, all_indices, indices);
            await this.decimated_glyph.set_data(source, all_indices, indices);
            await this.selection_glyph.set_data(source, all_indices, indices);
            await this.nonselection_glyph.set_data(source, all_indices, indices);
            await this.hover_glyph?.set_data(source, all_indices, indices);
            await this.muted_glyph.set_data(source, all_indices, indices);
            await 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;
        }
        async set_visuals() {
            const source = this.model.data_source;
            const { all_indices } = this;
            this.glyph.set_visuals(source, all_indices);
            this.glyph.after_visuals();
            await this.glyph.after_lazy_visuals();
            this.decimated_glyph.set_visuals(source, all_indices);
            this.decimated_glyph.after_visuals();
            await this.decimated_glyph.after_lazy_visuals();
            this.selection_glyph.set_visuals(source, all_indices);
            this.selection_glyph.after_visuals();
            await this.selection_glyph.after_lazy_visuals();
            this.nonselection_glyph.set_visuals(source, all_indices);
            this.nonselection_glyph.after_visuals();
            await this.nonselection_glyph.after_lazy_visuals();
            this.hover_glyph?.set_visuals(source, all_indices);
            this.hover_glyph?.after_visuals();
            await this.hover_glyph?.after_lazy_visuals();
            this.muted_glyph.set_visuals(source, all_indices);
            this.muted_glyph.after_visuals();
            await this.muted_glyph.after_lazy_visuals();
        }
        map_data() {
            this.glyph.map_data();
            this.decimated_glyph.map_data();
            this.selection_glyph.map_data();
            this.nonselection_glyph.map_data();
            this.hover_glyph?.map_data();
            this.muted_glyph.map_data();
        }
        get bbox() {
            return this.glyph.bbox;
        }
        get has_webgl() {
            return this.glyph.has_webgl;
        }
        _paint() {
            const { has_webgl } = this;
            this.map_data();
            // all_indices is in full data space, indices is converted to subset space by mask_data (that may use the spatial index)
            const all_indices = [...this.all_indices];
            let indices = [...this._update_masked_indices()];
            const { ctx } = this.layer;
            ctx.save();
            // selected is in full set space
            const { selected } = this.model.data_source;
            const selected_full_indices = (() => {
                if (selected.is_empty()) {
                    return [];
                }
                else {
                    if (this.glyph instanceof line_1.LineView && selected.selected_glyph === this.glyph.model) {
                        return this.model.view.convert_indices_from_subset(indices);
                    }
                    else {
                        return selected.indices;
                    }
                }
            })();
            // inspected is in full set space
            const { inspected } = this.model.data_source;
            this._previous_inspected = {
                indices: inspected.indices,
                line_indices: inspected.line_indices,
                multiline_indices: inspected.multiline_indices,
                image_indices: inspected.image_indices,
                selected_glyphs: inspected.selected_glyphs,
            };
            const inspected_full_indices = new Set((() => {
                if (inspected.is_empty()) {
                    return [];
                }
                else {
                    if (inspected.selected_glyph != null) {
                        return this.model.view.convert_indices_from_subset(indices);
                    }
                    else if (inspected.indices.length > 0) {
                        return inspected.indices;
                    }
                    else {
                        // TODO: return inspected.multiline_indices.keys()
                        return Object.keys(inspected.multiline_indices).map((i) => parseInt(i));
                    }
                }
            })());
            // inspected is transformed to subset space
            const inspected_subset_indices = (0, arrayable_1.filter)(indices, (i) => inspected_full_indices.has(all_indices[i]));
            const { lod_threshold } = this.plot_model;
            let glyph;
            let nonselection_glyph;
            let selection_glyph;
            if ((this.model.document != null ? this.model.document.interactive_duration() > 0 : false)
                && !has_webgl && lod_threshold != null && all_indices.length > lod_threshold) {
                // Render decimated during interaction if too many elements and not using GL
                indices = [...this.decimated];
                glyph = this.decimated_glyph;
                nonselection_glyph = this.decimated_glyph;
                selection_glyph = this.selection_glyph;
            }
            else {
                glyph = this.model.muted ? this.muted_glyph : this.glyph;
                nonselection_glyph = this.nonselection_glyph;
                selection_glyph = this.selection_glyph;
            }
            if (this.hover_glyph != null && inspected_subset_indices.length != 0) {
                // TODO: keep working on Indices instead of converting back and forth
                const set = new Set(indices);
                for (const i of inspected_subset_indices) {
                    set.delete(i);
                }
                indices = [...set];
            }
            // Render with no selection
            if (selected_full_indices.length == 0) {
                if (this.glyph instanceof line_1.LineView) {
                    if (this.hover_glyph != null && inspected_subset_indices.length != 0) {
                        this.hover_glyph.paint(ctx, this.model.view.convert_indices_from_subset(inspected_subset_indices));
                    }
                    else {
                        glyph.paint(ctx, all_indices);
                    }
                }
                else if (this.glyph instanceof patch_1.PatchView ||
                    this.glyph instanceof harea_1.HAreaView ||
                    this.glyph instanceof varea_1.VAreaView ||
                    this.glyph instanceof varea_step_1.VAreaStepView ||
                    this.glyph instanceof harea_step_1.HAreaStepView) {
                    if (inspected.selected_glyphs.length == 0 || this.hover_glyph == null) {
                        glyph.paint(ctx, all_indices);
                    }
                    else {
                        for (const sglyph of inspected.selected_glyphs) {
                            if (sglyph == this.glyph.model) {
                                this.hover_glyph.paint(ctx, all_indices);
                            }
                        }
                    }
                }
                else {
                    glyph.paint(ctx, indices);
                    if (this.hover_glyph != null && inspected_subset_indices.length != 0) {
                        this.hover_glyph.paint(ctx, inspected_subset_indices);
                    }
                }
                // Render with selection
            }
            else {
                // reset the selection mask
                const selected_mask = new Set(selected_full_indices);
                // intersect/different selection with render mask
                const selected_subset_indices = new Array();
                const nonselected_subset_indices = new Array();
                // now, selected is changed to subset space, except for Line glyph
                if (this.glyph instanceof line_1.LineView) {
                    for (const i of all_indices) {
                        if (selected_mask.has(i)) {
                            selected_subset_indices.push(i);
                        }
                        else {
                            nonselected_subset_indices.push(i);
                        }
                    }
                }
                else {
                    for (const i of indices) {
                        if (selected_mask.has(all_indices[i])) {
                            selected_subset_indices.push(i);
                        }
                        else {
                            nonselected_subset_indices.push(i);
                        }
                    }
                }
                nonselection_glyph.paint(ctx, nonselected_subset_indices);
                selection_glyph.paint(ctx, selected_subset_indices);
                if (this.hover_glyph != null) {
                    if (this.glyph instanceof line_1.LineView) {
                        this.hover_glyph.paint(ctx, this.model.view.convert_indices_from_subset(inspected_subset_indices));
                    }
                    else {
                        this.hover_glyph.paint(ctx, inspected_subset_indices);
                    }
                }
            }
            ctx.restore();
        }
        get_reference_point(field, value) {
            if (field != null) {
                const array = this.model.data_source.get_column(field);
                if (array != null) {
                    for (const [key, index] of this.model.view.indices_map) {
                        if (array[key] == value) {
                            return index;
                        }
                    }
                }
            }
            return 0;
        }
        draw_legend(ctx, x0, x1, y0, y1, field, label, index) {
            if (this.glyph.data_size == 0) {
                return;
            }
            const subset_index = (() => {
                if (index == null) {
                    return this.get_reference_point(field, label);
                }
                else {
                    const { indices_map } = this.model.view;
                    return indices_map.get(index);
                }
            })();
            if (subset_index != null) {
                this.glyph.draw_legend_for_index(ctx, { x0, x1, y0, y1 }, subset_index);
            }
        }
        hit_test(geometry) {
            if (!this.model.visible) {
                return null;
            }
            const hit_test_result = this.glyph.hit_test(geometry);
            // glyphs that don't have hit-testing implemented will return null
            if (hit_test_result == null) {
                return null;
            }
            return this.model.view.convert_selection_from_subset(hit_test_result);
        }
    }
    exports.GlyphRendererView = GlyphRendererView;
    GlyphRendererView.__name__ = "GlyphRendererView";
    class GlyphRenderer extends data_renderer_1.DataRenderer {
        constructor(attrs) {
            super(attrs);
        }
        get_selection_manager() {
            return this.data_source.selection_manager;
        }
        add_decoration(marking, node) {
            const decoration = new decoration_1.Decoration({ marking, node });
            const glyphs = [
                this.glyph,
                this.selection_glyph,
                this.nonselection_glyph,
                this.hover_glyph,
                this.muted_glyph,
            ];
            for (const glyph of glyphs) {
                if (glyph instanceof glyph_1.Glyph) {
                    glyph.decorations = [...glyph.decorations, decoration];
                }
            }
            return decoration;
        }
    }
    exports.GlyphRenderer = GlyphRenderer;
    _a = GlyphRenderer;
    GlyphRenderer.__name__ = "GlyphRenderer";
    (() => {
        _a.prototype.default_view = GlyphRendererView;
        _a.define(({ Bool, Auto, Or, Ref, Null, Nullable }) => ({
            data_source: [Ref(columnar_data_source_1.ColumnarDataSource)],
            view: [Ref(cds_view_1.CDSView), () => new cds_view_1.CDSView()],
            glyph: [Ref(glyph_1.Glyph)],
            hover_glyph: [Nullable(Ref(glyph_1.Glyph)), null],
            nonselection_glyph: [Or(Ref(glyph_1.Glyph), Auto, Null), "auto"],
            selection_glyph: [Or(Ref(glyph_1.Glyph), Auto, Null), "auto"],
            muted_glyph: [Or(Ref(glyph_1.Glyph), Auto, Null), "auto"],
            muted: [Bool, false],
        }));
    })();
},
/* models/renderers/data_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b;
    __esModule();
    const renderer_1 = require(83) /* ./renderer */;
    const data_range1d_1 = require(106) /* ../ranges/data_range1d */;
    class DataRendererView extends renderer_1.RendererView {
        constructor() {
            super(...arguments);
            this[_a] = true;
        }
        get xscale() {
            return this.coordinates.x_scale;
        }
        get yscale() {
            return this.coordinates.y_scale;
        }
        bounds() {
            return this.glyph_view.bounds();
        }
        log_bounds() {
            return this.glyph_view.log_bounds();
        }
    }
    exports.DataRendererView = DataRendererView;
    _a = data_range1d_1.auto_ranged;
    DataRendererView.__name__ = "DataRendererView";
    class DataRenderer extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
        get selection_manager() {
            return this.get_selection_manager();
        }
    }
    exports.DataRenderer = DataRenderer;
    _b = DataRenderer;
    DataRenderer.__name__ = "DataRenderer";
    (() => {
        _b.override({
            level: "glyph",
        });
    })();
},
/* models/glyphs/line.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const utils_1 = require(228) /* ./utils */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const selection_1 = require(130) /* ../selections/selection */;
    class LineView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { LineGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(573) /* ./webgl/line_gl */));
            return LineGL;
        }
        _paint(ctx, indices, data) {
            const { sx, sy } = { ...this, ...data };
            const nonselection = this.parent.nonselection_glyph == this;
            let iprev = null;
            const gap = (i) => iprev != null && i - iprev != 1;
            let move = true;
            ctx.beginPath();
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                if (nonselection && !move && iprev != null && i - iprev > 1 && isFinite(sx[iprev + 1] + sy[iprev + 1])) {
                    ctx.lineTo(sx[iprev + 1], sy[iprev + 1]); // End of previous line
                }
                if (!isFinite(sx_i + sy_i)) {
                    move = true;
                }
                else {
                    if (move || gap(i)) {
                        if (nonselection && i > 0 && isFinite(sx[i - 1] + sy[i - 1])) {
                            ctx.moveTo(sx[i - 1], sy[i - 1]); // Start of new line
                            ctx.lineTo(sx_i, sy_i);
                        }
                        else {
                            ctx.moveTo(sx_i, sy_i);
                        }
                        move = false;
                    }
                    else {
                        ctx.lineTo(sx_i, sy_i);
                    }
                    iprev = i;
                }
            }
            if (nonselection && !move && iprev != null) {
                const n = sx.length;
                if (iprev < n - 1 && isFinite(sx[iprev + 1] + sy[iprev + 1])) {
                    ctx.lineTo(sx[iprev + 1], sy[iprev + 1]); // End of final line
                }
            }
            this.visuals.line.set_value(ctx);
            ctx.stroke();
        }
        _hit_point(geometry) {
            /* Check if the point geometry hits this line glyph and return an object
            that describes the hit result:
              Args:
                * geometry (object): object with the following keys
                  * sx (float): screen x coordinate of the point
                  * sy (float): screen y coordinate of the point
                  * type (str): type of geometry (in this case it's a point)
            */
            const result = new selection_1.Selection();
            const point = { x: geometry.sx, y: geometry.sy };
            let shortest = 9999;
            const threshold = Math.max(2, this.line_width.value / 2);
            for (let i = 0, end = this.sx.length - 1; i < end; i++) {
                const p0 = { x: this.sx[i], y: this.sy[i] };
                const p1 = { x: this.sx[i + 1], y: this.sy[i + 1] };
                const dist = hittest.dist_to_segment(point, p0, p1);
                if (dist < threshold && dist < shortest) {
                    shortest = dist;
                    result.add_to_selected_glyphs(this.model);
                    result.view = this;
                    result.line_indices = [i];
                }
            }
            return result;
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            let val;
            let values;
            if (geometry.direction == "v") {
                val = this.renderer.yscale.invert(sy);
                values = this.y;
            }
            else {
                val = this.renderer.xscale.invert(sx);
                values = this.x;
            }
            const indices = [];
            for (let i = 0, end = values.length - 1; i < end; i++) {
                const curr = values[i];
                const next = values[i + 1];
                if ((curr <= val && val <= next) || (next <= val && val <= curr)) {
                    indices.push(i);
                }
            }
            const result = new selection_1.Selection();
            if (indices.length != 0) {
                result.add_to_selected_glyphs(this.model);
                result.view = this;
                result.line_indices = indices;
            }
            return result;
        }
        get_interpolation_hit(i, geometry) {
            const [x2, y2, x3, y3] = [this.x[i], this.y[i], this.x[i + 1], this.y[i + 1]];
            return (0, utils_1.line_interpolation)(this.renderer, geometry, x2, y2, x3, y3);
        }
        draw_legend_for_index(ctx, bbox, _index) {
            (0, utils_1.generic_line_scalar_legend)(this.visuals, ctx, bbox);
        }
    }
    exports.LineView = LineView;
    LineView.__name__ = "LineView";
    class Line extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Line = Line;
    _a = Line;
    Line.__name__ = "Line";
    (() => {
        _a.prototype.default_view = LineView;
        _a.mixins(mixins.LineScalar);
    })();
},
/* models/glyphs/xy_glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const glyph_1 = require(222) /* ./glyph */;
    class XYGlyphView extends glyph_1.GlyphView {
        _project_data() {
            this._project_xy("x", this.x, "y", this.y);
        }
        _index_data(index) {
            const { x, y, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x_i = x[i];
                const y_i = y[i];
                index.add_point(x_i, y_i);
            }
        }
        scenterxy(i) {
            return [this.sx[i], this.sy[i]];
        }
    }
    exports.XYGlyphView = XYGlyphView;
    XYGlyphView.__name__ = "XYGlyphView";
    class XYGlyph extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.XYGlyph = XYGlyph;
    _a = XYGlyph;
    XYGlyph.__name__ = "XYGlyph";
    (() => {
        _a.define(() => ({
            x: [p.XCoordinateSpec, { field: "x" }],
            y: [p.YCoordinateSpec, { field: "y" }],
        }));
    })();
},
/* models/glyphs/glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const bbox = tslib_1.__importStar(require(64) /* ../../core/util/bbox */);
    const visuals = tslib_1.__importStar(require(87) /* ../../core/visuals */);
    const uniforms = tslib_1.__importStar(require(39) /* ../../core/uniforms */);
    const settings_1 = require(29) /* ../../core/settings */;
    const dom_view_1 = require(57) /* ../../core/dom_view */;
    const model_1 = require(51) /* ../../model */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const logging_1 = require(19) /* ../../core/logging */;
    const types_1 = require(24) /* ../../core/types */;
    const types_2 = require(8) /* ../../core/util/types */;
    const ragged_array_1 = require(223) /* ../../core/util/ragged_array */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const projections_1 = require(134) /* ../../core/util/projections */;
    const eq_1 = require(26) /* ../../core/util/eq */;
    const spatial_1 = require(224) /* ../../core/util/spatial */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const factor_range_1 = require(109) /* ../ranges/factor_range */;
    const selection_1 = require(130) /* ../selections/selection */;
    const decoration_1 = require(227) /* ../graphics/decoration */;
    const { abs, ceil } = Math;
    exports.inherit = Symbol("inherit");
    class GlyphView extends dom_view_1.DOMComponentView {
        constructor() {
            super(...arguments);
            this._index = null;
            this._data_size = null;
            this._nohit_warned = new Set();
            this.decorations = new Map();
            this._base = null;
        }
        get renderer() {
            return this.parent;
        }
        get has_webgl() {
            return this.glglyph != null;
        }
        get index() {
            const { _index } = this;
            if (_index != null) {
                return _index;
            }
            else {
                throw new Error(`${this}.index_data() wasn't called`);
            }
        }
        get data_size() {
            const { base } = this;
            if (base != null) {
                return base.data_size;
            }
            else {
                const { _data_size } = this;
                if (_data_size != null) {
                    return _data_size;
                }
                else {
                    throw new Error(`${this}.set_data() wasn't called`);
                }
            }
        }
        initialize() {
            super.initialize();
            this.visuals = new visuals.Visuals(this);
        }
        *children() {
            yield* super.children();
            yield* this.decorations.values();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await (0, build_views_1.build_views)(this.decorations, this.model.decorations, { parent: this.parent });
            const { webgl } = this.canvas;
            if (webgl != null && this.load_glglyph != null) {
                const cls = await this.load_glglyph();
                this.glglyph = new cls(webgl.regl_wrapper, this);
            }
        }
        request_paint() {
            this.parent.request_paint();
        }
        get canvas() {
            return this.renderer.parent.canvas_view;
        }
        paint(ctx, indices, data) {
            if (this.glglyph != null) {
                this.glglyph.render(ctx, indices, this.base ?? this);
            }
            else if (this.canvas.webgl != null && settings_1.settings.force_webgl) {
                throw new Error(`${this} doesn't support webgl rendering`);
            }
            else {
                this._paint(ctx, indices, data);
            }
        }
        has_finished() {
            return true;
        }
        notify_finished() {
            this.renderer.notify_finished();
        }
        _bounds(bounds) {
            return bounds;
        }
        bounds() {
            return this._bounds(this.index.bbox);
        }
        log_bounds() {
            const { x0, x1 } = this.index.bounds(bbox.positive_x());
            const { y0, y1 } = this.index.bounds(bbox.positive_y());
            return this._bounds({ x0, y0, x1, y1 });
        }
        get_anchor_point(anchor, i, [sx, sy]) {
            switch (anchor) {
                case "center":
                case "center_center": {
                    const [x, y] = this.scenterxy(i, sx, sy);
                    return { x, y };
                }
                default:
                    return null;
            }
        }
        sdist(scale, pts, spans, pts_location = "edge", dilate = false) {
            const n = pts.length;
            const sdist = new types_1.ScreenArray(n);
            const compute = scale.s_compute;
            if (pts_location == "center") {
                for (let i = 0; i < n; i++) {
                    const pts_i = pts[i];
                    const halfspan_i = spans.get(i) / 2;
                    const spt0 = compute(pts_i - halfspan_i);
                    const spt1 = compute(pts_i + halfspan_i);
                    sdist[i] = abs(spt1 - spt0);
                }
            }
            else {
                for (let i = 0; i < n; i++) {
                    const pts_i = pts[i];
                    const spt0 = compute(pts_i);
                    const spt1 = compute(pts_i + spans.get(i));
                    sdist[i] = abs(spt1 - spt0);
                }
            }
            if (dilate) {
                (0, arrayable_1.inplace_map)(sdist, (sd) => ceil(sd));
            }
            return sdist;
        }
        draw_legend_for_index(_ctx, _bbox, _index) { }
        hit_test(geometry) {
            const hit = (() => {
                switch (geometry.type) {
                    case "point": return this._hit_point?.(geometry);
                    case "span": return this._hit_span?.(geometry);
                    case "rect": return this._hit_rect?.(geometry);
                    case "poly": return this._hit_poly?.(geometry);
                }
            })();
            if (hit != null) {
                return hit;
            }
            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_xy(x, xs, y, ys) {
            const inherited_x = this._is_inherited(x);
            const inherited_y = this._is_inherited(y);
            if (!inherited_x && !inherited_y) {
                projections_1.inplace.project_xy(xs, ys);
            }
            else if (!inherited_x || !inherited_y) {
                const [proj_x, proj_y] = (0, projections_1.project_xy)(xs, ys);
                this._define_attr(x, proj_x);
                this._define_attr(y, proj_y);
            }
        }
        _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;
                    }
                }
            }
        }
        get base() {
            return this._base;
        }
        set_base(base) {
            if (base != this && base instanceof this.constructor) {
                this._base = base;
            }
            else {
                this._base = null;
            }
        }
        _define_or_inherit_attr(attr, fn) {
            const value = fn();
            if (value === exports.inherit) {
                this._inherit_attr(attr);
            }
            else {
                this._define_attr(attr, value);
            }
        }
        _define_attr(attr, value) {
            Object.defineProperty(this, attr, {
                configurable: true,
                enumerable: true,
                value,
            });
            this._define_inherited(attr, false);
        }
        _inherit_attr(attr) {
            const { base } = this;
            (0, assert_1.assert)(base != null);
            this._inherit_from(attr, base);
        }
        _inherit_from(attr, base) {
            Object.defineProperty(this, attr, {
                configurable: true,
                enumerable: true,
                get() {
                    return base[attr];
                },
            });
            this._define_inherited(attr, true);
        }
        _define_inherited(attr, value) {
            Object.defineProperty(this, `inherited_${attr}`, {
                configurable: true,
                enumerable: true,
                value,
            });
        }
        _can_inherit_from(prop, base) {
            if (base == null) {
                return false;
            }
            const base_prop = base.model.property(prop.attr);
            const value = prop.get_value();
            const base_value = base_prop.get_value();
            try {
                return (0, eq_1.is_equal)(value, base_value);
            }
            catch (error) {
                if (error instanceof eq_1.EqNotImplemented) {
                    return false;
                }
                else {
                    throw error;
                }
            }
        }
        _is_inherited(prop) {
            const name = (0, types_2.isString)(prop) ? prop : prop.attr;
            return this[`inherited_${name}`];
        }
        set_visuals(source, indices) {
            for (const prop of this._iter_visuals()) {
                const { base } = this;
                if (base != null && this._can_inherit_from(prop, base)) {
                    this._inherit_from(prop.attr, base);
                }
                else {
                    const uniform = prop.uniform(source).select(indices);
                    this._define_attr(prop.attr, uniform);
                }
            }
            for (const visual of this.visuals) {
                visual.update();
            }
            this.glglyph?.set_visuals_changed();
        }
        _transform_array(prop, array) {
            const { x_source, y_source } = this.renderer.coordinates;
            const range = prop.dimension == "x" ? x_source : y_source;
            if (range instanceof factor_range_1.FactorRange) {
                if (prop instanceof p.CoordinateSpec) {
                    array = range.v_synthetic(array);
                }
                else if (prop instanceof p.CoordinateSeqSpec) {
                    for (let i = 0; i < array.length; i++) {
                        array[i] = range.v_synthetic(array[i]);
                    }
                }
                else if (prop instanceof p.CoordinateSeqSeqSeqSpec) {
                    // TODO
                }
            }
            let final_array;
            if (prop instanceof p.CoordinateSeqSpec) {
                // TODO: infer precision
                final_array = ragged_array_1.RaggedArray.from(array, Float64Array);
            }
            else if (prop instanceof p.CoordinateSeqSeqSeqSpec) {
                // TODO RaggedArrayN
                final_array = array;
            }
            else {
                final_array = array;
            }
            return final_array;
        }
        async set_data(source, indices, indices_to_update) {
            const visuals = new Set(this._iter_visuals());
            const { base } = this;
            this._data_size = indices.count;
            for (const prop of this.model) {
                if (!(prop instanceof p.VectorSpec || prop instanceof p.ScalarSpec)) {
                    continue;
                }
                if (visuals.has(prop)) { // let set_visuals() do the work, at least for now
                    continue;
                }
                if (base != null && this._can_inherit_from(prop, base)) {
                    this._inherit_from(prop.attr, base);
                    if (prop instanceof p.DistanceSpec || prop instanceof p.ScreenSizeSpec) {
                        this._inherit_from(`max_${prop.attr}`, base);
                    }
                }
                else {
                    if (prop instanceof p.BaseCoordinateSpec) {
                        const array = this._transform_array(prop, indices.select(prop.array(source)));
                        this._define_attr(prop.attr, array);
                    }
                    else {
                        const uniform = prop.uniform(source).select(indices);
                        this._define_attr(prop.attr, uniform);
                        if (prop instanceof p.DistanceSpec || prop instanceof p.ScreenSizeSpec) {
                            const max_value = uniforms.max(uniform);
                            this._define_attr(`max_${prop.attr}`, max_value);
                        }
                    }
                }
            }
            if (this.renderer.plot_view.model.use_map) {
                this._project_data();
            }
            this._set_data(indices_to_update ?? null); // TODO doesn't take subset indices into account
            await this._set_lazy_data(indices_to_update ?? null); // TODO doesn't take subset indices into account
            for (const decoration of this.decorations.values()) {
                decoration.marking.set_data(source, indices);
            }
            this.glglyph?.set_data_changed();
            if (base == null) {
                this.index_data();
            }
        }
        _set_data(_indices) { }
        async _set_lazy_data(_indices) { }
        /**
         * Any data transformations that require visuals.
         */
        after_visuals() { }
        async after_lazy_visuals() { }
        get _index_size() {
            return this.data_size;
        }
        index_data() {
            const index = new spatial_1.SpatialIndex(this._index_size);
            this._index_data(index);
            index.finish();
            this._index = index;
        }
        mask_data() {
            /** Returns subset indices in the viewport. */
            if (this._mask_data == null) {
                return types_1.Indices.all_set(this.data_size);
            }
            else {
                return this._mask_data();
            }
        }
        map_data() {
            const { x_scale, y_scale } = this.renderer.coordinates;
            const { base } = this;
            const v_compute = (prop) => {
                const scale = prop.dimension == "x" ? x_scale : y_scale;
                const array = this[prop.attr];
                if (array instanceof ragged_array_1.RaggedArray) {
                    return new ragged_array_1.RaggedArray(array.offsets, scale.v_compute(array.data));
                }
                else {
                    return scale.v_compute(array);
                }
            };
            for (const prop of this.model) {
                if (prop instanceof p.BaseCoordinateSpec) {
                    if (base != null && this._is_inherited(prop)) {
                        this._inherit_from(`s${prop.attr}`, base);
                    }
                    else {
                        const array = v_compute(prop);
                        this._define_attr(`s${prop.attr}`, array);
                    }
                }
            }
            this._map_data();
            this.glglyph?.set_data_mapped();
        }
        // This is where specs not included in coords are computed, e.g. radius.
        _map_data() { }
        get bbox() {
            if (this.base == null) {
                const { x0, y0, x1, y1 } = this.index.bbox;
                const { x_scale, y_scale } = this.renderer.coordinates;
                const [sx0, sx1] = x_scale.r_compute(x0, x1);
                const [sy0, sy1] = y_scale.r_compute(y0, y1);
                return bbox_1.BBox.from_rect({ x0: sx0, y0: sy0, x1: sx1, y1: sy1 });
            }
            else {
                return undefined;
            }
        }
    }
    exports.GlyphView = GlyphView;
    GlyphView.__name__ = "GlyphView";
    class Glyph extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Glyph = Glyph;
    _a = Glyph;
    Glyph.__name__ = "Glyph";
    (() => {
        _a.define(({ List, Ref }) => ({
            decorations: [List(Ref(decoration_1.Decoration)), []],
        }));
    })();
},
/* core/util/ragged_array.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const eq_1 = require(26) /* ./eq */;
    const assert_1 = require(12) /* ./assert */;
    class RaggedArray {
        constructor(offsets, data) {
            this.offsets = offsets;
            this.data = data;
        }
        [(_a = Symbol.toStringTag, eq_1.equals)](that, cmp) {
            return cmp.arrays(this.offsets, that.offsets) && cmp.arrays(this.data, that.data);
        }
        get length() {
            return this.offsets.length;
        }
        clone() {
            return new RaggedArray(this.offsets.slice(), this.data.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.data.subarray(offsets[i], offsets[i + 1]);
            }
        }
        _check_bounds(i) {
            (0, assert_1.assert)(0 <= i && i < this.length, `Out of bounds: 0 <= ${i} < ${this.length}`);
        }
        get(i) {
            this._check_bounds(i);
            const { offsets } = this;
            return this.data.subarray(offsets[i], offsets[i + 1]);
        }
        set(i, array) {
            this._check_bounds(i);
            this.data.set(array, this.offsets[i]);
        }
    }
    exports.RaggedArray = RaggedArray;
    RaggedArray.__name__ = "RaggedArray";
    RaggedArray[_a] = "RaggedArray";
},
/* core/util/spatial.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const flatbush_1 = tslib_1.__importDefault(require(225) /* flatbush */);
    const types_1 = require(24) /* ../types */;
    const bbox_1 = require(64) /* ./bbox */;
    function upperBound(value, arr) {
        let i = 0;
        let j = arr.length - 1;
        while (i < j) {
            const m = (i + j) >> 1;
            if (arr[m] > value) {
                j = m;
            }
            else {
                i = m + 1;
            }
        }
        return arr[i];
    }
    class _FlatBush extends flatbush_1.default {
        get boxes() {
            return this._boxes;
        }
        search_indices(minX, minY, maxX, maxY) {
            if (this._pos !== this._boxes.length) {
                throw new Error("Data not yet indexed - call index.finish().");
            }
            let nodeIndex = this._boxes.length - 4;
            const queue = [];
            const results = new types_1.Indices(this.numItems);
            while (nodeIndex !== undefined) {
                // find the end index of the node
                const end = Math.min(nodeIndex + this.nodeSize * 4, upperBound(nodeIndex, this._levelBounds));
                // search through child nodes
                for (let pos = nodeIndex; pos < end; pos += 4) {
                    const index = this._indices[pos >> 2] | 0;
                    // check if node bbox intersects with query bbox
                    const nodeMinX = this._boxes[pos + 0];
                    const nodeMinY = this._boxes[pos + 1];
                    const nodeMaxX = this._boxes[pos + 2];
                    const nodeMaxY = this._boxes[pos + 3];
                    if (maxX < nodeMinX || maxY < nodeMinY || minX > nodeMaxX || minY > nodeMaxY) {
                        continue;
                    }
                    if (nodeIndex < this.numItems * 4) {
                        results.set(index); // leaf item
                    }
                    else {
                        queue.push(index); // node; add it to the search queue
                    }
                }
                nodeIndex = queue.pop();
            }
            return results;
        }
    }
    _FlatBush.__name__ = "_FlatBush";
    class SpatialIndex {
        constructor(size) {
            this.index = null;
            if (size > 0) {
                this.index = new _FlatBush(size);
            }
        }
        add_rect(x0, y0, x1, y1) {
            if (!isFinite(x0 + y0 + x1 + y1)) {
                this.add_empty();
            }
            else {
                this.index?.add(x0, y0, x1, y1);
            }
        }
        add_point(x, y) {
            if (!isFinite(x + y)) {
                this.add_empty();
            }
            else {
                this.index?.add(x, y, x, y);
            }
        }
        add_empty() {
            this.index?.add(Infinity, Infinity, -Infinity, -Infinity);
        }
        finish() {
            this.index?.finish();
        }
        _normalize(rect) {
            let { x0, y0, x1, y1 } = rect;
            if (x0 > x1) {
                [x0, x1] = [x1, x0];
            }
            if (y0 > y1) {
                [y0, y1] = [y1, y0];
            }
            return { x0, y0, x1, y1 };
        }
        get bbox() {
            if (this.index == null) {
                return (0, bbox_1.empty)();
            }
            else {
                const { minX, minY, maxX, maxY } = this.index;
                return { x0: minX, y0: minY, x1: maxX, y1: maxY };
            }
        }
        indices(rect) {
            if (this.index == null) {
                return new types_1.Indices(0);
            }
            else {
                const { x0, y0, x1, y1 } = this._normalize(rect);
                return this.index.search_indices(x0, y0, x1, y1);
            }
        }
        bounds(rect) {
            const bounds = (0, bbox_1.empty)();
            if (this.index == null) {
                return bounds;
            }
            const { boxes } = this.index;
            for (const i of this.indices(rect)) {
                const x0 = boxes[4 * i + 0];
                const y0 = boxes[4 * i + 1];
                const x1 = boxes[4 * i + 2];
                const y1 = boxes[4 * i + 3];
                if (x0 >= rect.x0 && x0 < bounds.x0) {
                    bounds.x0 = x0;
                }
                if (x1 <= rect.x1 && x1 > bounds.x1) {
                    bounds.x1 = x1;
                }
                if (y0 >= rect.y0 && y0 < bounds.y0) {
                    bounds.y0 = y0;
                }
                if (y1 <= rect.y1 && y1 > bounds.y1) {
                    bounds.y1 = y1;
                }
            }
            return bounds;
        }
    }
    exports.SpatialIndex = SpatialIndex;
    SpatialIndex.__name__ = "SpatialIndex";
},
/* flatbush/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const flatqueue_1 = tslib_1.__importDefault(require(226) /* flatqueue */);
    const ARRAY_TYPES = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];
    const VERSION = 3; // serialized format version
    /** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */
    class Flatbush {
        /**
         * Recreate a Flatbush index from raw `ArrayBuffer` or `SharedArrayBuffer` data.
         * @param {ArrayBuffer | SharedArrayBuffer} data
         * @param {number} [byteOffset=0] byte offset to the start of the Flatbush buffer in the referenced ArrayBuffer.
         * @returns {Flatbush} index
         */
        static from(data, byteOffset = 0) {
            if (byteOffset % 8 !== 0) {
                throw new Error('byteOffset must be 8-byte aligned.');
            }
            // @ts-expect-error duck typing array buffers
            if (!data || data.byteLength === undefined || data.buffer) {
                throw new Error('Data must be an instance of ArrayBuffer or SharedArrayBuffer.');
            }
            const [magic, versionAndType] = new Uint8Array(data, byteOffset + 0, 2);
            if (magic !== 0xfb) {
                throw new Error('Data does not appear to be in a Flatbush format.');
            }
            const version = versionAndType >> 4;
            if (version !== VERSION) {
                throw new Error(`Got v${version} data when expected v${VERSION}.`);
            }
            const ArrayType = ARRAY_TYPES[versionAndType & 0x0f];
            if (!ArrayType) {
                throw new Error('Unrecognized array type.');
            }
            const [nodeSize] = new Uint16Array(data, byteOffset + 2, 1);
            const [numItems] = new Uint32Array(data, byteOffset + 4, 1);
            return new Flatbush(numItems, nodeSize, ArrayType, undefined, data, byteOffset);
        }
        /**
         * Create a Flatbush index that will hold a given number of items.
         * @param {number} numItems
         * @param {number} [nodeSize=16] Size of the tree node (16 by default).
         * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).
         * @param {ArrayBufferConstructor | SharedArrayBufferConstructor} [ArrayBufferType=ArrayBuffer] The array buffer type used to store data (`ArrayBuffer` by default).
         * @param {ArrayBuffer | SharedArrayBuffer} [data] (Only used internally)
         * @param {number} [byteOffset=0] (Only used internally)
         */
        constructor(numItems, nodeSize = 16, ArrayType = Float64Array, ArrayBufferType = ArrayBuffer, data, byteOffset = 0) {
            if (numItems === undefined)
                throw new Error('Missing required argument: numItems.');
            if (isNaN(numItems) || numItems <= 0)
                throw new Error(`Unexpected numItems value: ${numItems}.`);
            this.numItems = +numItems;
            this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
            this.byteOffset = byteOffset;
            // calculate the total number of nodes in the R-tree to allocate space for
            // and the index of each tree level (used in search later)
            let n = numItems;
            let numNodes = n;
            this._levelBounds = [n * 4];
            do {
                n = Math.ceil(n / this.nodeSize);
                numNodes += n;
                this._levelBounds.push(numNodes * 4);
            } while (n !== 1);
            this.ArrayType = ArrayType;
            this.IndexArrayType = numNodes < 16384 ? Uint16Array : Uint32Array;
            const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
            const nodesByteSize = numNodes * 4 * this.ArrayType.BYTES_PER_ELEMENT;
            if (arrayTypeIndex < 0) {
                throw new Error(`Unexpected typed array class: ${ArrayType}.`);
            }
            // @ts-expect-error duck typing array buffers
            if (data && data.byteLength !== undefined && !data.buffer) {
                this.data = data;
                this._boxes = new this.ArrayType(this.data, byteOffset + 8, numNodes * 4);
                this._indices = new this.IndexArrayType(this.data, byteOffset + 8 + nodesByteSize, numNodes);
                this._pos = numNodes * 4;
                this.minX = this._boxes[this._pos - 4];
                this.minY = this._boxes[this._pos - 3];
                this.maxX = this._boxes[this._pos - 2];
                this.maxY = this._boxes[this._pos - 1];
            }
            else {
                this.data = new ArrayBufferType(8 + nodesByteSize + numNodes * this.IndexArrayType.BYTES_PER_ELEMENT);
                this._boxes = new this.ArrayType(this.data, 8, numNodes * 4);
                this._indices = new this.IndexArrayType(this.data, 8 + nodesByteSize, numNodes);
                this._pos = 0;
                this.minX = Infinity;
                this.minY = Infinity;
                this.maxX = -Infinity;
                this.maxY = -Infinity;
                new Uint8Array(this.data, 0, 2).set([0xfb, (VERSION << 4) + arrayTypeIndex]);
                new Uint16Array(this.data, 2, 1)[0] = nodeSize;
                new Uint32Array(this.data, 4, 1)[0] = numItems;
            }
            // a priority queue for k-nearest-neighbors queries
            /** @type FlatQueue<number> */
            this._queue = new flatqueue_1.default();
        }
        /**
         * Add a given rectangle to the index.
         * @param {number} minX
         * @param {number} minY
         * @param {number} maxX
         * @param {number} maxY
         * @returns {number} A zero-based, incremental number that represents the newly added rectangle.
         */
        add(minX, minY, maxX = minX, maxY = minY) {
            const index = this._pos >> 2;
            const boxes = this._boxes;
            this._indices[index] = index;
            boxes[this._pos++] = minX;
            boxes[this._pos++] = minY;
            boxes[this._pos++] = maxX;
            boxes[this._pos++] = maxY;
            if (minX < this.minX)
                this.minX = minX;
            if (minY < this.minY)
                this.minY = minY;
            if (maxX > this.maxX)
                this.maxX = maxX;
            if (maxY > this.maxY)
                this.maxY = maxY;
            return index;
        }
        /** Perform indexing of the added rectangles. */
        finish() {
            if (this._pos >> 2 !== this.numItems) {
                throw new Error(`Added ${this._pos >> 2} items when expected ${this.numItems}.`);
            }
            const boxes = this._boxes;
            if (this.numItems <= this.nodeSize) {
                // only one node, skip sorting and just fill the root box
                boxes[this._pos++] = this.minX;
                boxes[this._pos++] = this.minY;
                boxes[this._pos++] = this.maxX;
                boxes[this._pos++] = this.maxY;
                return;
            }
            const width = (this.maxX - this.minX) || 1;
            const height = (this.maxY - this.minY) || 1;
            const hilbertValues = new Uint32Array(this.numItems);
            const hilbertMax = (1 << 16) - 1;
            // map item centers into Hilbert coordinate space and calculate Hilbert values
            for (let i = 0, pos = 0; i < this.numItems; i++) {
                const minX = boxes[pos++];
                const minY = boxes[pos++];
                const maxX = boxes[pos++];
                const maxY = boxes[pos++];
                const x = Math.floor(hilbertMax * ((minX + maxX) / 2 - this.minX) / width);
                const y = Math.floor(hilbertMax * ((minY + maxY) / 2 - this.minY) / height);
                hilbertValues[i] = hilbert(x, y);
            }
            // sort items by their Hilbert value (for packing later)
            sort(hilbertValues, boxes, this._indices, 0, this.numItems - 1, this.nodeSize);
            // generate nodes at each tree level, bottom-up
            for (let i = 0, pos = 0; i < this._levelBounds.length - 1; i++) {
                const end = this._levelBounds[i];
                // generate a parent node for each block of consecutive <nodeSize> nodes
                while (pos < end) {
                    const nodeIndex = pos;
                    // calculate bbox for the new node
                    let nodeMinX = boxes[pos++];
                    let nodeMinY = boxes[pos++];
                    let nodeMaxX = boxes[pos++];
                    let nodeMaxY = boxes[pos++];
                    for (let j = 1; j < this.nodeSize && pos < end; j++) {
                        nodeMinX = Math.min(nodeMinX, boxes[pos++]);
                        nodeMinY = Math.min(nodeMinY, boxes[pos++]);
                        nodeMaxX = Math.max(nodeMaxX, boxes[pos++]);
                        nodeMaxY = Math.max(nodeMaxY, boxes[pos++]);
                    }
                    // add the new node to the tree data
                    this._indices[this._pos >> 2] = nodeIndex;
                    boxes[this._pos++] = nodeMinX;
                    boxes[this._pos++] = nodeMinY;
                    boxes[this._pos++] = nodeMaxX;
                    boxes[this._pos++] = nodeMaxY;
                }
            }
        }
        /**
         * Search the index by a bounding box.
         * @param {number} minX
         * @param {number} minY
         * @param {number} maxX
         * @param {number} maxY
         * @param {(index: number) => boolean} [filterFn] An optional function for filtering the results.
         * @returns {number[]} An array of indices of items intersecting or touching the given bounding box.
         */
        search(minX, minY, maxX, maxY, filterFn) {
            if (this._pos !== this._boxes.length) {
                throw new Error('Data not yet indexed - call index.finish().');
            }
            /** @type number | undefined */
            let nodeIndex = this._boxes.length - 4;
            const queue = [];
            const results = [];
            while (nodeIndex !== undefined) {
                // find the end index of the node
                const end = Math.min(nodeIndex + this.nodeSize * 4, upperBound(nodeIndex, this._levelBounds));
                // search through child nodes
                for (let /** @type number */ pos = nodeIndex; pos < end; pos += 4) {
                    // check if node bbox intersects with query bbox
                    if (maxX < this._boxes[pos])
                        continue; // maxX < nodeMinX
                    if (maxY < this._boxes[pos + 1])
                        continue; // maxY < nodeMinY
                    if (minX > this._boxes[pos + 2])
                        continue; // minX > nodeMaxX
                    if (minY > this._boxes[pos + 3])
                        continue; // minY > nodeMaxY
                    const index = this._indices[pos >> 2] | 0;
                    if (nodeIndex >= this.numItems * 4) {
                        queue.push(index); // node; add it to the search queue
                    }
                    else if (filterFn === undefined || filterFn(index)) {
                        results.push(index); // leaf item
                    }
                }
                nodeIndex = queue.pop();
            }
            return results;
        }
        /**
         * Search items in order of distance from the given point.
         * @param {number} x
         * @param {number} y
         * @param {number} [maxResults=Infinity]
         * @param {number} [maxDistance=Infinity]
         * @param {(index: number) => boolean} [filterFn] An optional function for filtering the results.
         * @returns {number[]} An array of indices of items found.
         */
        neighbors(x, y, maxResults = Infinity, maxDistance = Infinity, filterFn) {
            if (this._pos !== this._boxes.length) {
                throw new Error('Data not yet indexed - call index.finish().');
            }
            /** @type number | undefined */
            let nodeIndex = this._boxes.length - 4;
            const q = this._queue;
            const results = [];
            const maxDistSquared = maxDistance * maxDistance;
            outer: while (nodeIndex !== undefined) {
                // find the end index of the node
                const end = Math.min(nodeIndex + this.nodeSize * 4, upperBound(nodeIndex, this._levelBounds));
                // add child nodes to the queue
                for (let pos = nodeIndex; pos < end; pos += 4) {
                    const index = this._indices[pos >> 2] | 0;
                    const dx = axisDist(x, this._boxes[pos], this._boxes[pos + 2]);
                    const dy = axisDist(y, this._boxes[pos + 1], this._boxes[pos + 3]);
                    const dist = dx * dx + dy * dy;
                    if (dist > maxDistSquared)
                        continue;
                    if (nodeIndex >= this.numItems * 4) {
                        q.push(index << 1, dist); // node (use even id)
                    }
                    else if (filterFn === undefined || filterFn(index)) {
                        q.push((index << 1) + 1, dist); // leaf item (use odd id)
                    }
                }
                // pop items from the queue
                // @ts-expect-error q.length check eliminates undefined values
                while (q.length && (q.peek() & 1)) {
                    const dist = q.peekValue();
                    // @ts-expect-error
                    if (dist > maxDistSquared)
                        break outer;
                    // @ts-expect-error
                    results.push(q.pop() >> 1);
                    if (results.length === maxResults)
                        break outer;
                }
                // @ts-expect-error
                nodeIndex = q.length ? q.pop() >> 1 : undefined;
            }
            q.clear();
            return results;
        }
    }
    exports.default = Flatbush;
    /**
     * 1D distance from a value to a range.
     * @param {number} k
     * @param {number} min
     * @param {number} max
     */
    function axisDist(k, min, max) {
        return k < min ? min - k : k <= max ? 0 : k - max;
    }
    /**
     * Binary search for the first value in the array bigger than the given.
     * @param {number} value
     * @param {number[]} arr
     */
    function upperBound(value, arr) {
        let i = 0;
        let j = arr.length - 1;
        while (i < j) {
            const m = (i + j) >> 1;
            if (arr[m] > value) {
                j = m;
            }
            else {
                i = m + 1;
            }
        }
        return arr[i];
    }
    /**
     * Custom quicksort that partially sorts bbox data alongside the hilbert values.
     * @param {Uint32Array} values
     * @param {InstanceType<TypedArrayConstructor>} boxes
     * @param {Uint16Array | Uint32Array} indices
     * @param {number} left
     * @param {number} right
     * @param {number} nodeSize
     */
    function sort(values, boxes, indices, left, right, nodeSize) {
        if (Math.floor(left / nodeSize) >= Math.floor(right / nodeSize))
            return;
        const pivot = values[(left + right) >> 1];
        let i = left - 1;
        let j = right + 1;
        while (true) {
            do
                i++;
            while (values[i] < pivot);
            do
                j--;
            while (values[j] > pivot);
            if (i >= j)
                break;
            swap(values, boxes, indices, i, j);
        }
        sort(values, boxes, indices, left, j, nodeSize);
        sort(values, boxes, indices, j + 1, right, nodeSize);
    }
    /**
     * Swap two values and two corresponding boxes.
     * @param {Uint32Array} values
     * @param {InstanceType<TypedArrayConstructor>} boxes
     * @param {Uint16Array | Uint32Array} indices
     * @param {number} i
     * @param {number} j
     */
    function swap(values, boxes, indices, i, j) {
        const temp = values[i];
        values[i] = values[j];
        values[j] = temp;
        const k = 4 * i;
        const m = 4 * j;
        const a = boxes[k];
        const b = boxes[k + 1];
        const c = boxes[k + 2];
        const d = boxes[k + 3];
        boxes[k] = boxes[m];
        boxes[k + 1] = boxes[m + 1];
        boxes[k + 2] = boxes[m + 2];
        boxes[k + 3] = boxes[m + 3];
        boxes[m] = a;
        boxes[m + 1] = b;
        boxes[m + 2] = c;
        boxes[m + 3] = d;
        const e = indices[i];
        indices[i] = indices[j];
        indices[j] = e;
    }
    /**
     * Fast Hilbert curve algorithm by http://threadlocalmutex.com/
     * Ported from C++ https://github.com/rawrunprotected/hilbert_curves (public domain)
     * @param {number} x
     * @param {number} y
     */
    function hilbert(x, y) {
        let a = x ^ y;
        let b = 0xFFFF ^ a;
        let c = 0xFFFF ^ (x | y);
        let d = x & (y ^ 0xFFFF);
        let A = a | (b >> 1);
        let B = (a >> 1) ^ a;
        let C = ((c >> 1) ^ (b & (d >> 1))) ^ c;
        let D = ((a & (c >> 1)) ^ (d >> 1)) ^ d;
        a = A;
        b = B;
        c = C;
        d = D;
        A = ((a & (a >> 2)) ^ (b & (b >> 2)));
        B = ((a & (b >> 2)) ^ (b & ((a ^ b) >> 2)));
        C ^= ((a & (c >> 2)) ^ (b & (d >> 2)));
        D ^= ((b & (c >> 2)) ^ ((a ^ b) & (d >> 2)));
        a = A;
        b = B;
        c = C;
        d = D;
        A = ((a & (a >> 4)) ^ (b & (b >> 4)));
        B = ((a & (b >> 4)) ^ (b & ((a ^ b) >> 4)));
        C ^= ((a & (c >> 4)) ^ (b & (d >> 4)));
        D ^= ((b & (c >> 4)) ^ ((a ^ b) & (d >> 4)));
        a = A;
        b = B;
        c = C;
        d = D;
        C ^= ((a & (c >> 8)) ^ (b & (d >> 8)));
        D ^= ((b & (c >> 8)) ^ ((a ^ b) & (d >> 8)));
        a = C ^ (C >> 1);
        b = D ^ (D >> 1);
        let i0 = x ^ y;
        let i1 = b | (0xFFFF ^ (i0 | a));
        i0 = (i0 | (i0 << 8)) & 0x00FF00FF;
        i0 = (i0 | (i0 << 4)) & 0x0F0F0F0F;
        i0 = (i0 | (i0 << 2)) & 0x33333333;
        i0 = (i0 | (i0 << 1)) & 0x55555555;
        i1 = (i1 | (i1 << 8)) & 0x00FF00FF;
        i1 = (i1 | (i1 << 4)) & 0x0F0F0F0F;
        i1 = (i1 | (i1 << 2)) & 0x33333333;
        i1 = (i1 | (i1 << 1)) & 0x55555555;
        return ((i1 << 1) | i0) >>> 0;
    }
},
/* flatqueue/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    class FlatQueue {
        constructor() {
            this.ids = [];
            this.values = [];
            this.length = 0;
        }
        clear() {
            this.length = 0;
        }
        push(id, value) {
            let pos = this.length++;
            while (pos > 0) {
                const parent = (pos - 1) >> 1;
                const parentValue = this.values[parent];
                if (value >= parentValue)
                    break;
                this.ids[pos] = this.ids[parent];
                this.values[pos] = parentValue;
                pos = parent;
            }
            this.ids[pos] = id;
            this.values[pos] = value;
        }
        pop() {
            if (this.length === 0)
                return undefined;
            const top = this.ids[0];
            this.length--;
            if (this.length > 0) {
                const id = this.ids[0] = this.ids[this.length];
                const value = this.values[0] = this.values[this.length];
                const halfLength = this.length >> 1;
                let pos = 0;
                while (pos < halfLength) {
                    let left = (pos << 1) + 1;
                    const right = left + 1;
                    let bestIndex = this.ids[left];
                    let bestValue = this.values[left];
                    const rightValue = this.values[right];
                    if (right < this.length && rightValue < bestValue) {
                        left = right;
                        bestIndex = this.ids[right];
                        bestValue = rightValue;
                    }
                    if (bestValue >= value)
                        break;
                    this.ids[pos] = bestIndex;
                    this.values[pos] = bestValue;
                    pos = left;
                }
                this.ids[pos] = id;
                this.values[pos] = value;
            }
            return top;
        }
        peek() {
            if (this.length === 0)
                return undefined;
            return this.ids[0];
        }
        peekValue() {
            if (this.length === 0)
                return undefined;
            return this.values[0];
        }
        shrink() {
            this.ids.length = this.values.length = this.length;
        }
    }
    exports.default = FlatQueue;
},
/* models/graphics/decoration.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const marking_1 = require(169) /* ./marking */;
    const model_1 = require(51) /* ../../model */;
    const view_1 = require(58) /* ../../core/view */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    class DecorationView extends view_1.View {
        *children() {
            yield* super.children();
            yield this.marking;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.marking = await (0, build_views_1.build_view)(this.model.marking, { parent: this.parent });
        }
    }
    exports.DecorationView = DecorationView;
    DecorationView.__name__ = "DecorationView";
    class Decoration extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Decoration = Decoration;
    _a = Decoration;
    Decoration.__name__ = "Decoration";
    (() => {
        _a.prototype.default_view = DecorationView;
        _a.define(({ Enum, Ref }) => ({
            marking: [Ref(marking_1.Marking)],
            node: [Enum("start", "middle", "end")],
        }));
    })();
},
/* models/glyphs/utils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.generic_line_scalar_legend = generic_line_scalar_legend;
    exports.generic_line_vector_legend = generic_line_vector_legend;
    exports.generic_line_legend = generic_line_vector_legend;
    exports.generic_area_scalar_legend = generic_area_scalar_legend;
    exports.generic_area_vector_legend = generic_area_vector_legend;
    exports.generic_area_legend = generic_area_vector_legend;
    exports.line_interpolation = line_interpolation;
    const tslib_1 = require(1) /* tslib */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    function generic_line_scalar_legend(visuals, ctx, { x0, x1, y0, y1 }) {
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(x0, (y0 + y1) / 2);
        ctx.lineTo(x1, (y0 + y1) / 2);
        visuals.line.apply(ctx);
        ctx.restore();
    }
    function generic_line_vector_legend(visuals, ctx, { x0, x1, y0, y1 }, i) {
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(x0, (y0 + y1) / 2);
        ctx.lineTo(x1, (y0 + y1) / 2);
        visuals.line.apply(ctx, i);
        ctx.restore();
    }
    function generic_area_scalar_legend(visuals, ctx, { x0, x1, y0, y1 }) {
        const w = Math.abs(x1 - x0);
        const dw = w * 0.1;
        const h = Math.abs(y1 - y0);
        const dh = h * 0.1;
        const sx0 = x0 + dw;
        const sx1 = x1 - dw;
        const sy0 = y0 + dh;
        const sy1 = y1 - dh;
        ctx.beginPath();
        ctx.rect(sx0, sy0, sx1 - sx0, sy1 - sy0);
        visuals.fill.apply(ctx);
        visuals.hatch?.apply(ctx);
        visuals.line?.apply(ctx);
    }
    function generic_area_vector_legend(visuals, ctx, { x0, x1, y0, y1 }, i) {
        const w = Math.abs(x1 - x0);
        const dw = w * 0.1;
        const h = Math.abs(y1 - y0);
        const dh = h * 0.1;
        const sx0 = x0 + dw;
        const sx1 = x1 - dw;
        const sy0 = y0 + dh;
        const sy1 = y1 - dh;
        ctx.beginPath();
        ctx.rect(sx0, sy0, sx1 - sx0, sy1 - sy0);
        visuals.fill.apply(ctx, i);
        visuals.hatch?.apply(ctx, i);
        visuals.line?.apply(ctx, i);
    }
    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
    }
},
/* core/hittest.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.point_in_poly = point_in_poly;
    exports.point_in_ellipse = point_in_ellipse;
    exports.dist_2_pts = dist_2_pts;
    exports.dist_to_segment_squared = dist_to_segment_squared;
    exports.dist_to_segment = dist_to_segment;
    exports.check_2_segments_intersect = check_2_segments_intersect;
    exports.vertex_overlap = vertex_overlap;
    exports.edge_intersection = edge_intersection;
    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;
    }
    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;
    }
    function dist_2_pts(p0, p1) {
        return (p0.x - p1.x) ** 2 + (p0.y - p1.y) ** 2;
    }
    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);
    }
    function dist_to_segment(p, v, w) {
        return Math.sqrt(dist_to_segment_squared(p, v, w));
    }
    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 };
        }
    }
    // Given two polygons, is any vertex of one inside the other
    function vertex_overlap(x0, y0, x1, y1) {
        // need to check "both directions" to handle total inclusion cases
        for (let i = 0; i < x0.length; i++) {
            if (point_in_poly(x0[i], y0[i], x1, y1)) {
                return true;
            }
        }
        for (let i = 0; i < x1.length; i++) {
            if (point_in_poly(x1[i], y1[i], x0, y0)) {
                return true;
            }
        }
        return false;
    }
    // Given two polygons, do any pair of edges intersect
    function edge_intersection(x0, y0, x1, y1) {
        for (let i = 0; i < x0.length - 1; i++) {
            for (let j = 0; j < x1.length - 1; j++) {
                if (check_2_segments_intersect(x0[i], y0[i], x0[i + 1], y0[i + 1], x1[j], y1[j], x1[j + 1], y1[j + 1]).hit) {
                    return true;
                }
            }
            // consider x1, y1 "closing" segment
            if (check_2_segments_intersect(x0[i], y0[i], x0[i + 1], y0[i + 1], x1[x1.length - 1], y1[x1.length - 1], x1[0], y1[0]).hit) {
                return true;
            }
        }
        // consider x0, y0, "closing" segment
        if (check_2_segments_intersect(x0[x0.length - 1], y0[x0.length - 1], x0[0], y0[0], x1[x1.length - 1], y1[x1.length - 1], x1[0], y1[0]).hit) {
            return true;
        }
        return false;
    }
},
/* models/glyphs/patch.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const utils_1 = require(228) /* ./utils */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const selection_1 = require(130) /* ../selections/selection */;
    class PatchView extends xy_glyph_1.XYGlyphView {
        _paint(ctx, indices, data) {
            const { sx, sy } = { ...this, ...data };
            let move = true;
            ctx.beginPath();
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                if (!isFinite(sx_i + sy_i)) {
                    ctx.closePath();
                    move = true;
                }
                else {
                    if (move) {
                        ctx.moveTo(sx_i, sy_i);
                        move = false;
                    }
                    else {
                        ctx.lineTo(sx_i, sy_i);
                    }
                }
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
            this.visuals.line.apply(ctx);
        }
        draw_legend_for_index(ctx, bbox, _index) {
            (0, utils_1.generic_area_scalar_legend)(this.visuals, ctx, bbox);
        }
        _hit_point(geometry) {
            const result = new selection_1.Selection();
            if (hittest.point_in_poly(geometry.sx, geometry.sy, this.sx, this.sy)) {
                result.add_to_selected_glyphs(this.model);
                result.view = this;
            }
            return result;
        }
    }
    exports.PatchView = PatchView;
    PatchView.__name__ = "PatchView";
    class Patch extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Patch = Patch;
    _a = Patch;
    Patch.__name__ = "Patch";
    (() => {
        _a.prototype.default_view = PatchView;
        _a.mixins([mixins.LineScalar, mixins.FillScalar, mixins.HatchScalar]);
    })();
},
/* models/glyphs/harea_step.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const area_1 = require(232) /* ./area */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const enums_1 = require(20) /* ../../core/enums */;
    const flip_step_mode_1 = require(233) /* ../../core/util/flip_step_mode */;
    const selection_1 = require(130) /* ../selections/selection */;
    class HAreaStepView extends area_1.AreaView {
        _index_data(index) {
            const { min, max } = Math;
            const { x1, x2, y } = this;
            for (let i = 0; i < this.data_size; i++) {
                const x1_i = x1[i];
                const x2_i = x2[i];
                const y_i = y[i];
                index.add_rect(min(x1_i, x2_i), y_i, max(x1_i, x2_i), y_i);
            }
        }
        _step_path(ctx, mode, sx, sy, from_i, to_i) {
            // Assume the path was already moved to the first point
            let prev_x = sx[from_i];
            let prev_y = sy[from_i];
            const idx_dir = from_i < to_i ? 1 : -1;
            for (let i = from_i + idx_dir; i != to_i; i += idx_dir) {
                switch (mode) {
                    case "before": {
                        ctx.lineTo(sx[i], prev_y);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    }
                    case "after": {
                        ctx.lineTo(prev_x, sy[i]);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    }
                    case "center": {
                        const mid_y = (prev_y + sy[i]) / 2;
                        ctx.lineTo(prev_x, mid_y);
                        ctx.lineTo(sx[i], mid_y);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    }
                }
                prev_x = sx[i];
                prev_y = sy[i];
            }
        }
        _paint(ctx, _indices, data) {
            const { sx1, sx2, sy } = { ...this, ...data };
            const forward_mode = this.model.step_mode;
            const backward_mode = (0, flip_step_mode_1.flip_step_mode)(this.model.step_mode);
            ctx.beginPath();
            ctx.moveTo(sx1[0], sy[0]);
            this._step_path(ctx, forward_mode, sx1, sy, 0, sy.length);
            this._step_path(ctx, backward_mode, sx2, sy, sy.length, -1);
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
        }
        scenterxy(i) {
            const scx = (this.sx1[i] + this.sx2[i]) / 2;
            const scy = this.sy[i];
            return [scx, scy];
        }
        _line_selection_for(i) {
            return new selection_1.Selection({ line_indices: [i], selected_glyphs: [this.model], view: this });
        }
        _hit_point_before(geometry) {
            const { sy, sx1, sx2 } = this;
            for (let i = 1; i < this.data_size; i++) {
                const px = [sx1[i], sx1[i], sx2[i], sx2[i]];
                const py = [sy[i - 1], sy[i], sy[i], sy[i - 1]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    return this._line_selection_for(i);
                }
            }
            return new selection_1.Selection();
        }
        _hit_point_after(geometry) {
            const { sy, sx1, sx2 } = this;
            for (let i = 0; i < this.data_size - 1; i++) {
                const px = [sx1[i], sx1[i], sx2[i], sx2[i]];
                const py = [sy[i], sy[i + 1], sy[i + 1], sy[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    return this._line_selection_for(i);
                }
            }
            return new selection_1.Selection();
        }
        _hit_point_center(geometry) {
            const { sy, sx1, sx2 } = this;
            for (let i = 0; i < this.data_size; i++) {
                const mid_prev_y = (sy[i - 1] + sy[i]) / 2; /* undefined for first */
                const mid_next_y = (sy[i] + sy[i + 1]) / 2; /* undefined for last  */
                const px = [sx1[i], sx1[i], sx2[i], sx2[i]];
                const py = (() => {
                    if (i == 0) {
                        return [sy[i], mid_next_y, mid_next_y, sy[i]];
                    }
                    else if (i == this.data_size - 1) {
                        return [mid_prev_y, sy[i], sy[i], mid_prev_y];
                    }
                    else {
                        return [mid_prev_y, mid_next_y, mid_next_y, mid_prev_y];
                    }
                })();
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    return this._line_selection_for(i);
                }
            }
            return new selection_1.Selection();
        }
        _hit_point(geometry) {
            switch (this.model.step_mode) {
                case "before": return this._hit_point_before(geometry);
                case "after": return this._hit_point_after(geometry);
                case "center": return this._hit_point_center(geometry);
            }
        }
    }
    exports.HAreaStepView = HAreaStepView;
    HAreaStepView.__name__ = "HAreaStepView";
    class HAreaStep extends area_1.Area {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HAreaStep = HAreaStep;
    _a = HAreaStep;
    HAreaStep.__name__ = "HAreaStep";
    (() => {
        _a.prototype.default_view = HAreaStepView;
        _a.define(({}) => ({
            x1: [p.XCoordinateSpec, { field: "x1" }],
            x2: [p.XCoordinateSpec, { field: "x2" }],
            y: [p.YCoordinateSpec, { field: "y" }],
            step_mode: [enums_1.StepMode, "before"],
        }));
    })();
},
/* models/glyphs/area.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    class AreaView extends glyph_1.GlyphView {
        draw_legend_for_index(ctx, bbox, _index) {
            (0, utils_1.generic_area_scalar_legend)(this.visuals, ctx, bbox);
        }
    }
    exports.AreaView = AreaView;
    AreaView.__name__ = "AreaView";
    class Area extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Area = Area;
    _a = Area;
    Area.__name__ = "Area";
    (() => {
        _a.mixins([mixins.FillScalar, mixins.HatchScalar]);
    })();
},
/* core/util/flip_step_mode.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.flip_step_mode = flip_step_mode;
    function flip_step_mode(mode) {
        switch (mode) {
            case "before":
                return "after";
            case "after":
                return "before";
            case "center":
                return "center";
        }
    }
},
/* models/glyphs/harea.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const area_1 = require(232) /* ./area */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(130) /* ../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_i = this.x1[i];
                const x2_i = this.x2[i];
                const y_i = this.y[i];
                index.add_rect(min(x1_i, x2_i), y_i, max(x1_i, x2_i), y_i);
            }
        }
        _paint(ctx, _indices, data) {
            const { sx1, sx2, sy } = { ...this, ...data };
            ctx.beginPath();
            for (let i = 0, end = sx1.length; i < end; i++) {
                ctx.lineTo(sx1[i], sy[i]);
            }
            // iterate backwards so that the upper end is below the lower start
            for (let i = sx2.length - 1; i >= 0; i--) {
                ctx.lineTo(sx2[i], sy[i]);
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
        }
        _hit_point(geometry) {
            const L = this.sy.length;
            const result = new selection_1.Selection();
            for (let i = 0, end = L - 1; i < end; i++) {
                const sx = [this.sx1[i], this.sx1[i + 1], this.sx2[i + 1], this.sx2[i]];
                const sy = [this.sy[i], this.sy[i + 1], this.sy[i + 1], this.sy[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, sx, sy)) {
                    result.add_to_selected_glyphs(this.model);
                    result.view = this;
                    result.line_indices = [i];
                    break;
                }
            }
            return result;
        }
        scenterxy(i) {
            const scx = (this.sx1[i] + this.sx2[i]) / 2;
            const scy = this.sy[i];
            return [scx, scy];
        }
    }
    exports.HAreaView = HAreaView;
    HAreaView.__name__ = "HAreaView";
    class HArea extends area_1.Area {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HArea = HArea;
    _a = HArea;
    HArea.__name__ = "HArea";
    (() => {
        _a.prototype.default_view = HAreaView;
        _a.define(({}) => ({
            x1: [p.XCoordinateSpec, { field: "x1" }],
            x2: [p.XCoordinateSpec, { field: "x2" }],
            y: [p.YCoordinateSpec, { field: "y" }],
        }));
    })();
},
/* models/glyphs/varea_step.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const area_1 = require(232) /* ./area */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const enums_1 = require(20) /* ../../core/enums */;
    const flip_step_mode_1 = require(233) /* ../../core/util/flip_step_mode */;
    const selection_1 = require(130) /* ../selections/selection */;
    class VAreaStepView extends area_1.AreaView {
        _index_data(index) {
            const { min, max } = Math;
            const { x, y1, y2 } = this;
            for (let i = 0; i < this.data_size; i++) {
                const x_i = x[i];
                const y1_i = y1[i];
                const y2_i = y2[i];
                index.add_rect(x_i, min(y1_i, y2_i), x_i, max(y1_i, y2_i));
            }
        }
        _step_path(ctx, mode, sx, sy, from_i, to_i) {
            // Assume the path was already moved to the first point
            let prev_x = sx[from_i];
            let prev_y = sy[from_i];
            const idx_dir = from_i < to_i ? 1 : -1;
            for (let i = from_i + idx_dir; i != to_i; i += idx_dir) {
                switch (mode) {
                    case "before": {
                        ctx.lineTo(prev_x, sy[i]);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    }
                    case "after": {
                        ctx.lineTo(sx[i], prev_y);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    }
                    case "center": {
                        const mid_x = (prev_x + sx[i]) / 2;
                        ctx.lineTo(mid_x, prev_y);
                        ctx.lineTo(mid_x, sy[i]);
                        ctx.lineTo(sx[i], sy[i]);
                        break;
                    }
                }
                prev_x = sx[i];
                prev_y = sy[i];
            }
        }
        _paint(ctx, _indices, data) {
            const { sx, sy1, sy2 } = { ...this, ...data };
            const forward_mode = this.model.step_mode;
            const backward_mode = (0, flip_step_mode_1.flip_step_mode)(this.model.step_mode);
            ctx.beginPath();
            ctx.moveTo(sx[0], sy1[0]);
            this._step_path(ctx, forward_mode, sx, sy1, 0, sx.length);
            this._step_path(ctx, backward_mode, sx, sy2, sx.length, -1);
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
        }
        scenterxy(i) {
            const scx = this.sx[i];
            const scy = (this.sy1[i] + this.sy2[i]) / 2;
            return [scx, scy];
        }
        _line_selection_for(i) {
            return new selection_1.Selection({ line_indices: [i], selected_glyphs: [this.model], view: this });
        }
        _hit_point_before(geometry) {
            const { sx, sy1, sy2 } = this;
            for (let i = 1; i < this.data_size; i++) {
                const px = [sx[i - 1], sx[i], sx[i], sx[i - 1]];
                const py = [sy1[i], sy1[i], sy2[i], sy2[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    return this._line_selection_for(i);
                }
            }
            return new selection_1.Selection();
        }
        _hit_point_after(geometry) {
            const { sx, sy1, sy2 } = this;
            for (let i = 0; i < this.data_size - 1; i++) {
                const px = [sx[i], sx[i + 1], sx[i + 1], sx[i]];
                const py = [sy1[i], sy1[i], sy2[i], sy2[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    return this._line_selection_for(i);
                }
            }
            return new selection_1.Selection();
        }
        _hit_point_center(geometry) {
            const { sx, sy1, sy2 } = this;
            for (let i = 0; i < this.data_size; i++) {
                const mid_prev_x = (sx[i - 1] + sx[i]) / 2; /* undefined for first */
                const mid_next_x = (sx[i] + sx[i + 1]) / 2; /* undefined for last  */
                const px = (() => {
                    if (i == 0) {
                        return [sx[i], mid_next_x, mid_next_x, sx[i]];
                    }
                    else if (i == this.data_size - 1) {
                        return [mid_prev_x, sx[i], sx[i], mid_prev_x];
                    }
                    else {
                        return [mid_prev_x, mid_next_x, mid_next_x, mid_prev_x];
                    }
                })();
                const py = [sy1[i], sy1[i], sy2[i], sy2[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, px, py)) {
                    return this._line_selection_for(i);
                }
            }
            return new selection_1.Selection();
        }
        _hit_point(geometry) {
            switch (this.model.step_mode) {
                case "before": return this._hit_point_before(geometry);
                case "after": return this._hit_point_after(geometry);
                case "center": return this._hit_point_center(geometry);
            }
        }
    }
    exports.VAreaStepView = VAreaStepView;
    VAreaStepView.__name__ = "VAreaStepView";
    class VAreaStep extends area_1.Area {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VAreaStep = VAreaStep;
    _a = VAreaStep;
    VAreaStep.__name__ = "VAreaStep";
    (() => {
        _a.prototype.default_view = VAreaStepView;
        _a.define(({}) => ({
            x: [p.XCoordinateSpec, { field: "x" }],
            y1: [p.YCoordinateSpec, { field: "y1" }],
            y2: [p.YCoordinateSpec, { field: "y2" }],
            step_mode: [enums_1.StepMode, "before"],
        }));
    })();
},
/* models/glyphs/varea.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const area_1 = require(232) /* ./area */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(130) /* ../selections/selection */;
    class VAreaView extends area_1.AreaView {
        _index_data(index) {
            const { min, max } = Math;
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x = this.x[i];
                const y1 = this.y1[i];
                const y2 = this.y2[i];
                index.add_rect(x, min(y1, y2), x, max(y1, y2));
            }
        }
        _paint(ctx, _indices, data) {
            const { sx, sy1, sy2 } = { ...this, ...data };
            ctx.beginPath();
            for (let i = 0, end = sy1.length; i < end; i++) {
                ctx.lineTo(sx[i], sy1[i]);
            }
            // iterate backwards so that the upper end is below the lower start
            for (let i = sy2.length - 1; i >= 0; i--) {
                ctx.lineTo(sx[i], sy2[i]);
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            this.visuals.hatch.apply(ctx);
        }
        scenterxy(i) {
            const scx = this.sx[i];
            const scy = (this.sy1[i] + this.sy2[i]) / 2;
            return [scx, scy];
        }
        _hit_point(geometry) {
            const L = this.sx.length;
            const result = new selection_1.Selection();
            for (let i = 0, end = L - 1; i < end; i++) {
                const sx = [this.sx[i], this.sx[i + 1], this.sx[i + 1], this.sx[i]];
                const sy = [this.sy1[i], this.sy1[i + 1], this.sy2[i + 1], this.sy2[i]];
                if (hittest.point_in_poly(geometry.sx, geometry.sy, sx, sy)) {
                    result.add_to_selected_glyphs(this.model);
                    result.view = this;
                    result.line_indices = [i];
                    break;
                }
            }
            return result;
        }
    }
    exports.VAreaView = VAreaView;
    VAreaView.__name__ = "VAreaView";
    class VArea extends area_1.Area {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VArea = VArea;
    _a = VArea;
    VArea.__name__ = "VArea";
    (() => {
        _a.prototype.default_view = VAreaView;
        _a.define(({}) => ({
            x: [p.XCoordinateSpec, { field: "x" }],
            y1: [p.YCoordinateSpec, { field: "y1" }],
            y2: [p.YCoordinateSpec, { field: "y2" }],
        }));
    })();
},
/* models/sources/cds_view.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const view_1 = require(58) /* ../../core/view */;
    const types_1 = require(24) /* ../../core/types */;
    const filter_1 = require(238) /* ../filters/filter */;
    const all_indices_1 = require(239) /* ../filters/all_indices */;
    const intersection_filter_1 = require(240) /* ../filters/intersection_filter */;
    class CDSViewView extends view_1.View {
        initialize() {
            super.initialize();
            this.compute_indices();
        }
        connect_signals() {
            super.connect_signals();
            const compute_indices = () => {
                this.compute_indices();
            };
            const connect_filter = (filter) => {
                this.connect(filter.change, compute_indices);
            };
            const disconnect_filter = (filter) => {
                this.disconnect(filter.change, compute_indices);
            };
            let { filter } = this.model;
            connect_filter(filter);
            this.on_change(this.model.properties.filter, () => {
                disconnect_filter(filter);
                filter = this.model.filter;
                connect_filter(filter);
                compute_indices();
            });
            const connect_data_source = (data_source) => {
                this.connect(data_source.change, compute_indices);
                this.connect(data_source.streaming, compute_indices);
                this.connect(data_source.patching, compute_indices);
                this.connect(data_source.properties.data.change, compute_indices);
            };
            const disconnect_data_source = (data_source) => {
                this.disconnect(data_source.change, compute_indices);
                this.disconnect(data_source.streaming, compute_indices);
                this.disconnect(data_source.patching, compute_indices);
                this.disconnect(data_source.properties.data.change, compute_indices);
            };
            let data_source = this.parent.data_source.get_value();
            connect_data_source(data_source);
            this.on_change(this.parent.data_source, () => {
                disconnect_data_source(data_source);
                data_source = this.parent.data_source.get_value();
                connect_data_source(data_source);
                compute_indices();
            });
        }
        compute_indices() {
            // XXX: if the data source is empty, there still may be one
            // index originating from glyph's scalar values.
            const source = this.parent.data_source.get_value();
            const size = source.get_length() ?? 1;
            const indices = types_1.Indices.all_set(size);
            const filtered = this.model.filter.compute_indices(source);
            indices.intersect(filtered);
            this.model.indices = indices;
            this.model._indices_map_to_subset();
        }
    }
    exports.CDSViewView = CDSViewView;
    CDSViewView.__name__ = "CDSViewView";
    class CDSView extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        _indices_map_to_subset() {
            this._indices = [...this.indices];
            this.indices_map = new Map();
            const { _indices, indices_map } = this;
            const n = _indices.length;
            for (let i = 0; i < n; i++) {
                indices_map.set(_indices[i], i);
            }
        }
        convert_selection_from_subset(selection_subset) {
            return selection_subset.map((i) => this._indices[i]);
        }
        convert_selection_to_subset(selection_full) {
            return selection_full.map((i) => this.indices_map.get(i)); // XXX ?? NaN
        }
        convert_indices_from_subset(indices) {
            return indices.map((i) => this._indices[i]);
        }
        /** @deprecated */
        get filters() {
            const { filter } = this;
            if (filter instanceof intersection_filter_1.IntersectionFilter) {
                return filter.operands;
            }
            else if (filter instanceof all_indices_1.AllIndices) {
                return [];
            }
            else {
                return [filter];
            }
        }
        /** @deprecated */
        set filters(filters) {
            if (filters.length == 0) {
                this.filter = new all_indices_1.AllIndices();
            }
            else if (filters.length == 1) {
                this.filter = filters[0];
            }
            else {
                this.filter = new intersection_filter_1.IntersectionFilter({ operands: filters });
            }
        }
    }
    exports.CDSView = CDSView;
    _a = CDSView;
    CDSView.__name__ = "CDSView";
    (() => {
        _a.prototype.default_view = CDSViewView;
        _a.define(({ Ref }) => ({
            filter: [Ref(filter_1.Filter), () => new all_indices_1.AllIndices()],
        }));
        _a.internal(({ Int, Mapping, Ref, Nullable }) => ({
            indices: [Ref(types_1.Indices)],
            indices_map: [Mapping(Int, Int), new Map()],
            masked: [Nullable(Ref(types_1.Indices)), null],
        }));
    })();
},
/* models/filters/filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(51) /* ../../model */;
    class Filter extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Filter = Filter;
    Filter.__name__ = "Filter";
},
/* models/filters/all_indices.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const filter_1 = require(238) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    class AllIndices extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            const size = source.get_length() ?? 1;
            return types_1.Indices.all_set(size);
        }
    }
    exports.AllIndices = AllIndices;
    AllIndices.__name__ = "AllIndices";
},
/* models/filters/intersection_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const composite_filter_1 = require(241) /* ./composite_filter */;
    class IntersectionFilter extends composite_filter_1.CompositeFilter {
        constructor(attrs) {
            super(attrs);
        }
        _inplace_op(index, op) {
            index.intersect(op);
        }
    }
    exports.IntersectionFilter = IntersectionFilter;
    IntersectionFilter.__name__ = "IntersectionFilter";
},
/* models/filters/composite_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(238) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    class CompositeFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        connect_signals() {
            super.connect_signals();
            const emit_changed = () => {
                this.change.emit();
            };
            const connect_operands = (operands) => {
                for (const operand of operands) {
                    this.connect(operand.change, emit_changed);
                }
            };
            const disconnect_operands = (operands) => {
                for (const operand of operands) {
                    this.disconnect(operand.change, emit_changed);
                }
            };
            let operands = (() => {
                const { operands } = this.properties;
                return operands.is_unset ? [] : operands.get_value();
            })();
            connect_operands(operands);
            this.on_change(this.properties.operands, () => {
                disconnect_operands(operands);
                operands = this.operands;
                connect_operands(operands);
            });
        }
        compute_indices(source) {
            const { operands } = this;
            if (operands.length == 0) {
                const size = source.get_length() ?? 1;
                return types_1.Indices.all_set(size);
            }
            else {
                const [index, ...rest] = operands.map((op) => op.compute_indices(source));
                for (const op of rest) {
                    this._inplace_op(index, op);
                }
                return index;
            }
        }
    }
    exports.CompositeFilter = CompositeFilter;
    _a = CompositeFilter;
    CompositeFilter.__name__ = "CompositeFilter";
    (() => {
        _a.define(({ List, Ref }) => ({
            operands: [List(Ref(filter_1.Filter))],
        }));
    })();
},
/* models/formatters/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var basic_tick_formatter_1 = require(196) /* ./basic_tick_formatter */;
    __esExport("BasicTickFormatter", basic_tick_formatter_1.BasicTickFormatter);
    var categorical_tick_formatter_1 = require(243) /* ./categorical_tick_formatter */;
    __esExport("CategoricalTickFormatter", categorical_tick_formatter_1.CategoricalTickFormatter);
    var datetime_tick_formatter_1 = require(244) /* ./datetime_tick_formatter */;
    __esExport("DatetimeTickFormatter", datetime_tick_formatter_1.DatetimeTickFormatter);
    var customjs_tick_formatter_1 = require(249) /* ./customjs_tick_formatter */;
    __esExport("CustomJSTickFormatter", customjs_tick_formatter_1.CustomJSTickFormatter);
    var log_tick_formatter_1 = require(250) /* ./log_tick_formatter */;
    __esExport("LogTickFormatter", log_tick_formatter_1.LogTickFormatter);
    var mercator_tick_formatter_1 = require(251) /* ./mercator_tick_formatter */;
    __esExport("MercatorTickFormatter", mercator_tick_formatter_1.MercatorTickFormatter);
    var numeral_tick_formatter_1 = require(252) /* ./numeral_tick_formatter */;
    __esExport("NumeralTickFormatter", numeral_tick_formatter_1.NumeralTickFormatter);
    var printf_tick_formatter_1 = require(253) /* ./printf_tick_formatter */;
    __esExport("PrintfTickFormatter", printf_tick_formatter_1.PrintfTickFormatter);
    var tick_formatter_1 = require(192) /* ./tick_formatter */;
    __esExport("TickFormatter", tick_formatter_1.TickFormatter);
},
/* models/formatters/categorical_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tick_formatter_1 = require(192) /* ./tick_formatter */;
    const array_1 = require(10) /* ../../core/util/array */;
    class CategoricalTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        doFormat(ticks, _opts) {
            return (0, array_1.copy)(ticks);
        }
    }
    exports.CategoricalTickFormatter = CategoricalTickFormatter;
    CategoricalTickFormatter.__name__ = "CategoricalTickFormatter";
},
/* models/formatters/datetime_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    exports._get_resolution = _get_resolution;
    exports._mktime = _mktime;
    exports._strftime = _strftime;
    exports._us = _us;
    const tslib_1 = require(1) /* tslib */;
    const enums_1 = require(20) /* ../../core/enums */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const templating_1 = require(245) /* ../../core/util/templating */;
    const types_1 = require(8) /* ../../core/util/types */;
    const tick_formatter_1 = require(192) /* ./tick_formatter */;
    const util_1 = require(207) /* ../tickers/util */;
    const timezone_1 = tslib_1.__importDefault(require(248) /* timezone */);
    // Labels of time units, from finest to coarsest.
    exports.resolution_order = [
        "microseconds", "milliseconds", "seconds", "minsec", "minutes", "hourmin", "hours", "days", "months", "years",
    ];
    // This dictionary maps the name of a time resolution (in @resolution_order)
    // to its index in a time.localtime() time tuple. The default is to map
    // everything to index 0, which is year. This is not ideal; it might cause
    // a problem with the tick at midnight, january 1st, 0 a.d. being incorrectly
    // promoted at certain tick resolutions.
    exports.tm_index_for_resolution = {
        microseconds: 0,
        milliseconds: 0,
        seconds: 5,
        minsec: 4,
        minutes: 4,
        hourmin: 3,
        hours: 3,
        days: 0,
        months: 0,
        years: 0,
    };
    function _get_resolution(resolution_secs, span_secs) {
        // Our resolution boundaries should not be round numbers, because we want
        // them to fall between the possible tick intervals (which *are* round
        // numbers, as we've worked hard to ensure). Consequently, we adjust the
        // resolution upwards a small amount (less than any possible step in
        // scales) to make the effective boundaries slightly lower.
        const adjusted_ms = resolution_secs * 1.1 * 1000;
        const span_ms = span_secs * 1000;
        if (adjusted_ms < util_1.ONE_MILLI) {
            return "microseconds";
        }
        if (adjusted_ms < util_1.ONE_SECOND) {
            return "milliseconds";
        }
        if (adjusted_ms < util_1.ONE_MINUTE) {
            return span_ms >= util_1.ONE_MINUTE ? "minsec" : "seconds";
        }
        if (adjusted_ms < util_1.ONE_HOUR) {
            return span_ms >= util_1.ONE_HOUR ? "hourmin" : "minutes";
        }
        if (adjusted_ms < util_1.ONE_DAY) {
            return "hours";
        }
        if (adjusted_ms < util_1.ONE_MONTH) {
            return "days";
        }
        if (adjusted_ms < util_1.ONE_YEAR) {
            return "months";
        }
        return "years";
    }
    function _mktime(t) {
        return (0, timezone_1.default)(t, "%Y %m %d %H %M %S").split(/\s+/).map(e => parseInt(e, 10));
    }
    function _strftime(t, format) {
        // Python's datetime library augments the microsecond directive %f, which is not
        // supported by the javascript library timezone: http://bigeasy.github.io/timezone/.
        // Use a regular expression to replace %f directive with microseconds.
        const microsecond_replacement_string = (0, templating_1.sprintf)("$1%06d", _us(t));
        format = format.replace(/((^|[^%])(%%)*)%f/, microsecond_replacement_string);
        // timezone seems to ignore any strings without any formatting directives,
        // and just return the time argument back instead of the string argument.
        // But we want the string argument, in case a user supplies a format string
        // which doesn't contain a formatting directive or is only using %f.
        if (format.indexOf("%") == -1) {
            return format;
        }
        return (0, timezone_1.default)(t, format);
    }
    function _us(t) {
        // From double-precision unix (millisecond) timestamp, get microseconds since
        // last second. Precision seems to run out around the hundreds of nanoseconds
        // scale, so rounding to the nearest microsecond should round to a nice
        // microsecond / millisecond tick.
        // Note: for negative timestamps (pre epoch) the microsecond scale needs to be
        // inverted as we are counting backwards.
        let us = Math.round(((t / 1000) % 1) * 1000000);
        if (t < 0.0) {
            us = (1000000 + us) % 1000000;
        }
        return us;
    }
    class DatetimeTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        doFormat(ticks, _opts, _resolution) {
            if (ticks.length == 0) {
                return [];
            }
            const span = Math.abs(ticks[ticks.length - 1] - ticks[0]) / 1000.0;
            const r = span / (ticks.length - 1);
            const resolution = (0, types_1.is_undefined)(_resolution) ? _get_resolution(r, span) : _resolution;
            let base_labels = [];
            for (const tick of ticks) {
                const base_label = this._compute_label(tick, resolution);
                base_labels.push(base_label);
            }
            if (this.hide_repeats) {
                base_labels = this._hide_repeating_labels(base_labels);
            }
            if (this.context == null) {
                return base_labels;
            }
            const context_labels = this._compute_context_labels(ticks, resolution);
            return this._build_full_labels(base_labels, context_labels);
        }
        _compute_label(t, resolution) {
            const s0 = _strftime(t, this[resolution]);
            const tm = _mktime(t);
            const resolution_index = exports.resolution_order.indexOf(resolution);
            let final_resolution = resolution;
            let s = s0;
            if (this.boundary_scaling) {
                let hybrid_handled = false;
                let next_index = resolution_index;
                let next_resolution = resolution;
                // As we format each tick, check to see if we are at a boundary of the
                // next higher unit of time. If so, replace the current format with one
                // from that resolution. This is not the best heuristic but it works.
                while (tm[exports.tm_index_for_resolution[exports.resolution_order[next_index]]] == 0) {
                    next_index += 1;
                    if (next_index == exports.resolution_order.length) {
                        break;
                    }
                    // The way to check that we are at the boundary of the next unit of
                    // time is by checking that we have 0 units of the resolution, i.e.
                    // we are at zero minutes, so display hours, or we are at zero seconds,
                    // so display minutes (and if that is zero as well, then display hours).
                    if ((resolution == "minsec" || resolution == "hourmin") && !hybrid_handled) {
                        if ((resolution == "minsec" && tm[4] == 0 && tm[5] != 0) || (resolution == "hourmin" && tm[3] == 0 && tm[4] != 0)) {
                            next_resolution = exports.resolution_order[resolution_index - 1];
                            s = _strftime(t, this[next_resolution]);
                            break;
                        }
                        else {
                            hybrid_handled = true;
                        }
                    }
                    next_resolution = exports.resolution_order[next_index];
                    s = _strftime(t, this[next_resolution]);
                }
                final_resolution = next_resolution;
            }
            const { strip_leading_zeros } = this;
            if (((0, types_1.isBoolean)(strip_leading_zeros) && strip_leading_zeros) ||
                ((0, types_1.isArray)(strip_leading_zeros) && strip_leading_zeros.includes(final_resolution))) {
                const ss = s.replace(/^0+/g, "");
                if (ss != s && !Number.isInteger(Number(ss[0]))) {
                    // If the string can now be parsed as starting with an integer, then
                    // leave all zeros stripped, otherwise start with a zero.
                    return `0${ss}`;
                }
                return ss;
            }
            return s;
        }
        _compute_context_labels(ticks, resolution) {
            const { context } = this;
            (0, assert_1.assert)(context != null);
            const context_labels = [];
            if ((0, types_1.isString)(context)) {
                for (const tick of ticks) {
                    context_labels.push(_strftime(tick, context));
                }
            }
            else {
                context_labels.push(...context.doFormat(ticks, { loc: 0 }, resolution));
            }
            const which = this.context_which;
            const N = context_labels.length;
            for (let i = 0; i < context_labels.length; i++) {
                if ((which == "start" && i != 0) ||
                    (which == "end" && i != N - 1) ||
                    (which == "center" && i != Math.floor(N / 2))) {
                    context_labels[i] = "";
                }
            }
            return context_labels;
        }
        _build_full_labels(base_labels, context_labels) {
            const loc = this.context_location;
            const full_labels = [];
            if (context_labels.every(v => v === "")) {
                return base_labels;
            }
            for (let i = 0; i < base_labels.length; i++) {
                const label = base_labels[i];
                const context = context_labels[i];
                // In case of above and below blank strings are not trimmed in order to
                // keep the same visual format across all ticks.
                const full_label = (() => {
                    switch (loc) {
                        case "above": return `${context}\n${label}`;
                        case "below": return `${label}\n${context}`;
                        case "left": return context == "" ? label : `${context} ${label}`;
                        case "right": return context == "" ? label : `${label} ${context}`;
                    }
                })();
                full_labels.push(full_label);
            }
            return full_labels;
        }
        _hide_repeating_labels(labels) {
            // For repeating labels only utilize the first entry
            if (labels.length <= 1) {
                return labels;
            }
            const labels_h = [labels[0]];
            let index_first_entry = 0;
            for (let i = 1; i < labels.length; i++) {
                if (labels[index_first_entry] == labels[i]) {
                    labels_h.push("");
                }
                else {
                    labels_h.push(labels[i]);
                    index_first_entry = i;
                }
            }
            return labels_h;
        }
    }
    exports.DatetimeTickFormatter = DatetimeTickFormatter;
    _a = DatetimeTickFormatter;
    DatetimeTickFormatter.__name__ = "DatetimeTickFormatter";
    (() => {
        _a.define(({ Bool, Nullable, Or, Ref, Str, Arrayable }) => ({
            microseconds: [Str, "%fus"],
            milliseconds: [Str, "%3Nms"],
            seconds: [Str, "%Ss"],
            minsec: [Str, ":%M:%S"],
            minutes: [Str, ":%M"],
            hourmin: [Str, "%H:%M"],
            hours: [Str, "%Hh"],
            days: [Str, "%m/%d"],
            months: [Str, "%m/%Y"],
            years: [Str, "%Y"],
            strip_leading_zeros: [Or(Bool, Arrayable(enums_1.ResolutionType)), false],
            boundary_scaling: [Bool, true],
            hide_repeats: [Bool, false],
            context: [Nullable(Or(Str, Ref(_a))), null],
            context_which: [enums_1.ContextWhich, "start"],
            context_location: [enums_1.Location, "below"],
        }));
    })();
},
/* core/util/templating.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.sprintf = sprintf;
    exports.basic_formatter = basic_formatter;
    exports.get_formatter = get_formatter;
    exports._get_column_value = _get_column_value;
    exports.get_value = get_value;
    exports.replace_placeholders = replace_placeholders;
    exports.process_placeholders = process_placeholders;
    const tslib_1 = require(1) /* tslib */;
    const Numbro = tslib_1.__importStar(require(246) /* @bokeh/numbro */);
    const sprintf_js_1 = require(247) /* sprintf-js */;
    const timezone_1 = tslib_1.__importDefault(require(248) /* timezone */);
    const logging_1 = require(19) /* ../logging */;
    const object_1 = require(9) /* ./object */;
    const ndarray_1 = require(30) /* ./ndarray */;
    const types_1 = require(8) /* ./types */;
    const { abs } = Math;
    exports.DEFAULT_FORMATTERS = {
        raw: (value, _format, _special_vars) => `${value}`,
        basic: (value, format, special_vars) => basic_formatter(value, format, special_vars),
        numeral: (value, format, _special_vars) => Numbro.format(value, format),
        datetime: (value, format, _special_vars) => (0, timezone_1.default)(value, format),
        printf: (value, format, _special_vars) => sprintf(format, value),
    };
    function sprintf(format, ...args) {
        return (0, sprintf_js_1.sprintf)(format, ...args);
    }
    function basic_formatter(value, _format, _special_vars) {
        if ((0, types_1.isNumber)(value)) {
            const format = (() => {
                if (Number.isInteger(value)) {
                    return "%d";
                }
                else if (0.1 < abs(value) && abs(value) < 1000) {
                    return "%0.3f";
                }
                else {
                    return "%0.3e";
                }
            })();
            return sprintf(format, value);
        }
        else {
            return `${value}`; // get strings for categorical types
        }
    }
    function get_formatter(spec, format, formatters) {
        // no format, use default built in formatter
        if (format == null) {
            return exports.DEFAULT_FORMATTERS.basic;
        }
        // format spec in the formatters dict, use that
        if (formatters != null) {
            const formatter = (0, object_1.dict)(formatters).get(spec);
            if (formatter != null) {
                if ((0, types_1.isString)(formatter)) {
                    if (formatter in exports.DEFAULT_FORMATTERS) {
                        return exports.DEFAULT_FORMATTERS[formatter];
                    }
                    else {
                        throw new Error(`Unknown tooltip field formatter type '${formatter}'`);
                    }
                }
                return function (value, format, special_vars) {
                    return formatter.format(value, format, special_vars);
                };
            }
        }
        // otherwise use "numeral" as default
        return exports.DEFAULT_FORMATTERS.numeral;
    }
    exports.MISSING = "???";
    function _get_special_value(name, special_vars) {
        if (name in special_vars) {
            return special_vars[name];
        }
        else {
            logging_1.logger.warn(`unknown special variable '\$${name}'`);
            return exports.MISSING;
        }
    }
    function _get_column_value(name, data_source, ind) {
        const column = data_source.get_column(name);
        // missing column
        if (column == null) {
            return null;
        }
        // null index (e.g for patch)
        if (ind == null) {
            return null;
        }
        // typical (non-image) index
        if ((0, types_1.isNumber)(ind)) {
            return column[ind];
        }
        // image index
        const data = column[ind.index];
        if ((0, types_1.isTypedArray)(data) || (0, types_1.isArray)(data)) {
            // inspect array of arrays
            if ((0, types_1.isArray)(data[0])) {
                const row = data[ind.j];
                return row[ind.i];
            }
            else if ((0, ndarray_1.is_NDArray)(data) && data.dimension == 3) {
                // For 3d array return whole of 3rd axis
                return data.slice(ind.flat_index * data.shape[2], (ind.flat_index + 1) * data.shape[2]);
            }
            else {
                // inspect flat array
                return data[ind.flat_index];
            }
        }
        else {
            // inspect per-image scalar data
            return data;
        }
    }
    function get_value(type, name, data_source, i, special_vars) {
        switch (type) {
            case "$": return _get_special_value(name, special_vars);
            case "@": return _get_column_value(name, data_source, i);
        }
    }
    function replace_placeholders(content, data_source, i, formatters, special_vars = {}, encode) {
        let str;
        let has_html;
        if ((0, types_1.isString)(content)) {
            str = content;
            has_html = false;
        }
        else {
            str = content.html;
            has_html = true;
        }
        // this handles the special case @$name, replacing it with an @var corresponding to special_vars.name
        str = str.replace(/@\$name/g, (_match) => `@{${special_vars.name}}`);
        str = process_placeholders(str, (type, name, format, _, spec) => {
            const value = get_value(type, name, data_source, i, special_vars);
            // 'safe' format, return the value as-is
            if (format == "safe") {
                has_html = true;
                if (value == null) {
                    return exports.MISSING;
                }
                else if ((0, types_1.isNumber)(value) && isNaN(value)) {
                    return "NaN";
                }
                else {
                    return `${value}`;
                }
            }
            else {
                const result = (() => {
                    if (value == null) {
                        return exports.MISSING;
                    }
                    else if ((0, types_1.isNumber)(value) && isNaN(value)) {
                        return "NaN";
                    }
                    else {
                        const formatter = get_formatter(spec, format, formatters);
                        return `${formatter(value, format ?? "", special_vars)}`;
                    }
                })();
                return encode != null ? encode(result) : result;
            }
        });
        if (!has_html) {
            return str;
        }
        else {
            const parser = new DOMParser();
            const document = parser.parseFromString(str, "text/html");
            return [...document.body.childNodes];
        }
    }
    /**
     * This supports the following:
     *
     * - simple vars: $x
     * - simple names: @x, @słowa_0, @Wörter (@ symbol followed by unicode letters, numbers or underscore)
     * - full vars: ${one two}
     * - full names: @{one two} (@{anything except curly brackets}
     * - optional formatting: $x{format}, ${x}{format}, @x{format}, @{one two}{format}
     */
    const regex = /((?:[$@][\p{Letter}\p{Number}_]+)|(?:[$@]\{(?:[^{}]+)\}))(?:\{([^{}]+)\})?/gu;
    function process_placeholders(text, fn) {
        let i = 0; // this var is used for testing purposes
        return text.replace(regex, (_match, spec, format) => {
            const type = spec[0];
            const name = spec.substring(1).replace(/^{/, "").replace(/}$/, "").trim();
            return fn(type, name, format, i++, spec) ?? exports.MISSING;
        });
    }
},
/* @bokeh/numbro/numbro.js */ function _(require, module, exports, __esModule, __esExport) {
    /*!
     * numbro.js
     * version : 1.6.2
     * author : Företagsplatsen AB
     * license : MIT
     * http://www.foretagsplatsen.se
     */
    /************************************
        Constants
    ************************************/
    var numbro, VERSION = '1.6.2', 
    // internal storage for culture config files
    cultures = {}, 
    // Todo: Remove in 2.0.0
    languages = cultures, currentCulture = 'en-US', zeroFormat = null, defaultFormat = '0,0', defaultCurrencyFormat = '0$', 
    // check for nodeJS
    hasModule = (typeof module !== 'undefined' && module.exports), 
    // default culture
    enUS = {
        delimiters: {
            thousands: ',',
            decimal: '.'
        },
        abbreviations: {
            thousand: 'k',
            million: 'm',
            billion: 'b',
            trillion: 't'
        },
        ordinal: function (number) {
            var b = number % 10;
            return (~~(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                    (b === 2) ? 'nd' :
                        (b === 3) ? 'rd' : 'th';
        },
        currency: {
            symbol: '$',
            position: 'prefix'
        },
        defaults: {
            currencyFormat: ',0000 a'
        },
        formats: {
            fourDigits: '0000 a',
            fullWithTwoDecimals: '$ ,0.00',
            fullWithTwoDecimalsNoCurrency: ',0.00'
        }
    };
    /************************************
        Constructors
    ************************************/
    // Numbro prototype object
    function Numbro(number) {
        this._value = number;
    }
    function zeroes(count) {
        var i, ret = '';
        for (i = 0; i < count; i++) {
            ret += '0';
        }
        return ret;
    }
    /**
     * Implementation of toFixed() for numbers with exponent > 21
     *
     *
     */
    function toFixedLarge(value, precision) {
        var mantissa, beforeDec, afterDec, exponent, str;
        str = value.toString();
        mantissa = str.split('e')[0];
        exponent = str.split('e')[1];
        beforeDec = mantissa.split('.')[0];
        afterDec = mantissa.split('.')[1] || '';
        str = beforeDec + afterDec + zeroes(exponent - afterDec.length);
        if (precision > 0) {
            str += '.' + zeroes(precision);
        }
        return str;
    }
    /**
     * Implementation of toFixed() that treats floats more like decimals
     *
     * Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
     * problems for accounting- and finance-related software.
     */
    function toFixed(value, precision, roundingFunction, optionals) {
        var power = Math.pow(10, precision), optionalsRegExp, output;
        if (value.toFixed(0).search('e') > -1) {
            // Above 1e21, toFixed returns scientific notation, which
            // is useless and unexpected
            output = toFixedLarge(value, precision);
        }
        else {
            //roundingFunction = (roundingFunction !== undefined ? roundingFunction : Math.round);
            // Multiply up by precision, round accurately, then divide and use native toFixed():
            output = (roundingFunction(value * power) / power).toFixed(precision);
        }
        if (optionals) {
            optionalsRegExp = new RegExp('0{1,' + optionals + '}$');
            output = output.replace(optionalsRegExp, '');
        }
        return output;
    }
    /************************************
        Formatting
    ************************************/
    // determine what type of formatting we need to do
    function formatNumbro(value, format, roundingFunction) {
        var output;
        // TODO: do something with `language`
        // figure out what kind of format we are dealing with
        if (format.indexOf('$') > -1) { // currency!!!!!
            output = formatCurrency(value, format, roundingFunction);
        }
        else if (format.indexOf('%') > -1) { // percentage
            output = formatPercentage(value, format, roundingFunction);
        }
        else if (format.indexOf(':') > -1) { // time
            output = formatTime(value);
        }
        else { // plain ol' numbers or bytes
            output = formatNumber(value, format, roundingFunction);
        }
        // return string
        return output;
    }
    function formatCurrency(value, originalFormat, roundingFunction) {
        var format = originalFormat, symbolIndex = format.indexOf('$'), openParenIndex = format.indexOf('('), plusSignIndex = format.indexOf('+'), minusSignIndex = format.indexOf('-'), space = '', decimalSeparator = '', spliceIndex, output;
        if (format.indexOf('$') === -1) {
            // Use defaults instead of the format provided
            if (cultures[currentCulture].currency.position === 'infix') {
                decimalSeparator = cultures[currentCulture].currency.symbol;
                if (cultures[currentCulture].currency.spaceSeparated) {
                    decimalSeparator = ' ' + decimalSeparator + ' ';
                }
            }
            else if (cultures[currentCulture].currency.spaceSeparated) {
                space = ' ';
            }
        }
        else {
            // check for space before or after currency
            if (format.indexOf(' $') > -1) {
                space = ' ';
                format = format.replace(' $', '');
            }
            else if (format.indexOf('$ ') > -1) {
                space = ' ';
                format = format.replace('$ ', '');
            }
            else {
                format = format.replace('$', '');
            }
        }
        // Format The Number
        output = formatNumber(value, format, roundingFunction, decimalSeparator);
        if (originalFormat.indexOf('$') === -1) {
            // Use defaults instead of the format provided
            switch (cultures[currentCulture].currency.position) {
                case 'postfix':
                    if (output.indexOf(')') > -1) {
                        output = output.split('');
                        output.splice(-1, 0, space + cultures[currentCulture].currency.symbol);
                        output = output.join('');
                    }
                    else {
                        output = output + space + cultures[currentCulture].currency.symbol;
                    }
                    break;
                case 'infix':
                    break;
                case 'prefix':
                    if (output.indexOf('(') > -1 || output.indexOf('-') > -1) {
                        output = output.split('');
                        spliceIndex = Math.max(openParenIndex, minusSignIndex) + 1;
                        output.splice(spliceIndex, 0, cultures[currentCulture].currency.symbol + space);
                        output = output.join('');
                    }
                    else {
                        output = cultures[currentCulture].currency.symbol + space + output;
                    }
                    break;
                default:
                    throw Error('Currency position should be among ["prefix", "infix", "postfix"]');
            }
        }
        else {
            // position the symbol
            if (symbolIndex <= 1) {
                if (output.indexOf('(') > -1 || output.indexOf('+') > -1 || output.indexOf('-') > -1) {
                    output = output.split('');
                    spliceIndex = 1;
                    if (symbolIndex < openParenIndex || symbolIndex < plusSignIndex || symbolIndex < minusSignIndex) {
                        // the symbol appears before the "(", "+" or "-"
                        spliceIndex = 0;
                    }
                    output.splice(spliceIndex, 0, cultures[currentCulture].currency.symbol + space);
                    output = output.join('');
                }
                else {
                    output = cultures[currentCulture].currency.symbol + space + output;
                }
            }
            else {
                if (output.indexOf(')') > -1) {
                    output = output.split('');
                    output.splice(-1, 0, space + cultures[currentCulture].currency.symbol);
                    output = output.join('');
                }
                else {
                    output = output + space + cultures[currentCulture].currency.symbol;
                }
            }
        }
        return output;
    }
    function formatPercentage(value, format, roundingFunction) {
        var space = '', output;
        value = value * 100;
        // check for space before %
        if (format.indexOf(' %') > -1) {
            space = ' ';
            format = format.replace(' %', '');
        }
        else {
            format = format.replace('%', '');
        }
        output = formatNumber(value, format, roundingFunction);
        if (output.indexOf(')') > -1) {
            output = output.split('');
            output.splice(-1, 0, space + '%');
            output = output.join('');
        }
        else {
            output = output + space + '%';
        }
        return output;
    }
    function formatTime(value) {
        var hours = Math.floor(value / 60 / 60), minutes = Math.floor((value - (hours * 60 * 60)) / 60), seconds = Math.round(value - (hours * 60 * 60) - (minutes * 60));
        return hours + ':' +
            ((minutes < 10) ? '0' + minutes : minutes) + ':' +
            ((seconds < 10) ? '0' + seconds : seconds);
    }
    function formatNumber(value, format, roundingFunction, sep) {
        var negP = false, signed = false, optDec = false, abbr = '', i, abbrK = false, // force abbreviation to thousands
        abbrM = false, // force abbreviation to millions
        abbrB = false, // force abbreviation to billions
        abbrT = false, // force abbreviation to trillions
        abbrForce = false, // force abbreviation
        bytes = '', ord = '', abs = Math.abs(value), binarySuffixes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'], decimalSuffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], min, max, power, totalLength, length, minimumPrecision, pow, w, intPrecision, precision, prefix, postfix, thousands, d = '', forcedNeg = false, neg = false, indexOpenP, size, indexMinus, paren = '', minlen;
        // check if number is zero and a custom zero format has been set
        if (value === 0 && zeroFormat !== null) {
            return zeroFormat;
        }
        if (!isFinite(value)) {
            return '' + value;
        }
        if (format.indexOf('{') === 0) {
            var end = format.indexOf('}');
            if (end === -1) {
                throw Error('Format should also contain a "}"');
            }
            prefix = format.slice(1, end);
            format = format.slice(end + 1);
        }
        else {
            prefix = '';
        }
        if (format.indexOf('}') === format.length - 1) {
            var start = format.indexOf('{');
            if (start === -1) {
                throw Error('Format should also contain a "{"');
            }
            postfix = format.slice(start + 1, -1);
            format = format.slice(0, start + 1);
        }
        else {
            postfix = '';
        }
        // check for min length
        var info;
        if (format.indexOf('.') === -1) {
            info = format.match(/([0-9]+).*/);
        }
        else {
            info = format.match(/([0-9]+)\..*/);
        }
        minlen = info === null ? -1 : info[1].length;
        // see if we should use parentheses for negative number or if we should prefix with a sign
        // if both are present we default to parentheses
        if (format.indexOf('-') !== -1) {
            forcedNeg = true;
        }
        if (format.indexOf('(') > -1) {
            negP = true;
            format = format.slice(1, -1);
        }
        else if (format.indexOf('+') > -1) {
            signed = true;
            format = format.replace(/\+/g, '');
        }
        // see if abbreviation is wanted
        if (format.indexOf('a') > -1) {
            intPrecision = format.split('.')[0].match(/[0-9]+/g) || ['0'];
            intPrecision = parseInt(intPrecision[0], 10);
            // check if abbreviation is specified
            abbrK = format.indexOf('aK') >= 0;
            abbrM = format.indexOf('aM') >= 0;
            abbrB = format.indexOf('aB') >= 0;
            abbrT = format.indexOf('aT') >= 0;
            abbrForce = abbrK || abbrM || abbrB || abbrT;
            // check for space before abbreviation
            if (format.indexOf(' a') > -1) {
                abbr = ' ';
                format = format.replace(' a', '');
            }
            else {
                format = format.replace('a', '');
            }
            totalLength = Math.floor(Math.log(abs) / Math.LN10) + 1;
            minimumPrecision = totalLength % 3;
            minimumPrecision = minimumPrecision === 0 ? 3 : minimumPrecision;
            if (intPrecision && abs !== 0) {
                length = Math.floor(Math.log(abs) / Math.LN10) + 1 - intPrecision;
                pow = 3 * ~~((Math.min(intPrecision, totalLength) - minimumPrecision) / 3);
                abs = abs / Math.pow(10, pow);
                if (format.indexOf('.') === -1 && intPrecision > 3) {
                    format += '[.]';
                    size = length === 0 ? 0 : 3 * ~~(length / 3) - length;
                    size = size < 0 ? size + 3 : size;
                    for (i = 0; i < size; i++) {
                        format += '0';
                    }
                }
            }
            if (Math.floor(Math.log(Math.abs(value)) / Math.LN10) + 1 !== intPrecision) {
                if (abs >= Math.pow(10, 12) && !abbrForce || abbrT) {
                    // trillion
                    abbr = abbr + cultures[currentCulture].abbreviations.trillion;
                    value = value / Math.pow(10, 12);
                }
                else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9) && !abbrForce || abbrB) {
                    // billion
                    abbr = abbr + cultures[currentCulture].abbreviations.billion;
                    value = value / Math.pow(10, 9);
                }
                else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6) && !abbrForce || abbrM) {
                    // million
                    abbr = abbr + cultures[currentCulture].abbreviations.million;
                    value = value / Math.pow(10, 6);
                }
                else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3) && !abbrForce || abbrK) {
                    // thousand
                    abbr = abbr + cultures[currentCulture].abbreviations.thousand;
                    value = value / Math.pow(10, 3);
                }
            }
        }
        // see if we are formatting binary bytes
        if (format.indexOf('b') > -1) {
            // check for space before
            if (format.indexOf(' b') > -1) {
                bytes = ' ';
                format = format.replace(' b', '');
            }
            else {
                format = format.replace('b', '');
            }
            for (power = 0; power <= binarySuffixes.length; power++) {
                min = Math.pow(1024, power);
                max = Math.pow(1024, power + 1);
                if (value >= min && value < max) {
                    bytes = bytes + binarySuffixes[power];
                    if (min > 0) {
                        value = value / min;
                    }
                    break;
                }
            }
        }
        // see if we are formatting decimal bytes
        if (format.indexOf('d') > -1) {
            // check for space before
            if (format.indexOf(' d') > -1) {
                bytes = ' ';
                format = format.replace(' d', '');
            }
            else {
                format = format.replace('d', '');
            }
            for (power = 0; power <= decimalSuffixes.length; power++) {
                min = Math.pow(1000, power);
                max = Math.pow(1000, power + 1);
                if (value >= min && value < max) {
                    bytes = bytes + decimalSuffixes[power];
                    if (min > 0) {
                        value = value / min;
                    }
                    break;
                }
            }
        }
        // see if ordinal is wanted
        if (format.indexOf('o') > -1) {
            // check for space before
            if (format.indexOf(' o') > -1) {
                ord = ' ';
                format = format.replace(' o', '');
            }
            else {
                format = format.replace('o', '');
            }
            if (cultures[currentCulture].ordinal) {
                ord = ord + cultures[currentCulture].ordinal(value);
            }
        }
        if (format.indexOf('[.]') > -1) {
            optDec = true;
            format = format.replace('[.]', '.');
        }
        w = value.toString().split('.')[0];
        precision = format.split('.')[1];
        thousands = format.indexOf(',');
        if (precision) {
            if (precision.indexOf('*') !== -1) {
                d = toFixed(value, value.toString().split('.')[1].length, roundingFunction);
            }
            else {
                if (precision.indexOf('[') > -1) {
                    precision = precision.replace(']', '');
                    precision = precision.split('[');
                    d = toFixed(value, (precision[0].length + precision[1].length), roundingFunction, precision[1].length);
                }
                else {
                    d = toFixed(value, precision.length, roundingFunction);
                }
            }
            w = d.split('.')[0];
            if (d.split('.')[1].length) {
                var p = sep ? abbr + sep : cultures[currentCulture].delimiters.decimal;
                d = p + d.split('.')[1];
            }
            else {
                d = '';
            }
            if (optDec && Number(d.slice(1)) === 0) {
                d = '';
            }
        }
        else {
            w = toFixed(value, null, roundingFunction);
        }
        // format number
        if (w.indexOf('-') > -1) {
            w = w.slice(1);
            neg = true;
        }
        if (w.length < minlen) {
            w = new Array(minlen - w.length + 1).join('0') + w;
        }
        if (thousands > -1) {
            w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' +
                cultures[currentCulture].delimiters.thousands);
        }
        if (format.indexOf('.') === 0) {
            w = '';
        }
        indexOpenP = format.indexOf('(');
        indexMinus = format.indexOf('-');
        if (indexOpenP < indexMinus) {
            paren = ((negP && neg) ? '(' : '') + (((forcedNeg && neg) || (!negP && neg)) ? '-' : '');
        }
        else {
            paren = (((forcedNeg && neg) || (!negP && neg)) ? '-' : '') + ((negP && neg) ? '(' : '');
        }
        return prefix +
            paren + ((!neg && signed && value !== 0) ? '+' : '') +
            w + d +
            ((ord) ? ord : '') +
            ((abbr && !sep) ? abbr : '') +
            ((bytes) ? bytes : '') +
            ((negP && neg) ? ')' : '') +
            postfix;
    }
    /************************************
        Top Level Functions
    ************************************/
    numbro = function (input) {
        if (numbro.isNumbro(input)) {
            input = input.value();
        }
        else if (input === 0 || typeof input === 'undefined') {
            input = 0;
        }
        else if (!Number(input)) {
            input = numbro.fn.unformat(input);
        }
        return new Numbro(Number(input));
    };
    // version number
    numbro.version = VERSION;
    // compare numbro object
    numbro.isNumbro = function (obj) {
        return obj instanceof Numbro;
    };
    /**
     * This function allow the user to set a new language with a fallback if
     * the language does not exist. If no fallback language is provided,
     * it fallbacks to english.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `setCulture` should be used instead.
     */
    numbro.setLanguage = function (newLanguage, fallbackLanguage) {
        console.warn('`setLanguage` is deprecated since version 1.6.0. Use `setCulture` instead');
        var key = newLanguage, prefix = newLanguage.split('-')[0], matchingLanguage = null;
        if (!languages[key]) {
            Object.keys(languages).forEach(function (language) {
                if (!matchingLanguage && language.split('-')[0] === prefix) {
                    matchingLanguage = language;
                }
            });
            key = matchingLanguage || fallbackLanguage || 'en-US';
        }
        chooseCulture(key);
    };
    /**
     * This function allow the user to set a new culture with a fallback if
     * the culture does not exist. If no fallback culture is provided,
     * it fallbacks to "en-US".
     */
    numbro.setCulture = function (newCulture, fallbackCulture) {
        var key = newCulture, suffix = newCulture.split('-')[1], matchingCulture = null;
        if (!cultures[key]) {
            if (suffix) {
                Object.keys(cultures).forEach(function (language) {
                    if (!matchingCulture && language.split('-')[1] === suffix) {
                        matchingCulture = language;
                    }
                });
            }
            key = matchingCulture || fallbackCulture || 'en-US';
        }
        chooseCulture(key);
    };
    /**
     * This function will load languages and then set the global language.  If
     * no arguments are passed in, it will simply return the current global
     * language key.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `culture` should be used instead.
     */
    numbro.language = function (key, values) {
        console.warn('`language` is deprecated since version 1.6.0. Use `culture` instead');
        if (!key) {
            return currentCulture;
        }
        if (key && !values) {
            if (!languages[key]) {
                throw new Error('Unknown language : ' + key);
            }
            chooseCulture(key);
        }
        if (values || !languages[key]) {
            setCulture(key, values);
        }
        return numbro;
    };
    /**
     * This function will load cultures and then set the global culture.  If
     * no arguments are passed in, it will simply return the current global
     * culture code.
     */
    numbro.culture = function (code, values) {
        if (!code) {
            return currentCulture;
        }
        if (code && !values) {
            if (!cultures[code]) {
                throw new Error('Unknown culture : ' + code);
            }
            chooseCulture(code);
        }
        if (values || !cultures[code]) {
            setCulture(code, values);
        }
        return numbro;
    };
    /**
     * This function provides access to the loaded language data.  If
     * no arguments are passed in, it will simply return the current
     * global language object.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `culture` should be used instead.
     */
    numbro.languageData = function (key) {
        console.warn('`languageData` is deprecated since version 1.6.0. Use `cultureData` instead');
        if (!key) {
            return languages[currentCulture];
        }
        if (!languages[key]) {
            throw new Error('Unknown language : ' + key);
        }
        return languages[key];
    };
    /**
     * This function provides access to the loaded culture data.  If
     * no arguments are passed in, it will simply return the current
     * global culture object.
     */
    numbro.cultureData = function (code) {
        if (!code) {
            return cultures[currentCulture];
        }
        if (!cultures[code]) {
            throw new Error('Unknown culture : ' + code);
        }
        return cultures[code];
    };
    numbro.culture('en-US', enUS);
    /**
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `cultures` should be used instead.
     */
    numbro.languages = function () {
        console.warn('`languages` is deprecated since version 1.6.0. Use `cultures` instead');
        return languages;
    };
    numbro.cultures = function () {
        return cultures;
    };
    numbro.zeroFormat = function (format) {
        zeroFormat = typeof (format) === 'string' ? format : null;
    };
    numbro.defaultFormat = function (format) {
        defaultFormat = typeof (format) === 'string' ? format : '0.0';
    };
    numbro.defaultCurrencyFormat = function (format) {
        defaultCurrencyFormat = typeof (format) === 'string' ? format : '0$';
    };
    numbro.validate = function (val, culture) {
        var _decimalSep, _thousandSep, _currSymbol, _valArray, _abbrObj, _thousandRegEx, cultureData, temp;
        //coerce val to string
        if (typeof val !== 'string') {
            val += '';
            if (console.warn) {
                console.warn('Numbro.js: Value is not string. It has been co-erced to: ', val);
            }
        }
        //trim whitespaces from either sides
        val = val.trim();
        //if val is just digits return true
        if (!!val.match(/^\d+$/)) {
            return true;
        }
        //if val is empty return false
        if (val === '') {
            return false;
        }
        //get the decimal and thousands separator from numbro.cultureData
        try {
            //check if the culture is understood by numbro. if not, default it to current culture
            cultureData = numbro.cultureData(culture);
        }
        catch (e) {
            cultureData = numbro.cultureData(numbro.culture());
        }
        //setup the delimiters and currency symbol based on culture
        _currSymbol = cultureData.currency.symbol;
        _abbrObj = cultureData.abbreviations;
        _decimalSep = cultureData.delimiters.decimal;
        if (cultureData.delimiters.thousands === '.') {
            _thousandSep = '\\.';
        }
        else {
            _thousandSep = cultureData.delimiters.thousands;
        }
        // validating currency symbol
        temp = val.match(/^[^\d]+/);
        if (temp !== null) {
            val = val.substr(1);
            if (temp[0] !== _currSymbol) {
                return false;
            }
        }
        //validating abbreviation symbol
        temp = val.match(/[^\d]+$/);
        if (temp !== null) {
            val = val.slice(0, -1);
            if (temp[0] !== _abbrObj.thousand && temp[0] !== _abbrObj.million &&
                temp[0] !== _abbrObj.billion && temp[0] !== _abbrObj.trillion) {
                return false;
            }
        }
        _thousandRegEx = new RegExp(_thousandSep + '{2}');
        if (!val.match(/[^\d.,]/g)) {
            _valArray = val.split(_decimalSep);
            if (_valArray.length > 2) {
                return false;
            }
            else {
                if (_valArray.length < 2) {
                    return (!!_valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx));
                }
                else {
                    if (_valArray[0].length === 1) {
                        return (!!_valArray[0].match(/^\d+$/) &&
                            !_valArray[0].match(_thousandRegEx) &&
                            !!_valArray[1].match(/^\d+$/));
                    }
                    else {
                        return (!!_valArray[0].match(/^\d+.*\d$/) &&
                            !_valArray[0].match(_thousandRegEx) &&
                            !!_valArray[1].match(/^\d+$/));
                    }
                }
            }
        }
        return false;
    };
    /************************************
        Helpers
    ************************************/
    function setCulture(code, values) {
        cultures[code] = values;
    }
    function chooseCulture(code) {
        currentCulture = code;
        var defaults = cultures[code].defaults;
        if (defaults && defaults.format) {
            numbro.defaultFormat(defaults.format);
        }
        if (defaults && defaults.currencyFormat) {
            numbro.defaultCurrencyFormat(defaults.currencyFormat);
        }
    }
    function format(input, formatString, language, roundingFunction) {
        if (language != null && language !== numbro.culture()) {
            numbro.setCulture(language);
        }
        return formatNumbro(Number(input), formatString != null ? formatString : defaultFormat, roundingFunction == null ? Math.round : roundingFunction);
    }
    module.exports = { "format": format };
},
/* sprintf-js/src/sprintf.js */ function _(require, module, exports, __esModule, __esExport) {
    /* global window, exports, define */
    !function () {
        'use strict';
        var re = {
            not_string: /[^s]/,
            not_bool: /[^t]/,
            not_type: /[^T]/,
            not_primitive: /[^v]/,
            number: /[diefg]/,
            numeric_arg: /[bcdiefguxX]/,
            json: /[j]/,
            not_json: /[^j]/,
            text: /^[^\x25]+/,
            modulo: /^\x25{2}/,
            placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
            key: /^([a-z_][a-z_\d]*)/i,
            key_access: /^\.([a-z_][a-z_\d]*)/i,
            index_access: /^\[(\d+)\]/,
            sign: /^[+-]/
        };
        function sprintf(key) {
            // `arguments` is not an array, but should be fine for this call
            return sprintf_format(sprintf_parse(key), arguments);
        }
        function vsprintf(fmt, argv) {
            return sprintf.apply(null, [fmt].concat(argv || []));
        }
        function sprintf_format(parse_tree, argv) {
            var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign;
            for (i = 0; i < tree_length; i++) {
                if (typeof parse_tree[i] === 'string') {
                    output += parse_tree[i];
                }
                else if (typeof parse_tree[i] === 'object') {
                    ph = parse_tree[i]; // convenience purposes only
                    if (ph.keys) { // keyword argument
                        arg = argv[cursor];
                        for (k = 0; k < ph.keys.length; k++) {
                            if (arg == undefined) {
                                throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1]));
                            }
                            arg = arg[ph.keys[k]];
                        }
                    }
                    else if (ph.param_no) { // positional argument (explicit)
                        arg = argv[ph.param_no];
                    }
                    else { // positional argument (implicit)
                        arg = argv[cursor++];
                    }
                    if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
                        arg = arg();
                    }
                    if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
                        throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg));
                    }
                    if (re.number.test(ph.type)) {
                        is_positive = arg >= 0;
                    }
                    switch (ph.type) {
                        case 'b':
                            arg = parseInt(arg, 10).toString(2);
                            break;
                        case 'c':
                            arg = String.fromCharCode(parseInt(arg, 10));
                            break;
                        case 'd':
                        case 'i':
                            arg = parseInt(arg, 10);
                            break;
                        case 'j':
                            arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
                            break;
                        case 'e':
                            arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential();
                            break;
                        case 'f':
                            arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg);
                            break;
                        case 'g':
                            arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg);
                            break;
                        case 'o':
                            arg = (parseInt(arg, 10) >>> 0).toString(8);
                            break;
                        case 's':
                            arg = String(arg);
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 't':
                            arg = String(!!arg);
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 'T':
                            arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 'u':
                            arg = parseInt(arg, 10) >>> 0;
                            break;
                        case 'v':
                            arg = arg.valueOf();
                            arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
                            break;
                        case 'x':
                            arg = (parseInt(arg, 10) >>> 0).toString(16);
                            break;
                        case 'X':
                            arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
                            break;
                    }
                    if (re.json.test(ph.type)) {
                        output += arg;
                    }
                    else {
                        if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
                            sign = is_positive ? '+' : '-';
                            arg = arg.toString().replace(re.sign, '');
                        }
                        else {
                            sign = '';
                        }
                        pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ';
                        pad_length = ph.width - (sign + arg).length;
                        pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '';
                        output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg);
                    }
                }
            }
            return output;
        }
        var sprintf_cache = Object.create(null);
        function sprintf_parse(fmt) {
            if (sprintf_cache[fmt]) {
                return sprintf_cache[fmt];
            }
            var _fmt = fmt, match, parse_tree = [], arg_names = 0;
            while (_fmt) {
                if ((match = re.text.exec(_fmt)) !== null) {
                    parse_tree.push(match[0]);
                }
                else if ((match = re.modulo.exec(_fmt)) !== null) {
                    parse_tree.push('%');
                }
                else if ((match = re.placeholder.exec(_fmt)) !== null) {
                    if (match[2]) {
                        arg_names |= 1;
                        var field_list = [], replacement_field = match[2], field_match = [];
                        if ((field_match = re.key.exec(replacement_field)) !== null) {
                            field_list.push(field_match[1]);
                            while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
                                if ((field_match = re.key_access.exec(replacement_field)) !== null) {
                                    field_list.push(field_match[1]);
                                }
                                else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
                                    field_list.push(field_match[1]);
                                }
                                else {
                                    throw new SyntaxError('[sprintf] failed to parse named argument key');
                                }
                            }
                        }
                        else {
                            throw new SyntaxError('[sprintf] failed to parse named argument key');
                        }
                        match[2] = field_list;
                    }
                    else {
                        arg_names |= 2;
                    }
                    if (arg_names === 3) {
                        throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported');
                    }
                    parse_tree.push({
                        placeholder: match[0],
                        param_no: match[1],
                        keys: match[2],
                        sign: match[3],
                        pad_char: match[4],
                        align: match[5],
                        width: match[6],
                        precision: match[7],
                        type: match[8]
                    });
                }
                else {
                    throw new SyntaxError('[sprintf] unexpected placeholder');
                }
                _fmt = _fmt.substring(match[0].length);
            }
            return sprintf_cache[fmt] = parse_tree;
        }
        /**
         * export to either browser or node.js
         */
        /* eslint-disable quote-props */
        if (typeof exports !== 'undefined') {
            exports['sprintf'] = sprintf;
            exports['vsprintf'] = vsprintf;
        }
        if (typeof window !== 'undefined') {
            window['sprintf'] = sprintf;
            window['vsprintf'] = vsprintf;
            if (typeof define === 'function' && define['amd']) {
                define(function () {
                    return {
                        'sprintf': sprintf,
                        'vsprintf': vsprintf
                    };
                });
            }
        }
        /* eslint-enable quote-props */
    }(); // eslint-disable-line
},
/* timezone/index.js */ function _(require, module, exports, __esModule, __esExport) {
    !function (definition) {
        if (typeof module == "object" && module.exports)
            module.exports = definition();
        else if (typeof define == "function")
            define(definition);
        else
            this.tz = definition();
    }(function () {
        /*
          function die () {
            console.log.apply(console, __slice.call(arguments, 0));
            return process.exit(1);
          }
        
          function say () { return console.log.apply(console, __slice.call(arguments, 0)) }
        */
        function actualize(entry, rule, year) {
            var actualized, date = rule.day[1];
            do {
                actualized = new Date(Date.UTC(year, rule.month, Math.abs(date++)));
            } while (rule.day[0] < 7 && actualized.getUTCDay() != rule.day[0]);
            actualized = {
                clock: rule.clock,
                sort: actualized.getTime(),
                rule: rule,
                save: rule.save * 6e4,
                offset: entry.offset
            };
            actualized[actualized.clock] = actualized.sort + rule.time * 6e4;
            if (actualized.posix) {
                actualized.wallclock = actualized[actualized.clock] + (entry.offset + rule.saved);
            }
            else {
                actualized.posix = actualized[actualized.clock] - (entry.offset + rule.saved);
            }
            return actualized;
        }
        function find(request, clock, time) {
            var i, I, entry, found, zone = request[request.zone], actualized = [], abbrev, rules, j, year = new Date(time).getUTCFullYear(), off = 1;
            for (i = 1, I = zone.length; i < I; i++)
                if (zone[i][clock] <= time)
                    break;
            entry = zone[i];
            if (entry.rules) {
                rules = request[entry.rules];
                for (j = year + 1; j >= year - off; --j)
                    for (i = 0, I = rules.length; i < I; i++)
                        if (rules[i].from <= j && j <= rules[i].to)
                            actualized.push(actualize(entry, rules[i], j));
                        else if (rules[i].to < j && off == 1)
                            off = j - rules[i].to;
                actualized.sort(function (a, b) { return a.sort - b.sort; });
                for (i = 0, I = actualized.length; i < I; i++) {
                    if (time >= actualized[i][clock] && actualized[i][actualized[i].clock] > entry[actualized[i].clock])
                        found = actualized[i];
                }
            }
            if (found) {
                if (abbrev = /^(.*)\/(.*)$/.exec(entry.format)) {
                    found.abbrev = abbrev[found.save ? 2 : 1];
                }
                else {
                    found.abbrev = entry.format.replace(/%s/, found.rule.letter);
                }
            }
            return found || entry;
        }
        function convertToWallclock(request, posix) {
            if (request.zone == "UTC")
                return posix;
            request.entry = find(request, "posix", posix);
            return posix + request.entry.offset + request.entry.save;
        }
        function convertToPOSIX(request, wallclock) {
            if (request.zone == "UTC")
                return wallclock;
            var entry, diff;
            request.entry = entry = find(request, "wallclock", wallclock);
            diff = wallclock - entry.wallclock;
            return 0 < diff && diff < entry.save ? null : wallclock - entry.offset - entry.save;
        }
        function adjust(request, posix, match) {
            var increment = +(match[1] + 1) // conversion necessary for week day addition
            , offset = match[2] * increment, index = UNITS.indexOf(match[3].toLowerCase()), date;
            if (index > 9) {
                posix += offset * TIME[index - 10];
            }
            else {
                date = new Date(convertToWallclock(request, posix));
                if (index < 7) {
                    while (offset) {
                        date.setUTCDate(date.getUTCDate() + increment);
                        if (date.getUTCDay() == index)
                            offset -= increment;
                    }
                }
                else if (index == 7) {
                    date.setUTCFullYear(date.getUTCFullYear() + offset);
                }
                else if (index == 8) {
                    date.setUTCMonth(date.getUTCMonth() + offset);
                }
                else {
                    date.setUTCDate(date.getUTCDate() + offset);
                }
                if ((posix = convertToPOSIX(request, date.getTime())) == null) {
                    posix = convertToPOSIX(request, date.getTime() + 864e5 * increment) - 864e5 * increment;
                }
            }
            return posix;
        }
        function convert(vargs) {
            if (!vargs.length)
                return "1.0.23";
            var request = Object.create(this), adjustments = [], i, I, $, argument, date;
            for (i = 0; i < vargs.length; i++) { // leave the for loop alone, it works.
                argument = vargs[i];
                // https://twitter.com/bigeasy/status/215112186572439552
                if (Array.isArray(argument)) {
                    if (!i && !isNaN(argument[1])) {
                        date = argument;
                    }
                    else {
                        argument.splice.apply(vargs, [i--, 1].concat(argument));
                    }
                }
                else if (isNaN(argument)) {
                    $ = typeof argument;
                    if ($ == "string") {
                        if (~argument.indexOf("%")) {
                            request.format = argument;
                        }
                        else if (!i && argument == "*") {
                            date = argument;
                        }
                        else if (!i && ($ = /^(\d{4})-(\d{2})-(\d{2})(?:[T\s](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|(([+-])(\d{2}(:\d{2}){0,2})))?)?$/.exec(argument))) {
                            date = [];
                            date.push.apply(date, $.slice(1, 8));
                            if ($[9]) {
                                date.push($[10] + 1);
                                date.push.apply(date, $[11].split(/:/));
                            }
                            else if ($[8]) {
                                date.push(1);
                            }
                        }
                        else if (/^\w{2,3}_\w{2}$/.test(argument)) {
                            request.locale = argument;
                        }
                        else if ($ = UNIT_RE.exec(argument)) {
                            adjustments.push($);
                        }
                        else {
                            request.zone = argument;
                        }
                    }
                    else if ($ == "function") {
                        if ($ = argument.call(request))
                            return $;
                    }
                    else if (/^\w{2,3}_\w{2}$/.test(argument.name)) {
                        request[argument.name] = argument;
                    }
                    else if (argument.zones) {
                        for ($ in argument.zones)
                            request[$] = argument.zones[$];
                        for ($ in argument.rules)
                            request[$] = argument.rules[$];
                    }
                }
                else if (!i) {
                    date = argument;
                }
            }
            if (!request[request.locale])
                delete request.locale;
            if (!request[request.zone])
                delete request.zone;
            if (date != null) {
                if (date == "*") {
                    date = request.clock();
                }
                else if (Array.isArray(date)) {
                    $ = [];
                    I = !date[7];
                    for (i = 0; i < 11; i++)
                        $[i] = +(date[i] || 0); // conversion necessary for decrement
                    --$[1]; // Grr..
                    date = Date.UTC.apply(Date.UTC, $) + -$[7] * ($[8] * 36e5 + $[9] * 6e4 + $[10] * 1e3);
                }
                else {
                    date = Math.floor(date);
                }
                if (!isNaN(date)) {
                    if (I)
                        date = convertToPOSIX(request, date);
                    if (date == null)
                        return date;
                    for (i = 0, I = adjustments.length; i < I; i++) {
                        date = adjust(request, date, adjustments[i]);
                    }
                    if (!request.format)
                        return date;
                    $ = new Date(convertToWallclock(request, date));
                    return request.format.replace(/%([-0_^]?)(:{0,3})(\d*)(.)/g, function (value, flag, colons, padding, specifier) {
                        var f, fill = "0", pad;
                        if (f = request[specifier]) {
                            value = String(f.call(request, $, date, flag, colons.length));
                            if ((flag || f.style) == "_")
                                fill = " ";
                            pad = flag == "-" ? 0 : f.pad || 0;
                            while (value.length < pad)
                                value = fill + value;
                            pad = flag == "-" ? 0 : padding || f.pad;
                            while (value.length < pad)
                                value = fill + value;
                            if (specifier == "N" && pad < value.length)
                                value = value.slice(0, pad);
                            if (flag == "^")
                                value = value.toUpperCase();
                        }
                        return value;
                    });
                }
            }
            return function () { return request.convert(arguments); };
        }
        var context = { clock: function () { return +(new Date()); },
            zone: "UTC",
            entry: { abbrev: "UTC", offset: 0, save: 0 },
            UTC: 1,
            z: function (date, posix, flag, delimiters) {
                var offset = this.entry.offset + this.entry.save, seconds = Math.abs(offset / 1000), parts = [], part = 3600, i, z;
                for (i = 0; i < 3; i++) {
                    parts.push(("0" + Math.floor(seconds / part)).slice(-2));
                    seconds %= part;
                    part /= 60;
                }
                if (flag == "^" && !offset)
                    return "Z";
                if (flag == "^")
                    delimiters = 3;
                if (delimiters == 3) {
                    z = parts.join(":");
                    z = z.replace(/:00$/, "");
                    if (flag != "^")
                        z = z.replace(/:00$/, "");
                }
                else if (delimiters) {
                    z = parts.slice(0, delimiters + 1).join(":");
                    if (flag == "^")
                        z = z.replace(/:00$/, "");
                }
                else {
                    z = parts.slice(0, 2).join("");
                }
                z = (offset < 0 ? "-" : "+") + z;
                z = z.replace(/([-+])(0)/, { "_": " $1", "-": "$1" }[flag] || "$1$2");
                return z;
            },
            "%": function (date) { return "%"; },
            n: function (date) { return "\n"; },
            t: function (date) { return "\t"; },
            U: function (date) { return weekOfYear(date, 0); },
            W: function (date) { return weekOfYear(date, 1); },
            V: function (date) { return isoWeek(date)[0]; },
            G: function (date) { return isoWeek(date)[1]; },
            g: function (date) { return isoWeek(date)[1] % 100; },
            j: function (date) { return Math.floor((date.getTime() - Date.UTC(date.getUTCFullYear(), 0)) / 864e5) + 1; },
            s: function (date) { return Math.floor(date.getTime() / 1000); },
            C: function (date) { return Math.floor(date.getUTCFullYear() / 100); },
            N: function (date) { return date.getTime() % 1000 * 1000000; },
            m: function (date) { return date.getUTCMonth() + 1; },
            Y: function (date) { return date.getUTCFullYear(); },
            y: function (date) { return date.getUTCFullYear() % 100; },
            H: function (date) { return date.getUTCHours(); },
            M: function (date) { return date.getUTCMinutes(); },
            S: function (date) { return date.getUTCSeconds(); },
            e: function (date) { return date.getUTCDate(); },
            d: function (date) { return date.getUTCDate(); },
            u: function (date) { return date.getUTCDay() || 7; },
            w: function (date) { return date.getUTCDay(); },
            l: function (date) { return date.getUTCHours() % 12 || 12; },
            I: function (date) { return date.getUTCHours() % 12 || 12; },
            k: function (date) { return date.getUTCHours(); },
            Z: function (date) { return this.entry.abbrev; },
            a: function (date) { return this[this.locale].day.abbrev[date.getUTCDay()]; },
            A: function (date) { return this[this.locale].day.full[date.getUTCDay()]; },
            h: function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()]; },
            b: function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()]; },
            B: function (date) { return this[this.locale].month.full[date.getUTCMonth()]; },
            P: function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)].toLowerCase(); },
            p: function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)]; },
            R: function (date, posix) { return this.convert([posix, "%H:%M"]); },
            T: function (date, posix) { return this.convert([posix, "%H:%M:%S"]); },
            D: function (date, posix) { return this.convert([posix, "%m/%d/%y"]); },
            F: function (date, posix) { return this.convert([posix, "%Y-%m-%d"]); },
            x: function (date, posix) { return this.convert([posix, this[this.locale].date]); },
            r: function (date, posix) { return this.convert([posix, this[this.locale].time12 || '%I:%M:%S']); },
            X: function (date, posix) { return this.convert([posix, this[this.locale].time24]); },
            c: function (date, posix) { return this.convert([posix, this[this.locale].dateTime]); },
            convert: convert,
            locale: "en_US",
            en_US: {
                date: "%m/%d/%Y",
                time24: "%I:%M:%S %p",
                time12: "%I:%M:%S %p",
                dateTime: "%a %d %b %Y %I:%M:%S %p %Z",
                meridiem: ["AM", "PM"],
                month: {
                    abbrev: "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec".split("|"),
                    full: "January|February|March|April|May|June|July|August|September|October|November|December".split("|")
                },
                day: {
                    abbrev: "Sun|Mon|Tue|Wed|Thu|Fri|Sat".split("|"),
                    full: "Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday".split("|")
                }
            }
        };
        var UNITS = "Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|year|month|day|hour|minute|second|millisecond", UNIT_RE = new RegExp("^\\s*([+-])(\\d+)\\s+(" + UNITS + ")s?\\s*$", "i"), TIME = [36e5, 6e4, 1e3, 1];
        UNITS = UNITS.toLowerCase().split("|");
        "delmHMSUWVgCIky".replace(/./g, function (e) { context[e].pad = 2; });
        context.N.pad = 9;
        context.j.pad = 3;
        context.k.style = "_";
        context.l.style = "_";
        context.e.style = "_";
        function weekOfYear(date, startOfWeek) {
            var diff, nyd, weekStart;
            nyd = new Date(Date.UTC(date.getUTCFullYear(), 0));
            diff = Math.floor((date.getTime() - nyd.getTime()) / 864e5);
            if (nyd.getUTCDay() == startOfWeek) {
                weekStart = 0;
            }
            else {
                weekStart = 7 - nyd.getUTCDay() + startOfWeek;
                if (weekStart == 8) {
                    weekStart = 1;
                }
            }
            return diff >= weekStart ? Math.floor((diff - weekStart) / 7) + 1 : 0;
        }
        function isoWeek(date) {
            var nyd, nyy, week;
            nyy = date.getUTCFullYear();
            nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
            week = weekOfYear(date, 1) + (nyd > 1 && nyd <= 4 ? 1 : 0);
            if (!week) {
                nyy = date.getUTCFullYear() - 1;
                nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
                week = nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29) ? 53 : 52;
                return [week, date.getUTCFullYear() - 1];
            }
            else if (week == 53 && !(nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29))) {
                return [1, date.getUTCFullYear() + 1];
            }
            else {
                return [week, date.getUTCFullYear()];
            }
        }
        return function () { return context.convert(arguments); };
    });
},
/* models/formatters/customjs_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tick_formatter_1 = require(192) /* ./tick_formatter */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(40) /* ../../core/util/string */;
    class CustomJSTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        /*protected*/ _make_func() {
            const code = (0, string_1.use_strict)(this.code);
            return new Function("tick", "index", "ticks", ...this.names, code);
        }
        doFormat(ticks, _opts) {
            const cache = {};
            const func = this._make_func().bind(cache);
            return ticks.map((tick, index, ticks) => `${func(tick, index, ticks, ...this.values)}`);
        }
    }
    exports.CustomJSTickFormatter = CustomJSTickFormatter;
    _a = CustomJSTickFormatter;
    CustomJSTickFormatter.__name__ = "CustomJSTickFormatter";
    (() => {
        _a.define(({ Unknown, Str, Dict }) => ({
            args: [Dict(Unknown), {}],
            code: [Str, ""],
        }));
    })();
},
/* models/formatters/log_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tick_formatter_1 = require(192) /* ./tick_formatter */;
    const basic_tick_formatter_1 = require(196) /* ./basic_tick_formatter */;
    const log_ticker_1 = require(211) /* ../tickers/log_ticker */;
    const graphics_1 = require(180) /* ../../core/graphics */;
    const { abs, log, round } = Math;
    class LogTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this.basic_formatter = new basic_tick_formatter_1.BasicTickFormatter();
        }
        format_graphics(ticks, opts) {
            if (ticks.length == 0) {
                return [];
            }
            const base = this.ticker?.base ?? 10;
            const expos = this._exponents(ticks, base);
            if (expos == null) {
                return this.basic_formatter.format_graphics(ticks, opts);
            }
            else {
                return expos.map((expo) => {
                    if (abs(expo) < this.min_exponent) {
                        const b = new graphics_1.TextBox({ text: (0, basic_tick_formatter_1.unicode_replace)(`${base ** expo}`) });
                        const e = new graphics_1.TextBox({ text: "" });
                        return new graphics_1.BaseExpo(b, e);
                    }
                    else {
                        const b = new graphics_1.TextBox({ text: (0, basic_tick_formatter_1.unicode_replace)(`${base}`) });
                        const e = new graphics_1.TextBox({ text: (0, basic_tick_formatter_1.unicode_replace)(`${expo}`) });
                        return new graphics_1.BaseExpo(b, e);
                    }
                });
            }
        }
        _exponents(ticks, base) {
            let last_exponent = null;
            const exponents = [];
            for (const tick of ticks) {
                const exponent = round(log(tick) / log(base));
                if (last_exponent != exponent) {
                    last_exponent = exponent;
                    exponents.push(exponent);
                }
                else {
                    return null;
                }
            }
            return exponents;
        }
        doFormat(ticks, opts) {
            if (ticks.length == 0) {
                return [];
            }
            const base = this.ticker?.base ?? 10;
            const expos = this._exponents(ticks, base);
            if (expos == null) {
                return this.basic_formatter.doFormat(ticks, opts);
            }
            else {
                return expos.map((expo) => {
                    if (abs(expo) < this.min_exponent) {
                        return (0, basic_tick_formatter_1.unicode_replace)(`${base ** expo}`);
                    }
                    else {
                        return (0, basic_tick_formatter_1.unicode_replace)(`${base}^${expo}`);
                    }
                });
            }
        }
    }
    exports.LogTickFormatter = LogTickFormatter;
    _a = LogTickFormatter;
    LogTickFormatter.__name__ = "LogTickFormatter";
    (() => {
        _a.define(({ Int, Ref, Nullable }) => ({
            ticker: [Nullable(Ref(log_ticker_1.LogTicker)), null],
            min_exponent: [Int, 0],
        }));
    })();
},
/* models/formatters/mercator_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const basic_tick_formatter_1 = require(196) /* ./basic_tick_formatter */;
    const enums_1 = require(20) /* ../../core/enums */;
    const projections_1 = require(134) /* ../../core/util/projections */;
    class MercatorTickFormatter extends basic_tick_formatter_1.BasicTickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        doFormat(ticks, opts) {
            if (this.dimension == null) {
                throw new Error("MercatorTickFormatter.dimension not configured");
            }
            if (ticks.length == 0) {
                return [];
            }
            const n = ticks.length;
            const proj_ticks = new Array(n);
            if (this.dimension == "lon") {
                for (let i = 0; i < n; i++) {
                    const [lon] = projections_1.wgs84_mercator.invert(ticks[i], opts.loc);
                    proj_ticks[i] = lon;
                }
            }
            else {
                for (let i = 0; i < n; i++) {
                    const [, lat] = projections_1.wgs84_mercator.invert(opts.loc, ticks[i]);
                    proj_ticks[i] = lat;
                }
            }
            return super.doFormat(proj_ticks, opts);
        }
    }
    exports.MercatorTickFormatter = MercatorTickFormatter;
    _a = MercatorTickFormatter;
    MercatorTickFormatter.__name__ = "MercatorTickFormatter";
    (() => {
        _a.define(({ Nullable }) => ({
            dimension: [Nullable(enums_1.LatLon), null],
        }));
    })();
},
/* models/formatters/numeral_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const Numbro = tslib_1.__importStar(require(246) /* @bokeh/numbro */);
    const tick_formatter_1 = require(192) /* ./tick_formatter */;
    const enums_1 = require(20) /* ../../core/enums */;
    class NumeralTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        get _rounding_fn() {
            switch (this.rounding) {
                case "round":
                case "nearest":
                    return Math.round;
                case "floor":
                case "rounddown":
                    return Math.floor;
                case "ceil":
                case "roundup":
                    return Math.ceil;
            }
        }
        doFormat(ticks, _opts) {
            const { format, language, _rounding_fn } = this;
            return ticks.map((tick) => Numbro.format(tick, format, language, _rounding_fn));
        }
    }
    exports.NumeralTickFormatter = NumeralTickFormatter;
    _a = NumeralTickFormatter;
    NumeralTickFormatter.__name__ = "NumeralTickFormatter";
    (() => {
        _a.define(({ Str }) => ({
            // TODO (bev) all of these could be tightened up
            format: [Str, "0,0"],
            language: [Str, "en"],
            rounding: [enums_1.RoundingFunction, "round"],
        }));
    })();
},
/* models/formatters/printf_tick_formatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tick_formatter_1 = require(192) /* ./tick_formatter */;
    const templating_1 = require(245) /* ../../core/util/templating */;
    class PrintfTickFormatter extends tick_formatter_1.TickFormatter {
        constructor(attrs) {
            super(attrs);
        }
        doFormat(ticks, _opts) {
            return ticks.map((tick) => (0, templating_1.sprintf)(this.format, tick));
        }
    }
    exports.PrintfTickFormatter = PrintfTickFormatter;
    _a = PrintfTickFormatter;
    PrintfTickFormatter.__name__ = "PrintfTickFormatter";
    (() => {
        _a.define(({ Str }) => ({
            format: [Str, "%s"],
        }));
    })();
},
/* models/scales/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var categorical_scale_1 = require(104) /* ./categorical_scale */;
    __esExport("CategoricalScale", categorical_scale_1.CategoricalScale);
    var composite_scale_1 = require(105) /* ./composite_scale */;
    __esExport("CompositeScale", composite_scale_1.CompositeScale);
    var continuous_scale_1 = require(102) /* ./continuous_scale */;
    __esExport("ContinuousScale", continuous_scale_1.ContinuousScale);
    var linear_interpolation_scale_1 = require(255) /* ./linear_interpolation_scale */;
    __esExport("LinearInterpolationScale", linear_interpolation_scale_1.LinearInterpolationScale);
    var linear_scale_1 = require(101) /* ./linear_scale */;
    __esExport("LinearScale", linear_scale_1.LinearScale);
    var log_scale_1 = require(103) /* ./log_scale */;
    __esExport("LogScale", log_scale_1.LogScale);
    var scale_1 = require(96) /* ./scale */;
    __esExport("Scale", scale_1.Scale);
},
/* models/scales/linear_interpolation_scale.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const scale_1 = require(96) /* ./scale */;
    const linear_scale_1 = require(101) /* ./linear_scale */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    class LinearInterpolationScale extends scale_1.Scale {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            const { source_range, target_range } = this.properties;
            if (!source_range.is_unset && !target_range.is_unset) {
                this.linear_scale = new linear_scale_1.LinearScale({
                    source_range: source_range.get_value(),
                    target_range: target_range.get_value(),
                });
            }
        }
        connect_signals() {
            super.connect_signals();
            const { source_range, target_range } = this.properties;
            this.on_change([source_range, target_range], () => {
                this.linear_scale = new linear_scale_1.LinearScale({
                    source_range: this.source_range,
                    target_range: this.target_range,
                });
            });
        }
        get s_compute() {
            throw new Error("not implemented");
        }
        get s_invert() {
            throw new Error("not implemented");
        }
        compute(x) {
            return x;
        }
        v_compute(vs) {
            const { binning } = this;
            const { start, end } = this.source_range;
            const min_val = start;
            const max_val = end;
            const n = binning.length;
            const step = (end - start) / (n - 1);
            const mapping = new Float64Array(n);
            for (let i = 0; i < n; i++) {
                mapping[i] = start + i * step;
            }
            const vvs = (0, arrayable_1.map)(vs, (v) => {
                if (v < min_val) {
                    return min_val;
                }
                if (v > max_val) {
                    return max_val;
                }
                const k = (0, arrayable_1.left_edge_index)(v, binning);
                if (k == -1) {
                    return min_val;
                }
                if (k >= n - 1) {
                    return max_val;
                }
                const b0 = binning[k];
                const b1 = binning[k + 1];
                const c = (v - b0) / (b1 - b0);
                const m0 = mapping[k];
                const m1 = mapping[k + 1];
                return m0 + c * (m1 - m0);
            });
            return this.linear_scale.v_compute(vvs);
        }
        invert(xprime) {
            return xprime;
        }
        v_invert(xprimes) {
            return new Float64Array(xprimes);
        }
    }
    exports.LinearInterpolationScale = LinearInterpolationScale;
    _a = LinearInterpolationScale;
    LinearInterpolationScale.__name__ = "LinearInterpolationScale";
    (() => {
        _a.internal(({ Float, Arrayable, Ref }) => ({
            binning: [Arrayable(Float)],
            linear_scale: [Ref(linear_scale_1.LinearScale)],
        }));
    })();
},
/* models/ranges/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var data_range_1 = require(107) /* ./data_range */;
    __esExport("DataRange", data_range_1.DataRange);
    var data_range1d_1 = require(106) /* ./data_range1d */;
    __esExport("DataRange1d", data_range1d_1.DataRange1d);
    var factor_range_1 = require(109) /* ./factor_range */;
    __esExport("FactorRange", factor_range_1.FactorRange);
    var range_1 = require(98) /* ./range */;
    __esExport("Range", range_1.Range);
    var range1d_1 = require(99) /* ./range1d */;
    __esExport("Range1d", range1d_1.Range1d);
},
/* core/layout/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var types_1 = require(174) /* ./types */;
    __esExport("Sizeable", types_1.Sizeable);
    __esExport("SizingPolicy", types_1.SizingPolicy);
    var layoutable_1 = require(175) /* ./layoutable */;
    __esExport("Layoutable", layoutable_1.Layoutable);
    __esExport("ContentLayoutable", layoutable_1.ContentLayoutable);
    __esExport("TextLayout", layoutable_1.TextLayout);
    __esExport("FixedLayout", layoutable_1.FixedLayout);
    var alignments_1 = require(258) /* ./alignments */;
    __esExport("HStack", alignments_1.HStack);
    __esExport("VStack", alignments_1.VStack);
    var grid_1 = require(259) /* ./grid */;
    __esExport("Grid", grid_1.Grid);
    __esExport("Row", grid_1.Row);
    __esExport("Column", grid_1.Column);
},
/* core/layout/alignments.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layoutable_1 = require(175) /* ./layoutable */;
    const bbox_1 = require(64) /* ../util/bbox */;
    const { max, round } = Math;
    class Stack extends layoutable_1.Layoutable {
        constructor() {
            super(...arguments);
            this.children = [];
        }
        *[Symbol.iterator]() {
            yield* this.children;
        }
    }
    exports.Stack = Stack;
    Stack.__name__ = "Stack";
    class HStack extends Stack {
        _measure(_viewport) {
            let width = 0;
            let height = 0;
            for (const child of this.children) {
                const size_hint = child.measure({ width: 0, height: 0 });
                width += size_hint.width;
                height = max(height, size_hint.height);
            }
            return { width, height };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            if (outer.is_empty) {
                for (const child of this.children) {
                    child.set_geometry(new bbox_1.BBox());
                }
            }
            else {
                const top = this.absolute ? outer.top : 0;
                let left = this.absolute ? outer.left : 0;
                const { height } = outer;
                for (const child of this.children) {
                    const { width } = child.measure({ width: 0, height: 0 });
                    child.set_geometry(new bbox_1.BBox({ left, width, top, height }));
                    left += width;
                }
            }
        }
    }
    exports.HStack = HStack;
    HStack.__name__ = "HStack";
    class VStack extends Stack {
        _measure(_viewport) {
            let width = 0;
            let height = 0;
            for (const child of this.children) {
                const size_hint = child.measure({ width: 0, height: 0 });
                width = max(width, size_hint.width);
                height += size_hint.height;
            }
            return { width, height };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            if (outer.is_empty) {
                for (const child of this.children) {
                    child.set_geometry(new bbox_1.BBox());
                }
            }
            else {
                const left = this.absolute ? outer.left : 0;
                let top = this.absolute ? outer.top : 0;
                const { width } = outer;
                for (const child of this.children) {
                    const { height } = child.measure({ width: 0, height: 0 });
                    child.set_geometry(new bbox_1.BBox({ top, height, left, width }));
                    top += height;
                }
            }
        }
    }
    exports.VStack = VStack;
    VStack.__name__ = "VStack";
    class NodeLayout extends layoutable_1.Layoutable {
        constructor() {
            super(...arguments);
            this.children = [];
        }
        *[Symbol.iterator]() {
            yield* this.children;
        }
        _measure(viewport) {
            const { width_policy, height_policy } = this.sizing;
            const { min, max } = Math;
            let max_width = 0;
            let max_height = 0;
            for (const layout of this.children) {
                const { width, height } = layout.measure(viewport);
                max_width = max(max_width, width);
                max_height = max(max_height, height);
            }
            const width = (() => {
                const { width } = this.sizing;
                if (viewport.width == Infinity) {
                    return width_policy == "fixed" ? width ?? max_width : max_width;
                }
                else {
                    switch (width_policy) {
                        case "fixed": return 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 ?? max_height : max_height;
                }
                else {
                    switch (height_policy) {
                        case "fixed": return height ?? max_height;
                        case "min": return /*height != null ? min(viewport.height, height) :*/ max_height;
                        case "fit": return height != null ? min(viewport.height, height) : viewport.height;
                        case "max": return height != null ? max(viewport.height, height) : viewport.height;
                    }
                }
            })();
            return { width, height };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            if (outer.is_empty) {
                for (const child of this.children) {
                    child.set_geometry(new bbox_1.BBox());
                }
            }
            else {
                const bbox = this.absolute ? outer : outer.relative();
                const { left, right, top, bottom } = bbox;
                const vcenter = round(bbox.vcenter);
                const hcenter = round(bbox.hcenter);
                for (const layout of this.children) {
                    const { margin, halign = "start", valign = "start" } = layout.sizing;
                    const { width, height, inner } = layout.measure(outer);
                    const bbox = (() => {
                        const anchor = `${valign}_${halign}`;
                        switch (anchor) {
                            case "start_start": // "top_left"
                                return new bbox_1.BBox({ left: left + margin.left, top: top + margin.top, width, height });
                            case "start_center": // "top_center"
                                return new bbox_1.BBox({ hcenter, top: top + margin.top, width, height });
                            case "start_end": // "top_right"
                                return new bbox_1.BBox({ right: right - margin.right, top: top + margin.top, width, height });
                            case "center_start": // "center_left"
                                return new bbox_1.BBox({ left: left + margin.left, vcenter, width, height });
                            case "center_center": // "center"
                                return new bbox_1.BBox({ hcenter, vcenter, width, height });
                            case "center_end": // "center_right"
                                return new bbox_1.BBox({ right: right - margin.right, vcenter, width, height });
                            case "end_start": // "bottom_left"
                                return new bbox_1.BBox({ left: left + margin.left, bottom: bottom - margin.bottom, width, height });
                            case "end_center": // "bottom_center"
                                return new bbox_1.BBox({ hcenter, bottom: bottom - margin.bottom, width, height });
                            case "end_end": // "bottom_right"
                                return new bbox_1.BBox({ right: right - margin.right, bottom: bottom - margin.bottom, width, height });
                        }
                    })();
                    const inner_bbox = inner == null ? bbox : new bbox_1.BBox({
                        left: bbox.left + inner.left,
                        top: bbox.top + inner.top,
                        right: bbox.right - inner.right,
                        bottom: bbox.bottom - inner.bottom,
                    });
                    layout.set_geometry(bbox, inner_bbox);
                }
            }
        }
    }
    exports.NodeLayout = NodeLayout;
    NodeLayout.__name__ = "NodeLayout";
},
/* core/layout/grid.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(174) /* ./types */;
    const layoutable_1 = require(175) /* ./layoutable */;
    const types_2 = require(8) /* ../util/types */;
    const bbox_1 = require(64) /* ../util/bbox */;
    const array_1 = require(10) /* ../util/array */;
    const { max, round } = Math;
    class DefaultMap {
        constructor(def) {
            this._map = new Map();
            this.def = def;
        }
        get(key) {
            let value = this._map.get(key);
            if (value === undefined) {
                value = this.def();
                this._map.set(key, value);
            }
            return value;
        }
        apply(key, fn) {
            const value = this.get(key);
            this._map.set(key, fn(value));
        }
    }
    exports.DefaultMap = DefaultMap;
    DefaultMap.__name__ = "DefaultMap";
    class Container {
        constructor() {
            this._items = [];
            this._nrows = 0;
            this._ncols = 0;
        }
        get size() {
            return this._items.length;
        }
        get nrows() {
            return this._nrows;
        }
        get ncols() {
            return this._ncols;
        }
        add(span, data) {
            const { r1, c1 } = span;
            this._nrows = max(this._nrows, r1 + 1);
            this._ncols = max(this._ncols, c1 + 1);
            this._items.push({ span, data });
        }
        at(r, c) {
            const selected = this._items.filter(({ span }) => {
                return span.r0 <= r && r <= span.r1 &&
                    span.c0 <= c && c <= span.c1;
            });
            return selected.map(({ data }) => data);
        }
        row(r) {
            const selected = this._items.filter(({ span }) => span.r0 <= r && r <= span.r1);
            return selected.map(({ data }) => data);
        }
        col(c) {
            const selected = this._items.filter(({ span }) => span.c0 <= c && c <= span.c1);
            return selected.map(({ data }) => data);
        }
        *[Symbol.iterator]() {
            yield* this._items;
        }
        foreach(fn) {
            for (const { span, data } of this._items) {
                fn(span, data);
            }
        }
        map(fn) {
            const result = new Container();
            for (const { span, data } of this._items) {
                result.add(span, fn(span, data));
            }
            return result;
        }
    }
    exports.Container = Container;
    Container.__name__ = "Container";
    class Grid extends layoutable_1.Layoutable {
        *[Symbol.iterator]() {
            for (const { layout } of this.items) {
                yield layout;
            }
        }
        constructor(items = []) {
            super();
            this.rows = "auto";
            this.cols = "auto";
            this.spacing = 0;
            this.items = items;
        }
        is_width_expanding() {
            if (super.is_width_expanding()) {
                return true;
            }
            if (this.sizing.width_policy == "fixed") {
                return false;
            }
            const { cols } = this._state;
            return (0, array_1.some)(cols, (col) => col.policy == "max");
        }
        is_height_expanding() {
            if (super.is_height_expanding()) {
                return true;
            }
            if (this.sizing.height_policy == "fixed") {
                return false;
            }
            const { rows } = this._state;
            return (0, array_1.some)(rows, (row) => row.policy == "max");
        }
        _init() {
            super._init();
            const items = new Container();
            for (const { layout, row, col, row_span = 1, col_span = 1 } of this.items) {
                if (layout.sizing.visible) {
                    const r0 = row;
                    const c0 = col;
                    const r1 = row + row_span - 1;
                    const c1 = col + col_span - 1;
                    items.add({ r0, c0, r1, c1 }, layout);
                }
            }
            const { nrows, ncols } = items;
            const rows = new Array(nrows);
            for (let y = 0; y < nrows; y++) {
                const row = (() => {
                    const sizing = (0, types_2.isPlainObject)(this.rows) ? this.rows[y] ?? this.rows["*"] : this.rows;
                    if (sizing == null) {
                        return { policy: "auto" };
                    }
                    else if ((0, types_2.isNumber)(sizing)) {
                        return { policy: "fixed", height: sizing };
                    }
                    else if ((0, types_2.isString)(sizing)) {
                        return { policy: sizing };
                    }
                    else {
                        return sizing;
                    }
                })();
                const align = row.align ?? "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: row.flex ?? 1, align };
                }
                else {
                    if ((0, array_1.some)(items.row(y), (layout) => layout.is_height_expanding())) {
                        rows[y] = { policy: "max", flex: 1, align };
                    }
                    else {
                        rows[y] = { policy: "min", align };
                    }
                }
            }
            const cols = new Array(ncols);
            for (let x = 0; x < ncols; x++) {
                const col = (() => {
                    const sizing = (0, types_2.isPlainObject)(this.cols) ? this.cols[x] ?? this.cols["*"] : this.cols;
                    if (sizing == null) {
                        return { policy: "auto" };
                    }
                    else if ((0, types_2.isNumber)(sizing)) {
                        return { policy: "fixed", width: sizing };
                    }
                    else if ((0, types_2.isString)(sizing)) {
                        return { policy: sizing };
                    }
                    else {
                        return sizing;
                    }
                })();
                const align = col.align ?? "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: col.flex ?? 1, align };
                }
                else {
                    if ((0, array_1.some)(items.col(x), (layout) => layout.is_width_expanding())) {
                        cols[x] = { policy: "max", flex: 1, align };
                    }
                    else {
                        cols[x] = { policy: "min", align };
                    }
                }
            }
            const [rspacing, cspacing] = (0, types_2.isNumber)(this.spacing) ? [this.spacing, this.spacing] : this.spacing;
            this._state = { items, nrows, ncols, rows, cols, rspacing, cspacing };
        }
        _measure_totals(row_heights, col_widths) {
            const { nrows, ncols, rspacing, cspacing } = this._state;
            return {
                height: (0, array_1.sum)(row_heights) + (nrows - 1) * rspacing,
                width: (0, array_1.sum)(col_widths) + (ncols - 1) * cspacing,
            };
        }
        _measure_cells(cell_viewport) {
            const { items, nrows, ncols, rows, cols, rspacing, cspacing } = this._state;
            const row_heights = new Array(nrows);
            for (let r = 0; r < nrows; r++) {
                const row = rows[r];
                row_heights[r] = row.policy == "fixed" ? row.height : 0;
            }
            const col_widths = new Array(ncols);
            for (let c = 0; c < ncols; c++) {
                const col = cols[c];
                col_widths[c] = col.policy == "fixed" ? col.width : 0;
            }
            const size_hints = new Container();
            items.foreach((span, layout) => {
                const { r0, c0, r1, c1 } = span;
                const rspace = (r1 - r0) * rspacing;
                const cspace = (c1 - c0) * cspacing;
                let height = 0;
                for (let r = r0; r <= r1; r++) {
                    height += cell_viewport(r, c0).height;
                }
                height += rspace;
                let width = 0;
                for (let c = c0; c <= c1; c++) {
                    width += cell_viewport(r0, c).width;
                }
                width += cspace;
                const size_hint = layout.measure({ width, height });
                size_hints.add(span, { layout, size_hint });
                const size = new types_1.Sizeable(size_hint).grow_by(layout.sizing.margin);
                size.height -= rspace;
                size.width -= cspace;
                const radjustable = [];
                for (let r = r0; r <= r1; r++) {
                    const row = rows[r];
                    if (row.policy == "fixed") {
                        size.height -= row.height;
                    }
                    else {
                        radjustable.push(r);
                    }
                }
                if (size.height > 0) {
                    const rheight = round(size.height / radjustable.length);
                    for (const r of radjustable) {
                        row_heights[r] = max(row_heights[r], rheight);
                    }
                }
                const cadjustable = [];
                for (let c = c0; c <= c1; c++) {
                    const col = cols[c];
                    if (col.policy == "fixed") {
                        size.width -= col.width;
                    }
                    else {
                        cadjustable.push(c);
                    }
                }
                if (size.width > 0) {
                    const cwidth = round(size.width / cadjustable.length);
                    for (const c of cadjustable) {
                        col_widths[c] = max(col_widths[c], cwidth);
                    }
                }
            });
            const size = this._measure_totals(row_heights, col_widths);
            return { size, row_heights, col_widths, size_hints };
        }
        _measure_grid(viewport) {
            const { nrows, ncols, rows, cols, rspacing, cspacing } = this._state;
            const preferred = this._measure_cells((y, x) => {
                const row = rows[y];
                const col = cols[x];
                return {
                    width: col.policy == "fixed" ? col.width : Infinity,
                    height: row.policy == "fixed" ? row.height : Infinity,
                };
            });
            let available_height;
            if (this.sizing.height_policy == "fixed" && this.sizing.height != null) {
                available_height = this.sizing.height;
            }
            else if (viewport.height != Infinity && this.is_height_expanding()) {
                available_height = viewport.height;
            }
            else {
                available_height = preferred.size.height;
            }
            let height_flex = 0;
            for (let y = 0; y < nrows; y++) {
                const row = rows[y];
                if (row.policy == "fit" || row.policy == "max") {
                    height_flex += row.flex;
                }
                else {
                    available_height -= preferred.row_heights[y];
                }
            }
            available_height -= (nrows - 1) * rspacing;
            if (height_flex != 0 && available_height > 0) {
                for (let y = 0; y < nrows; y++) {
                    const row = rows[y];
                    if (row.policy == "fit" || row.policy == "max") {
                        const height = round(available_height * (row.flex / height_flex));
                        available_height -= height;
                        preferred.row_heights[y] = height;
                        height_flex -= row.flex;
                    }
                }
            }
            else if (available_height < 0) {
                let nadjustable = 0;
                for (let y = 0; y < nrows; y++) {
                    const row = rows[y];
                    if (row.policy != "fixed") {
                        nadjustable++;
                    }
                }
                let overflow_height = -available_height;
                for (let y = 0; y < nrows; y++) {
                    const row = rows[y];
                    if (row.policy != "fixed") {
                        const height = preferred.row_heights[y];
                        const cutoff = round(overflow_height / nadjustable);
                        preferred.row_heights[y] = max(height - cutoff, 0);
                        overflow_height -= cutoff > height ? height : cutoff;
                        nadjustable--;
                    }
                }
            }
            let available_width;
            if (this.sizing.width_policy == "fixed" && this.sizing.width != null) {
                available_width = this.sizing.width;
            }
            else if (viewport.width != Infinity && this.is_width_expanding()) {
                available_width = viewport.width;
            }
            else {
                available_width = preferred.size.width;
            }
            let width_flex = 0;
            for (let x = 0; x < ncols; x++) {
                const col = cols[x];
                if (col.policy == "fit" || col.policy == "max") {
                    width_flex += col.flex;
                }
                else {
                    available_width -= preferred.col_widths[x];
                }
            }
            available_width -= (ncols - 1) * cspacing;
            if (width_flex != 0 && available_width > 0) {
                for (let x = 0; x < ncols; x++) {
                    const col = cols[x];
                    if (col.policy == "fit" || col.policy == "max") {
                        const width = round(available_width * (col.flex / width_flex));
                        available_width -= width;
                        preferred.col_widths[x] = width;
                        width_flex -= col.flex;
                    }
                }
            }
            else if (available_width < 0) {
                let nadjustable = 0;
                for (let x = 0; x < ncols; x++) {
                    const col = cols[x];
                    if (col.policy != "fixed") {
                        nadjustable++;
                    }
                }
                let overflow_width = -available_width;
                for (let x = 0; x < ncols; x++) {
                    const col = cols[x];
                    if (col.policy != "fixed") {
                        const width = preferred.col_widths[x];
                        const cutoff = round(overflow_width / nadjustable);
                        preferred.col_widths[x] = max(width - cutoff, 0);
                        overflow_width -= cutoff > width ? width : cutoff;
                        nadjustable--;
                    }
                }
            }
            const { row_heights, col_widths, size_hints } = this._measure_cells((y, x) => {
                return {
                    width: preferred.col_widths[x],
                    height: preferred.row_heights[y],
                };
            });
            const size = this._measure_totals(row_heights, col_widths);
            return { size, row_heights, col_widths, size_hints };
        }
        _measure(viewport) {
            const { size } = this._measure_grid(viewport);
            return size;
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            const { nrows, ncols, rspacing, cspacing } = this._state;
            const { row_heights, col_widths, size_hints } = this._measure_grid(outer);
            const rows = this._state.rows.map((row, r) => {
                return { ...row, top: 0, height: row_heights[r], get bottom() {
                        return this.top + this.height;
                    } };
            });
            const cols = this._state.cols.map((col, c) => {
                return { ...col, left: 0, width: col_widths[c], get right() {
                        return this.left + this.width;
                    } };
            });
            const items = size_hints.map((_, item) => {
                return { ...item, outer: new bbox_1.BBox(), inner: new bbox_1.BBox() };
            });
            for (let r = 0, top = !this.absolute ? this.position.top : outer.top; r < nrows; r++) {
                const row = rows[r];
                row.top = top;
                top += row.height + rspacing;
            }
            for (let c = 0, left = !this.absolute ? this.position.left : outer.left; c < ncols; c++) {
                const col = cols[c];
                col.left = left;
                left += col.width + cspacing;
            }
            function span_width(c0, c1) {
                let width = (c1 - c0) * cspacing;
                for (let c = c0; c <= c1; c++) {
                    width += cols[c].width;
                }
                return width;
            }
            function span_height(r0, r1) {
                let height = (r1 - r0) * rspacing;
                for (let r = r0; r <= r1; r++) {
                    height += rows[r].height;
                }
                return height;
            }
            items.foreach(({ r0, c0, r1, c1 }, item) => {
                const { layout, size_hint } = item;
                const { sizing } = layout;
                const { width, height } = size_hint;
                const span = {
                    width: span_width(c0, c1),
                    height: span_height(r0, r1),
                };
                const halign = c0 == c1 && cols[c0].align != "auto" ? cols[c0].align : sizing.halign;
                const valign = r0 == r1 && rows[r0].align != "auto" ? rows[r0].align : sizing.valign;
                let left = cols[c0].left;
                if (halign == "start") {
                    left += sizing.margin.left;
                }
                else if (halign == "center") {
                    left += round((span.width - width) / 2);
                }
                else if (halign == "end") {
                    left += span.width - sizing.margin.right - width;
                }
                let top = rows[r0].top;
                if (valign == "start") {
                    top += sizing.margin.top;
                }
                else if (valign == "center") {
                    top += round((span.height - height) / 2);
                }
                else if (valign == "end") {
                    top += span.height - sizing.margin.bottom - height;
                }
                item.outer = new bbox_1.BBox({ left, top, width, height });
            });
            const row_aligns = rows.map(() => {
                return {
                    start: new DefaultMap(() => 0),
                    end: new DefaultMap(() => 0),
                };
            });
            const col_aligns = cols.map(() => {
                return {
                    start: new DefaultMap(() => 0),
                    end: new DefaultMap(() => 0),
                };
            });
            items.foreach(({ r0, c0, r1, c1 }, { size_hint, outer }) => {
                const { inner } = size_hint;
                if (inner != null) {
                    row_aligns[r0].start.apply(outer.top, (v) => max(v, inner.top));
                    row_aligns[r1].end.apply(rows[r1].bottom - outer.bottom, (v) => max(v, inner.bottom));
                    col_aligns[c0].start.apply(outer.left, (v) => max(v, inner.left));
                    col_aligns[c1].end.apply(cols[c1].right - outer.right, (v) => max(v, inner.right));
                }
            });
            items.foreach(({ r0, c0, r1, c1 }, item) => {
                const { size_hint, outer } = item;
                const inner_bbox = (extents) => {
                    const outer_bbox = this.absolute ? outer : outer.relative();
                    const left = outer_bbox.left + extents.left;
                    const top = outer_bbox.top + extents.top;
                    const right = outer_bbox.right - extents.right;
                    const bottom = outer_bbox.bottom - extents.bottom;
                    return new bbox_1.BBox({ left, top, right, bottom });
                };
                if (size_hint.inner != null) {
                    let inner = inner_bbox(size_hint.inner);
                    //if (size_hint.align !== false) {
                    const top = row_aligns[r0].start.get(outer.top);
                    const bottom = row_aligns[r1].end.get(rows[r1].bottom - outer.bottom);
                    const left = col_aligns[c0].start.get(outer.left);
                    const right = col_aligns[c1].end.get(cols[c1].right - outer.right);
                    try {
                        inner = inner_bbox({ top, bottom, left, right });
                    }
                    catch { }
                    //}
                    item.inner = inner;
                }
                else {
                    item.inner = outer;
                }
            });
            items.foreach((_, { layout, outer, inner }) => {
                layout.set_geometry(outer, inner);
            });
        }
    }
    exports.Grid = Grid;
    Grid.__name__ = "Grid";
    class Row extends Grid {
        constructor(items) {
            super();
            this.items = items.map((item, i) => ({ layout: item, row: 0, col: i }));
            this.rows = "fit";
        }
    }
    exports.Row = Row;
    Row.__name__ = "Row";
    class Column extends Grid {
        constructor(items) {
            super();
            this.items = items.map((item, i) => ({ layout: item, row: i, col: 0 }));
            this.cols = "fit";
        }
    }
    exports.Column = Column;
    Column.__name__ = "Column";
},
/* core/layout/border.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const types_1 = require(174) /* ./types */;
    const layoutable_1 = require(175) /* ./layoutable */;
    const bbox_1 = require(64) /* ../util/bbox */;
    class BorderLayout extends layoutable_1.Layoutable {
        constructor() {
            super(...arguments);
            this.aligns = { left: true, right: true, top: true, bottom: true };
            this.min_border = { left: 0, top: 0, right: 0, bottom: 0 };
            this.padding = { left: 0, top: 0, right: 0, bottom: 0 };
            this.center_border_width = 0;
        }
        *[Symbol.iterator]() {
            yield this.top_panel;
            yield this.bottom_panel;
            yield this.left_panel;
            yield this.right_panel;
            yield this.center_panel;
        }
        _measure(viewport) {
            viewport = new types_1.Sizeable({
                width: this.sizing.width_policy == "fixed" || viewport.width == Infinity ? this.sizing.width : viewport.width,
                height: this.sizing.height_policy == "fixed" || viewport.height == Infinity ? this.sizing.height : viewport.height,
            });
            const left_hint = this.left_panel.measure({ width: 0, height: viewport.height });
            const left = Math.max(left_hint.width, this.min_border.left) + this.padding.left;
            const right_hint = this.right_panel.measure({ width: 0, height: viewport.height });
            const right = Math.max(right_hint.width, this.min_border.right) + this.padding.right;
            const top_hint = this.top_panel.measure({ width: viewport.width, height: 0 });
            const top = Math.max(top_hint.height, this.min_border.top) + this.padding.top;
            const bottom_hint = this.bottom_panel.measure({ width: viewport.width, height: 0 });
            const bottom = Math.max(bottom_hint.height, this.min_border.bottom) + this.padding.bottom;
            const center_viewport = new types_1.Sizeable(viewport).shrink_by({ left, right, top, bottom });
            const center = this.center_panel.measure(center_viewport);
            const width = left + center.width + right;
            const height = top + center.height + bottom;
            const align = (() => {
                const { width_policy, height_policy } = this.center_panel.sizing;
                return {
                    ...this.aligns,
                    fixed_width: width_policy == "fixed",
                    fixed_height: height_policy == "fixed",
                };
            })();
            return { width, height, inner: { left, right, top, bottom }, align };
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            if (this.sizing.visible) {
                this.center_panel.set_geometry(inner);
                const left_hint = this.left_panel.measure({ width: 0, height: outer.height });
                const right_hint = this.right_panel.measure({ width: 0, height: outer.height });
                const top_hint = this.top_panel.measure({ width: outer.width, height: 0 });
                const bottom_hint = this.bottom_panel.measure({ width: outer.width, height: 0 });
                const { left, top, right, bottom } = inner;
                this.top_panel.set_geometry(new bbox_1.BBox({ left, right, bottom: top, height: top_hint.height }));
                this.bottom_panel.set_geometry(new bbox_1.BBox({ left, right, top: bottom, height: bottom_hint.height }));
                this.left_panel.set_geometry(new bbox_1.BBox({ top, bottom, right: left, width: left_hint.width }));
                this.right_panel.set_geometry(new bbox_1.BBox({ top, bottom, left: right, width: right_hint.width }));
                const adjusted_inner = inner.shrink_by(this.center_border_width);
                if (this.inner_top_panel != null) {
                    const { left, right, top, width } = adjusted_inner;
                    const inner_top_hint = this.inner_top_panel.measure({ width, height: 0 });
                    this.inner_top_panel.set_geometry(new bbox_1.BBox({ left, right, top, height: inner_top_hint.height }));
                }
                if (this.inner_bottom_panel != null) {
                    const { left, right, bottom, width } = adjusted_inner;
                    const inner_bottom_hint = this.inner_bottom_panel.measure({ width, height: 0 });
                    this.inner_bottom_panel.set_geometry(new bbox_1.BBox({ left, right, bottom, height: inner_bottom_hint.height }));
                }
                if (this.inner_left_panel != null) {
                    const { top, bottom, left, height } = adjusted_inner;
                    const inner_left_hint = this.inner_left_panel.measure({ width: 0, height });
                    this.inner_left_panel.set_geometry(new bbox_1.BBox({ top, bottom, left, width: inner_left_hint.width }));
                }
                if (this.inner_right_panel != null) {
                    const { top, bottom, right, height } = adjusted_inner;
                    const inner_right_hint = this.inner_right_panel.measure({ width: 0, height });
                    this.inner_right_panel.set_geometry(new bbox_1.BBox({ top, bottom, right, width: inner_right_hint.width }));
                }
            }
            else {
                this.center_panel.set_geometry(new bbox_1.BBox());
                this.top_panel.set_geometry(new bbox_1.BBox());
                this.bottom_panel.set_geometry(new bbox_1.BBox());
                this.left_panel.set_geometry(new bbox_1.BBox());
                this.right_panel.set_geometry(new bbox_1.BBox());
                this.inner_top_panel?.set_geometry(new bbox_1.BBox());
                this.inner_bottom_panel?.set_geometry(new bbox_1.BBox());
                this.inner_left_panel?.set_geometry(new bbox_1.BBox());
                this.inner_right_panel?.set_geometry(new bbox_1.BBox());
            }
        }
    }
    exports.BorderLayout = BorderLayout;
    BorderLayout.__name__ = "BorderLayout";
},
/* models/annotations/band.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const upper_lower_1 = require(262) /* ./upper_lower */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    class BandView extends upper_lower_1.UpperLowerView {
        _paint_data(ctx) {
            // Draw the band body
            ctx.beginPath();
            ctx.moveTo(this._lower_sx[0], this._lower_sy[0]);
            for (let i = 0, end = this._lower_sx.length; i < end; i++) {
                ctx.lineTo(this._lower_sx[i], this._lower_sy[i]);
            }
            // iterate backwards so that the upper end is below the lower start
            for (let i = this._upper_sx.length - 1; i >= 0; i--) {
                ctx.lineTo(this._upper_sx[i], this._upper_sy[i]);
            }
            ctx.closePath();
            this.visuals.fill.apply(ctx);
            // Draw the lower band edge
            ctx.beginPath();
            ctx.moveTo(this._lower_sx[0], this._lower_sy[0]);
            for (let i = 0, end = this._lower_sx.length; i < end; i++) {
                ctx.lineTo(this._lower_sx[i], this._lower_sy[i]);
            }
            this.visuals.line.apply(ctx);
            // Draw the upper band edge
            ctx.beginPath();
            ctx.moveTo(this._upper_sx[0], this._upper_sy[0]);
            for (let i = 0, end = this._upper_sx.length; i < end; i++) {
                ctx.lineTo(this._upper_sx[i], this._upper_sy[i]);
            }
            this.visuals.line.apply(ctx);
        }
    }
    exports.BandView = BandView;
    BandView.__name__ = "BandView";
    class Band extends upper_lower_1.UpperLower {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Band = Band;
    _a = Band;
    Band.__name__ = "Band";
    (() => {
        _a.prototype.default_view = BandView;
        _a.mixins([mixins.Line, mixins.Fill]);
        _a.override({
            fill_color: "#fff9ba",
            fill_alpha: 0.4,
            line_color: "#cccccc",
            line_alpha: 0.3,
        });
    })();
},
/* models/annotations/upper_lower.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(127) /* ./data_annotation */;
    const types_1 = require(24) /* ../../core/types */;
    const enums_1 = require(20) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class UpperLowerView extends data_annotation_1.DataAnnotationView {
        map_data() {
            const { frame } = this.plot_view;
            const dim = this.model.dimension;
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            const limit_scale = dim == "height" ? yscale : xscale;
            const base_scale = dim == "height" ? xscale : yscale;
            const limit_view = dim == "height" ? frame.bbox.yview : frame.bbox.xview;
            const base_view = dim == "height" ? frame.bbox.xview : frame.bbox.yview;
            const _lower_sx = (() => {
                switch (this.model.properties.lower.units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._lower);
                    case "screen":
                        return limit_view.v_compute(this._lower);
                    case "data":
                        return limit_scale.v_compute(this._lower);
                }
            })();
            const _upper_sx = (() => {
                switch (this.model.properties.upper.units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._upper);
                    case "screen":
                        return limit_view.v_compute(this._upper);
                    case "data":
                        return limit_scale.v_compute(this._upper);
                }
            })();
            const _base_sx = (() => {
                switch (this.model.properties.base.units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._base);
                    case "screen":
                        return base_view.v_compute(this._base);
                    case "data":
                        return base_scale.v_compute(this._base);
                }
            })();
            const [i, j] = dim == "height" ? [1, 0] : [0, 1];
            const _lower = [_lower_sx, _base_sx];
            const _upper = [_upper_sx, _base_sx];
            this._lower_sx = _lower[i];
            this._lower_sy = _lower[j];
            this._upper_sx = _upper[i];
            this._upper_sy = _upper[j];
        }
    }
    exports.UpperLowerView = UpperLowerView;
    UpperLowerView.__name__ = "UpperLowerView";
    class XOrYCoordinateSpec extends p.CoordinateSpec {
        constructor() {
            super(...arguments);
            this._value = p.unset;
        }
        get dimension() {
            return this.obj.dimension == "width" ? "x" : "y";
        }
        // XXX: a hack to make a coordinate & unit spec
        get units() {
            return this._value === p.unset ? "data" : this._value.units ?? "data";
        }
    }
    exports.XOrYCoordinateSpec = XOrYCoordinateSpec;
    XOrYCoordinateSpec.__name__ = "XOrYCoordinateSpec";
    class UpperLower extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.UpperLower = UpperLower;
    _a = UpperLower;
    UpperLower.__name__ = "UpperLower";
    (() => {
        _a.define(() => ({
            dimension: [enums_1.Dimension, "height"],
            lower: [XOrYCoordinateSpec, { field: "lower" }],
            upper: [XOrYCoordinateSpec, { field: "upper" }],
            base: [XOrYCoordinateSpec, { field: "base" }],
        }));
    })();
},
/* models/annotations/box_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(81) /* ./annotation */;
    const model_1 = require(51) /* ../../model */;
    const area_visuals_1 = require(79) /* ./area_visuals */;
    const data_range1d_1 = require(106) /* ../ranges/data_range1d */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const math_1 = require(11) /* ../../core/util/math */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const object_1 = require(9) /* ../../core/util/object */;
    const kinds_1 = require(185) /* ../common/kinds */;
    const Box = tslib_1.__importStar(require(264) /* ../common/box_kinds */);
    const painting_1 = require(187) /* ../common/painting */;
    const resolve = tslib_1.__importStar(require(186) /* ../common/resolve */);
    const node_1 = require(59) /* ../coordinates/node */;
    const coordinate_1 = require(60) /* ../coordinates/coordinate */;
    exports.EDGE_TOLERANCE = 2.5;
    const { abs } = Math;
    class BoxInteractionHandles extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.BoxInteractionHandles = BoxInteractionHandles;
    _a = BoxInteractionHandles;
    BoxInteractionHandles.__name__ = "BoxInteractionHandles";
    (() => {
        _a.define(({ Ref, Nullable }) => ({
            all: [Ref(area_visuals_1.AreaVisuals)],
            move: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
            resize: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
            sides: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
            corners: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
            left: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
            right: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
            top: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
            bottom: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
            top_left: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
            top_right: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
            bottom_left: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
            bottom_right: [Nullable(Ref(area_visuals_1.AreaVisuals)), null],
        }));
    })();
    const DEFAULT_HANDLES = () => {
        return new BoxInteractionHandles({
            all: new area_visuals_1.AreaVisuals({
                fill_color: "white",
                fill_alpha: 1.0,
                line_color: "black",
                line_alpha: 1.0,
                hover_fill_color: "lightgray",
                hover_fill_alpha: 1.0,
            }),
        });
    };
    class BoxAnnotationView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this._bbox = new bbox_1.BBox();
            this._handles_views = {};
            this[_b] = true;
            this._pan_state = null;
            this._pinch_state = null;
            this._is_hovered = false;
        }
        get bbox() {
            return this._bbox;
        }
        initialize() {
            super.initialize();
            this._update_handles();
        }
        _update_handles() {
            const { editable, use_handles, handles } = this.model;
            if (editable && use_handles) {
                const { movable, resizable } = this;
                const common = {
                    visible: true,
                    resizable: "none",
                    left_units: "canvas",
                    right_units: "canvas",
                    top_units: "canvas",
                    bottom_units: "canvas",
                    level: this.model.level,
                };
                function attrs_of(source) {
                    return {
                        ...mixins.attrs_of(source, "", mixins.Line, true),
                        ...mixins.attrs_of(source, "", mixins.Fill, true),
                        ...mixins.attrs_of(source, "", mixins.Hatch, true),
                        ...mixins.attrs_of(source, "hover_", mixins.Line, true),
                        ...mixins.attrs_of(source, "hover_", mixins.Fill, true),
                        ...mixins.attrs_of(source, "hover_", mixins.Hatch, true),
                    };
                }
                const h = handles;
                const attrs = {
                    area: attrs_of(h.move ?? h.all),
                    left: attrs_of(h.left ?? h.sides ?? h.resize ?? h.all),
                    right: attrs_of(h.right ?? h.sides ?? h.resize ?? h.all),
                    top: attrs_of(h.top ?? h.sides ?? h.resize ?? h.all),
                    bottom: attrs_of(h.bottom ?? h.sides ?? h.resize ?? h.all),
                    top_left: attrs_of(h.top_left ?? h.corners ?? h.resize ?? h.all),
                    top_right: attrs_of(h.top_right ?? h.corners ?? h.resize ?? h.all),
                    bottom_left: attrs_of(h.bottom_left ?? h.corners ?? h.resize ?? h.all),
                    bottom_right: attrs_of(h.bottom_right ?? h.corners ?? h.resize ?? h.all),
                };
                const { tl_cursor, tr_cursor, bl_cursor, br_cursor, ew_cursor, ns_cursor, } = this.model;
                this._handles = {
                    area: movable ? new BoxAnnotation({ ...common, ...attrs.area, movable: this.model.movable }) : null,
                    left: resizable.left ? new BoxAnnotation({ ...common, ...attrs.left, in_cursor: ew_cursor }) : null,
                    right: resizable.right ? new BoxAnnotation({ ...common, ...attrs.right, in_cursor: ew_cursor }) : null,
                    top: resizable.top ? new BoxAnnotation({ ...common, ...attrs.top, in_cursor: ns_cursor }) : null,
                    bottom: resizable.bottom ? new BoxAnnotation({ ...common, ...attrs.bottom, in_cursor: ns_cursor }) : null,
                    top_left: resizable.top_left ? new BoxAnnotation({ ...common, ...attrs.top_left, in_cursor: tl_cursor }) : null,
                    top_right: resizable.top_right ? new BoxAnnotation({ ...common, ...attrs.top_right, in_cursor: tr_cursor }) : null,
                    bottom_left: resizable.bottom_left ? new BoxAnnotation({ ...common, ...attrs.bottom_left, in_cursor: bl_cursor }) : null,
                    bottom_right: resizable.bottom_right ? new BoxAnnotation({ ...common, ...attrs.bottom_right, in_cursor: br_cursor }) : null,
                };
            }
            else {
                this._handles = {
                    area: null,
                    left: null,
                    right: null,
                    top: null,
                    bottom: null,
                    top_left: null,
                    top_right: null,
                    bottom_left: null,
                    bottom_right: null,
                };
            }
        }
        get computed_renderers() {
            return [...super.computed_renderers, ...(0, object_1.values)(this._handles).filter((handle) => handle != null)];
        }
        connect_signals() {
            super.connect_signals();
            const { editable, use_handles, handles, resizable, movable } = this.model.properties;
            this.on_change([editable, use_handles, handles, resizable, movable], async () => {
                this._update_handles();
                await this._update_renderers();
            });
            this.connect(this.model.change, () => this.request_paint());
        }
        async _build_renderers() {
            const build_result = await super._build_renderers();
            const get = (handle) => {
                return handle != null ? this._renderer_views.get(handle) : undefined;
            };
            this._handles_views = {
                area: get(this._handles.area),
                left: get(this._handles.left),
                right: get(this._handles.right),
                top: get(this._handles.top),
                bottom: get(this._handles.bottom),
                top_left: get(this._handles.top_left),
                top_right: get(this._handles.top_right),
                bottom_left: get(this._handles.bottom_left),
                bottom_right: get(this._handles.bottom_right),
            };
            return build_result;
        }
        bounds() {
            const { left, left_units, right, right_units, top, top_units, bottom, bottom_units, } = this.model;
            const left_ok = left_units == "data" && !(left instanceof coordinate_1.Coordinate);
            const right_ok = right_units == "data" && !(right instanceof coordinate_1.Coordinate);
            const top_ok = top_units == "data" && !(top instanceof coordinate_1.Coordinate);
            const bottom_ok = bottom_units == "data" && !(bottom instanceof coordinate_1.Coordinate);
            const [x0, x1] = (() => {
                if (left_ok && right_ok) {
                    return left <= right ? [left, right] : [right, left];
                }
                else if (left_ok) {
                    return [left, left];
                }
                else if (right_ok) {
                    return [right, right];
                }
                else {
                    return [NaN, NaN];
                }
            })();
            const [y0, y1] = (() => {
                if (top_ok && bottom_ok) {
                    return top <= bottom ? [top, bottom] : [bottom, top];
                }
                else if (top_ok) {
                    return [top, top];
                }
                else if (bottom_ok) {
                    return [bottom, bottom];
                }
                else {
                    return [NaN, NaN];
                }
            })();
            return { x0, x1, y0, y1 };
        }
        log_bounds() {
            return (0, bbox_1.empty)();
        }
        get mappers() {
            function mapper(units, scale, view, canvas) {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            }
            const overlay = this.model;
            const { x_scale, y_scale } = this.coordinates;
            const { x_view, y_view } = this.plot_view.frame.bbox;
            const { x_screen, y_screen } = this.plot_view.canvas.bbox;
            const lrtb = {
                left: mapper(overlay.left_units, x_scale, x_view, x_screen),
                right: mapper(overlay.right_units, x_scale, x_view, x_screen),
                top: mapper(overlay.top_units, y_scale, y_view, y_screen),
                bottom: mapper(overlay.bottom_units, y_scale, y_view, y_screen),
            };
            return lrtb;
        }
        get border_radius() {
            return resolve.border_radius(this.model.border_radius);
        }
        compute_geometry() {
            super.compute_geometry();
            const bbox = (() => {
                const compute = (dim, value, mapper) => {
                    return value instanceof coordinate_1.Coordinate ? this.resolve_as_scalar(value, dim) : mapper.compute(value);
                };
                const { left, right, top, bottom } = this.model;
                const { mappers } = this;
                return bbox_1.BBox.from_lrtb({
                    left: compute("x", left, mappers.left),
                    right: compute("x", right, mappers.right),
                    top: compute("y", top, mappers.top),
                    bottom: compute("y", bottom, mappers.bottom),
                });
            })();
            this._bbox = bbox;
            const width = 10;
            const height = 10;
            function update(renderer, bbox) {
                const { left, right, top, bottom } = bbox;
                renderer?.setv({ left, right, top, bottom }, { silent: true });
            }
            update(this._handles.area, new bbox_1.BBox({ ...bbox.center, width, height, origin: "center" }));
            update(this._handles.left, new bbox_1.BBox({ ...bbox.center_left, width, height, origin: "center" }));
            update(this._handles.right, new bbox_1.BBox({ ...bbox.center_right, width, height, origin: "center" }));
            update(this._handles.top, new bbox_1.BBox({ ...bbox.top_center, width, height, origin: "center" }));
            update(this._handles.bottom, new bbox_1.BBox({ ...bbox.bottom_center, width, height, origin: "center" }));
            update(this._handles.top_left, new bbox_1.BBox({ ...bbox.top_left, width, height, origin: "center" }));
            update(this._handles.top_right, new bbox_1.BBox({ ...bbox.top_right, width, height, origin: "center" }));
            update(this._handles.bottom_left, new bbox_1.BBox({ ...bbox.bottom_left, width, height, origin: "center" }));
            update(this._handles.bottom_right, new bbox_1.BBox({ ...bbox.bottom_right, width, height, origin: "center" }));
        }
        _paint() {
            if (!this.bbox.is_valid) {
                return;
            }
            const { _is_hovered, visuals } = this;
            const fill = _is_hovered && visuals.hover_fill.doit ? visuals.hover_fill : visuals.fill;
            const hatch = _is_hovered && visuals.hover_hatch.doit ? visuals.hover_hatch : visuals.hatch;
            const line = _is_hovered && visuals.hover_line.doit ? visuals.hover_line : visuals.line;
            const { ctx } = this.layer;
            ctx.save();
            const { inverted } = this.model;
            if (!inverted) {
                ctx.beginPath();
                (0, painting_1.round_rect)(ctx, this.bbox, this.border_radius);
                fill.apply(ctx);
                hatch.apply(ctx);
                line.apply(ctx);
            }
            else {
                ctx.beginPath();
                const parent = this.layout ?? this.plot_view.frame;
                const { x, y, width, height } = parent.bbox;
                ctx.rect(x, y, width, height);
                (0, painting_1.round_rect)(ctx, this.bbox, this.border_radius);
                fill.apply(ctx, "evenodd");
                hatch.apply(ctx, "evenodd");
                ctx.beginPath();
                (0, painting_1.round_rect)(ctx, this.bbox, this.border_radius);
                line.apply(ctx);
            }
            ctx.restore();
        }
        interactive_bbox() {
            const tolerance = this.model.line_width + exports.EDGE_TOLERANCE;
            return this.bbox.grow_by(tolerance);
        }
        interactive_hit(sx, sy) {
            if (!this.model.visible) {
                return false;
            }
            const bbox = this.interactive_bbox();
            return bbox.contains(sx, sy);
        }
        _hit_test(sx, sy) {
            const { left, right, bottom, top } = this.bbox;
            const tolerance = Math.max(exports.EDGE_TOLERANCE, this.model.line_width / 2);
            const dl = abs(left - sx);
            const dr = abs(right - sx);
            const dt = abs(top - sy);
            const db = abs(bottom - sy);
            const hits = {
                left: dl < tolerance && dl < dr,
                right: dr < tolerance && dr < dl,
                top: dt < tolerance && dt < db,
                bottom: db < tolerance && db < dt,
            };
            const hittable = this._hittable();
            const hits_handle = (hit_target, condition) => {
                if (!hittable[hit_target]) {
                    return false;
                }
                const handle = this._handles_views[hit_target];
                if (handle != null) {
                    return handle.bbox.contains(sx, sy);
                }
                else {
                    return condition;
                }
            };
            if (hits_handle("top_left", hits.top && hits.left)) {
                return "top_left";
            }
            if (hits_handle("top_right", hits.top && hits.right)) {
                return "top_right";
            }
            if (hits_handle("bottom_left", hits.bottom && hits.left)) {
                return "bottom_left";
            }
            if (hits_handle("bottom_right", hits.bottom && hits.right)) {
                return "bottom_right";
            }
            if (hits_handle("left", hits.left)) {
                return "left";
            }
            if (hits_handle("right", hits.right)) {
                return "right";
            }
            if (hits_handle("top", hits.top)) {
                return "top";
            }
            if (hits_handle("bottom", hits.bottom)) {
                return "bottom";
            }
            if (hits_handle("area", this.bbox.contains(sx, sy))) {
                return "area";
            }
            return null;
        }
        get resizable() {
            const { resizable } = this.model;
            const left = resizable == "left" || resizable == "x" || resizable == "all";
            const right = resizable == "right" || resizable == "x" || resizable == "all";
            const top = resizable == "top" || resizable == "y" || resizable == "all";
            const bottom = resizable == "bottom" || resizable == "y" || resizable == "all";
            return {
                left,
                right,
                top,
                bottom,
                top_left: top && left,
                top_right: top && right,
                bottom_left: bottom && left,
                bottom_right: bottom && right,
            };
        }
        get movable() {
            return this.model.movable != "none";
        }
        _hittable() {
            const { left, right, top, bottom } = this.resizable;
            return {
                top_left: top && left,
                top_right: top && right,
                bottom_left: bottom && left,
                bottom_right: bottom && right,
                left,
                right,
                top,
                bottom,
                area: this.movable,
            };
        }
        _can_hit(target) {
            const { left, right, top, bottom } = this.resizable;
            switch (target) {
                case "top_left": return top && left;
                case "top_right": return top && right;
                case "bottom_left": return bottom && left;
                case "bottom_right": return bottom && right;
                case "left": return left;
                case "right": return right;
                case "top": return top;
                case "bottom": return bottom;
                case "area": return this.movable;
            }
        }
        on_pan_start(ev) {
            if (this.model.visible && this.model.editable) {
                const { sx, sy } = ev;
                const target = this._hit_test(sx, sy);
                if (target != null && this._can_hit(target)) {
                    this._pan_state = {
                        bbox: this.bbox.clone(),
                        target,
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]);
                    return true;
                }
            }
            return false;
        }
        on_pan(ev) {
            (0, assert_1.assert)(this._pan_state != null);
            const { mappers } = this;
            const resolve = (dim, limit, mapper) => {
                if (limit instanceof coordinate_1.Coordinate) {
                    return this.resolve_as_scalar(limit, dim);
                }
                else if (limit == null) {
                    return NaN;
                }
                else {
                    return mapper.compute(limit);
                }
            };
            const slimits = bbox_1.BBox.from_lrtb({
                left: resolve("x", this.model.left_limit, mappers.left),
                right: resolve("x", this.model.right_limit, mappers.right),
                top: resolve("y", this.model.top_limit, mappers.top),
                bottom: resolve("y", this.model.bottom_limit, mappers.bottom),
            });
            const [dl, dr, dt, db] = (() => {
                const { dx, dy } = ev;
                const { target } = this._pan_state;
                const { symmetric } = this.model;
                const [Dx, Dy] = symmetric ? [-dx, -dy] : [0, 0];
                switch (target) {
                    // corners
                    case "top_left": return [dx, Dx, dy, Dy];
                    case "top_right": return [Dx, dx, dy, Dy];
                    case "bottom_left": return [dx, Dx, Dy, dy];
                    case "bottom_right": return [Dx, dx, Dy, dy];
                    // edges
                    case "left": return [dx, Dx, 0, 0];
                    case "right": return [Dx, dx, 0, 0];
                    case "top": return [0, 0, dy, Dy];
                    case "bottom": return [0, 0, Dy, dy];
                    // area
                    case "area": {
                        switch (this.model.movable) {
                            case "both": return [dx, dx, dy, dy];
                            case "x": return [dx, dx, 0, 0];
                            case "y": return [0, 0, dy, dy];
                            case "none": return [0, 0, 0, 0];
                        }
                    }
                }
            })();
            const slrtb = (() => {
                const min = (a, b) => (0, array_1.min)([a, b]);
                const sgn = (v) => v < 0 ? -1 : (v > 0 ? 1 : 0);
                const { bbox } = this._pan_state;
                let { left, right, left_sign, right_sign } = (() => {
                    const left = bbox.left + dl;
                    const right = bbox.right + dr;
                    const left_sign = sgn(dl);
                    const right_sign = sgn(dr);
                    if (left <= right) {
                        return { left, right, left_sign, right_sign };
                    }
                    else {
                        return { left: right, right: left, left_sign: right_sign, right_sign: left_sign };
                    }
                })();
                let { top, bottom, top_sign, bottom_sign } = (() => {
                    const top = bbox.top + dt;
                    const bottom = bbox.bottom + db;
                    const top_sign = sgn(dt);
                    const bottom_sign = sgn(db);
                    if (top <= bottom) {
                        return { top, bottom, top_sign, bottom_sign };
                    }
                    else {
                        return { top: bottom, bottom: top, top_sign: bottom_sign, bottom_sign: top_sign };
                    }
                })();
                const Dl = left - slimits.left;
                const Dr = slimits.right - right;
                const Dx = min(Dl < 0 ? Dl : NaN, Dr < 0 ? Dr : NaN);
                if (isFinite(Dx) && Dx < 0) {
                    left += -left_sign * (-Dx);
                    right += -right_sign * (-Dx);
                }
                const Dt = top - slimits.top;
                const Db = slimits.bottom - bottom;
                const Dy = min(Dt < 0 ? Dt : NaN, Db < 0 ? Db : NaN);
                if (isFinite(Dy) && Dy < 0) {
                    top += -top_sign * (-Dy);
                    bottom += -bottom_sign * (-Dy);
                }
                return bbox_1.BBox.from_lrtb({ left, right, top, bottom });
            })();
            const { min_width, min_height, max_width, max_height } = this.model;
            const { left, right, top, bottom } = this.model;
            const lrtb = {
                left: mappers.left.invert(slrtb.left),
                right: mappers.right.invert(slrtb.right),
                top: mappers.top.invert(slrtb.top),
                bottom: mappers.bottom.invert(slrtb.bottom),
            };
            if (0 < min_width || max_width < Infinity) {
                if (dl != 0 && dr == 0) {
                    const min_left = lrtb.right - max_width;
                    const max_left = lrtb.right - min_width;
                    lrtb.left = (0, math_1.clamp)(lrtb.left, min_left, max_left);
                }
                else if (dl == 0 && dr != 0) {
                    const min_right = lrtb.left + min_width;
                    const max_right = lrtb.left + max_width;
                    lrtb.right = (0, math_1.clamp)(lrtb.right, min_right, max_right);
                }
            }
            if (0 < min_height || max_height < Infinity) {
                if (dt != 0 && db == 0) {
                    const min_top = lrtb.bottom + max_height;
                    const max_top = lrtb.bottom + min_height;
                    lrtb.top = (0, math_1.clamp)(lrtb.top, min_top, max_top);
                }
                else if (dt == 0 && db != 0) {
                    const min_bottom = lrtb.top - min_height;
                    const max_bottom = lrtb.top - max_height;
                    lrtb.bottom = (0, math_1.clamp)(lrtb.bottom, min_bottom, max_bottom);
                }
            }
            const computed_lrtb = (() => {
                return {
                    left: left instanceof coordinate_1.Coordinate ? left : lrtb.left,
                    right: right instanceof coordinate_1.Coordinate ? right : lrtb.right,
                    top: top instanceof coordinate_1.Coordinate ? top : lrtb.top,
                    bottom: bottom instanceof coordinate_1.Coordinate ? bottom : lrtb.bottom,
                };
            })();
            this.model.update(computed_lrtb);
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        on_pan_end(ev) {
            this._pan_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        on_pinch_start(ev) {
            if (this.model.visible && this.model.editable && this.model.resizable != "none") {
                const { sx, sy } = ev;
                if (this.bbox.contains(sx, sy)) {
                    this._pinch_state = {
                        bbox: this.bbox.clone(),
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]); // TODO: pinch signal
                    return true;
                }
            }
            return false;
        }
        on_pinch(ev) {
            (0, assert_1.assert)(this._pinch_state != null);
            const slrtb = (() => {
                const { scale } = ev;
                const { bbox } = this._pinch_state;
                const { left, top, right, bottom, width, height } = bbox;
                const dw = width * (scale - 1);
                const dh = height * (scale - 1);
                const { resizable } = this;
                const dl = resizable.left ? -dw / 2 : 0;
                const dr = resizable.right ? dw / 2 : 0;
                const dt = resizable.top ? -dh / 2 : 0;
                const db = resizable.bottom ? dh / 2 : 0;
                return bbox_1.BBox.from_lrtb({
                    left: left + dl,
                    right: right + dr,
                    top: top + dt,
                    bottom: bottom + db,
                });
            })();
            const lrtb = (() => {
                const { left, right, top, bottom } = this.model;
                const { mappers } = this;
                return {
                    left: left instanceof coordinate_1.Coordinate ? left : mappers.left.invert(slrtb.left),
                    right: right instanceof coordinate_1.Coordinate ? right : mappers.right.invert(slrtb.right),
                    top: top instanceof coordinate_1.Coordinate ? top : mappers.top.invert(slrtb.top),
                    bottom: bottom instanceof coordinate_1.Coordinate ? bottom : mappers.bottom.invert(slrtb.bottom),
                };
            })();
            this.model.update(lrtb);
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        on_pinch_end(ev) {
            this._pinch_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        get _has_hover() {
            const { hover_line, hover_fill, hover_hatch } = this.visuals;
            return hover_line.doit || hover_fill.doit || hover_hatch.doit;
        }
        on_enter(_ev) {
            const { _has_hover } = this;
            if (_has_hover) {
                this._is_hovered = true;
                this.request_paint();
            }
            return _has_hover;
        }
        on_move(_ev) { }
        on_leave(_ev) {
            if (this._has_hover) {
                this._is_hovered = false;
                this.request_paint();
            }
        }
        cursor(sx, sy) {
            const target = this._pan_state?.target ?? this._hit_test(sx, sy);
            if (target == null || !this._can_hit(target)) {
                return null;
            }
            const { tl_cursor, tr_cursor, bl_cursor, br_cursor, ew_cursor, ns_cursor, in_cursor, } = this.model;
            switch (target) {
                case "top_left": return this._handles.top_left == null ? tl_cursor : null;
                case "top_right": return this._handles.top_right == null ? tr_cursor : null;
                case "bottom_left": return this._handles.bottom_left == null ? bl_cursor : null;
                case "bottom_right": return this._handles.bottom_right == null ? br_cursor : null;
                case "left": return this._handles.left == null ? ew_cursor : null;
                case "right": return this._handles.right == null ? ew_cursor : null;
                case "top": return this._handles.top == null ? ns_cursor : null;
                case "bottom": return this._handles.bottom == null ? ns_cursor : null;
                case "area": {
                    if (this._handles.area == null) {
                        switch (this.model.movable) {
                            case "both": return in_cursor;
                            case "x": return ew_cursor;
                            case "y": return ns_cursor;
                            case "none": return null;
                        }
                    }
                    else {
                        return null;
                    }
                }
            }
        }
    }
    exports.BoxAnnotationView = BoxAnnotationView;
    _b = data_range1d_1.auto_ranged;
    BoxAnnotationView.__name__ = "BoxAnnotationView";
    class BoxAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
            this.pan = new signaling_1.Signal(this, "pan");
            this.nodes = (() => {
                const known = new Map();
                const node = (symbol) => {
                    let node = known.get(symbol);
                    if (node === undefined) {
                        known.set(symbol, node = new node_1.Node({ target: this, symbol }));
                    }
                    return node;
                };
                return {
                    get left() { return node("left"); },
                    get right() { return node("right"); },
                    get top() { return node("top"); },
                    get bottom() { return node("bottom"); },
                    get top_left() { return node("top_left"); },
                    get top_center() { return node("top_center"); },
                    get top_right() { return node("top_right"); },
                    get center_left() { return node("center_left"); },
                    get center() { return node("center"); },
                    get center_right() { return node("center_right"); },
                    get bottom_left() { return node("bottom_left"); },
                    get bottom_center() { return node("bottom_center"); },
                    get bottom_right() { return node("bottom_right"); },
                    get width() { return node("width"); },
                    get height() { return node("height"); },
                };
            })();
        }
        clone(attrs) {
            return super.clone(attrs);
        }
        update({ left, right, top, bottom }) {
            this.setv({ left, right, top, bottom, visible: true });
        }
        clear() {
            this.visible = false;
        }
    }
    exports.BoxAnnotation = BoxAnnotation;
    _c = BoxAnnotation;
    BoxAnnotation.__name__ = "BoxAnnotation";
    (() => {
        _c.prototype.default_view = BoxAnnotationView;
        _c.mixins([
            mixins.Line,
            mixins.Fill,
            mixins.Hatch,
            ["hover_", mixins.Line],
            ["hover_", mixins.Fill],
            ["hover_", mixins.Hatch],
        ]);
        _c.define(({ Bool, Float, Ref, Or, NonNegative, Positive }) => ({
            top: [Or(Float, Ref(coordinate_1.Coordinate)), () => new node_1.Node({ target: "frame", symbol: "top" })],
            bottom: [Or(Float, Ref(coordinate_1.Coordinate)), () => new node_1.Node({ target: "frame", symbol: "bottom" })],
            left: [Or(Float, Ref(coordinate_1.Coordinate)), () => new node_1.Node({ target: "frame", symbol: "left" })],
            right: [Or(Float, Ref(coordinate_1.Coordinate)), () => new node_1.Node({ target: "frame", symbol: "right" })],
            top_units: [enums_1.CoordinateUnits, "data"],
            bottom_units: [enums_1.CoordinateUnits, "data"],
            left_units: [enums_1.CoordinateUnits, "data"],
            right_units: [enums_1.CoordinateUnits, "data"],
            top_limit: [Box.Limit, null],
            bottom_limit: [Box.Limit, null],
            left_limit: [Box.Limit, null],
            right_limit: [Box.Limit, null],
            min_width: [NonNegative(Float), 0],
            min_height: [NonNegative(Float), 0],
            max_width: [Positive(Float), Infinity],
            max_height: [Positive(Float), Infinity],
            border_radius: [kinds_1.BorderRadius, 0],
            editable: [Bool, false],
            resizable: [Box.Resizable, "all"],
            movable: [Box.Movable, "both"],
            symmetric: [Bool, false],
            use_handles: [Bool, false],
            handles: [Ref(BoxInteractionHandles), DEFAULT_HANDLES],
            inverted: [Bool, false],
        }));
        _c.internal(({ Str }) => ({
            tl_cursor: [Str, "nwse-resize"],
            tr_cursor: [Str, "nesw-resize"],
            bl_cursor: [Str, "nesw-resize"],
            br_cursor: [Str, "nwse-resize"],
            ew_cursor: [Str, "ew-resize"],
            ns_cursor: [Str, "ns-resize"],
            in_cursor: [Str, "move"],
        }));
        _c.override({
            fill_color: "#fff9ba",
            fill_alpha: 0.4,
            line_color: "#cccccc",
            line_alpha: 0.3,
            hover_fill_color: null,
            hover_fill_alpha: 0.4,
            hover_line_color: null,
            hover_line_alpha: 0.3,
        });
    })();
},
/* models/common/box_kinds.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const kinds_1 = require(21) /* ../../core/kinds */;
    const node_1 = require(59) /* ../coordinates/node */;
    exports.Corner = (0, kinds_1.Enum)("top_left", "top_right", "bottom_left", "bottom_right");
    exports.Edge = (0, kinds_1.Enum)("left", "right", "top", "bottom");
    exports.HitTarget = (0, kinds_1.Enum)(...exports.Corner, ...exports.Edge, "area");
    exports.Resizable = (0, kinds_1.Enum)("none", "left", "right", "top", "bottom", "x", "y", "all");
    exports.Movable = (0, kinds_1.Enum)("none", "x", "y", "both");
    exports.Limit = (0, kinds_1.Nullable)((0, kinds_1.Or)(kinds_1.Float, (0, kinds_1.Ref)(node_1.Node)));
},
/* models/annotations/color_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const base_color_bar_1 = require(170) /* ./base_color_bar */;
    const axes_1 = require(266) /* ../axes */;
    const formatters_1 = require(242) /* ../formatters */;
    const color_mapper_1 = require(216) /* ../mappers/color_mapper */;
    const mappers_1 = require(271) /* ../mappers */;
    const ranges_1 = require(256) /* ../ranges */;
    const scales_1 = require(254) /* ../scales */;
    const tickers_1 = require(200) /* ../tickers */;
    const array_1 = require(10) /* ../../core/util/array */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class ColorBarView extends base_color_bar_1.BaseColorBarView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.color_mapper.change, async () => {
                this._title_view.remove();
                this._axis_view.remove();
                this.initialize();
                await this.lazy_initialize();
                this.plot_view.invalidate_layout();
            });
            this.connect(this.model.color_mapper.metrics_change, () => this._metrics_changed());
            this.connect(this.model.properties.display_low.change, () => this._metrics_changed());
            this.connect(this.model.properties.display_high.change, () => this._metrics_changed());
        }
        get color_mapper() {
            // Color mapper that is used to render this colorbar.
            let mapper = this.model.color_mapper;
            if (mapper instanceof mappers_1.WeightedStackColorMapper) {
                mapper = mapper.alpha_mapper;
            }
            return mapper;
        }
        update_layout() {
            super.update_layout();
            this._set_canvas_image();
        }
        _create_axis() {
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                return new axes_1.CategoricalAxis();
            }
            else if (color_mapper instanceof mappers_1.LogColorMapper) {
                return new axes_1.LogAxis();
            }
            else {
                return new axes_1.LinearAxis();
            }
        }
        _create_formatter() {
            const { color_mapper } = this;
            if (this._ticker instanceof tickers_1.LogTicker) {
                return new formatters_1.LogTickFormatter();
            }
            else if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                return new formatters_1.CategoricalTickFormatter();
            }
            else {
                return new formatters_1.BasicTickFormatter();
            }
        }
        _create_major_range() {
            /*
            Creates and returns a scale instance that maps the `color_mapper` range
            (low to high) to a screen space range equal to the length of the ColorBar's
            scale image. The scale is used to calculate the tick coordinates in screen
            coordinates for plotting purposes.
        
            Note: the type of color_mapper has to match the type of scale (i.e.
            a LinearColorMapper will require a corresponding LinearScale instance).
            */
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                return new ranges_1.FactorRange({ factors: color_mapper.factors });
            }
            else if (color_mapper instanceof mappers_1.ContinuousColorMapper) {
                const { min, max } = this._continuous_metrics(color_mapper);
                return new ranges_1.Range1d({ start: min, end: max });
            }
            else {
                (0, assert_1.unreachable)();
            }
        }
        _create_major_scale() {
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.LinearColorMapper) {
                return new scales_1.LinearScale();
            }
            else if (color_mapper instanceof mappers_1.LogColorMapper) {
                return new scales_1.LogScale();
            }
            else if (color_mapper instanceof mappers_1.ScanningColorMapper) {
                return new scales_1.LinearInterpolationScale({ binning: this._scanning_binning(color_mapper) });
            }
            else if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                return new scales_1.CategoricalScale();
            }
            else {
                (0, assert_1.unreachable)();
            }
        }
        _create_ticker() {
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.LogColorMapper) {
                return new tickers_1.LogTicker();
            }
            else if (color_mapper instanceof mappers_1.ScanningColorMapper) {
                return new tickers_1.BinnedTicker({ mapper: color_mapper });
            }
            else if (color_mapper instanceof mappers_1.CategoricalColorMapper) {
                return new tickers_1.CategoricalTicker();
            }
            else {
                return new tickers_1.BasicTicker();
            }
        }
        // Return min and max metrics of ContinuousColorMapper, modified to account
        // for low and high display cutoffs.
        _continuous_metrics(color_mapper) {
            const { display_low, display_high } = this.model;
            let { min, max } = color_mapper.metrics;
            if (display_high != null && display_low != null && display_high < display_low) {
                // Empty color bar.
                this._index_low = 0;
                this._index_high = -1;
                return { min: NaN, max: NaN };
            }
            this._index_high = null;
            if (display_high != null) {
                const palette_length = color_mapper.palette.length;
                const index_high = color_mapper.value_to_index(display_high, palette_length);
                if (index_high < palette_length - 1) {
                    this._index_high = index_high;
                    max = color_mapper.index_to_value(index_high + 1);
                }
            }
            this._index_low = null;
            if (display_low != null) {
                const index_low = color_mapper.value_to_index(display_low, color_mapper.palette.length);
                if (index_low > 0) {
                    this._index_low = index_low;
                    min = color_mapper.index_to_value(index_low);
                }
            }
            return { min, max };
        }
        _get_major_size_factor() {
            return this.color_mapper.palette.length;
        }
        _metrics_changed() {
            const range = this._major_range;
            const scale = this._major_scale;
            const { color_mapper } = this;
            if (color_mapper instanceof mappers_1.ScanningColorMapper && scale instanceof scales_1.LinearInterpolationScale) {
                const binning = this._scanning_binning(color_mapper);
                scale.binning = binning;
                // Update the frame's LinearInterpolationScale and Range1d as they are
                // different objects to this._major_scale and this._major_range.
                const vertical = this.orientation == "vertical";
                const frame_scale = vertical ? this._frame_view.y_scale : this._frame_view.x_scale;
                if (frame_scale instanceof scales_1.LinearInterpolationScale) {
                    frame_scale.binning = binning;
                    const frame_range = vertical ? this._frame_view.y_range : this._frame_view.x_range;
                    if (frame_range instanceof ranges_1.Range1d) {
                        frame_range.start = binning[0];
                        frame_range.end = binning[binning.length - 1];
                    }
                }
            }
            else if (color_mapper instanceof mappers_1.ContinuousColorMapper && range instanceof ranges_1.Range1d) {
                const { min, max } = this._continuous_metrics(color_mapper);
                range.setv({ start: min, end: max });
            }
            this._set_canvas_image();
            this.plot_view.request_layout(); // this.request_paint()
        }
        _paint_colors(ctx, bbox) {
            const { x, y, width, height } = bbox;
            ctx.save();
            ctx.globalAlpha = this.model.scale_alpha;
            if (this._image != null) {
                ctx.imageSmoothingEnabled = false;
                ctx.drawImage(this._image, x, y, width, height);
            }
            if (this.visuals.bar_line.doit) {
                this.visuals.bar_line.set_value(ctx);
                ctx.strokeRect(x, y, width, height);
            }
            ctx.restore();
        }
        // Return binning array of ScanningColorMapper, modified to account for low
        // and high display cutoffs.
        _scanning_binning(color_mapper) {
            let { binning, force_low_cutoff } = color_mapper.metrics;
            const { display_high } = this.model;
            let { display_low } = this.model;
            if (force_low_cutoff && (display_low == null || color_mapper.metrics.min > display_low)) {
                // ScanningColorMapper overrides display_low, for example when EqHistColorMapper
                // uses rescale_discrete_levels=True.
                display_low = color_mapper.metrics.min;
            }
            if (display_high != null && display_low != null && display_high < display_low) {
                // Empty color bar.
                this._index_low = 0;
                this._index_high = -1;
                return [NaN];
            }
            this._index_high = null;
            if (display_high != null) {
                const index_high = color_mapper.value_to_index(display_high, binning.length);
                if (index_high < binning.length - 1) {
                    this._index_high = index_high;
                }
            }
            this._index_low = null;
            if (display_low != null) {
                const index_low = color_mapper.value_to_index(display_low, binning.length);
                if (index_low > 0) {
                    this._index_low = index_low;
                }
            }
            if (this._index_low != null || this._index_high != null) {
                // Slice binning array.
                const start = this._index_low != null ? this._index_low : 0;
                const end = this._index_high != null ? this._index_high + 1 : binning.length - 1;
                const n = end - start + 1;
                if (n > 0) {
                    const new_binning = new Array(n);
                    for (let i = 0; i < n; i++) {
                        new_binning[i] = binning[i + start];
                    }
                    binning = new_binning;
                }
                else {
                    binning = [NaN];
                }
            }
            return binning;
        }
        _set_canvas_image() {
            const { orientation } = this;
            let { palette } = this.color_mapper;
            if (this._index_high != null || this._index_low != null) {
                palette = palette.slice(this._index_low != null ? this._index_low : 0, this._index_high != null ? this._index_high + 1 : palette.length);
            }
            if (palette.length < 1) {
                // Early exit for empty color bar.
                this._image = null;
                return;
            }
            if (orientation == "vertical") {
                palette = (0, array_1.reversed)(palette);
            }
            const [w, h] = (() => {
                if (orientation == "vertical") {
                    return [1, palette.length];
                }
                else {
                    return [palette.length, 1];
                }
            })();
            const canvas = this._image = document.createElement("canvas");
            canvas.width = w;
            canvas.height = h;
            const image_ctx = canvas.getContext("2d");
            const image_data = image_ctx.getImageData(0, 0, w, h);
            // We always want to draw the entire palette linearly, so we create a new
            // LinearColorMapper instance and map a monotonic range of values with
            // length = palette.length to get each palette color in order.
            const cmap = new mappers_1.LinearColorMapper({ palette }).rgba_mapper;
            const buf8 = cmap.v_compute((0, array_1.range)(0, palette.length));
            image_data.data.set(buf8);
            image_ctx.putImageData(image_data, 0, 0);
        }
    }
    exports.ColorBarView = ColorBarView;
    ColorBarView.__name__ = "ColorBarView";
    class ColorBar extends base_color_bar_1.BaseColorBar {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ColorBar = ColorBar;
    _a = ColorBar;
    ColorBar.__name__ = "ColorBar";
    (() => {
        _a.prototype.default_view = ColorBarView;
        _a.define(({ Nullable, Float, Ref }) => ({
            color_mapper: [Ref(color_mapper_1.ColorMapper)],
            display_low: [Nullable(Float), null],
            display_high: [Nullable(Float), null],
        }));
    })();
},
/* models/axes/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var axis_1 = require(189) /* ./axis */;
    __esExport("Axis", axis_1.Axis);
    var categorical_axis_1 = require(267) /* ./categorical_axis */;
    __esExport("CategoricalAxis", categorical_axis_1.CategoricalAxis);
    var continuous_axis_1 = require(195) /* ./continuous_axis */;
    __esExport("ContinuousAxis", continuous_axis_1.ContinuousAxis);
    var datetime_axis_1 = require(268) /* ./datetime_axis */;
    __esExport("DatetimeAxis", datetime_axis_1.DatetimeAxis);
    var linear_axis_1 = require(194) /* ./linear_axis */;
    __esExport("LinearAxis", linear_axis_1.LinearAxis);
    var log_axis_1 = require(269) /* ./log_axis */;
    __esExport("LogAxis", log_axis_1.LogAxis);
    var mercator_axis_1 = require(270) /* ./mercator_axis */;
    __esExport("MercatorAxis", mercator_axis_1.MercatorAxis);
},
/* models/axes/categorical_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const axis_1 = require(189) /* ./axis */;
    const categorical_ticker_1 = require(201) /* ../tickers/categorical_ticker */;
    const categorical_tick_formatter_1 = require(243) /* ../formatters/categorical_tick_formatter */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const graphics_1 = require(180) /* ../../core/graphics */;
    const types_1 = require(8) /* ../../core/util/types */;
    class CategoricalAxisView extends axis_1.AxisView {
        _hit_value(sx, sy) {
            const [range] = this.ranges;
            const { start, end, span } = range;
            switch (this.dimension) {
                case 0: {
                    const { x0, width } = this.bbox;
                    return range.factor(span * (sx - x0) / width + start);
                }
                case 1: {
                    const { y0, height } = this.bbox;
                    return range.factor(end - span * (sy - y0) / height);
                }
            }
        }
        _paint() {
            const { tick_coords, extents } = this;
            const ctx = this.layer.ctx;
            super._paint();
            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;
            const { factors } = range;
            const { tops } = range.mapper;
            if (tops == null || tops.length < 2 || !this.visuals.separator_line.doit) {
                return;
            }
            const dim = this.dimension;
            const alt = 1 - dim;
            const coords = [[], []];
            let ind = 0;
            for (let i = 0; i < tops.length - 1; i++) {
                let first, last;
                for (let j = ind; j < factors.length; j++) {
                    if (factors[j][0] == tops[i + 1]) {
                        [first, last] = [factors[j - 1], factors[j]];
                        ind = j;
                        break;
                    }
                }
                const pt = (range.synthetic(first) + range.synthetic(last)) / 2;
                if (pt > start && pt < end) {
                    coords[dim].push(pt);
                    coords[alt].push(this.loc);
                }
            }
            const tex = this.extents.tick_label;
            this._draw_ticks(ctx, coords, -3, tex - 6, this.visuals.separator_line);
        }
        _draw_major_labels(ctx, extents, _tick_coords) {
            const info = this._get_factor_info();
            let standoff = extents.tick + this.model.major_label_standoff;
            for (let i = 0; i < info.length; i++) {
                const [labels, coords, orient, visuals] = info[i];
                this._draw_oriented_labels(ctx, labels, coords, orient, standoff, visuals);
                standoff += extents.tick_labels[i];
            }
        }
        _tick_label_extents() {
            const info = this._get_factor_info();
            const extents = [];
            for (const [labels, , orient, visuals] of info) {
                const extent = this._oriented_labels_extent(labels, orient, this.model.major_label_standoff, visuals);
                extents.push(extent);
            }
            return extents;
        }
        _get_factor_info() {
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            const loc = this.loc;
            const ticks = this.model.ticker.get_ticks(start, end, range, loc);
            const coords = this.tick_coords;
            const info = [];
            const map = (labels) => {
                return new graphics_1.GraphicsBoxes(labels.map((label) => (0, types_1.isString)(label) ? new graphics_1.TextBox({ text: label }) : label));
            };
            const format = (ticks) => {
                return map(this.model.formatter.doFormat(ticks, this));
            };
            switch (range.mapper.levels) {
                case 1: {
                    const major = ticks.major;
                    const labels = format(major);
                    info.push([labels, coords.major, this.model.major_label_orientation, this.visuals.major_label_text]);
                    break;
                }
                case 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]);
                    break;
                }
                case 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]);
                    break;
                }
            }
            return info;
        }
        get tick_coords() {
            const i = this.dimension;
            const j = 1 - i;
            const [range] = this.ranges;
            const [start, end] = this.computed_bounds;
            const ticks = this.model.ticker.get_ticks(start, end, range, this.loc);
            const coords = {
                major: [[], []],
                mids: [[], []],
                tops: [[], []],
                minor: [[], []],
            };
            coords.major[i] = ticks.major;
            coords.major[j] = ticks.major.map(() => this.loc);
            const { levels } = range.mapper;
            if (levels == 3) {
                coords.mids[i] = ticks.mids;
                coords.mids[j] = ticks.mids.map(() => this.loc);
            }
            if (levels > 1) {
                coords.tops[i] = ticks.tops;
                coords.tops[j] = ticks.tops.map(() => this.loc);
            }
            return coords;
        }
    }
    exports.CategoricalAxisView = CategoricalAxisView;
    CategoricalAxisView.__name__ = "CategoricalAxisView";
    class CategoricalAxis extends axis_1.Axis {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.CategoricalAxis = CategoricalAxis;
    _a = CategoricalAxis;
    CategoricalAxis.__name__ = "CategoricalAxis";
    (() => {
        _a.prototype.default_view = CategoricalAxisView;
        _a.mixins([
            ["separator_", mixins.Line],
            ["group_", mixins.Text],
            ["subgroup_", mixins.Text],
        ]);
        _a.define(({ Float, Or }) => ({
            group_label_orientation: [Or(enums_1.LabelOrientation, Float), "parallel"],
            subgroup_label_orientation: [Or(enums_1.LabelOrientation, Float), "parallel"],
        }));
        _a.override({
            ticker: () => new categorical_ticker_1.CategoricalTicker(),
            formatter: () => new categorical_tick_formatter_1.CategoricalTickFormatter(),
            separator_line_color: "lightgrey",
            separator_line_width: 2,
            group_text_font_style: "bold",
            group_text_font_size: "11px",
            group_text_color: "grey",
            subgroup_text_font_style: "bold",
            subgroup_text_font_size: "11px",
        });
    })();
},
/* models/axes/datetime_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const continuous_axis_1 = require(195) /* ./continuous_axis */;
    const datetime_tick_formatter_1 = require(244) /* ../formatters/datetime_tick_formatter */;
    const datetime_ticker_1 = require(204) /* ../tickers/datetime_ticker */;
    class DatetimeAxisView extends continuous_axis_1.ContinuousAxisView {
    }
    exports.DatetimeAxisView = DatetimeAxisView;
    DatetimeAxisView.__name__ = "DatetimeAxisView";
    class DatetimeAxis extends continuous_axis_1.ContinuousAxis {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DatetimeAxis = DatetimeAxis;
    _a = DatetimeAxis;
    DatetimeAxis.__name__ = "DatetimeAxis";
    (() => {
        _a.prototype.default_view = DatetimeAxisView;
        _a.override({
            ticker: () => new datetime_ticker_1.DatetimeTicker(),
            formatter: () => new datetime_tick_formatter_1.DatetimeTickFormatter(),
        });
    })();
},
/* models/axes/log_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const continuous_axis_1 = require(195) /* ./continuous_axis */;
    const log_tick_formatter_1 = require(250) /* ../formatters/log_tick_formatter */;
    const log_ticker_1 = require(211) /* ../tickers/log_ticker */;
    class LogAxisView extends continuous_axis_1.ContinuousAxisView {
        _hit_value(sx, sy) {
            const [range] = this.ranges;
            const { start, end } = range;
            const { log10 } = Math;
            switch (this.dimension) {
                case 0: {
                    const { x0, width } = this.bbox;
                    return log10(end / start) * (sx - x0) / width + log10(start);
                }
                case 1: {
                    const { y0, height } = this.bbox;
                    return log10(end) - log10(end / start) * (sy - y0) / height;
                }
            }
        }
    }
    exports.LogAxisView = LogAxisView;
    LogAxisView.__name__ = "LogAxisView";
    class LogAxis extends continuous_axis_1.ContinuousAxis {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LogAxis = LogAxis;
    _a = LogAxis;
    LogAxis.__name__ = "LogAxis";
    (() => {
        _a.prototype.default_view = LogAxisView;
        _a.override({
            ticker: () => new log_ticker_1.LogTicker(),
            formatter: () => new log_tick_formatter_1.LogTickFormatter(),
        });
    })();
},
/* models/axes/mercator_axis.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const linear_axis_1 = require(194) /* ./linear_axis */;
    const mercator_tick_formatter_1 = require(251) /* ../formatters/mercator_tick_formatter */;
    const mercator_ticker_1 = require(212) /* ../tickers/mercator_ticker */;
    class MercatorAxisView extends linear_axis_1.LinearAxisView {
    }
    exports.MercatorAxisView = MercatorAxisView;
    MercatorAxisView.__name__ = "MercatorAxisView";
    class MercatorAxis extends linear_axis_1.LinearAxis {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MercatorAxis = MercatorAxis;
    _a = MercatorAxis;
    MercatorAxis.__name__ = "MercatorAxis";
    (() => {
        _a.prototype.default_view = MercatorAxisView;
        _a.override({
            ticker: () => new mercator_ticker_1.MercatorTicker({ dimension: "lat" }),
            formatter: () => new mercator_tick_formatter_1.MercatorTickFormatter({ dimension: "lat" }),
        });
    })();
},
/* models/mappers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var categorical_color_mapper_1 = require(272) /* ./categorical_color_mapper */;
    __esExport("CategoricalColorMapper", categorical_color_mapper_1.CategoricalColorMapper);
    var categorical_marker_mapper_1 = require(274) /* ./categorical_marker_mapper */;
    __esExport("CategoricalMarkerMapper", categorical_marker_mapper_1.CategoricalMarkerMapper);
    var categorical_pattern_mapper_1 = require(275) /* ./categorical_pattern_mapper */;
    __esExport("CategoricalPatternMapper", categorical_pattern_mapper_1.CategoricalPatternMapper);
    var continuous_color_mapper_1 = require(215) /* ./continuous_color_mapper */;
    __esExport("ContinuousColorMapper", continuous_color_mapper_1.ContinuousColorMapper);
    var color_mapper_1 = require(216) /* ./color_mapper */;
    __esExport("ColorMapper", color_mapper_1.ColorMapper);
    var linear_color_mapper_1 = require(276) /* ./linear_color_mapper */;
    __esExport("LinearColorMapper", linear_color_mapper_1.LinearColorMapper);
    var log_color_mapper_1 = require(277) /* ./log_color_mapper */;
    __esExport("LogColorMapper", log_color_mapper_1.LogColorMapper);
    var scanning_color_mapper_1 = require(214) /* ./scanning_color_mapper */;
    __esExport("ScanningColorMapper", scanning_color_mapper_1.ScanningColorMapper);
    var eqhist_color_mapper_1 = require(278) /* ./eqhist_color_mapper */;
    __esExport("EqHistColorMapper", eqhist_color_mapper_1.EqHistColorMapper);
    var stack_color_mapper_1 = require(279) /* ./stack_color_mapper */;
    __esExport("StackColorMapper", stack_color_mapper_1.StackColorMapper);
    var weighted_stack_color_mapper_1 = require(280) /* ./weighted_stack_color_mapper */;
    __esExport("WeightedStackColorMapper", weighted_stack_color_mapper_1.WeightedStackColorMapper);
},
/* models/mappers/categorical_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const categorical_mapper_1 = require(273) /* ./categorical_mapper */;
    const color_mapper_1 = require(216) /* ./color_mapper */;
    const factor_range_1 = require(109) /* ../ranges/factor_range */;
    class CategoricalColorMapper extends color_mapper_1.ColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(data, values, palette, { nan_color }) {
            (0, categorical_mapper_1.cat_v_compute)(data, this.factors, palette, values, this.start, this.end, nan_color);
        }
    }
    exports.CategoricalColorMapper = CategoricalColorMapper;
    _a = CategoricalColorMapper;
    CategoricalColorMapper.__name__ = "CategoricalColorMapper";
    (() => {
        _a.define(({ Float, Nullable }) => ({
            factors: [factor_range_1.FactorSeq],
            start: [Float, 0],
            end: [Nullable(Float), null],
        }));
    })();
},
/* models/mappers/categorical_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports._cat_equals = _cat_equals;
    exports.cat_v_compute = cat_v_compute;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const types_1 = require(8) /* ../../core/util/types */;
    function _cat_equals(a, b) {
        if (a.length != b.length) {
            return false;
        }
        const n = a.length;
        for (let i = 0; i < n; i++) {
            if (a[i] !== b[i]) {
                return false;
            }
        }
        return true;
    }
    function cat_v_compute(data, factors, targets, values, start, end, extra_value) {
        let i = 0;
        for (const item of data) {
            let key;
            if (!(0, types_1.isArray)(item)) {
                key = (0, arrayable_1.index_of)(factors, item);
            }
            else {
                const d = item.slice(start, end ?? undefined);
                if (d.length == 1) {
                    key = (0, arrayable_1.index_of)(factors, d[0]);
                }
                else {
                    key = (0, arrayable_1.find_index)(factors, (x) => _cat_equals(x, d));
                }
            }
            const value = key in targets ? targets[key] : extra_value;
            values[i++] = value;
        }
    }
},
/* models/mappers/categorical_marker_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const categorical_mapper_1 = require(273) /* ./categorical_mapper */;
    const factor_range_1 = require(109) /* ../ranges/factor_range */;
    const mapper_1 = require(217) /* ./mapper */;
    const enums_1 = require(20) /* ../../core/enums */;
    class CategoricalMarkerMapper extends mapper_1.Mapper {
        constructor(attrs) {
            super(attrs);
        }
        v_compute(xs) {
            const values = new Array(xs.length);
            (0, categorical_mapper_1.cat_v_compute)(xs, this.factors, this.markers, values, this.start, this.end, this.default_value);
            return values;
        }
    }
    exports.CategoricalMarkerMapper = CategoricalMarkerMapper;
    _a = CategoricalMarkerMapper;
    CategoricalMarkerMapper.__name__ = "CategoricalMarkerMapper";
    (() => {
        _a.define(({ Float, List, Nullable }) => ({
            factors: [factor_range_1.FactorSeq],
            markers: [List(enums_1.MarkerType)],
            start: [Float, 0],
            end: [Nullable(Float), null],
            default_value: [enums_1.MarkerType, "circle"],
        }));
    })();
},
/* models/mappers/categorical_pattern_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const categorical_mapper_1 = require(273) /* ./categorical_mapper */;
    const factor_range_1 = require(109) /* ../ranges/factor_range */;
    const mapper_1 = require(217) /* ./mapper */;
    const enums_1 = require(20) /* ../../core/enums */;
    class CategoricalPatternMapper extends mapper_1.Mapper {
        constructor(attrs) {
            super(attrs);
        }
        v_compute(xs) {
            const values = new Array(xs.length);
            (0, categorical_mapper_1.cat_v_compute)(xs, this.factors, this.patterns, values, this.start, this.end, this.default_value);
            return values;
        }
    }
    exports.CategoricalPatternMapper = CategoricalPatternMapper;
    _a = CategoricalPatternMapper;
    CategoricalPatternMapper.__name__ = "CategoricalPatternMapper";
    (() => {
        _a.define(({ Float, List, Nullable }) => ({
            factors: [factor_range_1.FactorSeq],
            patterns: [List(enums_1.HatchPatternType)],
            start: [Float, 0],
            end: [Nullable(Float), null],
            default_value: [enums_1.HatchPatternType, " "],
        }));
    })();
},
/* models/mappers/linear_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_color_mapper_1 = require(215) /* ./continuous_color_mapper */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const math_1 = require(11) /* ../../core/util/math */;
    class LinearColorMapper extends continuous_color_mapper_1.ContinuousColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        scan(data, n) {
            const low = this.low != null ? this.low : (0, arrayable_1.min)(data);
            const high = this.high != null ? this.high : (0, arrayable_1.max)(data);
            const norm_factor = 1 / (high - low);
            const normed_interval = 1 / n;
            return { max: high, min: low, norm_factor, normed_interval };
        }
        index_to_value(index) {
            const scan_data = this._scan_data;
            return scan_data.min + scan_data.normed_interval * index / scan_data.norm_factor;
        }
        value_to_index(value, palette_length) {
            const scan_data = this._scan_data;
            // This handles the edge case where value == high, since the code below maps
            // values exactly equal to high to palette.length when it should be one less.
            if (value == scan_data.max) {
                return palette_length - 1;
            }
            const normed_value = (value - scan_data.min) * scan_data.norm_factor;
            const index = Math.floor(normed_value / scan_data.normed_interval);
            return (0, math_1.clamp)(index, -1, palette_length);
        }
    }
    exports.LinearColorMapper = LinearColorMapper;
    LinearColorMapper.__name__ = "LinearColorMapper";
},
/* models/mappers/log_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const continuous_color_mapper_1 = require(215) /* ./continuous_color_mapper */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const math_1 = require(11) /* ../../core/util/math */;
    class LogColorMapper extends continuous_color_mapper_1.ContinuousColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        scan(data, n) {
            const low = this.low != null ? this.low : (0, arrayable_1.min)(data);
            const high = this.high != null ? this.high : (0, arrayable_1.max)(data);
            const scale = n / Math.log(high / low); // subtract the low offset
            return { max: high, min: low, scale };
        }
        index_to_value(index) {
            const scan_data = this._scan_data;
            return scan_data.min * Math.exp(index / scan_data.scale);
        }
        value_to_index(value, palette_length) {
            const scan_data = this._scan_data;
            // This handles the edge case where value == high, since the code below maps
            // values exactly equal to high to palette.length when it should be one less.
            if (value == scan_data.max) {
                return palette_length - 1;
            }
            else if (value > scan_data.max) {
                return palette_length;
            }
            else if (value < scan_data.min) {
                return -1;
            }
            const log = Math.log(value / scan_data.min);
            const index = Math.floor(log * scan_data.scale);
            return (0, math_1.clamp)(index, -1, palette_length);
        }
    }
    exports.LogColorMapper = LogColorMapper;
    LogColorMapper.__name__ = "LogColorMapper";
},
/* models/mappers/eqhist_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const scanning_color_mapper_1 = require(214) /* ./scanning_color_mapper */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const array_1 = require(10) /* ../../core/util/array */;
    class EqHistColorMapper extends scanning_color_mapper_1.ScanningColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        // Public for unit tests
        /*protected*/ scan(data, n) {
            const low = this.low != null ? this.low : (0, arrayable_1.min)(data);
            const high = this.high != null ? this.high : (0, arrayable_1.max)(data);
            const nbins = this.bins;
            const eq_bin_edges = (0, array_1.linspace)(low, high, nbins + 1);
            const full_hist = (0, arrayable_1.bin_counts)(data, eq_bin_edges);
            // Remove empty bins from histogram to make interpolation more accurate and faster
            // 1) Count non-zeros
            let nhist = 0;
            for (let i = 0; i < nbins; i++) {
                if (full_hist[i] != 0) {
                    nhist++;
                }
            }
            // 2) Remove zeros, leaving extra element at beginning for rescale_discrete_levels
            const hist = new Array(nhist + 1);
            const eq_bin_centers = new Array(nhist + 1);
            for (let i = 0, j = 1; i < nbins; i++) {
                if (full_hist[i] != 0) {
                    hist[j] = full_hist[i];
                    eq_bin_centers[j] = (eq_bin_edges[i] + eq_bin_edges[i + 1]) / 2;
                    j++;
                }
            }
            hist[0] = 0;
            eq_bin_centers[0] = 2 * eq_bin_centers[1] - eq_bin_centers[nhist];
            // CDF scaled from 0 to 1 except for first value
            const cdf = (0, array_1.cumsum)(hist);
            const lo = cdf[1];
            const diff = cdf[nhist] - lo;
            for (let i = 1; i <= nhist; i++) {
                cdf[i] = (cdf[i] - lo) / diff;
            }
            cdf[0] = -1.0;
            let { rescale_discrete_levels } = this;
            let lower_span = 0;
            if (rescale_discrete_levels) {
                const discrete_levels = nhist;
                // Straight line y = mx + c through (2, 1.5) and (100, 1) where
                // x is number of discrete_levels and y is lower span limit.
                const m = -0.5 / 98.0; // (y[1] - y[0]) / (x[1] - x[0])
                const c = 1.5 - 2 * m; // y[0] - m*x[0]
                const multiple = m * discrete_levels + c;
                if (multiple > 1) {
                    lower_span = 1 - multiple;
                }
                else {
                    rescale_discrete_levels = false;
                }
            }
            // Color bin boundaries are equally spaced in CDF
            const cdf_bins = (0, array_1.linspace)(lower_span, 1, n + 1);
            const binning = (0, arrayable_1.interpolate)(cdf_bins, cdf, eq_bin_centers);
            // Ensure binning limits are correct
            let force_low_cutoff = false;
            if (rescale_discrete_levels) {
                const low_cutoff_index = (0, arrayable_1.sorted_index)(binning, low);
                // This index satisfies: binning[low_cutoff_index-1] < low <= binning[low_cutoff_index]
                // If low < binning[low_cutoff_index] then set previous bin to low so that the
                // lowest colorbar label equals low rather than than the arbitrary value set by
                // rescale_discrete_levels. This ensures the bottom colorbar label is correct.
                // If low == binning[low_cutoff_index] then do nothing as label is already correct.
                if (low < binning[low_cutoff_index] && low_cutoff_index > 0) {
                    binning[low_cutoff_index - 1] = low;
                }
                force_low_cutoff = true;
            }
            else {
                binning[0] = low;
            }
            binning[binning.length - 1] = high;
            return { min: low, max: high, binning, force_low_cutoff };
        }
    }
    exports.EqHistColorMapper = EqHistColorMapper;
    _a = EqHistColorMapper;
    EqHistColorMapper.__name__ = "EqHistColorMapper";
    (() => {
        _a.define(({ Bool, Int }) => ({
            bins: [Int, 256 * 256],
            rescale_discrete_levels: [Bool, false],
        }));
    })();
},
/* models/mappers/stack_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const color_mapper_1 = require(216) /* ./color_mapper */;
    class StackColorMapper extends color_mapper_1.ColorMapper {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.StackColorMapper = StackColorMapper;
    StackColorMapper.__name__ = "StackColorMapper";
},
/* models/mappers/weighted_stack_color_mapper.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const color_mapper_1 = require(216) /* ./color_mapper */;
    const continuous_color_mapper_1 = require(215) /* ./continuous_color_mapper */;
    const stack_color_mapper_1 = require(279) /* ./stack_color_mapper */;
    const types_1 = require(24) /* ../../core/types */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const color_1 = require(22) /* ../../core/util/color */;
    class WeightedStackColorMapper extends stack_color_mapper_1.StackColorMapper {
        constructor(attrs) {
            super(attrs);
        }
        // Weighted mix of colors.
        _mix_colors(colors_rgba, nan_color, weights, total_weight) {
            if (isNaN(total_weight)) {
                return nan_color;
            }
            let r = 0.0, g = 0.0, b = 0.0, a = 0.0;
            const n = weights.length;
            if (total_weight != 0) {
                for (let i = 0; i < n; i++) {
                    if (isNaN(weights[i])) {
                        continue;
                    }
                    const weight = weights[i] / total_weight;
                    r += colors_rgba[i * 4] * weight;
                    g += colors_rgba[i * 4 + 1] * weight;
                    b += colors_rgba[i * 4 + 2] * weight;
                    a += colors_rgba[i * 4 + 3] * weight;
                }
            }
            else {
                // Special case if total is zero then take mean color of all non-nan categories.
                let count = 0;
                for (let i = 0; i < n; i++) {
                    if (weights[i] == 0) {
                        r += colors_rgba[i * 4];
                        g += colors_rgba[i * 4 + 1];
                        b += colors_rgba[i * 4 + 2];
                        a += colors_rgba[i * 4 + 3];
                        count++;
                    }
                }
                r /= count;
                g /= count;
                b /= count;
                a /= count;
            }
            return (0, color_1.encode_rgba)([(0, color_1.byte)(r), (0, color_1.byte)(g), (0, color_1.byte)(b), (0, color_1.byte)(a)]);
        }
        _v_compute(_data, _values, _palette, _colors) {
            (0, assert_1.unreachable)();
        }
        _v_compute_uint32(data, values, palette, colors) {
            const n = values.length;
            const ncolor = palette.length;
            const nstack = data.length / n;
            (0, assert_1.assert)(nstack == ncolor, `Expected ${nstack} not ${ncolor} colors in palette`);
            // Color mixing is performed separately on each RGBA component, decode them just once
            const palette_as_rgba = new types_1.RGBAArray(ncolor * 4);
            for (let i = 0; i < ncolor; i++) {
                const [r, g, b, a] = (0, color_1.decode_rgba)(palette[i]);
                palette_as_rgba[i * 4] = r;
                palette_as_rgba[i * 4 + 1] = g;
                palette_as_rgba[i * 4 + 2] = b;
                palette_as_rgba[i * 4 + 3] = a;
            }
            // If color_baseline not specified, use nan-aware minimum of data.
            const color_baseline = this.color_baseline;
            const baseline = color_baseline == null ? (0, arrayable_1.min)(data) : color_baseline;
            // Mix colors based on weights.
            const { nan_color } = colors;
            const totals = new Array(n); // Array of totals per pixel
            const weights = new Array(ncolor); // For single pixel
            for (let i = 0; i < n; i++) {
                let total = NaN;
                for (let icol = 0; icol < ncolor; icol++) {
                    const index = i * ncolor + icol;
                    // If baseline non-zero, subtract it and clip to zero. Datashader only clips non-integers.
                    const val = baseline == 0 ? data[index] : Math.max(data[index] - baseline, 0);
                    weights[icol] = val;
                    if (!isNaN(val)) {
                        if (isNaN(total)) {
                            total = val;
                        }
                        else {
                            total += val;
                        }
                    }
                }
                values[i] = this._mix_colors(palette_as_rgba, nan_color, weights, total);
                totals[i] = total + baseline * ncolor;
            }
            // Calculate alphas using alpha_mapper.
            const alpha_palette = (0, color_mapper_1._convert_palette)(this.alpha_mapper.palette);
            const alphas = new Uint32Array(n);
            this.alpha_mapper._v_compute(totals, alphas, alpha_palette, colors);
            // Combine RGBA and alphas.
            for (let i = 0; i < n; i++) {
                const alpha = (0, color_1.byte)((values[i] & 0xff) * (alphas[i] & 0xff) / 255.0);
                values[i] = (values[i] & 0xffffff00) | alpha;
            }
        }
    }
    exports.WeightedStackColorMapper = WeightedStackColorMapper;
    _a = WeightedStackColorMapper;
    WeightedStackColorMapper.__name__ = "WeightedStackColorMapper";
    (() => {
        _a.define(({ List, Nullable, Float, Ref, Str }) => ({
            alpha_mapper: [Ref(continuous_color_mapper_1.ContinuousColorMapper)],
            color_baseline: [Nullable(Float), null],
            stack_labels: [Nullable(List(Str)), null],
        }));
    })();
},
/* models/annotations/contour_color_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const base_color_bar_1 = require(170) /* ./base_color_bar */;
    const ranges_1 = require(256) /* ../ranges */;
    const glyph_renderer_1 = require(218) /* ../renderers/glyph_renderer */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class ContourColorBarView extends base_color_bar_1.BaseColorBarView {
        *children() {
            yield* super.children();
            yield this._fill_view;
            yield this._line_view;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { fill_renderer, line_renderer } = this.model;
            this._fill_view = await (0, build_views_1.build_view)(fill_renderer, { parent: this.parent });
            this._line_view = await (0, build_views_1.build_view)(line_renderer, { parent: this.parent });
        }
        remove() {
            this._fill_view.remove();
            this._line_view.remove();
            super.remove();
        }
        _create_major_range() {
            const levels = this.model.levels;
            if (levels.length > 0) {
                return new ranges_1.Range1d({ start: levels[0], end: levels[levels.length - 1] });
            }
            else {
                return new ranges_1.Range1d({ start: 0, end: 1 });
            }
        }
        _paint_colors(ctx, bbox) {
            const vertical = this.orientation == "vertical";
            const levels = this.model.levels;
            const scale = this._major_scale;
            scale.source_range = this._major_range;
            if (vertical) {
                scale.target_range = new ranges_1.Range1d({ start: bbox.bottom, end: bbox.top });
            }
            else {
                scale.target_range = new ranges_1.Range1d({ start: bbox.left, end: bbox.right });
            }
            const scaled_levels = scale.v_compute(levels);
            const multi_polygons = this._fill_view.glyph;
            const nfill = multi_polygons.data_size;
            if (nfill > 0) {
                (0, assert_1.assert)(levels.length == nfill + 1, "Inconsistent number of filled contour levels");
                ctx.save();
                for (let i = 0; i < nfill; i++) {
                    ctx.beginPath();
                    if (vertical) {
                        ctx.rect(bbox.left, scaled_levels[i], bbox.width, scaled_levels[i + 1] - scaled_levels[i]);
                    }
                    else {
                        ctx.rect(scaled_levels[i], bbox.top, scaled_levels[i + 1] - scaled_levels[i], bbox.height);
                    }
                    multi_polygons.visuals.fill.apply(ctx, i);
                    multi_polygons.visuals.hatch.apply(ctx, i);
                }
                ctx.restore();
            }
            const multi_line = this._line_view.glyph;
            const nline = multi_line.data_size;
            if (nline > 0) {
                (0, assert_1.assert)(levels.length == nline, "Inconsistent number of line contour levels");
                ctx.save();
                for (let i = 0; i < nline; i++) {
                    ctx.beginPath();
                    if (vertical) {
                        ctx.moveTo(bbox.left, scaled_levels[i]);
                        ctx.lineTo(bbox.right, scaled_levels[i]);
                    }
                    else {
                        ctx.moveTo(scaled_levels[i], bbox.bottom);
                        ctx.lineTo(scaled_levels[i], bbox.top);
                    }
                    multi_line.visuals.line.set_vectorize(ctx, i);
                    ctx.stroke();
                }
                ctx.restore();
            }
        }
    }
    exports.ContourColorBarView = ContourColorBarView;
    ContourColorBarView.__name__ = "ContourColorBarView";
    class ContourColorBar extends base_color_bar_1.BaseColorBar {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ContourColorBar = ContourColorBar;
    _a = ContourColorBar;
    ContourColorBar.__name__ = "ContourColorBar";
    (() => {
        _a.prototype.default_view = ContourColorBarView;
        _a.define(({ List, Float, Ref }) => ({
            fill_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
            line_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
            levels: [List(Float), []],
        }));
    })();
},
/* models/annotations/label.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const text_annotation_1 = require(172) /* ./text_annotation */;
    const math_1 = require(11) /* ../../core/util/math */;
    const enums_1 = require(20) /* ../../core/enums */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const affine_1 = require(114) /* ../../core/util/affine */;
    const kinds_1 = require(185) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(186) /* ../common/resolve */);
    const coordinate_1 = require(60) /* ../coordinates/coordinate */;
    function xy(x, y) {
        return { x, y };
    }
    class LabelView extends text_annotation_1.TextAnnotationView {
        constructor() {
            super(...arguments);
            this._pan_state = null;
        }
        get mappers() {
            function mapper(units, scale, view, canvas) {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            }
            const overlay = this.model;
            const parent = this.layout ?? this.plot_view.frame;
            const { x_scale, y_scale } = this.coordinates;
            const { x_view, y_view } = parent.bbox;
            const { x_screen, y_screen } = this.plot_view.canvas.bbox;
            const xy = {
                x: mapper(overlay.x_units, x_scale, x_view, x_screen),
                y: mapper(overlay.y_units, y_scale, y_view, y_screen),
            };
            return xy;
        }
        get anchor() {
            const { align, baseline } = this.visuals.text.values();
            return resolve.text_anchor(this.model.anchor, align, baseline);
        }
        get angle() {
            const { angle, angle_units, direction } = this.model;
            return (0, math_1.compute_angle)(angle, angle_units, direction);
        }
        get origin() {
            const { mappers } = this;
            const { x, y, x_offset, y_offset } = this.model;
            const compute = (dim, value, mapper) => {
                return value instanceof coordinate_1.Coordinate ? this.resolve_as_scalar(value, dim) : mapper.compute(value);
            };
            const sx = compute("x", x, mappers.x) + x_offset;
            const sy = compute("y", y, mappers.y) - y_offset; // TODO this needs to be unified with the rest of bokehjs
            return { sx, sy };
        }
        interactive_hit(sx, sy) {
            if (!this.model.visible || !this.model.editable) {
                return false;
            }
            return this._hit_test(sx, sy) == "area";
        }
        _hit_test(cx, cy) {
            const { sx, sy, anchor, angle, width, height } = this._rect;
            const { x, y } = (0, affine_1.rotate_around)(xy(cx, cy), xy(sx, sy), -angle);
            const left = sx - anchor.x * width;
            const top = sy - anchor.y * height;
            const right = left + width;
            const bottom = top + height;
            if (left <= x && x <= right && top <= y && y <= bottom) {
                return "area";
            }
            else {
                return null;
            }
        }
        _can_hit(_target) {
            return true;
        }
        on_pan_start(ev) {
            if (this.model.visible && this.model.editable) {
                const { sx, sy } = ev;
                const target = this._hit_test(sx, sy);
                if (target != null && this._can_hit(target)) {
                    this._pan_state = {
                        angle: this.angle,
                        base: { sx, sy },
                        target,
                        action: "rotate",
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]);
                    return true;
                }
            }
            return false;
        }
        on_pan(ev) {
            (0, assert_1.assert)(this._pan_state != null);
            const { dx, dy } = ev;
            const { angle, base } = this._pan_state;
            const { origin } = this;
            const angle0 = (0, math_1.atan2)([origin.sx, origin.sy], [base.sx, base.sy]);
            const angle1 = (0, math_1.atan2)([origin.sx, origin.sy], [base.sx + dx, base.sy + dy]);
            const da = angle1 - angle0;
            const na = angle + da;
            const nna = na % (2 * Math.PI);
            const { angle_units, direction } = this.model;
            this.model.angle = (0, math_1.invert_angle)(nna, angle_units, direction);
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        on_pan_end(ev) {
            this._pan_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        cursor(sx, sy) {
            const target = this._pan_state?.target ?? this._hit_test(sx, sy);
            if (target == null || !this._can_hit(target)) {
                return null;
            }
            return "var(--bokeh-cursor-rotate)";
        }
    }
    exports.LabelView = LabelView;
    LabelView.__name__ = "LabelView";
    class Label extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
            this.pan = new signaling_1.Signal(this, "pan");
        }
    }
    exports.Label = Label;
    _a = Label;
    Label.__name__ = "Label";
    (() => {
        _a.prototype.default_view = LabelView;
        _a.define(({ Bool, Float, Angle, Or, Ref }) => ({
            anchor: [kinds_1.TextAnchor, "auto"],
            x: [Or(Float, Ref(coordinate_1.Coordinate))],
            y: [Or(Float, Ref(coordinate_1.Coordinate))],
            x_units: [enums_1.CoordinateUnits, "data"],
            y_units: [enums_1.CoordinateUnits, "data"],
            x_offset: [Float, 0],
            y_offset: [Float, 0],
            angle: [Angle, 0],
            angle_units: [enums_1.AngleUnits, "rad"],
            direction: [enums_1.Direction, "anticlock"],
            editable: [Bool, false],
        }));
    })();
},
/* models/annotations/label_set.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(127) /* ./data_annotation */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const graphics_1 = require(180) /* ../../core/graphics */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const types_1 = require(24) /* ../../core/types */;
    class LabelSetView extends data_annotation_1.DataAnnotationView {
        map_data() {
            const { x_scale, y_scale } = this.coordinates;
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            this.sx = (() => {
                switch (this.model.x_units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._x);
                    case "screen":
                        return panel.bbox.xview.v_compute(this._x);
                    case "data":
                        return x_scale.v_compute(this._x);
                }
            })();
            this.sy = (() => {
                switch (this.model.y_units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._y);
                    case "screen":
                        return panel.bbox.yview.v_compute(this._y);
                    case "data":
                        return y_scale.v_compute(this._y);
                }
            })();
        }
        _paint_data() {
            const { ctx } = this.layer;
            for (let i = 0, end = this.text.length; i < end; i++) {
                const x_offset_i = this.x_offset.get(i);
                const y_offset_i = this.y_offset.get(i);
                const sx_i = this.sx[i] + x_offset_i;
                const sy_i = this.sy[i] - y_offset_i;
                const angle_i = this.angle.get(i);
                const text_i = this.text.get(i);
                if (!isFinite(sx_i + sy_i + angle_i) || text_i == null) {
                    continue;
                }
                this._paint_text(ctx, i, `${text_i}`, sx_i, sy_i, angle_i);
            }
        }
        _paint_text(ctx, i, text, sx, sy, angle) {
            const graphics = new graphics_1.TextBox({ text });
            graphics.angle = angle;
            graphics.position = { sx, sy };
            graphics.visuals = this.visuals.text.values(i);
            const { background_fill, border_line } = this.visuals;
            if (background_fill.doit || border_line.doit) {
                const { p0, p1, p2, p3 } = graphics.rect();
                ctx.beginPath();
                ctx.moveTo(p0.x, p0.y);
                ctx.lineTo(p1.x, p1.y);
                ctx.lineTo(p2.x, p2.y);
                ctx.lineTo(p3.x, p3.y);
                ctx.closePath();
                this.visuals.background_fill.apply(ctx, i);
                this.visuals.border_line.apply(ctx, i);
            }
            if (this.visuals.text.doit) {
                graphics.paint(ctx);
            }
        }
    }
    exports.LabelSetView = LabelSetView;
    LabelSetView.__name__ = "LabelSetView";
    class LabelSet extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LabelSet = LabelSet;
    _a = LabelSet;
    LabelSet.__name__ = "LabelSet";
    (() => {
        _a.prototype.default_view = LabelSetView;
        _a.mixins([
            mixins.TextVector,
            ["border_", mixins.LineVector],
            ["background_", mixins.FillVector],
        ]);
        _a.define(() => ({
            x: [p.XCoordinateSpec, { field: "x" }],
            y: [p.YCoordinateSpec, { field: "y" }],
            x_units: [enums_1.CoordinateUnits, "data"],
            y_units: [enums_1.CoordinateUnits, "data"],
            text: [p.NullStringSpec, { field: "text" }],
            angle: [p.AngleSpec, 0],
            x_offset: [p.NumberSpec, { value: 0 }],
            y_offset: [p.NumberSpec, { value: 0 }],
        }));
        _a.override({
            background_fill_color: null,
            border_line_color: null,
        });
    })();
},
/* models/annotations/legend.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(81) /* ./annotation */;
    const legend_item_1 = require(285) /* ./legend_item */;
    const enums_1 = require(20) /* ../../core/enums */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const signaling_1 = require(15) /* ../../core/signaling */;
    const side_panel_1 = require(173) /* ../../core/layout/side_panel */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const types_1 = require(8) /* ../../core/util/types */;
    const graphics_1 = require(180) /* ../../core/graphics */;
    const layout_1 = require(257) /* ../../core/layout */;
    const bokeh_events_1 = require(53) /* ../../core/bokeh_events */;
    const { max, ceil } = Math;
    class LegendEntry extends layout_1.ContentLayoutable {
        constructor(item, label, text, settings) {
            super();
            this.item = item;
            this.label = label;
            this.text = text;
            this.settings = settings;
        }
        get field() {
            return this.item.get_field_from_label_prop();
        }
        _content_size() {
            const text = this.text.size();
            const { glyph_width, glyph_height, label_standoff, label_width, label_height } = this.settings;
            const width = glyph_width + label_standoff + max(text.width, label_width);
            const height = max(glyph_height, text.height, label_height);
            return new layout_1.Sizeable({ width, height });
        }
    }
    LegendEntry.__name__ = "LegendEntry";
    class LegendView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this._bbox = new bbox_1.BBox();
        }
        _get_size() {
            const { width, height } = this.bbox;
            const { margin } = this.model;
            return {
                width: width + 2 * margin,
                height: height + 2 * margin,
            };
        }
        update_layout() {
            this.update_geometry();
            const { panel } = this;
            if (panel != null) {
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size());
            }
            else {
                this.layout = undefined;
            }
        }
        connect_signals() {
            super.connect_signals();
            const repaint = () => this.request_paint();
            this.connect(this.model.change, repaint);
            this.connect(this.model.item_change, repaint);
        }
        get bbox() {
            return this._bbox;
        }
        get padding() {
            return this.model.border_line_color != null ? this.model.padding : 0;
        }
        update_geometry() {
            super.update_geometry();
            const { spacing, orientation } = this.model;
            const vertical = orientation == "vertical";
            const { padding } = this;
            const left = padding;
            const top = padding;
            const { title } = this.model;
            const title_box = new graphics_1.TextBox({ text: title ?? "" });
            title_box.position = { sx: 0, sy: 0, x_anchor: "left", y_anchor: "top" };
            title_box.visuals = this.visuals.title_text.values();
            const _title_panel = new side_panel_1.SidePanel(this.model.title_location);
            title_box.angle = _title_panel.get_label_angle_heuristic("parallel");
            const entries = [];
            for (const item of this.model.items) {
                // Set a backref on render so that items can later signal item_change
                // upates on the model to trigger a re-render.
                item.legend = this.model;
                const labels = item.get_labels_list_from_label_prop();
                for (const label of labels) {
                    const text_box = new graphics_1.TextBox({ text: `${label}` }); // XXX: not always string
                    text_box.position = { sx: 0, sy: 0, x_anchor: "left", y_anchor: "center" };
                    text_box.visuals = this.visuals.label_text.values();
                    const layout = new LegendEntry(item, label, text_box, this.model);
                    layout.set_sizing({ visible: item.visible });
                    entries.push({ layout, row: 0, col: 0 });
                }
            }
            const { ncols, nrows } = (() => {
                let { ncols, nrows } = this.model;
                const n = entries.length;
                if (vertical) {
                    if (nrows != "auto") {
                    }
                    else if (ncols != "auto") {
                        nrows = ceil(n / ncols);
                    }
                    else {
                        nrows = Infinity;
                    }
                    ncols = Infinity;
                }
                else {
                    if (ncols != "auto") {
                    }
                    else if (nrows != "auto") {
                        ncols = ceil(n / nrows);
                    }
                    else {
                        ncols = Infinity;
                    }
                    nrows = Infinity;
                }
                return { ncols, nrows };
            })();
            let row = 0;
            let col = 0;
            for (const entry of entries) {
                entry.row = row;
                entry.col = col;
                if (vertical) {
                    row += 1;
                    if (row >= nrows) {
                        row = 0;
                        col += 1;
                    }
                }
                else {
                    col += 1;
                    if (col >= ncols) {
                        col = 0;
                        row += 1;
                    }
                }
            }
            const grid = new layout_1.Grid(entries);
            this.grid = grid;
            grid.spacing = spacing;
            grid.set_sizing();
            const title_panel = new layout_1.TextLayout(title_box);
            this.title_panel = title_panel;
            const title_visible = title_box.text != "" && this.visuals.title_text.doit;
            title_panel.set_sizing({ visible: title_visible }); // doesn't work
            const border_box = (() => {
                if (!title_visible) {
                    return new layout_1.Column([grid]);
                }
                switch (this.model.title_location) {
                    case "above": return new layout_1.Column([title_panel, grid]);
                    case "below": return new layout_1.Column([grid, title_panel]);
                    case "left": return new layout_1.Row([title_panel, grid]);
                    case "right": return new layout_1.Row([grid, title_panel]);
                }
            })();
            this.border_box = border_box;
            border_box.position = { left, top };
            border_box.spacing = this.model.title_standoff;
            border_box.set_sizing();
            border_box.compute();
            const width = padding + border_box.bbox.width + padding;
            const height = padding + border_box.bbox.height + padding;
            // Position will be filled-in in `compute_geometry()`.
            this._bbox = new bbox_1.BBox({ left: 0, top: 0, width, height });
        }
        compute_geometry() {
            super.compute_geometry();
            const { margin, location } = this.model;
            const { width, height } = this.bbox;
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            const [hr, vr] = panel.bbox.ranges;
            let sx, sy;
            if ((0, types_1.isString)(location)) {
                switch (location) {
                    case "top_left":
                        sx = hr.start + margin;
                        sy = vr.start + margin;
                        break;
                    case "top":
                    case "top_center":
                        sx = (hr.end + hr.start) / 2 - width / 2;
                        sy = vr.start + margin;
                        break;
                    case "top_right":
                        sx = hr.end - margin - width;
                        sy = vr.start + margin;
                        break;
                    case "bottom_right":
                        sx = hr.end - margin - width;
                        sy = vr.end - margin - height;
                        break;
                    case "bottom":
                    case "bottom_center":
                        sx = (hr.end + hr.start) / 2 - width / 2;
                        sy = vr.end - margin - height;
                        break;
                    case "bottom_left":
                        sx = hr.start + margin;
                        sy = vr.end - margin - height;
                        break;
                    case "left":
                    case "center_left":
                        sx = hr.start + margin;
                        sy = (vr.end + vr.start) / 2 - height / 2;
                        break;
                    case "center":
                    case "center_center":
                        sx = (hr.end + hr.start) / 2 - width / 2;
                        sy = (vr.end + vr.start) / 2 - height / 2;
                        break;
                    case "right":
                    case "center_right":
                        sx = hr.end - margin - width;
                        sy = (vr.end + vr.start) / 2 - height / 2;
                        break;
                }
            }
            else {
                const [vx, vy] = location;
                sx = panel.bbox.xview.compute(vx);
                sy = panel.bbox.yview.compute(vy) - height;
            }
            this._bbox = new bbox_1.BBox({ left: sx, top: sy, width, height });
        }
        interactive_hit(sx, sy) {
            return this.bbox.contains(sx, sy);
        }
        _hit_test(sx, sy) {
            const { left, top } = this.bbox;
            sx -= left + this.grid.bbox.left;
            sy -= top + this.grid.bbox.top;
            for (const entry of this.grid) {
                if (entry.bbox.contains(sx, sy)) {
                    return { type: "entry", entry };
                }
            }
            return null;
        }
        cursor(sx, sy) {
            if (this.model.click_policy == "none" && !(0, object_1.dict)(this.model.js_event_callbacks).has("legend_item_click")) { // this doesn't cover server callbacks
                return null;
            }
            if (this._hit_test(sx, sy) != null) {
                return "pointer";
            }
            return null;
        }
        on_hit(sx, sy) {
            const fn = (() => {
                switch (this.model.click_policy) {
                    case "hide": return (r) => r.visible = !r.visible;
                    case "mute": return (r) => r.muted = !r.muted;
                    case "none": return (_) => { };
                }
            })();
            const target = this._hit_test(sx, sy);
            if (target != null) {
                const { item } = target.entry;
                this.model.trigger_event(new bokeh_events_1.LegendItemClick(this.model, item));
                for (const renderer of item.renderers) {
                    fn(renderer);
                }
                return true;
            }
            return false;
        }
        _paint() {
            if (this.model.items.length == 0) {
                return;
            }
            if (!(0, array_1.some)(this.model.items, (item) => item.visible)) {
                return;
            }
            const { ctx } = this.layer;
            ctx.save();
            this._draw_legend_box(ctx);
            this._draw_legend_items(ctx);
            this._draw_title(ctx);
            ctx.restore();
        }
        _draw_legend_box(ctx) {
            const { x, y, width, height } = this.bbox;
            ctx.beginPath();
            ctx.rect(x, y, width, height);
            this.visuals.background_fill.apply(ctx);
            this.visuals.border_line.apply(ctx);
        }
        _draw_title(ctx) {
            const { title } = this.model;
            if (title == null || title.length == 0 || !this.visuals.title_text.doit) {
                return;
            }
            const { left, top } = this.bbox;
            ctx.save();
            ctx.translate(left, top);
            ctx.translate(this.title_panel.bbox.left, this.title_panel.bbox.top);
            switch (this.model.title_location) {
                case "left": {
                    ctx.translate(0, this.title_panel.bbox.height);
                    break;
                }
                case "right": {
                    ctx.translate(this.title_panel.bbox.width, 0);
                    break;
                }
                case "above":
                case "below": {
                    break;
                }
            }
            this.title_panel.text.paint(ctx);
            ctx.restore();
        }
        _draw_legend_items(ctx) {
            const is_active = (() => {
                switch (this.model.click_policy) {
                    case "none": return (_item) => true;
                    case "hide": return (item) => (0, array_1.every)(item.renderers, (r) => r.visible);
                    case "mute": return (item) => (0, array_1.every)(item.renderers, (r) => !r.muted);
                }
            })();
            const has_item_background = (_i, row, col) => {
                if (!this.visuals.item_background_fill.doit) {
                    return false;
                }
                switch (this.model.item_background_policy) {
                    case "every": return true;
                    case "even": return (row % 2 == 0) == (col % 2 == 0);
                    case "odd": return (row % 2 == 0) != (col % 2 == 0);
                    case "none": return false;
                }
            };
            const { left, top } = this.bbox;
            ctx.translate(left, top);
            ctx.translate(this.grid.bbox.left, this.grid.bbox.top);
            for (const [{ layout: entry, row, col }, i] of (0, iterator_1.enumerate)(this.grid.items)) {
                const { bbox, text, item, label, field, settings } = entry;
                const { glyph_width, glyph_height, label_standoff } = settings;
                const { left, top, width, height } = bbox;
                ctx.translate(left, top);
                if (has_item_background(i, row, col)) {
                    ctx.beginPath();
                    ctx.rect(0, 0, width, height);
                    this.visuals.item_background_fill.apply(ctx);
                }
                const vcenter = height / 2;
                const x0 = 0;
                const y0 = vcenter - glyph_height / 2;
                const x1 = x0 + glyph_width;
                const y1 = y0 + glyph_height;
                for (const renderer of item.renderers) {
                    const view = this.plot_view.views.find_one(renderer);
                    view?.draw_legend(ctx, x0, x1, y0, y1, field, label, item.index);
                }
                ctx.translate(x1 + label_standoff, vcenter);
                text.paint(ctx);
                ctx.translate(-x1 - label_standoff, -vcenter);
                if (!is_active(item)) {
                    ctx.beginPath();
                    ctx.rect(0, 0, width, height);
                    this.visuals.inactive_fill.set_value(ctx);
                    ctx.fill();
                }
                ctx.translate(-left, -top);
            }
            ctx.translate(-this.grid.bbox.left, -this.grid.bbox.top);
            ctx.translate(-left, -top);
        }
    }
    exports.LegendView = LegendView;
    LegendView.__name__ = "LegendView";
    class Legend extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this.item_change = new signaling_1.Signal0(this, "item_change");
        }
    }
    exports.Legend = Legend;
    _a = Legend;
    Legend.__name__ = "Legend";
    (() => {
        _a.prototype.default_view = LegendView;
        _a.mixins([
            ["label_", mixins.Text],
            ["title_", mixins.Text],
            ["inactive_", mixins.Fill],
            ["border_", mixins.Line],
            ["background_", mixins.Fill],
            ["item_background_", mixins.Fill],
        ]);
        _a.define(({ Float, Int, Str, List, Tuple, Or, Ref, Nullable, Positive, Auto }) => ({
            orientation: [enums_1.Orientation, "vertical"],
            ncols: [Or(Positive(Int), Auto), "auto"],
            nrows: [Or(Positive(Int), Auto), "auto"],
            location: [Or(enums_1.LegendLocation, Tuple(Float, Float)), "top_right"],
            title: [Nullable(Str), null],
            title_location: [enums_1.Location, "above"],
            title_standoff: [Float, 5],
            label_standoff: [Float, 5],
            glyph_height: [Float, 20],
            glyph_width: [Float, 20],
            label_height: [Float, 20],
            label_width: [Float, 20],
            margin: [Float, 10],
            padding: [Float, 10],
            spacing: [Float, 3],
            items: [List(Ref(legend_item_1.LegendItem)), []],
            click_policy: [enums_1.LegendClickPolicy, "none"],
            item_background_policy: [enums_1.AlternationPolicy, "none"],
        }));
        _a.override({
            border_line_color: "#e5e5e5",
            border_line_alpha: 0.5,
            border_line_width: 1,
            background_fill_color: "#ffffff",
            background_fill_alpha: 0.95,
            item_background_fill_color: "#f1f1f1",
            item_background_fill_alpha: 0.8,
            inactive_fill_color: "white",
            inactive_fill_alpha: 0.7,
            label_text_font_size: "13px",
            label_text_baseline: "middle",
            title_text_font_size: "13px",
            title_text_font_style: "italic",
        });
    })();
},
/* models/annotations/legend_item.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const model_1 = require(51) /* ../../model */;
    const glyph_renderer_1 = require(218) /* ../renderers/glyph_renderer */;
    const columnar_data_source_1 = require(128) /* ../sources/columnar_data_source */;
    const vectorization_1 = require(28) /* ../../core/vectorization */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const logging_1 = require(19) /* ../../core/logging */;
    const array_1 = require(10) /* ../../core/util/array */;
    class LegendItem extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        /*protected*/ _check_data_sources_on_renderers() {
            const field = this.get_field_from_label_prop();
            if (field != null) {
                if (this.renderers.length < 1) {
                    return false;
                }
                const source = this.renderers[0].data_source;
                for (const r of this.renderers) {
                    if (r.data_source != source) {
                        return false;
                    }
                }
            }
            return true;
        }
        /*protected*/ _check_field_label_on_data_source() {
            const field = this.get_field_from_label_prop();
            if (field != null) {
                if (this.renderers.length < 1) {
                    return false;
                }
                const source = this.renderers[0].data_source;
                if (!(0, array_1.includes)(source.columns(), field)) {
                    return false;
                }
            }
            return true;
        }
        initialize() {
            super.initialize();
            this.legend = null;
            this.connect(this.change, () => this.legend?.item_change.emit());
            // Validate data_sources match
            const data_source_validation = this._check_data_sources_on_renderers();
            if (!data_source_validation) {
                logging_1.logger.error("Non matching data sources on legend item renderers");
            }
            // Validate label in data_source
            const field_validation = this._check_field_label_on_data_source();
            if (!field_validation) {
                logging_1.logger.error(`Bad column name on label: ${this.label}`);
            }
        }
        get_field_from_label_prop() {
            const { label } = this;
            return (0, vectorization_1.isField)(label) ? label.field : null;
        }
        get_labels_list_from_label_prop() {
            if (!this.visible) {
                return [];
            }
            const { index } = this;
            if (index != null && this.renderers.every((r) => !r.view.indices_map.has(index))) {
                // this index points to nowhere, so skip this item altogether from its legend
                return [];
            }
            if ((0, vectorization_1.isValue)(this.label)) {
                const { value } = this.label;
                return value != null ? [value] : [];
            }
            const field = this.get_field_from_label_prop();
            if (field != null) {
                let source;
                if (this.renderers.length != 0) {
                    source = this.renderers[0].data_source;
                }
                else {
                    return ["No source found"];
                }
                if (source instanceof columnar_data_source_1.ColumnarDataSource) {
                    const data = source.get_column(field);
                    if (data != null) {
                        return (0, array_1.uniq)(Array.from(data));
                    }
                    else {
                        return ["Invalid field"];
                    }
                }
            }
            return [];
        }
    }
    exports.LegendItem = LegendItem;
    _a = LegendItem;
    LegendItem.__name__ = "LegendItem";
    (() => {
        _a.define(({ Bool, Int, List, Ref, Nullable }) => ({
            label: [p.NullStringSpec, null],
            renderers: [List(Ref(glyph_renderer_1.GlyphRenderer)), []],
            index: [Nullable(Int), null],
            visible: [Bool, true],
        }));
    })();
},
/* models/annotations/poly_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(81) /* ./annotation */;
    const data_range1d_1 = require(106) /* ../ranges/data_range1d */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const hittest_1 = require(229) /* ../../core/hittest */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class Polygon {
        constructor(xs = [], ys = []) {
            this.xs = xs;
            this.ys = ys;
            (0, assert_1.assert)(xs.length == ys.length);
        }
        clone() {
            return new Polygon(this.xs.slice(), this.ys.slice());
        }
        [Symbol.iterator]() {
            return this.nodes();
        }
        *nodes() {
            const { xs, ys, n } = this;
            for (let i = 0; i < n; i++) {
                yield [xs[i], ys[i], i];
            }
        }
        *edges() {
            const { xs, ys, n } = this;
            for (let i = 1; i < n; i++) {
                const p0 = { x: xs[i - 1], y: ys[i - 1] };
                const p1 = { x: xs[i], y: ys[i] };
                yield [p0, p1, i - 1];
            }
            if (n >= 3) {
                const p0 = { x: xs[n - 1], y: ys[n - 1] };
                const p1 = { x: xs[0], y: ys[0] };
                yield [p0, p1, n - 1];
            }
        }
        contains(x, y) {
            return (0, hittest_1.point_in_poly)(x, y, this.xs, this.ys);
        }
        get bbox() {
            const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(this.xs, this.ys);
            return new bbox_1.BBox({ x0, x1, y0, y1 });
        }
        get n() {
            return this.xs.length;
        }
        translate(dx, dy, ...i) {
            const poly = this.clone();
            const { xs, ys, n } = poly;
            if (i.length != 0) {
                for (const j of i) {
                    const k = j % n;
                    xs[k] += dx;
                    ys[k] += dy;
                }
            }
            else {
                for (let i = 0; i < n; i++) {
                    xs[i] += dx;
                    ys[i] += dy;
                }
            }
            return poly;
        }
    }
    Polygon.__name__ = "Polygon";
    class PolyAnnotationView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this.poly = new Polygon();
            this[_a] = true;
            this._pan_state = null;
            this._is_hovered = false;
        }
        get bbox() {
            return this.poly.bbox;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_paint());
        }
        bounds() {
            const { xs_units, ys_units } = this.model;
            if (xs_units == "data" && ys_units == "data") {
                const { xs, ys } = this.model;
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return { x0, x1, y0, y1 };
            }
            else {
                return (0, bbox_1.empty)();
            }
        }
        log_bounds() {
            return (0, bbox_1.empty)();
        }
        _mappers() {
            const mapper = (units, scale, view, canvas) => {
                switch (units) {
                    case "canvas": return canvas;
                    case "screen": return view;
                    case "data": return scale;
                }
            };
            const overlay = this.model;
            const { frame, canvas } = this.plot_view;
            const { x_scale, y_scale } = frame;
            const { x_view, y_view } = frame.bbox;
            const { x_screen, y_screen } = canvas.bbox;
            return {
                x: mapper(overlay.xs_units, x_scale, x_view, x_screen),
                y: mapper(overlay.ys_units, y_scale, y_view, y_screen),
            };
        }
        _paint() {
            const { xs, ys } = this.model;
            (0, assert_1.assert)(xs.length == ys.length);
            this.poly = (() => {
                const { x, y } = this._mappers();
                return new Polygon(x.v_compute(xs), y.v_compute(ys));
            })();
            const { ctx } = this.layer;
            ctx.beginPath();
            for (const [sx, sy] of this.poly) {
                ctx.lineTo(sx, sy);
            }
            const { _is_hovered, visuals } = this;
            const fill = _is_hovered && visuals.hover_fill.doit ? visuals.hover_fill : visuals.fill;
            const hatch = _is_hovered && visuals.hover_hatch.doit ? visuals.hover_hatch : visuals.hatch;
            const line = _is_hovered && visuals.hover_line.doit ? visuals.hover_line : visuals.line;
            if (this.poly.n >= 3) {
                ctx.closePath();
                fill.apply(ctx);
                hatch.apply(ctx);
            }
            line.apply(ctx);
        }
        interactive_hit(sx, sy) {
            if (!this.model.visible || !this.model.editable) {
                return false;
            }
            return this.poly.contains(sx, sy);
        }
        _hit_test(sx, sy) {
            const { abs } = Math;
            const EDGE_TOLERANCE = 2.5;
            const tolerance = Math.max(EDGE_TOLERANCE, this.model.line_width / 2);
            for (const [px, py, i] of this.poly) {
                if (abs(px - sx) < tolerance && abs(py - sy) < tolerance) {
                    return { type: "node", i };
                }
            }
            const spt = { x: sx, y: sy };
            let j = null;
            let dist = Infinity;
            for (const [p0, p1, i] of this.poly.edges()) {
                const d = (0, hittest_1.dist_to_segment)(spt, p0, p1);
                if (d < tolerance && d < dist) {
                    dist = d;
                    j = i;
                }
            }
            if (j != null) {
                return { type: "edge", i: j };
            }
            if (this.poly.contains(sx, sy)) {
                return { type: "area" };
            }
            return null;
        }
        _can_hit(_target) {
            return true;
        }
        on_pan_start(ev) {
            if (this.model.visible && this.model.editable) {
                const { sx, sy } = ev;
                const target = this._hit_test(sx, sy);
                if (target != null && this._can_hit(target)) {
                    this._pan_state = {
                        poly: this.poly.clone(),
                        target,
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]);
                    return true;
                }
            }
            return false;
        }
        on_pan(ev) {
            (0, assert_1.assert)(this._pan_state != null);
            const spoly = (() => {
                const { poly, target } = this._pan_state;
                const { dx, dy } = ev;
                switch (target.type) {
                    case "node": {
                        const { i } = target;
                        return poly.translate(dx, dy, i);
                    }
                    case "edge": {
                        const { i } = target;
                        return poly.translate(dx, dy, i, i + 1);
                    }
                    case "area": {
                        return poly.translate(dx, dy);
                    }
                }
            })();
            const { x, y } = this._mappers();
            const xs = x.v_invert(spoly.xs);
            const ys = y.v_invert(spoly.ys);
            this.model.update({ xs, ys });
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        on_pan_end(ev) {
            this._pan_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        get _has_hover() {
            const { hover_line, hover_fill, hover_hatch } = this.visuals;
            return hover_line.doit || hover_fill.doit || hover_hatch.doit;
        }
        on_enter(_ev) {
            const { _has_hover } = this;
            if (_has_hover) {
                this._is_hovered = true;
                this.request_paint();
            }
            return _has_hover;
        }
        on_move(_ev) { }
        on_leave(_ev) {
            if (this._has_hover) {
                this._is_hovered = false;
                this.request_paint();
            }
        }
        cursor(sx, sy) {
            const target = this._pan_state?.target ?? this._hit_test(sx, sy);
            if (target == null || !this._can_hit(target)) {
                return null;
            }
            switch (target.type) {
                case "node": return "move";
                case "edge": return "move";
                case "area": return "move";
            }
        }
    }
    exports.PolyAnnotationView = PolyAnnotationView;
    _a = data_range1d_1.auto_ranged;
    PolyAnnotationView.__name__ = "PolyAnnotationView";
    class PolyAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
            this.pan = new signaling_1.Signal(this, "pan");
        }
        update({ xs, ys }) {
            this.setv({ xs: xs.slice(), ys: ys.slice(), visible: true });
        }
        clear() {
            this.setv({ xs: [], ys: [], visible: false });
        }
    }
    exports.PolyAnnotation = PolyAnnotation;
    _b = PolyAnnotation;
    PolyAnnotation.__name__ = "PolyAnnotation";
    (() => {
        _b.prototype.default_view = PolyAnnotationView;
        _b.mixins([
            mixins.Line,
            mixins.Fill,
            mixins.Hatch,
            ["hover_", mixins.Line],
            ["hover_", mixins.Fill],
            ["hover_", mixins.Hatch],
        ]);
        _b.define(({ Bool, Float, Arrayable }) => ({
            xs: [Arrayable(Float), []],
            ys: [Arrayable(Float), []],
            xs_units: [enums_1.CoordinateUnits, "data"],
            ys_units: [enums_1.CoordinateUnits, "data"],
            editable: [Bool, false],
        }));
        _b.override({
            fill_color: "#fff9ba",
            fill_alpha: 0.4,
            line_color: "#cccccc",
            line_alpha: 0.3,
            hover_fill_color: null,
            hover_fill_alpha: 0.4,
            hover_line_color: null,
            hover_line_alpha: 0.3,
        });
    })();
},
/* models/annotations/scale_bar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(81) /* ./annotation */;
    const dimensional_1 = require(288) /* ./dimensional */;
    const range_1 = require(98) /* ../ranges/range */;
    const range1d_1 = require(99) /* ../ranges/range1d */;
    const enums_1 = require(20) /* ../../core/enums */;
    const enums = tslib_1.__importStar(require(20) /* ../../core/enums */);
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const graphics_1 = require(180) /* ../../core/graphics */;
    const side_panel_1 = require(173) /* ../../core/layout/side_panel */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const layout_1 = require(257) /* ../../core/layout */;
    const grid_1 = require(259) /* ../../core/layout/grid */;
    const linear_axis_1 = require(194) /* ../axes/linear_axis */;
    const ticker_1 = require(191) /* ../tickers/ticker */;
    const fixed_ticker_1 = require(210) /* ../tickers/fixed_ticker */;
    const linear_scale_1 = require(101) /* ../scales/linear_scale */;
    const categorical_scale_1 = require(104) /* ../scales/categorical_scale */;
    const coordinate_mapping_1 = require(95) /* ../coordinates/coordinate_mapping */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const math_1 = require(11) /* ../../core/util/math */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const types_1 = require(8) /* ../../core/util/types */;
    const templating_1 = require(245) /* ../../core/util/templating */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const kinds_2 = require(185) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(186) /* ../common/resolve */);
    const factor_range_1 = require(109) /* ../ranges/factor_range */;
    const { round } = Math;
    const Position = (0, kinds_1.Or)(enums.Anchor, (0, kinds_1.Tuple)((0, kinds_1.Or)(kinds_1.Float, factor_range_1.Factor, enums_1.HAlign), (0, kinds_1.Or)(kinds_1.Float, factor_range_1.Factor, enums_1.VAlign)));
    const PositionUnits = (0, kinds_1.Enum)("data", "screen", "view", "percent");
    const LengthUnits = (0, kinds_1.Enum)("screen", "data", "percent");
    const LengthSizing = (0, kinds_1.Enum)("adaptive", "exact");
    class ScaleBarView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this._bbox = new bbox_1.BBox();
        }
        get bbox() {
            return this._bbox;
        }
        _get_size() {
            const { width, height } = this.bbox;
            const { margin } = this.model;
            return {
                width: width + 2 * margin,
                height: height + 2 * margin,
            };
        }
        initialize() {
            super.initialize();
            const { ticker } = this.model;
            this.axis = new linear_axis_1.LinearAxis({
                ticker,
                ...mixins.attrs_of(this.model, "bar_", mixins.Line, "axis_"),
            });
            this.range = (() => {
                const { range, orientation } = this.model;
                if (range == "auto") {
                    const { frame } = this.parent;
                    switch (orientation) {
                        case "horizontal": return frame.x_range;
                        case "vertical": return frame.y_range;
                    }
                }
                else {
                    return range;
                }
            })();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const coordinates = (() => {
                const axis_source = new range1d_1.Range1d();
                const axis_target = new range1d_1.Range1d();
                const cross_source = new range1d_1.Range1d();
                const cross_target = new range1d_1.Range1d();
                this.axis_scale = new linear_scale_1.LinearScale({ source_range: axis_source, target_range: axis_target });
                this.cross_scale = new linear_scale_1.LinearScale({ source_range: cross_source, target_range: cross_target });
                if (this.model.orientation == "horizontal") {
                    return new coordinate_mapping_1.CoordinateTransform(this.axis_scale, this.cross_scale);
                }
                else {
                    return new coordinate_mapping_1.CoordinateTransform(this.cross_scale, this.axis_scale);
                }
            })();
            this.axis_view = await (0, build_views_1.build_view)(this.axis, { parent: this.plot_view });
            this.axis_view.coordinates = coordinates;
            this.axis_view.panel = new side_panel_1.SidePanel(this.model.orientation == "horizontal" ? "below" : "right");
            this.axis_view.update_layout();
        }
        remove() {
            this.axis_view.remove();
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => {
                this.request_paint();
            });
            this.connect(this.range.change, () => {
                this.request_paint();
            });
        }
        update_layout() {
            this.update_geometry();
            const { panel } = this;
            if (panel != null) {
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size());
            }
            else {
                this.layout = undefined;
            }
        }
        update_geometry() {
            super.update_geometry();
        }
        get horizontal() {
            return this.model.orientation == "horizontal";
        }
        text_layout(args) {
            const { text, location, align, visuals } = args;
            const { orientation } = this.model;
            const text_box = new graphics_1.TextBox({ text });
            const text_panel = new side_panel_1.SidePanel(location);
            text_box.visuals = visuals.values();
            const text_orientation = (() => {
                switch (location) {
                    case "above":
                    case "below": return "horizontal";
                    default: return orientation;
                }
            })();
            text_box.angle = text_panel.get_label_angle_heuristic(text_orientation);
            text_box.base_font_size = this.plot_view.base_font_size;
            text_box.position = {
                sx: 0,
                sy: 0,
                x_anchor: "left",
                y_anchor: "top",
            };
            text_box.align = "auto";
            const text_layout = new layout_1.TextLayout(text_box);
            text_layout.absolute = true;
            const horizontal = orientation == "horizontal";
            const halign = horizontal ? align : undefined;
            const valign = !horizontal ? align : undefined;
            text_layout.set_sizing({
                width_policy: "min",
                height_policy: "min",
                visible: text != "" && visuals.doit,
                halign, valign,
            });
            return text_layout;
        }
        compute_geometry() {
            super.compute_geometry();
            const { orientation, length_sizing, padding, margin } = this.model;
            const { border_line, bar_line } = this.visuals;
            const bar_width = bar_line.line_width.get_value();
            const border_width = border_line.line_width.get_value();
            const { frame } = this.parent;
            const frame_span = orientation == "horizontal" ? frame.bbox.width : frame.bbox.height;
            const bar_length_percent = (() => {
                const { bar_length, bar_length_units } = this.model;
                switch (bar_length_units) {
                    case "screen": {
                        if (0.0 <= bar_length && bar_length <= 1.0) {
                            return bar_length;
                        }
                        else {
                            return (0, math_1.clamp)(bar_length / frame_span, 0.0, 1.0);
                        }
                    }
                    case "data": {
                        const scale = orientation == "horizontal" ? this.coordinates.x_scale : this.coordinates.y_scale;
                        (0, assert_1.assert)(scale instanceof linear_scale_1.LinearScale || scale instanceof categorical_scale_1.CategoricalScale);
                        const [sv0, sv1] = scale.r_compute(0, bar_length);
                        const sdist = Math.abs(sv1 - sv0);
                        return sdist / frame_span;
                    }
                    case "percent": {
                        return (0, math_1.clamp)(bar_length, 0.0, 1.0);
                    }
                }
            })();
            const { new_value, new_unit, scale_factor, exact } = (() => {
                const { unit, dimensional } = this.model;
                const value = this.range.span * bar_length_percent;
                return dimensional.compute(value, unit, length_sizing == "exact");
            })();
            const init_bar_length_px = frame_span * bar_length_percent;
            const bar_length_px = round(init_bar_length_px * scale_factor);
            const label_text = (() => {
                const { label } = this.model;
                return (0, templating_1.process_placeholders)(label, (_, name, format) => {
                    switch (name) {
                        case "value": {
                            if (exact) {
                                if (format != null) {
                                    return (0, templating_1.sprintf)(format, new_value);
                                }
                                else {
                                    return new_value.toFixed(2);
                                }
                            }
                            else {
                                return `${new_value}`;
                            }
                        }
                        case "unit": {
                            switch (format ?? "short") {
                                case "short": return new_unit;
                            }
                        }
                        default: {
                            return null;
                        }
                    }
                });
            })();
            this.label_layout = this.text_layout({
                text: label_text,
                location: this.model.label_location,
                align: this.model.label_align,
                visuals: this.visuals.label_text,
            });
            this.title_layout = this.text_layout({
                text: this.model.title,
                location: this.model.title_location,
                align: this.model.title_align,
                visuals: this.visuals.title_text,
            });
            const bar_size = (() => {
                if (orientation == "horizontal") {
                    return { width: bar_length_px, height: bar_width };
                }
                else {
                    return { width: bar_width, height: bar_length_px };
                }
            })();
            const axis_layout = this.axis_view.layout;
            (0, assert_1.assert)(axis_layout != null);
            this.axis_layout = axis_layout;
            axis_layout.absolute = true;
            if (orientation == "horizontal") {
                axis_layout.set_sizing({
                    width_policy: "fixed", width: bar_size.width,
                    height_policy: "min",
                    valign: "center",
                });
            }
            else {
                axis_layout.set_sizing({
                    width_policy: "min",
                    height_policy: "fixed", height: bar_size.height,
                    halign: "center",
                });
            }
            this.box_layout = (() => {
                const panels = {
                    above: [],
                    below: [],
                    left: [],
                    right: [],
                };
                function spacer(location, spacing) {
                    const layout = new layout_1.FixedLayout();
                    layout.absolute = true;
                    layout.set_sizing((() => {
                        if (location == "left" || location == "right") {
                            return { width_policy: "fixed", width: spacing };
                        }
                        else {
                            return { height_policy: "fixed", height: spacing };
                        }
                    })());
                    return layout;
                }
                function insert(layout, location, spacing) {
                    if (layout.visible) {
                        panels[location].push(spacer(location, spacing), layout);
                    }
                }
                insert(this.label_layout, this.model.label_location, this.model.label_standoff);
                insert(this.title_layout, this.model.title_location, this.model.title_standoff);
                const row = panels.above.length;
                const col = panels.left.length;
                const items = [
                    { layout: axis_layout, row, col },
                ];
                for (const [layout, i] of (0, iterator_1.enumerate)(panels.above)) {
                    items.push({ layout, row: row - i - 1, col });
                }
                for (const [layout, i] of (0, iterator_1.enumerate)(panels.below)) {
                    items.push({ layout, row: row + i + 1, col });
                }
                for (const [layout, i] of (0, iterator_1.enumerate)(panels.left)) {
                    items.push({ layout, row, col: col - i - 1 });
                }
                for (const [layout, i] of (0, iterator_1.enumerate)(panels.right)) {
                    items.push({ layout, row, col: col + i + 1 });
                }
                return new grid_1.Grid(items);
            })();
            const { box_layout } = this;
            box_layout.absolute = true;
            box_layout.position = { left: padding, top: padding };
            box_layout.set_sizing();
            box_layout.compute();
            const [axis_range, cross_range] = (() => {
                const { x_range, y_range } = this.axis_view.bbox;
                if (orientation == "horizontal") {
                    return [x_range, y_range];
                }
                else {
                    return [y_range, x_range];
                }
            })();
            this.axis_scale.source_range.end = new_value;
            this.axis_scale.target_range.setv(axis_range);
            this.cross_scale.source_range.end = 1.0;
            this.cross_scale.target_range.setv(cross_range);
            const position = (() => {
                const { location: position } = this.model;
                if ((0, types_1.isString)(position)) {
                    const normalized = (() => {
                        switch (position) {
                            case "top": return "top_center";
                            case "bottom": return "bottom_center";
                            case "left": return "center_left";
                            case "center": return "center_center";
                            case "right": return "center_right";
                            default: return position;
                        }
                    })();
                    const [v_loc, h_loc] = normalized.split("_");
                    return { x: h_loc, y: v_loc };
                }
                else {
                    const [x_loc, y_loc] = position;
                    return { x: x_loc, y: y_loc };
                }
            })();
            const { x, y } = (() => {
                const panel = this.layout ?? this.plot_view.frame;
                const inset = panel.bbox.shrink_by(margin);
                const x_pos = (() => {
                    const { x } = position;
                    switch (x) {
                        case "left": return inset.left;
                        case "center": return inset.x_center;
                        case "right": return inset.right;
                    }
                    const x_mapper = (() => {
                        switch (this.model.x_units) {
                            case "data": return this.coordinates.x_scale;
                            case "screen": return panel.bbox.x_screen;
                            case "view": return panel.bbox.x_view;
                            case "percent": return panel.bbox.x_percent;
                        }
                    })();
                    return x_mapper.compute(
                    // @ts-ignore(TS2345): Argument of type 'number | ...' is not assignable to parameter of type 'number'.
                    x);
                })();
                const y_pos = (() => {
                    const { y } = position;
                    switch (y) {
                        case "top": return inset.top;
                        case "center": return inset.y_center;
                        case "bottom": return inset.right;
                    }
                    const y_mapper = (() => {
                        switch (this.model.y_units) {
                            case "data": return this.coordinates.y_scale;
                            case "screen": return panel.bbox.y_screen;
                            case "view": return panel.bbox.y_view;
                            case "percent": return panel.bbox.y_percent;
                        }
                    })();
                    return y_mapper.compute(
                    // @ts-ignore(TS2345): Argument of type 'number | ...' is not assignable to parameter of type 'number'.
                    y);
                })();
                return { x: x_pos, y: y_pos };
            })();
            const anchor = (() => {
                const anchor = resolve.anchor(this.model.anchor);
                const x_anchor = (() => {
                    if (anchor.x == "auto") {
                        switch (position.x) {
                            case "left": return 0.0;
                            case "center": return 0.5;
                            case "right": return 1.0;
                            default: return 0.5;
                        }
                    }
                    else {
                        return anchor.x;
                    }
                })();
                const y_anchor = (() => {
                    if (anchor.y == "auto") {
                        switch (position.y) {
                            case "top": return 0.0;
                            case "center": return 0.5;
                            case "bottom": return 1.0;
                            default: return 0.5;
                        }
                    }
                    else {
                        return anchor.y;
                    }
                })();
                return { x: x_anchor, y: y_anchor };
            })();
            const width = border_width + padding + box_layout.bbox.width + padding + border_width;
            const height = border_width + padding + box_layout.bbox.height + padding + border_width;
            const sx = x - anchor.x * width;
            const sy = y - anchor.y * height;
            this._bbox = new bbox_1.BBox({ left: sx, top: sy, width, height });
        }
        _draw_box(ctx) {
            const { width, height } = this.bbox;
            ctx.beginPath();
            ctx.rect(0, 0, width, height);
            this.visuals.background_fill.apply(ctx);
            this.visuals.background_hatch.apply(ctx);
            this.visuals.border_line.apply(ctx);
        }
        _draw_axis(_ctx) {
            this.axis_view.paint();
        }
        _draw_text(ctx, layout, location) {
            const { bbox } = layout;
            const [x_offset, y_offset] = (() => {
                const { orientation } = this.model;
                const horizontal = orientation == "horizontal";
                switch (location) {
                    case "left": return horizontal ? [0, 0] : [0, bbox.height];
                    case "right": return horizontal ? [0, 0] : [bbox.width, 0];
                    case "above": return [0, 0];
                    case "below": return [0, 0];
                }
            })();
            const { left, top } = bbox.translate(x_offset, y_offset);
            ctx.translate(left, top);
            layout.text.paint(ctx);
            ctx.translate(-left, -top);
        }
        _draw_label(ctx) {
            this._draw_text(ctx, this.label_layout, this.model.label_location);
        }
        _draw_title(ctx) {
            this._draw_text(ctx, this.title_layout, this.model.title_location);
        }
        _paint() {
            const { ctx } = this.layer;
            const { left, top } = this.bbox;
            ctx.translate(left, top);
            if (this.box_layout.visible) {
                this._draw_box(ctx);
            }
            if (this.axis_layout.visible) {
                this._draw_axis(ctx);
            }
            if (this.label_layout.visible) {
                this._draw_label(ctx);
            }
            if (this.title_layout.visible) {
                this._draw_title(ctx);
            }
            ctx.translate(-left, -top);
        }
    }
    exports.ScaleBarView = ScaleBarView;
    ScaleBarView.__name__ = "ScaleBarView";
    class ScaleBar extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ScaleBar = ScaleBar;
    _a = ScaleBar;
    ScaleBar.__name__ = "ScaleBar";
    (() => {
        _a.prototype.default_view = ScaleBarView;
        _a.mixins([
            ["background_", mixins.Fill],
            ["background_", mixins.Hatch],
            ["bar_", mixins.Line],
            ["border_", mixins.Line],
            ["label_", mixins.Text],
            ["title_", mixins.Text],
        ]);
        _a.define(({ NonNegative, Float, Str, Ref, Or, Auto }) => ({
            anchor: [kinds_2.AutoAnchor, "auto"],
            bar_length: [NonNegative(Float), 0.2],
            bar_length_units: [LengthUnits, "screen"],
            dimensional: [Ref(dimensional_1.Dimensional), () => new dimensional_1.MetricLength()],
            label: [Str, "@{value} @{unit}"],
            label_align: [enums_1.Align, "center"],
            label_location: [enums_1.Location, "below"],
            label_standoff: [Float, 5],
            length_sizing: [LengthSizing, "adaptive"],
            location: [Position, "top_right"],
            margin: [Float, 10],
            orientation: [enums_1.Orientation, "horizontal"],
            padding: [Float, 10],
            range: [Or(Ref(range_1.Range), Auto), "auto"],
            ticker: [Ref(ticker_1.Ticker), () => new fixed_ticker_1.FixedTicker({ ticks: [] })],
            title: [Str, ""],
            title_align: [enums_1.Align, "center"],
            title_location: [enums_1.Location, "above"],
            title_standoff: [Float, 5],
            unit: [Str, "m"],
            x_units: [PositionUnits, "data"],
            y_units: [PositionUnits, "data"],
        }));
        _a.override({
            background_fill_alpha: 0.95,
            background_fill_color: "#ffffff",
            bar_line_width: 2,
            border_line_alpha: 0.5,
            border_line_color: "#e5e5e5",
            border_line_width: 1,
            label_text_baseline: "middle",
            label_text_font_size: "13px",
            title_text_font_size: "13px",
            title_text_font_style: "italic",
        });
    })();
},
/* models/annotations/dimensional.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c, _d, _e, _f, _g;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const object_1 = require(9) /* ../../core/util/object */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const { min } = Math;
    class Dimensional extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        compute(value, unit, exact) {
            const basis = (() => {
                const { include, exclude } = this;
                const basis = (0, object_1.entries)(this.get_basis())
                    .map(([name, [factor, tex_name, long_name]]) => ({ name, factor, tex_name, long_name }))
                    .filter(({ name }) => (include == null || include.includes(name)) && !exclude.includes(name));
                return (0, arrayable_1.sort_by)(basis, ({ factor }) => factor);
            })();
            const { ticks } = this;
            const found_unit = basis.find(({ name }) => name == unit);
            (0, assert_1.assert)(found_unit != null);
            const value_in_unit = value * found_unit.factor;
            const [new_unit, new_value] = (() => {
                const index = (0, arrayable_1.bisect_right_by)(basis, value_in_unit, ({ factor }) => factor);
                if (index > 0) {
                    const { name: new_unit, factor } = basis[index - 1];
                    const new_value = value_in_unit / factor;
                    return [new_unit, new_value];
                }
                else {
                    return [unit, value_in_unit];
                }
            })();
            exact = exact ?? ticks.length == 0;
            const preferred_value = (() => {
                if (exact) {
                    return new_value;
                }
                else {
                    const index = (0, arrayable_1.bisect_right)(ticks, new_value);
                    return ticks[min(index, ticks.length - 1)];
                }
            })();
            const preferred_value_raw = preferred_value * (value_in_unit / new_value);
            const scale_factor = (preferred_value_raw / value) / found_unit.factor;
            return {
                new_value: preferred_value,
                new_unit,
                scale_factor,
                exact,
            };
        }
    }
    exports.Dimensional = Dimensional;
    _a = Dimensional;
    Dimensional.__name__ = "Dimensional";
    (() => {
        _a.define(({ Nullable, List, Str, Float }) => ({
            ticks: [List(Float)],
            include: [Nullable(List(Str)), null],
            exclude: [List(Str), []],
        }));
    })();
    class CustomDimensional extends Dimensional {
        constructor(attrs) {
            super(attrs);
        }
        get_basis() {
            return this.basis;
        }
    }
    exports.CustomDimensional = CustomDimensional;
    _b = CustomDimensional;
    CustomDimensional.__name__ = "CustomDimensional";
    (() => {
        _b.define(({ Dict, Tuple, Float, Str, Or }) => ({
            basis: [Dict(Or(Tuple(Float, Str), Tuple(Float, Str, Str)))],
        }));
    })();
    class Metric extends Dimensional {
        constructor(attrs) {
            super(attrs);
        }
        get_basis() {
            const { base_unit, full_unit } = this;
            const basis = {};
            for (const [prefix, factor, tex_prefix, long_prefix] of _c._metric_basis) {
                const name = `${prefix}${base_unit}`;
                const tex_name = `${tex_prefix}${base_unit}`;
                const long_name = full_unit != null ? `${long_prefix}${full_unit}` : undefined;
                basis[name] = [factor, tex_name, long_name];
            }
            return basis;
        }
    }
    exports.Metric = Metric;
    _c = Metric;
    Metric.__name__ = "Metric";
    (() => {
        _c.define(({ Str, Nullable }) => ({
            base_unit: [Str],
            full_unit: [Nullable(Str), null],
        }));
        _c.override({
            ticks: [1, 2, 5, 10, 15, 20, 25, 50, 75, 100, 125, 150, 200, 250, 500, 750],
        });
    })();
    Metric._metric_basis = [
        ["Q", 1e30, "Q", "quetta"],
        ["R", 1e27, "R", "ronna"],
        ["Y", 1e24, "Y", "yotta"],
        ["Z", 1e21, "Z", "zetta"],
        ["E", 1e18, "E", "exa"],
        ["P", 1e15, "P", "peta"],
        ["T", 1e12, "T", "tera"],
        ["G", 1e9, "G", "giga"],
        ["M", 1e6, "M", "mega"],
        ["k", 1e3, "k", "kilo"],
        ["h", 1e2, "h", "hecto"],
        ["", 1e0, "", ""],
        ["d", 1e-1, "d", "deci"],
        ["c", 1e-2, "c", "centi"],
        ["m", 1e-3, "m", "milli"],
        ["µ", 1e-6, "\\mu", "micro"],
        ["n", 1e-9, "n", "nano"],
        ["p", 1e-12, "p", "pico"],
        ["f", 1e-15, "f", "femto"],
        ["a", 1e-18, "a", "atto"],
        ["z", 1e-21, "z", "zepto"],
        ["y", 1e-24, "y", "yocto"],
        ["r", 1e-27, "r", "ronto"],
        ["q", 1e-30, "q", "quecto"],
    ];
    class ReciprocalMetric extends Metric {
        constructor(attrs) {
            super(attrs);
        }
        get_basis() {
            const basis = super.get_basis();
            const reciprocal_basis = {};
            for (const [name, [factor, tex_name]] of (0, object_1.entries)(basis)) {
                reciprocal_basis[`${name}⁻1`] = [factor ** -1, `${tex_name}^{-1}`];
            }
            return reciprocal_basis;
        }
    }
    exports.ReciprocalMetric = ReciprocalMetric;
    ReciprocalMetric.__name__ = "ReciprocalMetric";
    class MetricLength extends Metric {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MetricLength = MetricLength;
    _d = MetricLength;
    MetricLength.__name__ = "MetricLength";
    (() => {
        _d.override({
            base_unit: "m",
            exclude: ["dm", "hm"],
        });
    })();
    class ReciprocalMetricLength extends ReciprocalMetric {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ReciprocalMetricLength = ReciprocalMetricLength;
    _e = ReciprocalMetricLength;
    ReciprocalMetricLength.__name__ = "ReciprocalMetricLength";
    (() => {
        _e.override({
            base_unit: "m",
            exclude: ["dm", "hm"],
        });
    })();
    class ImperialLength extends CustomDimensional {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ImperialLength = ImperialLength;
    _f = ImperialLength;
    ImperialLength.__name__ = "ImperialLength";
    (() => {
        _f.override({
            basis: {
                in: [1 / 12, "in", "inch"],
                ft: [1, "ft", "foot"],
                yd: [3, "yd", "yard"],
                ch: [66, "ch", "chain"],
                fur: [660, "fur", "furlong"],
                mi: [5280, "mi", "mile"],
                lea: [15840, "lea", "league"],
            },
            ticks: [1, 3, 6, 12, 60],
        });
    })();
    class Angular extends CustomDimensional {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Angular = Angular;
    _g = Angular;
    Angular.__name__ = "Angular";
    (() => {
        _g.override({
            basis: {
                "°": [1, "^\\circ", "degree"],
                "'": [1 / 60, "^\\prime", "minute"],
                "''": [1 / 3600, "^{\\prime\\prime}", "second"],
            },
            ticks: [1, 3, 6, 12, 60, 120, 240, 360],
        });
    })();
},
/* models/annotations/slope.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(81) /* ./annotation */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    class SlopeView extends annotation_1.AnnotationView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_paint());
        }
        _paint() {
            const { gradient, y_intercept } = this.model;
            if (gradient == null || y_intercept == null) {
                return;
            }
            const { frame } = this.plot_view;
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            const [sx0, sx1, sy0, sy1] = (() => {
                if (gradient == 0) {
                    const sy_start = yscale.compute(y_intercept);
                    const sy_end = sy_start;
                    const sx_start = frame.bbox.left;
                    const sx_end = frame.bbox.right;
                    return [sx_start, sx_end, sy_start, sy_end];
                }
                else {
                    const sy_start = frame.bbox.top;
                    const sy_end = frame.bbox.bottom;
                    const y_start = yscale.invert(sy_start);
                    const y_end = yscale.invert(sy_end);
                    const x_start = (y_start - y_intercept) / gradient;
                    const x_end = (y_end - y_intercept) / gradient;
                    const sx_start = xscale.compute(x_start);
                    const sx_end = xscale.compute(x_end);
                    if (sx_start <= sx_end) {
                        return [sx_start, sx_end, sy_start, sy_end];
                    }
                    else {
                        return [sx_end, sx_start, sy_end, sy_start];
                    }
                }
            })();
            const { ctx } = this.layer;
            ctx.save();
            if (this.visuals.above_fill.doit || this.visuals.above_hatch.doit) {
                const { left, right, top, bottom } = frame.bbox;
                ctx.beginPath();
                ctx.moveTo(sx0, sy0);
                ctx.lineTo(sx0, sy0);
                ctx.lineTo(sx1, sy1);
                ctx.lineTo(sx1, sy1);
                if (sy0 <= sy1) {
                    if (sx1 < right) {
                        ctx.lineTo(right, bottom);
                    }
                    ctx.lineTo(right, top);
                    ctx.lineTo(left, top);
                }
                else {
                    ctx.lineTo(right, top);
                    ctx.lineTo(left, top);
                    if (sx0 > left) {
                        ctx.lineTo(left, bottom);
                    }
                }
                ctx.closePath();
                this.visuals.above_fill.apply(ctx);
                this.visuals.above_hatch.apply(ctx);
            }
            if (this.visuals.below_fill.doit || this.visuals.below_hatch.doit) {
                const { left, right, top, bottom } = frame.bbox;
                ctx.beginPath();
                ctx.moveTo(sx0, sy0);
                ctx.lineTo(sx0, sy0);
                ctx.lineTo(sx1, sy1);
                if (sy0 <= sy1) {
                    ctx.lineTo(right, bottom);
                    ctx.lineTo(left, bottom);
                    if (sx0 > left) {
                        ctx.lineTo(left, top);
                    }
                }
                else {
                    if (sx1 < right) {
                        ctx.lineTo(right, top);
                    }
                    ctx.lineTo(right, bottom);
                    ctx.lineTo(left, bottom);
                }
                ctx.closePath();
                this.visuals.below_fill.apply(ctx);
                this.visuals.below_hatch.apply(ctx);
            }
            ctx.beginPath();
            ctx.moveTo(sx0, sy0);
            ctx.lineTo(sx1, sy1);
            this.visuals.line.apply(ctx);
            ctx.restore();
        }
    }
    exports.SlopeView = SlopeView;
    SlopeView.__name__ = "SlopeView";
    class Slope extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Slope = Slope;
    _a = Slope;
    Slope.__name__ = "Slope";
    (() => {
        _a.prototype.default_view = SlopeView;
        _a.mixins([
            mixins.Line,
            ["above_", mixins.Fill],
            ["above_", mixins.Hatch],
            ["below_", mixins.Fill],
            ["below_", mixins.Hatch],
        ]);
        _a.define(({ Float, Nullable }) => ({
            gradient: [Nullable(Float), null],
            y_intercept: [Nullable(Float), null],
        }));
        _a.override({
            line_color: "black",
            above_fill_color: null,
            above_fill_alpha: 0.4,
            below_fill_color: null,
            below_fill_alpha: 0.4,
        });
    })();
},
/* models/annotations/span.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(81) /* ./annotation */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const hittest_1 = require(229) /* ../../core/hittest */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const EDGE_TOLERANCE = 2.5;
    class Line {
        constructor(p0, p1) {
            this.p0 = p0;
            this.p1 = p1;
        }
        clone() {
            return new Line({ ...this.p0 }, { ...this.p1 });
        }
        hit_test(pt, tolerance = EDGE_TOLERANCE) {
            return (0, hittest_1.dist_to_segment)(pt, this.p0, this.p1) < tolerance;
        }
        translate(dx, dy) {
            const { p0, p1 } = this;
            const dp0 = { x: p0.x + dx, y: p0.y + dy };
            const dp1 = { x: p1.x + dx, y: p1.y + dy };
            return new Line(dp0, dp1);
        }
    }
    Line.__name__ = "Line";
    class SpanView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this._pan_state = null;
            this._is_hovered = false;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.plot_view.request_paint(this));
        }
        _paint() {
            const { location, location_units } = this.model;
            if (location == null) {
                return;
            }
            function compute(value, units, scale, view, canvas) {
                switch (units) {
                    case "canvas": return canvas.compute(value);
                    case "screen": return view.compute(value);
                    case "data": return scale.compute(value);
                }
            }
            const { frame, canvas } = this.plot_view;
            const { x_scale, y_scale } = this.coordinates;
            let height, sleft, stop, width;
            if (this.model.dimension == "width") {
                stop = compute(location, location_units, y_scale, frame.bbox.yview, canvas.bbox.y_screen);
                sleft = frame.bbox.left;
                width = frame.bbox.width;
                height = this.model.line_width;
            }
            else {
                stop = frame.bbox.top;
                sleft = compute(location, location_units, x_scale, frame.bbox.xview, canvas.bbox.y_screen);
                width = this.model.line_width;
                height = frame.bbox.height;
            }
            const p0 = { x: sleft, y: stop };
            const p1 = { x: sleft + width, y: stop + height };
            this.line = new Line(p0, p1);
            const { _is_hovered, visuals } = this;
            const line = _is_hovered && visuals.hover_line.doit ? visuals.hover_line : visuals.line;
            const { ctx } = this.layer;
            ctx.save();
            ctx.beginPath();
            this.visuals.line.set_value(ctx);
            ctx.moveTo(sleft, stop);
            if (this.model.dimension == "width") {
                ctx.lineTo(sleft + width, stop);
            }
            else {
                ctx.lineTo(sleft, stop + height);
            }
            line.apply(ctx);
            ctx.restore();
        }
        interactive_hit(sx, sy) {
            if (!this.model.visible || !this.model.editable) {
                return false;
            }
            return this._hit_test(sx, sy) != null;
        }
        _hit_test(sx, sy) {
            const tolerance = Math.max(EDGE_TOLERANCE, this.model.line_width / 2);
            return this.line.hit_test({ x: sx, y: sy }, tolerance) ? "edge" : null;
        }
        _can_hit(_target) {
            return true;
        }
        on_pan_start(ev) {
            if (this.model.visible && this.model.editable) {
                const { sx, sy } = ev;
                const target = this._hit_test(sx, sy);
                if (target != null && this._can_hit(target)) {
                    this._pan_state = {
                        line: this.line.clone(),
                        target,
                    };
                    this.model.pan.emit(["pan:start", ev.modifiers]);
                    return true;
                }
            }
            return false;
        }
        on_pan(ev) {
            (0, assert_1.assert)(this._pan_state != null);
            function invert(sv, units, scale, view, canvas) {
                switch (units) {
                    case "canvas": return canvas.invert(sv);
                    case "screen": return view.invert(sv);
                    case "data": return scale.invert(sv);
                }
            }
            const sloc = (() => {
                const { dx, dy } = ev;
                const { line } = this._pan_state;
                if (this.model.dimension == "width") {
                    return line.translate(0, dy).p0.y;
                }
                else {
                    return line.translate(dx, 0).p0.x;
                }
            })();
            const loc = (() => {
                const { location_units } = this.model;
                const { frame, canvas } = this.plot_view;
                const { x_scale, y_scale } = this.coordinates;
                if (this.model.dimension == "width") {
                    return invert(sloc, location_units, y_scale, frame.bbox.yview, canvas.bbox.y_screen);
                }
                else {
                    return invert(sloc, location_units, x_scale, frame.bbox.xview, canvas.bbox.y_screen);
                }
            })();
            this.model.location = loc;
            this.model.pan.emit(["pan", ev.modifiers]);
        }
        on_pan_end(ev) {
            this._pan_state = null;
            this.model.pan.emit(["pan:end", ev.modifiers]);
        }
        get _has_hover() {
            const { hover_line } = this.visuals;
            return hover_line.doit;
        }
        on_enter(_ev) {
            const { _has_hover } = this;
            if (_has_hover) {
                this._is_hovered = true;
                this.request_paint();
            }
            return _has_hover;
        }
        on_move(_ev) { }
        on_leave(_ev) {
            if (this._has_hover) {
                this._is_hovered = false;
                this.request_paint();
            }
        }
        cursor(sx, sy) {
            const target = this._pan_state?.target ?? this._hit_test(sx, sy);
            if (target == null || !this._can_hit(target)) {
                return null;
            }
            return this.model.dimension == "width" ? "ns-resize" : "ew-resize";
        }
    }
    exports.SpanView = SpanView;
    SpanView.__name__ = "SpanView";
    class Span extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
            this.pan = new signaling_1.Signal(this, "pan");
        }
    }
    exports.Span = Span;
    _a = Span;
    Span.__name__ = "Span";
    (() => {
        _a.prototype.default_view = SpanView;
        _a.mixins([
            mixins.Line,
            ["hover_", mixins.Line],
        ]);
        _a.define(({ Bool, Float, Nullable }) => ({
            location: [Nullable(Float), null],
            location_units: [enums_1.CoordinateUnits, "data"],
            dimension: [enums_1.Dimension, "width"],
            editable: [Bool, false],
        }));
        _a.override({
            line_color: "black",
            hover_line_color: null,
            hover_line_alpha: 0.3,
        });
    })();
},
/* models/annotations/toolbar_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const annotation_1 = require(81) /* ./annotation */;
    const toolbar_1 = require(292) /* ../tools/toolbar */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const dom_1 = require(63) /* ../../core/dom */;
    const side_panel_1 = require(173) /* ../../core/layout/side_panel */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    class ToolbarPanelView extends annotation_1.AnnotationView {
        constructor() {
            super(...arguments);
            this._previous_bbox = new bbox_1.BBox();
        }
        rendering_target() {
            return this.plot_view.canvas_view.events_el;
        }
        update_layout() {
            this.layout = new side_panel_1.SideLayout(this.panel, () => this.get_size(), true);
        }
        after_layout() {
            this.toolbar_view.after_render();
        }
        has_finished() {
            return super.has_finished() && this.toolbar_view.has_finished();
        }
        *children() {
            yield* super.children();
            yield this.toolbar_view;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.toolbar_view = await (0, build_views_1.build_view)(this.model.toolbar, { parent: this.canvas });
        }
        connect_signals() {
            super.connect_signals();
            this.plot_view.mouseenter.connect(() => {
                this.toolbar_view.set_visibility(true);
            });
            this.plot_view.mouseleave.connect(() => {
                this.toolbar_view.set_visibility(false);
            });
        }
        remove() {
            this.toolbar_view.remove();
            super.remove();
        }
        render() {
            super.render();
            this.toolbar_view.render_to(this.shadow_el);
        }
        _paint() {
            // TODO this shouldn't be necessary
            (0, dom_1.display)(this.el);
            // TODO: this should be handled by the layout
            const { bbox } = this.layout;
            if (!this._previous_bbox.equals(bbox)) {
                (0, dom_1.position)(this.el, bbox);
                this._previous_bbox = bbox;
                (0, dom_1.empty)(this.el);
                this.el.style.position = "absolute";
                const { style } = this.toolbar_view.el;
                if (this.toolbar_view.model.horizontal) {
                    style.width = "100%";
                    style.height = "unset";
                }
                else {
                    style.width = "unset";
                    style.height = "100%";
                }
            }
            if (!this.model.visible) {
                (0, dom_1.undisplay)(this.el);
            }
        }
        _get_size() {
            const { tools, logo } = this.model.toolbar;
            return {
                width: tools.length * 30 + (logo != null ? 25 : 0) + 15, // TODO: approximate, use a proper layout instead.
                height: 30,
            };
        }
    }
    exports.ToolbarPanelView = ToolbarPanelView;
    ToolbarPanelView.__name__ = "ToolbarPanelView";
    class ToolbarPanel extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ToolbarPanel = ToolbarPanel;
    _a = ToolbarPanel;
    ToolbarPanel.__name__ = "ToolbarPanel";
    (() => {
        _a.prototype.default_view = ToolbarPanelView;
        _a.define(({ Ref }) => ({
            toolbar: [Ref(toolbar_1.Toolbar)],
        }));
    })();
},
/* models/tools/toolbar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const logging_1 = require(19) /* ../../core/logging */;
    const dom_1 = require(63) /* ../../core/dom */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_1 = require(8) /* ../../core/util/types */;
    const tool_1 = require(293) /* ./tool */;
    const tool_proxy_1 = require(294) /* ./tool_proxy */;
    const tool_button_1 = require(295) /* ./tool_button */;
    const gesture_tool_1 = require(300) /* ./gestures/gesture_tool */;
    const inspect_tool_1 = require(302) /* ./inspectors/inspect_tool */;
    const action_tool_1 = require(303) /* ./actions/action_tool */;
    const help_tool_1 = require(305) /* ./actions/help_tool */;
    const menus_1 = require(297) /* ../../core/util/menus */;
    const toolbar_css_1 = tslib_1.__importStar(require(306) /* ../../styles/toolbar.css */), toolbars = toolbar_css_1;
    const logo_css_1 = tslib_1.__importStar(require(307) /* ../../styles/logo.css */), logos = logo_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(123) /* ../../styles/icons.css */);
    class ToolbarView extends ui_element_1.UIElementView {
        constructor() {
            super(...arguments);
            this._tool_button_views = new Map();
            this._items = [];
            this._visible = null;
        }
        get tool_buttons() {
            return this._tool_buttons.flat();
        }
        get overflow_el() {
            return this._overflow_el;
        }
        get visible() {
            return !this.model.visible ? false : (!this.model.autohide || (this._visible ?? false));
        }
        *children() {
            yield* super.children();
            yield* this._tool_button_views.values();
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            for (const child_view of this._tool_button_views.values()) {
                if (!child_view.has_finished()) {
                    return false;
                }
            }
            return true;
        }
        initialize() {
            super.initialize();
            const { location } = this.model;
            const reversed = location == "left" || location == "above";
            const orientation = this.model.horizontal ? "vertical" : "horizontal";
            this._overflow_menu = new menus_1.ContextMenu([], {
                target: this.el,
                orientation,
                reversed,
                prevent_hide: (event) => {
                    return event.composedPath().includes(this._overflow_el);
                },
            });
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._build_tool_button_views();
        }
        connect_signals() {
            super.connect_signals();
            const { buttons, tools, location, autohide } = this.model.properties;
            this.on_change([buttons, tools], async () => {
                await this._build_tool_button_views();
                this.render();
            });
            this.on_change(location, () => {
                this.render();
            });
            this.on_change(autohide, () => {
                this._on_visible_change();
            });
        }
        stylesheets() {
            return [...super.stylesheets(), toolbar_css_1.default, logo_css_1.default, icons_css_1.default];
        }
        remove() {
            (0, build_views_1.remove_views)(this._tool_button_views);
            super.remove();
        }
        async _build_tool_button_views() {
            this._tool_buttons = (() => {
                const { buttons } = this.model;
                if (buttons == "auto") {
                    const groups = [
                        ...(0, object_1.values)(this.model.gestures).map((gesture) => gesture.tools),
                        this.model.actions,
                        this.model.inspectors,
                        this.model.auxiliaries,
                    ];
                    const buttons = groups.map((group) => {
                        return group
                            .filter((tool) => tool.visible)
                            .map((tool) => tool.tool_button());
                    });
                    return buttons;
                }
                else {
                    return (0, array_1.split)(buttons, null);
                }
            })();
            await (0, build_views_1.build_views)(this._tool_button_views, this._tool_buttons.flat(), { parent: this });
        }
        set_visibility(visible) {
            if (visible != this._visible) {
                this._visible = visible;
                this._on_visible_change();
            }
        }
        _on_visible_change() {
            this.el.classList.toggle(toolbars.hidden, !this.visible);
        }
        _after_resize() {
            super._after_resize();
            this._after_render();
        }
        _menu_at() {
            switch (this.model.location) {
                case "right": return { left_of: this._overflow_el };
                case "left": return { right_of: this._overflow_el };
                case "above": return { below: this._overflow_el };
                case "below": return { above: this._overflow_el };
            }
        }
        toggle_menu() {
            this._overflow_menu.toggle(this._menu_at());
        }
        render() {
            super.render();
            this.el.classList.add(toolbars[this.model.location]);
            this.el.classList.toggle(toolbars.inner, this.model.inner);
            this._on_visible_change();
            const { horizontal } = this.model;
            this._overflow_el = (0, dom_1.div)({ class: toolbars.tool_overflow, tabIndex: 0 }, horizontal ? "⋮" : "⋯");
            this._overflow_el.addEventListener("click", (_event) => {
                this.toggle_menu();
            });
            this._overflow_el.addEventListener("keydown", (event) => {
                if (event.key == "Enter") {
                    this.toggle_menu();
                }
            });
            this._items = [];
            if (this.model.logo != null) {
                const gray = this.model.logo === "grey" ? logos.grey : null;
                const logo_el = (0, dom_1.a)({ href: "https://bokeh.org/", target: "_blank", class: [logos.logo, logos.logo_small, gray] });
                this._items.push(logo_el);
                this.shadow_el.appendChild(logo_el);
            }
            for (const [, button_view] of this._tool_button_views) {
                button_view.render_to(this.shadow_el);
            }
            const bars = this._tool_buttons.map((group) => group.map((button) => this._tool_button_views.get(button).el));
            const non_empty = bars.filter((bar) => bar.length != 0);
            const divider = () => (0, dom_1.div)({ class: toolbars.divider });
            for (const el of (0, iterator_1.join)(non_empty, divider)) {
                this._items.push(el);
                this.shadow_el.append(el);
            }
        }
        _after_render() {
            super._after_render();
            (0, array_1.clear)(this._overflow_menu.items);
            if (this.shadow_el.contains(this._overflow_el)) {
                this.shadow_el.removeChild(this._overflow_el);
            }
            for (const el of this._items) {
                if (!this.shadow_el.contains(el)) {
                    this.shadow_el.append(el);
                }
            }
            const { horizontal } = this.model;
            const overflow_size = 15;
            const { bbox } = this;
            const overflow_cls = horizontal ? toolbars.right : toolbars.above;
            let size = 0;
            let overflowed = false;
            for (const el of this._items) {
                if (overflowed) {
                    this.shadow_el.removeChild(el);
                    this._overflow_menu.items.push({ custom: el, class: overflow_cls });
                }
                else {
                    const { width, height } = el.getBoundingClientRect();
                    size += horizontal ? width : height;
                    overflowed = horizontal ? size > bbox.width - overflow_size : size > bbox.height - overflow_size;
                    if (overflowed) {
                        this.shadow_el.removeChild(el);
                        this.shadow_el.appendChild(this._overflow_el);
                        this._overflow_menu.items.push({ custom: el, class: overflow_cls });
                    }
                }
            }
            if (this._overflow_menu.is_open) {
                this._overflow_menu.show(this._menu_at());
            }
        }
    }
    exports.ToolbarView = ToolbarView;
    ToolbarView.__name__ = "ToolbarView";
    const kinds_1 = require(21) /* ../../core/kinds */;
    const GestureToolLike = (0, kinds_1.Or)((0, kinds_1.Ref)(gesture_tool_1.GestureTool), (0, kinds_1.Ref)((tool_proxy_1.ToolProxy)));
    const GestureEntry = (0, kinds_1.Struct)({
        tools: (0, kinds_1.List)(GestureToolLike),
        active: (0, kinds_1.Nullable)(GestureToolLike),
    });
    const GesturesMap = (0, kinds_1.Struct)({
        pan: GestureEntry,
        scroll: GestureEntry,
        pinch: GestureEntry,
        rotate: GestureEntry,
        move: GestureEntry,
        tap: GestureEntry,
        doubletap: GestureEntry,
        press: GestureEntry,
        pressup: GestureEntry,
        multi: GestureEntry,
    });
    exports.Inspection = tool_1.Tool;
    function create_gesture_map() {
        return {
            pan: { tools: [], active: null },
            scroll: { tools: [], active: null },
            pinch: { tools: [], active: null },
            rotate: { tools: [], active: null },
            move: { tools: [], active: null },
            tap: { tools: [], active: null },
            doubletap: { tools: [], active: null },
            press: { tools: [], active: null },
            pressup: { tools: [], active: null },
            multi: { tools: [], active: null },
        };
    }
    class Toolbar extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        get horizontal() {
            return this.location == "above" || this.location == "below";
        }
        get vertical() {
            return this.location == "left" || this.location == "right";
        }
        connect_signals() {
            super.connect_signals();
            const { tools, active_drag, active_inspect, active_scroll, active_tap, active_multi } = this.properties;
            this.on_change([tools, active_drag, active_inspect, active_scroll, active_tap, active_multi], () => {
                this._init_tools();
                this._activate_tools();
            });
        }
        initialize() {
            super.initialize();
            this._init_tools();
            this._activate_tools();
        }
        _init_tools() {
            const visited = new Set();
            function isa(tool, type) {
                const is = (tool instanceof tool_proxy_1.ToolProxy ? tool.underlying : tool) instanceof type;
                if (is) {
                    visited.add(tool);
                }
                return is;
            }
            const new_inspectors = this.tools.filter(t => isa(t, inspect_tool_1.InspectTool));
            this.inspectors = new_inspectors;
            const new_help = this.tools.filter(t => isa(t, help_tool_1.HelpTool));
            this.help = new_help;
            const new_actions = this.tools.filter(t => isa(t, action_tool_1.ActionTool));
            this.actions = new_actions;
            const new_gestures = create_gesture_map();
            for (const tool of this.tools) {
                if (isa(tool, gesture_tool_1.GestureTool)) {
                    new_gestures[tool.event_role].tools.push(tool);
                }
            }
            for (const et of (0, object_1.typed_keys)(new_gestures)) {
                const gesture = this.gestures[et];
                gesture.tools = (0, array_1.sort_by)(new_gestures[et].tools, (tool) => tool.default_order);
                if (gesture.active != null && (0, array_1.every)(gesture.tools, (tool) => tool.id != gesture.active?.id)) {
                    gesture.active = null;
                }
            }
            const new_auxiliaries = this.tools.filter((tool) => !visited.has(tool));
            this.auxiliaries = new_auxiliaries;
        }
        _activate_tools() {
            if (this.active_inspect == "auto") {
                // do nothing as all tools are active be default
            }
            else if (this.active_inspect == null) {
                for (const inspector of this.inspectors) {
                    inspector.active = false;
                }
            }
            else if ((0, types_1.isArray)(this.active_inspect)) {
                const active_inspect = (0, array_1.intersection)(this.active_inspect, this.inspectors);
                if (active_inspect.length != this.active_inspect.length) {
                    this.active_inspect = active_inspect;
                }
                for (const inspector of this.inspectors) {
                    if (!(0, array_1.includes)(this.active_inspect, inspector)) {
                        inspector.active = false;
                    }
                }
            }
            else {
                let found = false;
                for (const inspector of this.inspectors) {
                    if (inspector != this.active_inspect) {
                        inspector.active = false;
                    }
                    else {
                        found = true;
                    }
                }
                if (!found) {
                    this.active_inspect = null;
                }
            }
            const _activate_gesture = (tool) => {
                if (tool.active) {
                    // tool was activated by a proxy, but we need to finish configuration manually
                    this._active_change(tool);
                }
                else {
                    tool.active = true;
                }
            };
            // Connecting signals has to be done before changing the active state of the tools.
            for (const gesture of (0, object_1.values)(this.gestures)) {
                for (const tool of gesture.tools) {
                    // XXX: connect once
                    this.connect(tool.properties.active.change, () => this._active_change(tool));
                }
            }
            function _get_active_attr(et) {
                switch (et) {
                    case "tap": return "active_tap";
                    case "pan": return "active_drag";
                    case "pinch":
                    case "scroll": return "active_scroll";
                    case "multi": return "active_multi";
                    default: return null;
                }
            }
            function _supports_auto(et, tool) {
                return et == "tap" || et == "pan" || tool.supports_auto();
            }
            const is_active_gesture = (active_tool) => {
                return this.tools.includes(active_tool) || (active_tool instanceof tool_1.Tool && this.tools.some((tool) => tool instanceof tool_proxy_1.ToolProxy && tool.tools.includes(active_tool)));
            };
            for (const [event_role, gesture] of (0, object_1.entries)(this.gestures)) {
                const et = event_role;
                const active_attr = _get_active_attr(et);
                if (active_attr != null) {
                    const active_tool = this[active_attr];
                    if (active_tool == "auto") {
                        if (gesture.tools.length != 0) {
                            const [tool] = gesture.tools;
                            if (_supports_auto(et, tool)) {
                                _activate_gesture(tool);
                            }
                        }
                    }
                    else if (active_tool != null) {
                        if (is_active_gesture(active_tool)) {
                            _activate_gesture(active_tool);
                        }
                        else {
                            this[active_attr] = null;
                        }
                    }
                    else {
                        this.gestures[et].active = null;
                        for (const tool of this.gestures[et].tools) {
                            tool.active = false;
                        }
                    }
                }
            }
        }
        _active_change(tool) {
            const { event_types } = tool;
            for (const et of event_types) {
                if (tool.active) {
                    const currently_active_tool = this.gestures[et].active;
                    if (currently_active_tool != null && tool != currently_active_tool) {
                        logging_1.logger.debug(`Toolbar: deactivating tool: ${currently_active_tool} for event type '${et}'`);
                        currently_active_tool.active = false;
                    }
                    this.gestures[et].active = tool;
                    logging_1.logger.debug(`Toolbar: activating tool: ${tool} for event type '${et}'`);
                }
                else {
                    this.gestures[et].active = null;
                }
            }
        }
    }
    exports.Toolbar = Toolbar;
    _a = Toolbar;
    Toolbar.__name__ = "Toolbar";
    (() => {
        _a.prototype.default_view = ToolbarView;
        _a.define(({ Bool, List, Or, Ref, Nullable, Auto }) => ({
            tools: [List(Or(Ref(tool_1.Tool), Ref(tool_proxy_1.ToolProxy))), []],
            logo: [Nullable(enums_1.Logo), "normal"],
            autohide: [Bool, false],
            active_drag: [Nullable(Or(GestureToolLike, Auto)), "auto"],
            active_inspect: [Nullable(Or(Ref(exports.Inspection), List(Ref(exports.Inspection)), Ref(tool_proxy_1.ToolProxy), Auto)), "auto"],
            active_scroll: [Nullable(Or(GestureToolLike, Auto)), "auto"],
            active_tap: [Nullable(Or(GestureToolLike, Auto)), "auto"],
            active_multi: [Nullable(Or(GestureToolLike, Auto)), "auto"],
        }));
        _a.internal(({ List, Bool, Ref, Or, Null, Auto }) => {
            return {
                buttons: [Or(List(Or(Ref(tool_button_1.ToolButton), Null)), Auto), "auto"],
                location: [enums_1.Location, "right"],
                inner: [Bool, false],
                gestures: [GesturesMap, create_gesture_map],
                actions: [List(Or(Ref(action_tool_1.ActionTool), Ref(tool_proxy_1.ToolProxy))), []],
                inspectors: [List(Or(Ref(inspect_tool_1.InspectTool), Ref(tool_proxy_1.ToolProxy))), []],
                auxiliaries: [List(Or(Ref(tool_1.Tool), Ref(tool_proxy_1.ToolProxy))), []],
                help: [List(Or(Ref(help_tool_1.HelpTool), Ref(tool_proxy_1.ToolProxy))), []],
            };
        });
    })();
},
/* models/tools/tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const view_1 = require(58) /* ../../core/view */;
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    const types_1 = require(8) /* ../../core/util/types */;
    const model_1 = require(51) /* ../../model */;
    class ToolView extends view_1.View {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.active.change, () => {
                if (this.model.active) {
                    this.activate();
                }
                else {
                    this.deactivate();
                }
            });
        }
        get overlays() {
            return [];
        }
        // activate is triggered by toolbar ui actions
        activate() { }
        // deactivate is triggered by toolbar ui actions
        deactivate() { }
    }
    exports.ToolView = ToolView;
    ToolView.__name__ = "ToolView";
    class Tool extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        get event_role() {
            const { event_type } = this;
            return (0, types_1.isString)(event_type) ? event_type : "multi";
        }
        get event_types() {
            const { event_type } = this;
            return event_type == null ? [] : ((0, types_1.isString)(event_type) ? [event_type] : event_type);
        }
        get tooltip() {
            return this.description ?? this.tool_name;
        }
        get computed_icon() {
            const { icon, tool_icon } = this;
            return icon ?? (tool_icon != null ? `.${tool_icon}` : undefined);
        }
        get menu() {
            return null;
        }
        supports_auto() {
            return false;
        }
        // utility function to get limits along both dimensions, given
        // optional dimensional constraints
        _get_dim_limits([sx0, sy0], [sx1, sy1], frame, dims) {
            const hr = frame.bbox.h_range;
            let sxlim;
            if (dims == "width" || dims == "both") {
                sxlim = [(0, array_1.min)([sx0, sx1]), (0, array_1.max)([sx0, sx1])];
                sxlim = [(0, array_1.max)([sxlim[0], hr.start]), (0, array_1.min)([sxlim[1], hr.end])];
            }
            else {
                sxlim = [hr.start, hr.end];
            }
            const vr = frame.bbox.v_range;
            let sylim;
            if (dims == "height" || dims == "both") {
                sylim = [(0, array_1.min)([sy0, sy1]), (0, array_1.max)([sy0, sy1])];
                sylim = [(0, array_1.max)([sylim[0], vr.start]), (0, array_1.min)([sylim[1], vr.end])];
            }
            else {
                sylim = [vr.start, vr.end];
            }
            return [sxlim, sylim];
        }
        // utility function to return a tool name, modified
        // by the active dimensions. Used by tools that have dimensions
        _get_dim_tooltip(dims) {
            const { description, tool_name } = this;
            if (description != null) {
                return description;
            }
            else if (dims == "both") {
                return tool_name;
            }
            else if (dims == "auto") {
                return `${tool_name} (either x, y or both dimensions)`;
            }
            else {
                return `${tool_name} (${dims == "width" ? "x" : "y"}-axis)`;
            }
        }
        static register_alias(name, fn) {
            this.prototype._known_aliases.set(name, fn);
        }
        static from_string(name) {
            const fn = this.prototype._known_aliases.get(name);
            if (fn != null) {
                return fn();
            }
            else {
                const names = [...this.prototype._known_aliases.keys()];
                throw new Error(`unexpected tool name '${name}', possible tools are ${names.join(", ")}`);
            }
        }
    }
    exports.Tool = Tool;
    _a = Tool;
    Tool.__name__ = "Tool";
    (() => {
        _a.prototype._known_aliases = new Map();
        _a.define(({ Bool, Str, Regex, Nullable, Or }) => ({
            icon: [Nullable(Or(enums_1.ToolIcon, Regex(/^--/), Regex(/^\./), Regex(/^data:image/))), null],
            description: [Nullable(Str), null],
            visible: [Bool, true],
        }));
        _a.internal(({ Bool }) => ({
            active: [Bool, false],
            disabled: [Bool, false],
        }));
    })();
},
/* models/tools/tool_proxy.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const signaling_1 = require(15) /* ../../core/signaling */;
    const model_1 = require(51) /* ../../model */;
    const tool_1 = require(293) /* ./tool */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    class ToolProxy extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        // Operates all the tools given only one button
        get underlying() {
            return this.tools[0];
        }
        tool_button() {
            const button = this.tools[0].tool_button();
            button.tool = this;
            return button;
        }
        get event_type() {
            return this.tools[0].event_type;
        }
        get event_role() {
            return this.tools[0].event_role;
        }
        get event_types() {
            return this.tools[0].event_types;
        }
        get default_order() {
            return this.tools[0].default_order; // only gestures etc.
        }
        get tooltip() {
            return this.tools[0].tooltip;
        }
        get tool_name() {
            return this.tools[0].tool_name;
        }
        get computed_icon() {
            return this.tools[0].computed_icon;
        }
        get toggleable() {
            const tool = this.tools[0];
            return "toggleable" in tool && tool.toggleable;
        }
        get visible() {
            const tool = this.tools[0];
            return tool.visible;
        }
        initialize() {
            super.initialize();
            this.do = new signaling_1.Signal0(this, "do");
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.do, () => this.doit());
            this.connect(this.properties.active.change, () => this.set_active());
            for (const tool of this.tools) {
                this.connect(tool.properties.active.change, () => {
                    this.active = tool.active;
                });
            }
        }
        doit() {
            for (const tool of this.tools) {
                tool.do.emit();
            }
        }
        set_active() {
            for (const tool of this.tools) {
                tool.active = this.active;
            }
        }
        get menu() {
            const { menu } = this.tools[0];
            if (menu == null) {
                return null;
            }
            const items = [];
            for (const [item, i] of (0, iterator_1.enumerate)(menu)) {
                if (item == null) {
                    items.push(null);
                }
                else {
                    const handler = () => {
                        for (const tool of this.tools) {
                            tool.menu?.[i]?.handler?.();
                        }
                    };
                    items.push({ ...item, handler });
                }
            }
            return items;
        }
        supports_auto() {
            return this.tools[0].supports_auto();
        }
    }
    exports.ToolProxy = ToolProxy;
    _a = ToolProxy;
    ToolProxy.__name__ = "ToolProxy";
    (() => {
        _a.define(({ Bool, List, Ref }) => ({
            tools: [List(Ref(tool_1.Tool)), []],
            active: [Bool, (self) => (0, iterator_1.some)(self.tools, (tool) => tool.active)],
            disabled: [Bool, false],
        }));
    })();
},
/* models/tools/tool_button.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    const tool_1 = require(293) /* ./tool */;
    const tool_proxy_1 = require(294) /* ./tool_proxy */;
    const ui_gestures_1 = require(296) /* ../../core/ui_gestures */;
    const dom_1 = require(63) /* ../../core/dom */;
    const enums_1 = require(20) /* ../../core/enums */;
    const menus_1 = require(297) /* ../../core/util/menus */;
    const array_1 = require(10) /* ../../core/util/array */;
    const tool_button_css_1 = tslib_1.__importStar(require(299) /* ../../styles/tool_button.css */), tool_button = tool_button_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(123) /* ../../styles/icons.css */);
    class ToolButtonView extends ui_element_1.UIElementView {
        initialize() {
            super.initialize();
            const { location } = this.parent.model;
            const reverse = location == "left" || location == "above";
            const orientation = this.parent.model.horizontal ? "vertical" : "horizontal";
            const items = this.model.tool.menu ?? [];
            this._menu = new menus_1.ContextMenu(!reverse ? items : (0, array_1.reversed)(items), {
                target: this.parent.el,
                orientation,
                prevent_hide: (event) => {
                    return event.composedPath().includes(this.el);
                },
            });
            this._ui_gestures = new ui_gestures_1.UIGestures(this.el, {
                on_tap: (event) => {
                    if (this._menu.is_open) {
                        this._menu.hide();
                        return;
                    }
                    if (event.native.composedPath().includes(this.el)) {
                        this._clicked();
                    }
                },
                on_press: () => {
                    this._pressed();
                },
            });
            this.el.addEventListener("keydown", (event) => {
                switch (event.key) {
                    case "Enter": {
                        this._clicked();
                        break;
                    }
                    case " ": {
                        this._pressed();
                        break;
                    }
                    default:
                }
            });
        }
        connect_signals() {
            super.connect_signals();
            this._ui_gestures.connect_signals();
            this.connect(this.model.change, () => this.render());
            this.connect(this.model.tool.change, () => this.render());
        }
        remove() {
            this._ui_gestures.remove();
            this._menu.remove();
            super.remove();
        }
        stylesheets() {
            return [...super.stylesheets(), tool_button_css_1.default, icons_css_1.default];
        }
        render() {
            super.render();
            this.class_list.add(tool_button[this.parent.model.location]);
            if (this.model.tool.disabled) {
                this.class_list.add(tool_button.disabled);
            }
            const icon_el = (0, dom_1.div)({ class: tool_button.tool_icon });
            this.shadow_el.appendChild(icon_el);
            const icon = this.model.icon ?? this.model.tool.computed_icon;
            if (icon != null) {
                if (icon.startsWith("data:image")) {
                    const url = `url("${encodeURI(icon)}")`;
                    icon_el.style.backgroundImage = url;
                }
                else if (icon.startsWith("--")) {
                    icon_el.style.backgroundImage = `var(${icon})`;
                }
                else if (icon.startsWith(".")) {
                    const cls = icon.substring(1);
                    icon_el.classList.add(cls);
                }
                else if (enums_1.ToolIcon.valid(icon)) {
                    const cls = `bk-tool-icon-${icon.replace(/_/g, "-")}`;
                    icon_el.classList.add(cls);
                }
            }
            if (this.model.tool.menu != null) {
                const chevron_el = (0, dom_1.div)({ class: tool_button.tool_chevron });
                this.shadow_el.appendChild(chevron_el);
            }
            const tooltip = this.model.tooltip ?? this.model.tool.tooltip;
            this.el.title = tooltip;
            this.el.tabIndex = 0;
        }
        _pressed() {
            const at = (() => {
                switch (this.parent.model.location) {
                    case "right": return { left_of: this.el };
                    case "left": return { right_of: this.el };
                    case "above": return { below: this.el };
                    case "below": return { above: this.el };
                }
            })();
            this._menu.toggle(at);
        }
    }
    exports.ToolButtonView = ToolButtonView;
    ToolButtonView.__name__ = "ToolButtonView";
    class ToolButton extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ToolButton = ToolButton;
    _a = ToolButton;
    ToolButton.__name__ = "ToolButton";
    (() => {
        _a.define(({ Str, Regex, Ref, Nullable, Or }) => ({
            tool: [Or(Ref(tool_1.Tool), Ref(tool_proxy_1.ToolProxy))],
            icon: [Nullable(Or(enums_1.ToolIcon, Regex(/^--/), Regex(/^\./), Regex(/^data:image/))), null],
            tooltip: [Nullable(Str), null],
        }));
    })();
},
/* core/ui_gestures.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const dom_1 = require(63) /* ./dom */;
    const assert_1 = require(12) /* ./util/assert */;
    class UIGestures {
        constructor(hit_area, handlers, options = {}) {
            this.phase = "idle";
            this.pointers = new Map();
            this.press_timer = null;
            this.tap_timestamp = -Infinity;
            this.last_scale = null;
            this.last_rotation = null;
            this.hit_area = hit_area;
            this.handlers = handlers;
            this.must_be_target = options.must_be_target ?? false;
            this._pointer_over = this._pointer_over.bind(this);
            this._pointer_out = this._pointer_out.bind(this);
            this._pointer_down = this._pointer_down.bind(this);
            this._pointer_move = this._pointer_move.bind(this);
            this._pointer_up = this._pointer_up.bind(this);
            this._pointer_cancel = this._pointer_cancel.bind(this);
        }
        connect_signals() {
            this.hit_area.addEventListener("pointerover", this._pointer_over);
            this.hit_area.addEventListener("pointerout", this._pointer_out);
            this.hit_area.addEventListener("pointerdown", this._pointer_down);
            this.hit_area.addEventListener("pointermove", this._pointer_move);
            this.hit_area.addEventListener("pointerup", this._pointer_up);
            this.hit_area.addEventListener("pointercancel", this._pointer_cancel);
        }
        disconnect_signals() {
            this.hit_area.removeEventListener("pointerover", this._pointer_over);
            this.hit_area.removeEventListener("pointerout", this._pointer_out);
            this.hit_area.removeEventListener("pointerdown", this._pointer_down);
            this.hit_area.removeEventListener("pointermove", this._pointer_move);
            this.hit_area.removeEventListener("pointerup", this._pointer_up);
            this.hit_area.removeEventListener("pointercancel", this._pointer_cancel);
        }
        remove() {
            this.disconnect_signals();
        }
        _self_is_target(event) {
            return event.composedPath()[0] == this.hit_area;
        }
        _is_event_target(event) {
            return !this.must_be_target || this._self_is_target(event);
        }
        reset() {
            this._cancel_timeout();
            this.phase = "idle";
            this.pointers.clear();
            this.press_timer = null;
            this.tap_timestamp = -Infinity;
            this.last_scale = null;
            this.last_rotation = null;
        }
        get _is_multi_gesture() {
            return this.pointers.size >= 2;
        }
        _within_threshold(ptr) {
            const { dx, dy } = this._movement(ptr);
            return dx ** 2 + dy ** 2 <= UIGestures.move_threshold ** 2;
        }
        get _any_movement() {
            return [...this.pointers.values()].some((ptr) => !this._within_threshold(ptr));
        }
        _start_timeout() {
            (0, assert_1.assert)(this.press_timer == null);
            this.press_timer = setTimeout(() => this._pointer_timeout(), UIGestures.press_threshold);
        }
        _cancel_timeout() {
            const { press_timer } = this;
            if (press_timer != null) {
                clearTimeout(press_timer);
                this.press_timer = null;
            }
        }
        _pointer_timeout() {
            (0, assert_1.assert)(this.phase == "started");
            (0, assert_1.assert)(!this._is_multi_gesture);
            this.phase = "pressing";
            this.press_timer = null;
            const [pointer] = this.pointers.values();
            this.on_press(pointer.init);
        }
        _pointer_over(event) {
            if (!this._is_event_target(event)) {
                return;
            }
            if (event.isPrimary) {
                this.on_enter(event);
            }
        }
        _pointer_out(event) {
            if (!this._is_event_target(event)) {
                return;
            }
            if (event.isPrimary) {
                this.on_leave(event);
            }
        }
        _pointer_down(event) {
            if (!this._is_event_target(event)) {
                return;
            }
            if (this._is_multi_gesture) {
                return;
            }
            if (this.pointers.has(event.pointerId)) {
                return;
            }
            if (event.isPrimary && event.pointerType == "mouse" && event.buttons != dom_1.MouseButton.Left) {
                return;
            }
            if (!this.hit_area.isConnected) {
                return;
            }
            this.pointers.set(event.pointerId, { init: event, last: event });
            this.hit_area.setPointerCapture(event.pointerId);
            switch (this.phase) {
                case "idle": {
                    this.phase = "started";
                    this._start_timeout();
                    break;
                }
                case "started": {
                    this._cancel_timeout();
                    break;
                }
                case "pressing":
                case "panning":
                case "pinching":
                case "rotating":
                case "transitional":
                    break;
            }
        }
        _pointer_move(event) {
            if (!this._is_event_target(event)) {
                return;
            }
            if (event.isPrimary) {
                this.on_move(event);
            }
            const pointer = this.pointers.get(event.pointerId);
            if (pointer == null) {
                return;
            }
            pointer.last = event;
            switch (this.phase) {
                case "idle": {
                    this.reset();
                    (0, assert_1.unreachable)();
                }
                case "started":
                case "transitional": {
                    if (!this._any_movement) {
                        return;
                    }
                    this._cancel_timeout();
                    if (!this._is_multi_gesture) {
                        this.phase = "panning";
                        const [ptr] = this.pointers.values();
                        const { dx, dy } = this._movement(ptr);
                        this.on_pan_start(ptr.init, 0, 0);
                        this.on_pan(ptr.last, dx, dy);
                    }
                    else {
                        const [ptr0, ptr1] = this.pointers.values();
                        const scale = this._scale(ptr0, ptr1);
                        const rotation = this._rotation(ptr0, ptr1);
                        if (Math.abs(scale - 1) > UIGestures.pinch_threshold) {
                            this.phase = "pinching";
                            this.on_pinch_start(ptr0.init, ptr1.init, 1);
                            this.on_pinch(ptr0.last, ptr1.last, scale);
                            this.last_scale = scale;
                        }
                        else if (Math.abs(rotation) > UIGestures.rotate_threshold) {
                            this.phase = "rotating";
                            this.on_rotate_start(ptr0.init, ptr1.init, 0);
                            this.on_rotate(ptr1.last, ptr1.last, rotation);
                            this.last_rotation = rotation;
                        }
                    }
                    break;
                }
                case "pressing": {
                    break;
                }
                case "panning": {
                    const [ptr] = this.pointers.values();
                    const { dx, dy } = this._movement(ptr);
                    this.on_pan(event, dx, dy);
                    break;
                }
                case "pinching": {
                    const [ptr0, ptr1] = this.pointers.values();
                    const scale = this._scale(ptr0, ptr1);
                    if (scale != this.last_scale) {
                        this.on_pinch(ptr0.last, ptr1.last, scale);
                        this.last_scale = scale;
                    }
                    break;
                }
                case "rotating": {
                    const [ptr0, ptr1] = this.pointers.values();
                    const rotation = this._rotation(ptr0, ptr1);
                    if (rotation != this.last_rotation) {
                        this.on_rotate(ptr0.last, ptr1.last, rotation);
                        this.last_rotation = rotation;
                    }
                    break;
                }
            }
        }
        _pointer_up(event) {
            if (!this._is_event_target(event)) {
                return;
            }
            const pointer = this.pointers.get(event.pointerId);
            if (pointer == null) {
                return;
            }
            pointer.last = event;
            this._cancel_timeout();
            switch (this.phase) {
                case "idle": {
                    this.reset();
                    (0, assert_1.unreachable)();
                }
                case "started": {
                    const [ptr] = this.pointers.values();
                    const { tap_timestamp } = this;
                    if (ptr.last.timeStamp - tap_timestamp < UIGestures.doubletap_threshold) {
                        this.tap_timestamp = -Infinity;
                        this.on_doubletap(ptr.last);
                    }
                    else {
                        this.tap_timestamp = ptr.last.timeStamp;
                        this.on_tap(ptr.last);
                    }
                    this.phase = "idle";
                    break;
                }
                case "transitional": {
                    this.phase = "idle";
                    break;
                }
                case "pressing": {
                    const [ptr] = this.pointers.values();
                    this.on_pressup(ptr.last);
                    this.phase = "idle";
                    break;
                }
                case "panning": {
                    const [ptr] = this.pointers.values();
                    const { dx, dy } = this._movement(ptr);
                    this.on_pan_end(event, dx, dy);
                    this.phase = "idle";
                    break;
                }
                case "pinching": {
                    const [ptr0, ptr1] = this.pointers.values();
                    const scale = this._scale(ptr0, ptr1);
                    this.on_pinch_end(ptr0.last, ptr1.last, scale);
                    this.phase = "transitional";
                    this.last_scale = null;
                    break;
                }
                case "rotating": {
                    const [ptr0, ptr1] = this.pointers.values();
                    const rotation = this._rotation(ptr0, ptr1);
                    this.on_rotate_end(ptr0.last, ptr1.last, rotation);
                    this.phase = "transitional";
                    this.last_rotation = null;
                    break;
                }
            }
            this.pointers.delete(event.pointerId);
            if (this.phase == "transitional") {
                const [ptr] = this.pointers.values();
                ptr.init = ptr.last;
            }
        }
        _pointer_cancel(event) {
            if (!this.pointers.has(event.pointerId)) {
                return;
            }
            this._cancel_timeout();
            switch (this.phase) {
                case "idle": {
                    this.reset();
                    (0, assert_1.unreachable)();
                }
                case "started":
                case "pressing":
                case "transitional": {
                    this.phase = "idle";
                    break;
                }
                case "panning": {
                    const [ptr] = this.pointers.values();
                    const { dx, dy } = this._movement(ptr);
                    this.on_pan_end(event, dx, dy);
                    this.phase = "idle";
                    break;
                }
                case "pinching": {
                    const [ptr0, ptr1] = this.pointers.values();
                    const scale = this._scale(ptr0, ptr1);
                    this.on_pinch_end(ptr0.last, ptr1.last, scale);
                    this.phase = "transitional";
                    this.last_scale = null;
                    break;
                }
                case "rotating": {
                    const [ptr0, ptr1] = this.pointers.values();
                    const rotation = this._rotation(ptr0, ptr1);
                    this.on_rotate_end(ptr0.last, ptr1.last, rotation);
                    this.phase = "transitional";
                    this.last_rotation = null;
                    break;
                }
            }
            this.pointers.delete(event.pointerId);
            if (this.phase == "transitional") {
                const [ptr] = this.pointers.values();
                ptr.init = ptr.last;
            }
        }
        on_tap(ev) {
            const { on_tap } = this.handlers;
            if (on_tap != null) {
                on_tap(this._tap_event("tap", ev));
            }
        }
        on_doubletap(ev) {
            const { on_doubletap } = this.handlers;
            if (on_doubletap != null) {
                on_doubletap(this._tap_event("double_tap", ev));
            }
        }
        on_press(ev) {
            const { on_press } = this.handlers;
            if (on_press != null) {
                on_press(this._tap_event("press", ev));
            }
        }
        on_pressup(ev) {
            const { on_pressup } = this.handlers;
            if (on_pressup != null) {
                on_pressup(this._tap_event("press_up", ev));
            }
        }
        on_enter(ev) {
            const { on_enter } = this.handlers;
            if (on_enter != null) {
                on_enter(this._move_event("enter", ev));
            }
        }
        on_move(ev) {
            const { on_move } = this.handlers;
            if (on_move != null) {
                on_move(this._move_event("move", ev));
            }
        }
        on_leave(ev) {
            const { on_leave } = this.handlers;
            if (on_leave != null) {
                on_leave(this._move_event("leave", ev));
            }
        }
        on_pan_start(ev, dx, dy) {
            const { on_pan_start } = this.handlers;
            if (on_pan_start != null) {
                on_pan_start(this._pan_event("pan_start", ev, dx, dy));
            }
        }
        on_pan(ev, dx, dy) {
            const { on_pan } = this.handlers;
            if (on_pan != null) {
                on_pan(this._pan_event("pan", ev, dx, dy));
            }
        }
        on_pan_end(ev, dx, dy) {
            const { on_pan_end } = this.handlers;
            if (on_pan_end != null) {
                on_pan_end(this._pan_event("pan_end", ev, dx, dy));
            }
        }
        on_pinch_start(ev0, ev1, scale) {
            const { on_pinch_start } = this.handlers;
            if (on_pinch_start != null) {
                on_pinch_start(this._pinch_event("pinch_start", ev0, ev1, scale));
            }
        }
        on_pinch(ev0, ev1, scale) {
            const { on_pinch } = this.handlers;
            if (on_pinch != null) {
                on_pinch(this._pinch_event("pinch", ev0, ev1, scale));
            }
        }
        on_pinch_end(ev0, ev1, scale) {
            const { on_pinch_end } = this.handlers;
            if (on_pinch_end != null) {
                on_pinch_end(this._pinch_event("pinch_end", ev0, ev1, scale));
            }
        }
        on_rotate_start(ev0, ev1, rotation) {
            const { on_rotate_start } = this.handlers;
            if (on_rotate_start != null) {
                on_rotate_start(this._rotate_event("rotate_start", ev0, ev1, rotation));
            }
        }
        on_rotate(ev0, ev1, rotation) {
            const { on_rotate } = this.handlers;
            if (on_rotate != null) {
                on_rotate(this._rotate_event("rotate", ev0, ev1, rotation));
            }
        }
        on_rotate_end(ev0, ev1, rotation) {
            const { on_rotate_end } = this.handlers;
            if (on_rotate_end != null) {
                on_rotate_end(this._rotate_event("rotate_end", ev0, ev1, rotation));
            }
        }
        _get_sxy(event) {
            const { pageX, pageY } = event;
            const { left, top } = (0, dom_1.offset_bbox)(this.hit_area);
            return {
                sx: pageX - left,
                sy: pageY - top,
            };
        }
        _get_modifiers(event) {
            return {
                shift: event.shiftKey,
                ctrl: event.ctrlKey,
                alt: event.altKey,
            };
        }
        _tap_event(type, event) {
            return {
                type,
                ...this._get_sxy(event),
                modifiers: this._get_modifiers(event),
                native: event,
            };
        }
        _move_event(type, event) {
            return {
                type,
                ...this._get_sxy(event),
                modifiers: this._get_modifiers(event),
                native: event,
            };
        }
        _pan_event(type, event, dx, dy) {
            return {
                type,
                ...this._get_sxy(event),
                dx,
                dy,
                modifiers: this._get_modifiers(event),
                native: event,
            };
        }
        _pinch_event(type, event0, event1, scale) {
            const { sx: sx0, sy: sy0 } = this._get_sxy(event0);
            const { sx: sx1, sy: sy1 } = this._get_sxy(event1);
            return {
                type,
                sx: (sx0 + sx1) / 2,
                sy: (sy0 + sy1) / 2,
                scale,
                modifiers: this._get_modifiers(event0),
                native: event0,
            };
        }
        _rotate_event(type, event0, event1, rotation) {
            const { sx: sx0, sy: sy0 } = this._get_sxy(event0);
            const { sx: sx1, sy: sy1 } = this._get_sxy(event1);
            return {
                type,
                sx: (sx0 + sx1) / 2,
                sy: (sy0 + sy1) / 2,
                rotation,
                modifiers: this._get_modifiers(event0),
                native: event0,
            };
        }
        _movement(ptr) {
            return {
                dx: ptr.last.x - ptr.init.x,
                dy: ptr.last.y - ptr.init.y,
            };
        }
        _distance(ev0, ev1) {
            const x = ev1.x - ev0.x;
            const y = ev1.y - ev0.y;
            return Math.sqrt(x ** 2 + y ** 2);
        }
        _angle(ev0, ev1) {
            const x = ev1.x - ev0.x;
            const y = ev1.y - ev0.y;
            return Math.atan2(y, x) * 180 / Math.PI;
        }
        _scale(ptr0, ptr1) {
            return this._distance(ptr0.last, ptr1.last) / this._distance(ptr0.init, ptr1.init);
        }
        _rotation(ptr0, ptr1) {
            return this._angle(ptr1.last, ptr0.last) + this._angle(ptr1.init, ptr0.init);
        }
    }
    exports.UIGestures = UIGestures;
    UIGestures.__name__ = "UIGestures";
    UIGestures.move_threshold = 5; /*px*/
    UIGestures.press_threshold = 300; /*ms*/
    UIGestures.doubletap_threshold = 300; /*ms*/
    UIGestures.pinch_threshold = 0; /*unit less*/
    UIGestures.rotate_threshold = 0; /*rad*/
},
/* core/util/menus.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const dom_1 = require(63) /* ../dom */;
    const array_1 = require(10) /* ./array */;
    const types_1 = require(8) /* ./types */;
    const iterator_1 = require(34) /* ./iterator */;
    const menus_css_1 = tslib_1.__importStar(require(298) /* ../../styles/menus.css */), menus = menus_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(123) /* ../../styles/icons.css */);
    const base_css_1 = tslib_1.__importDefault(require(66) /* ../../styles/base.css */);
    //import {DOMComponentView} from "../dom_view"
    class ContextMenu {
        get is_open() {
            return this._open;
        }
        get can_open() {
            return this.items.length != 0;
        }
        constructor(items, options) {
            this.el = (0, dom_1.div)();
            this._open = false;
            this._item_click = (entry, i) => {
                this.entry_handler?.(entry, i);
                entry.handler?.();
                this.hide();
            };
            this._on_mousedown = (event) => {
                if (event.composedPath().includes(this.el)) {
                    return;
                }
                if (this.prevent_hide?.(event) ?? false) {
                    return;
                }
                this.hide();
            };
            this._on_keydown = (event) => {
                if (event.key == "Escape") {
                    this.hide();
                }
            };
            this._on_blur = () => {
                this.hide();
            };
            this.items = items;
            this.target = options.target;
            this.orientation = options.orientation ?? "vertical";
            this.reversed = options.reversed ?? false;
            this.prevent_hide = options.prevent_hide;
            this.extra_styles = options.extra_styles ?? [];
            this.entry_handler = options.entry_handler;
            this.shadow_el = this.el.attachShadow({ mode: "open" });
            this.class_list = new dom_1.ClassList(this.el.classList);
        }
        remove() {
            this._unlisten();
            this.el.remove();
        }
        _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 pos = (() => {
                if ("left_of" in at) {
                    const { left, top } = at.left_of.getBoundingClientRect();
                    return { right: left, top };
                }
                if ("right_of" in at) {
                    const { top, right } = at.right_of.getBoundingClientRect();
                    return { left: right, top };
                }
                if ("below" in at) {
                    const { left, bottom } = at.below.getBoundingClientRect();
                    return { left, top: bottom };
                }
                if ("above" in at) {
                    const { left, top } = at.above.getBoundingClientRect();
                    return { left, bottom: top };
                }
                return at;
            })();
            const parent_el = this.el.offsetParent ?? document.body;
            const origin = (() => {
                const rect = parent_el.getBoundingClientRect();
                const style = getComputedStyle(parent_el);
                return {
                    left: rect.left - parseFloat(style.marginLeft),
                    right: rect.right + parseFloat(style.marginRight),
                    top: rect.top - parseFloat(style.marginTop),
                    bottom: rect.bottom + parseFloat(style.marginBottom),
                };
            })();
            const { style } = this.el;
            style.left = pos.left != null ? `${pos.left - origin.left}px` : "auto";
            style.top = pos.top != null ? `${pos.top - origin.top}px` : "auto";
            style.right = pos.right != null ? `${origin.right - pos.right}px` : "auto";
            style.bottom = pos.bottom != null ? `${origin.bottom - pos.bottom}px` : "auto";
        }
        stylesheets() {
            return [base_css_1.default, /*...super.stylesheets(), */ menus_css_1.default, icons_css_1.default, ...this.extra_styles];
        }
        empty() {
            (0, dom_1.empty)(this.shadow_el);
            this.class_list.clear();
        }
        render() {
            this.empty();
            for (const style of this.stylesheets()) {
                const stylesheet = (0, types_1.isString)(style) ? new dom_1.InlineStyleSheet(style) : style;
                stylesheet.install(this.shadow_el);
            }
            this.class_list.add(menus[this.orientation]);
            const items = this.reversed ? (0, array_1.reversed)(this.items) : this.items;
            for (const [item, i] of (0, iterator_1.enumerate)(items)) {
                let el;
                if (item == null) {
                    el = (0, dom_1.div)({ class: menus.divider });
                }
                else if (item.if != null && !item.if()) {
                    continue;
                }
                else if (item.custom != null) {
                    el = item.custom;
                }
                else {
                    const icon = item.icon != null ? (0, dom_1.div)({ class: [menus.menu_icon, item.icon] }) : null;
                    const classes = [item.active?.() ?? false ? menus.active : null, item.class];
                    el = (0, dom_1.div)({ class: classes, title: item.tooltip, tabIndex: 0 }, icon, item.label, item.content);
                    el.addEventListener("click", () => {
                        this._item_click(item, i);
                    });
                    el.addEventListener("keydown", (event) => {
                        if (event.key == "Enter") {
                            this._item_click(item, i);
                        }
                    });
                }
                this.shadow_el.appendChild(el);
            }
        }
        show(at) {
            if (this.items.length == 0) {
                return;
            }
            this.render();
            if (this.shadow_el.children.length == 0) {
                return;
            }
            (this.target.shadowRoot ?? this.target).appendChild(this.el);
            this._position(at ?? { left: 0, top: 0 });
            this._listen();
            this._open = true;
        }
        hide() {
            if (this._open) {
                this._open = false;
                this._unlisten();
                this.el.remove();
            }
        }
        toggle(at) {
            this._open ? this.hide() : this.show(at);
        }
    }
    exports.ContextMenu = ContextMenu;
    ContextMenu.__name__ = "ContextMenu";
},
/* styles/menus.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.menu_icon = "bk-menu-icon";
    exports.horizontal = "bk-horizontal";
    exports.vertical = "bk-vertical";
    exports.divider = "bk-divider";
    exports.active = "bk-active";
    exports.default = `.bk-menu-icon{width:28px;height:28px;mask-size:60% 60%;mask-position:center center;mask-repeat:no-repeat;-webkit-mask-size:60% 60%;-webkit-mask-position:center center;-webkit-mask-repeat:no-repeat;background-size:60%;background-color:transparent;background-repeat:no-repeat;background-position:center center;}:host{position:absolute;display:inline-flex;flex-wrap:nowrap;user-select:none;-webkit-user-select:none;width:auto;height:auto;z-index:var(--bokeh-top-level);cursor:pointer;font-size:var(--font-size);background-color:#fff;border:1px solid #ccc;border-radius:var(--border-radius);box-shadow:2px 4px 8px rgba(0, 0, 0, 0.175);}:host(.bk-horizontal){flex-direction:row;}:host(.bk-vertical){flex-direction:column;}.bk-divider{cursor:default;overflow:hidden;background-color:#e5e5e5;}:host(.bk-horizontal) > .bk-divider{width:1px;margin:5px 0;}:host(.bk-vertical) > .bk-divider{height:1px;margin:0 5px;}:host > :not(.bk-divider){border:1px solid transparent;--active-tool-highlight:#26aae1;}:host > :not(.bk-divider).bk-active{border-color:var(--active-tool-highlight);}:host > :not(.bk-divider):hover{background-color:#f9f9f9;}:host > :not(.bk-divider):focus,:host > :not(.bk-divider):focus-visible{outline:1px dotted var(--active-tool-highlight);outline-offset:-1px;}:host > :not(.bk-divider)::-moz-focus-inner{border:0;}:host(.bk-horizontal) > :not(.bk-divider):first-child{border-top-left-radius:var(--border-radius);border-bottom-left-radius:var(--border-radius);}:host(.bk-horizontal) > :not(.bk-divider):last-child{border-top-right-radius:var(--border-radius);border-bottom-right-radius:var(--border-radius);}:host(.bk-vertical) > :not(.bk-divider):first-child{border-top-left-radius:var(--border-radius);border-top-right-radius:var(--border-radius);}:host(.bk-vertical) > :not(.bk-divider):last-child{border-bottom-left-radius:var(--border-radius);border-bottom-right-radius:var(--border-radius);}`;
},
/* styles/tool_button.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.tool_icon = "bk-tool-icon";
    exports.disabled = "bk-disabled";
    exports.tool_chevron = "bk-tool-chevron";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.active = "bk-active";
    exports.default = `:host{--button-width:30px;--button-height:30px;--button-color:lightgray;--button-border:2px;--active-tool-highlight:#26aae1;--active-tool-border:var(--button-border) solid transparent;}:host{position:relative;width:var(--button-width);height:var(--button-height);cursor:pointer;user-select:none;-webkit-user-select:none;touch-action:none;}.bk-tool-icon{position:relative;top:calc(var(--button-border)/2);width:calc(var(--button-width) - var(--button-border));height:calc(var(--button-height) - var(--button-border));mask-size:60% 60%;mask-position:center center;mask-repeat:no-repeat;-webkit-mask-size:60% 60%;-webkit-mask-position:center center;-webkit-mask-repeat:no-repeat;background-size:60% 60%;background-origin:border-box;background-position:center center;background-repeat:no-repeat;}:host(.bk-disabled) .bk-tool-icon{background-color:var(--bokeh-icon-color-disabled);cursor:not-allowed;}.bk-tool-chevron{position:absolute;visibility:hidden;width:8px;height:8px;mask-size:100% 100%;mask-position:center center;mask-repeat:no-repeat;-webkit-mask-size:100% 100%;-webkit-mask-position:center center;-webkit-mask-repeat:no-repeat;}:host(:hover) .bk-tool-chevron{visibility:visible;}:host(.bk-above) .bk-tool-chevron{right:0;bottom:0;background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-down);-webkit-mask-image:var(--bokeh-icon-chevron-down);}:host(.bk-below) .bk-tool-chevron{right:0;top:0;background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-up);-webkit-mask-image:var(--bokeh-icon-chevron-up);}:host(.bk-left) .bk-tool-chevron{right:0;bottom:0;background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-right);-webkit-mask-image:var(--bokeh-icon-chevron-right);}:host(.bk-right) .bk-tool-chevron{left:0;bottom:0;background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-chevron-left);-webkit-mask-image:var(--bokeh-icon-chevron-left);}:host(:hover){background-color:rgba(192, 192, 192, 0.15);}:host(:focus),:host(:focus-visible){outline:1px dotted var(--active-tool-highlight);outline-offset:-1px;}:host::-moz-focus-inner{border:0;}:host(.bk-above){border-bottom:var(--active-tool-border);}:host(.bk-above.bk-active){border-bottom-color:var(--active-tool-highlight);}:host(.bk-below){border-top:var(--active-tool-border);}:host(.bk-below.bk-active){border-top-color:var(--active-tool-highlight);}:host(.bk-right){border-left:var(--active-tool-border);}:host(.bk-right.bk-active){border-left-color:var(--active-tool-highlight);}:host(.bk-left){border-right:var(--active-tool-border);}:host(.bk-left.bk-active){border-right-color:var(--active-tool-highlight);}`;
},
/* models/tools/gestures/gesture_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tool_1 = require(293) /* ../tool */;
    const on_off_button_1 = require(301) /* ../on_off_button */;
    class GestureToolView extends tool_1.ToolView {
        get plot_view() {
            return this.parent;
        }
    }
    exports.GestureToolView = GestureToolView;
    GestureToolView.__name__ = "GestureToolView";
    class GestureTool extends tool_1.Tool {
        constructor(attrs) {
            super(attrs);
        }
        tool_button() {
            return new on_off_button_1.OnOffButton({ tool: this });
        }
    }
    exports.GestureTool = GestureTool;
    GestureTool.__name__ = "GestureTool";
},
/* models/tools/on_off_button.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const tool_button_1 = require(295) /* ./tool_button */;
    const tools = tslib_1.__importStar(require(299) /* ../../styles/tool_button.css */);
    class OnOffButtonView extends tool_button_1.ToolButtonView {
        _toggle_active() {
            this.class_list.toggle(tools.active, this.model.tool.active);
        }
        connect_signals() {
            super.connect_signals();
            const { active } = this.model.tool.properties;
            this.on_change(active, () => {
                this._toggle_active();
            });
        }
        render() {
            super.render();
            this._toggle_active();
        }
        _clicked() {
            const { active } = this.model.tool;
            this.model.tool.active = !active;
        }
    }
    exports.OnOffButtonView = OnOffButtonView;
    OnOffButtonView.__name__ = "OnOffButtonView";
    class OnOffButton extends tool_button_1.ToolButton {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.OnOffButton = OnOffButton;
    _a = OnOffButton;
    OnOffButton.__name__ = "OnOffButton";
    (() => {
        _a.prototype.default_view = OnOffButtonView;
    })();
},
/* models/tools/inspectors/inspect_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const tool_1 = require(293) /* ../tool */;
    const on_off_button_1 = require(301) /* ../on_off_button */;
    const p = tslib_1.__importStar(require(18) /* ../../../core/properties */);
    class InspectToolView extends tool_1.ToolView {
        get plot_view() {
            return this.parent;
        }
    }
    exports.InspectToolView = InspectToolView;
    InspectToolView.__name__ = "InspectToolView";
    class InspectTool extends tool_1.Tool {
        constructor(attrs) {
            super(attrs);
            this.event_type = "move";
        }
        tool_button() {
            return new on_off_button_1.OnOffButton({ tool: this });
        }
    }
    exports.InspectTool = InspectTool;
    _a = InspectTool;
    InspectTool.__name__ = "InspectTool";
    (() => {
        _a.define(() => ({
            toggleable: [new p.PropertyAlias("visible")],
        }));
        _a.override({
            active: true,
        });
    })();
},
/* models/tools/actions/action_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tool_1 = require(293) /* ../tool */;
    const click_button_1 = require(304) /* ../click_button */;
    const signaling_1 = require(15) /* ../../../core/signaling */;
    class ActionToolView extends tool_1.ToolView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.do, (arg) => this.doit(arg));
        }
    }
    exports.ActionToolView = ActionToolView;
    ActionToolView.__name__ = "ActionToolView";
    class ActionTool extends tool_1.Tool {
        constructor(attrs) {
            super(attrs);
            this.do = new signaling_1.Signal(this, "do");
        }
        tool_button() {
            return new click_button_1.ClickButton({ tool: this });
        }
    }
    exports.ActionTool = ActionTool;
    ActionTool.__name__ = "ActionTool";
},
/* models/tools/click_button.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tool_button_1 = require(295) /* ./tool_button */;
    class ClickButtonView extends tool_button_1.ToolButtonView {
        _clicked() {
            this.model.tool.do.emit(undefined);
        }
    }
    exports.ClickButtonView = ClickButtonView;
    ClickButtonView.__name__ = "ClickButtonView";
    class ClickButton extends tool_button_1.ToolButton {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ClickButton = ClickButton;
    _a = ClickButton;
    ClickButton.__name__ = "ClickButton";
    (() => {
        _a.prototype.default_view = ClickButtonView;
    })();
},
/* models/tools/actions/help_tool.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const action_tool_1 = require(303) /* ./action_tool */;
    const icons_css_1 = require(123) /* ../../../styles/icons.css */;
    class HelpToolView extends action_tool_1.ActionToolView {
        doit() {
            window.open(this.model.redirect);
        }
    }
    exports.HelpToolView = HelpToolView;
    HelpToolView.__name__ = "HelpToolView";
    class HelpTool extends action_tool_1.ActionTool {
        constructor(attrs) {
            super(attrs);
            this.tool_name = "Help";
            this.tool_icon = icons_css_1.tool_icon_help;
        }
    }
    exports.HelpTool = HelpTool;
    _a = HelpTool;
    HelpTool.__name__ = "HelpTool";
    (() => {
        _a.prototype.default_view = HelpToolView;
        _a.define(({ Str }) => ({
            redirect: [Str, "https://docs.bokeh.org/en/latest/docs/user_guide/interaction/tools.html"],
        }));
        _a.override({
            description: "Click the question mark to learn more about Bokeh plot tools.",
        });
        _a.register_alias("help", () => new _a());
    })();
},
/* styles/toolbar.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.inner = "bk-inner";
    exports.hidden = "bk-hidden";
    exports.logo = "bk-logo";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.divider = "bk-divider";
    exports.tool_overflow = "bk-tool-overflow";
    exports.horizontal = "bk-horizontal";
    exports.vertical = "bk-vertical";
    exports.default = `:host{--button-width:30px;--button-height:30px;--button-color:lightgray;}:host{display:flex;flex-wrap:nowrap;align-items:center;user-select:none;-webkit-user-select:none;}:host(.bk-inner){background-color:white;opacity:0.8;}:host(.bk-hidden){visibility:hidden;opacity:0;transition:visibility 0.3s linear, opacity 0.3s linear;}.bk-logo{flex-shrink:0;}:host(.bk-above),:host(.bk-below){flex-direction:row;justify-content:flex-end;}:host(.bk-above) .bk-logo,:host(.bk-below) .bk-logo{order:1;margin-left:5px;margin-right:0px;}:host(.bk-left),:host(.bk-right){flex-direction:column;justify-content:flex-start;}:host(.bk-left) .bk-logo,:host(.bk-right) .bk-logo{order:0;margin-bottom:5px;margin-top:0px;}.bk-divider{content:" ";display:inline-block;background-color:var(--button-color);}:host(.bk-above) .bk-divider,:host(.bk-below) .bk-divider{height:10px;width:1px;}:host(.bk-left) .bk-divider,:host(.bk-right) .bk-divider{height:1px;width:10px;}.bk-tool-overflow{color:gray;display:flex;align-items:center;}.bk-tool-overflow:hover{background-color:rgba(192, 192, 192, 0.15);}.bk-tool-overflow:focus,.bk-tool-overflow:focus-visible{outline:1px dotted var(--active-tool-highlight);outline-offset:-1px;}.bk-tool-overflow::-moz-focus-inner{border:0;}:host(.bk-above) .bk-tool-overflow,:host(.bk-below) .bk-tool-overflow,:host(.bk-horizontal) .bk-tool-overflow{width:calc(var(--button-width)/2);height:var(--button-height);flex-direction:row;}:host(.bk-left) .bk-tool-overflow,:host(.bk-right) .bk-tool-overflow,:host(.bk-vertical) .bk-tool-overflow{width:var(--button-width);height:calc(var(--button-height)/2);flex-direction:column;}`;
},
/* styles/logo.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.logo = "bk-logo";
    exports.grey = "bk-grey";
    exports.logo_small = "bk-logo-small";
    exports.default = `.bk-logo{margin:5px;position:relative;display:block;background-repeat:no-repeat;}.bk-logo.bk-grey{filter:grayscale(100%);}.bk-logo-small{width:20px;height:20px;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAOkSURBVDiNjZRtaJVlGMd/1/08zzln5zjP1LWcU9N0NkN8m2CYjpgQYQXqSs0I84OLIC0hkEKoPtiH3gmKoiJDU7QpLgoLjLIQCpEsNJ1vqUOdO7ppbuec5+V+rj4ctwzd8IIbbi6u+8f1539dt3A78eXC7QizUF7gyV1fD1Yqg4JWz84yffhm0qkFqBogB9rM8tZdtwVsPUhWhGcFJngGeWrPzHm5oaMmkfEg1usvLFyc8jLRqDOMru7AyC8saQr7GG7f5fvDeH7Ej8CM66nIF+8yngt6HWaKh7k49Soy9nXurCi1o3qUbS3zWfrYeQDTB/Qj6kX6Ybhw4B+bOYoLKCC9H3Nu/leUTZ1JdRWkkn2ldcCamzrcf47KKXdAJllSlxAOkRgyHsGC/zRday5Qld9DyoM4/q/rUoy/CXh3jzOu3bHUVZeU+DEn8FInkPBFlu3+nW3Nw0mk6vCDiWg8CeJaxEwuHS3+z5RgY+YBR6V1Z1nxSOfoaPa4LASWxxdNp+VWTk7+4vzaou8v8PN+xo+KY2xsw6une2frhw05CTYOmQvsEhjhWjn0bmXPjpE1+kplmmkP3suftwTubK9Vq22qKmrBhpY4jvd5afdRA3wGjFAgcnTK2s4hY0/GPNIb0nErGMCRxWOOX64Z8RAC4oCXdklmEvcL8o0BfkNK4lUg9HTl+oPlQxdNo3Mg4Nv175e/1LDGzZen30MEjRUtmXSfiTVu1kK8W4txyV6BMKlbgk3lMwYCiusNy9fVfvvwMxv8Ynl6vxoByANLTWplvuj/nF9m2+PDtt1eiHPBr1oIfhCChQMBw6Aw0UulqTKZdfVvfG7VcfIqLG9bcldL/+pdWTLxLUy8Qq38heUIjh4XlzZxzQm19lLFlr8vdQ97rjZVOLf8nclzckbcD4wxXMidpX30sFd37Fv/GtwwhzhxGVAprjbg0gCAEeIgwCZyTV2Z1REEW8O4py0wsjeloKoMr6iCY6dP92H6Vw/oTyICIthibxjm/DfN9lVz8IqtqKYLUXfoKVMVQVVJOElGjrnnUt9T9wbgp8AyYKaGlqingHZU/uG2NTZSVqwHQTWkx9hxjkpWDaCg6Ckj5qebgBVbT3V3NNXMSiWSDdGV3hrtzla7J+duwPOToIg42ChPQOQjspnSlp1V+Gjdged7+8UN5CRAV7a5EdFNwCjEaBR27b3W890TE7g24NAP/mMDXRWrGoFPQI9ls/MWO2dWFAar/xcOIImbbpA3zgAAAABJRU5ErkJggg==);}`;
},
/* models/annotations/whisker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const upper_lower_1 = require(262) /* ./upper_lower */;
    const arrow_head_1 = require(168) /* ./arrow_head */;
    const types_1 = require(24) /* ../../core/types */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    class WhiskerView extends upper_lower_1.UpperLowerView {
        *children() {
            yield* super.children();
            const { lower_head, upper_head } = this;
            if (lower_head != null) {
                yield lower_head;
            }
            if (upper_head != null) {
                yield upper_head;
            }
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { lower_head, upper_head } = this.model;
            if (lower_head != null) {
                this.lower_head = await (0, build_views_1.build_view)(lower_head, { parent: this });
            }
            if (upper_head != null) {
                this.upper_head = await (0, build_views_1.build_view)(upper_head, { parent: this });
            }
        }
        set_data(source) {
            super.set_data(source);
            const indices = types_1.Indices.all_set(this._lower.length);
            this.lower_head?.set_data(source, indices);
            this.upper_head?.set_data(source, indices);
        }
        _paint_data(ctx) {
            if (this.visuals.line.doit) {
                for (let i = 0, end = this._lower_sx.length; i < end; i++) {
                    ctx.beginPath();
                    ctx.moveTo(this._lower_sx[i], this._lower_sy[i]);
                    ctx.lineTo(this._upper_sx[i], this._upper_sy[i]);
                    this.visuals.line.apply(ctx, i);
                }
            }
            const angle = this.model.dimension == "height" ? 0 : Math.PI / 2;
            if (this.lower_head != null) {
                for (let i = 0, end = this._lower_sx.length; i < end; i++) {
                    ctx.save();
                    ctx.translate(this._lower_sx[i], this._lower_sy[i]);
                    ctx.rotate(angle + Math.PI);
                    this.lower_head.paint(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.paint(ctx, i);
                    ctx.restore();
                }
            }
        }
    }
    exports.WhiskerView = WhiskerView;
    WhiskerView.__name__ = "WhiskerView";
    class Whisker extends upper_lower_1.UpperLower {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Whisker = Whisker;
    _a = Whisker;
    Whisker.__name__ = "Whisker";
    (() => {
        _a.prototype.default_view = WhiskerView;
        _a.mixins(property_mixins_1.LineVector);
        _a.define(({ Ref, Nullable }) => ({
            lower_head: [Nullable(Ref(arrow_head_1.ArrowHead)), () => new arrow_head_1.TeeHead({ size: 10 })],
            upper_head: [Nullable(Ref(arrow_head_1.ArrowHead)), () => new arrow_head_1.TeeHead({ size: 10 })],
        }));
        _a.override({
            level: "underlay",
        });
    })();
},
/* models/annotations/html/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var label_1 = require(310) /* ./label */;
    __esExport("HTMLLabel", label_1.HTMLLabel);
    var label_set_1 = require(312) /* ./label_set */;
    __esExport("HTMLLabelSet", label_set_1.HTMLLabelSet);
    var title_1 = require(313) /* ./title */;
    __esExport("HTMLTitle", title_1.HTMLTitle);
},
/* models/annotations/html/label.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const text_annotation_1 = require(311) /* ./text_annotation */;
    const math_1 = require(11) /* ../../../core/util/math */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const graphics_1 = require(180) /* ../../../core/graphics */;
    const side_panel_1 = require(173) /* ../../../core/layout/side_panel */;
    const mixins = tslib_1.__importStar(require(80) /* ../../../core/property_mixins */);
    class HTMLLabelView extends text_annotation_1.TextAnnotationView {
        update_layout() {
            const { panel } = this;
            if (panel != null) {
                this.layout = new side_panel_1.SideLayout(panel, () => this.get_size(), false);
            }
            else {
                this.layout = undefined;
            }
        }
        // XXX: this needs to use CSS computed styles
        _get_size() {
            const { text } = this.model;
            const graphics = new graphics_1.TextBox({ text });
            const { angle, angle_units } = this.model;
            graphics.angle = (0, math_1.compute_angle)(angle, angle_units);
            graphics.visuals = this.visuals.text.values();
            const size = graphics.size();
            const { padding } = this;
            const width = size.width + padding.left + padding.right;
            const height = size.height + padding.top + padding.bottom;
            return { width, height };
        }
        _paint() {
            const { angle, angle_units } = this.model;
            const rotation = (0, math_1.compute_angle)(angle, angle_units);
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            const xscale = this.coordinates.x_scale;
            const yscale = this.coordinates.y_scale;
            let sx = (() => {
                switch (this.model.x_units) {
                    case "canvas":
                        return this.model.x;
                    case "screen":
                        return panel.bbox.xview.compute(this.model.x);
                    case "data":
                        return xscale.compute(this.model.x);
                }
            })();
            let sy = (() => {
                switch (this.model.y_units) {
                    case "canvas":
                        return this.model.y;
                    case "screen":
                        return panel.bbox.yview.compute(this.model.y);
                    case "data":
                        return yscale.compute(this.model.y);
                }
            })();
            sx += this.model.x_offset;
            sy -= this.model.y_offset;
            this._paint_text(this.layer.ctx, this.model.text, sx, sy, rotation);
        }
    }
    exports.HTMLLabelView = HTMLLabelView;
    HTMLLabelView.__name__ = "HTMLLabelView";
    class HTMLLabel extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HTMLLabel = HTMLLabel;
    _a = HTMLLabel;
    HTMLLabel.__name__ = "HTMLLabel";
    (() => {
        _a.prototype.default_view = HTMLLabelView;
        _a.mixins([
            mixins.Text,
            ["border_", mixins.Line],
            ["background_", mixins.Fill],
            ["background_", mixins.Hatch],
        ]);
        _a.define(({ Float, Str, Angle }) => ({
            x: [Float],
            x_units: [enums_1.CoordinateUnits, "data"],
            y: [Float],
            y_units: [enums_1.CoordinateUnits, "data"],
            text: [Str, ""],
            angle: [Angle, 0],
            angle_units: [enums_1.AngleUnits, "rad"],
            x_offset: [Float, 0],
            y_offset: [Float, 0],
        }));
        _a.override({
            background_fill_color: null,
            background_hatch_color: null,
            border_line_color: null,
        });
    })();
},
/* models/annotations/html/text_annotation.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const annotation_1 = require(81) /* ../annotation */;
    const dom_1 = require(63) /* ../../../core/dom */;
    const side_panel_1 = require(173) /* ../../../core/layout/side_panel */;
    const kinds_1 = require(185) /* ../../common/kinds */;
    const resolve = tslib_1.__importStar(require(186) /* ../../common/resolve */);
    class TextAnnotationView extends annotation_1.AnnotationView {
        rendering_target() {
            return this.plot_view.canvas_view.overlays_el;
        }
        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();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.paint());
        }
        paint() {
            if (!this.model.visible) {
                (0, dom_1.undisplay)(this.el);
                return;
            }
            super.paint();
        }
        get padding() {
            return resolve.padding(this.model.padding);
        }
        get border_radius() {
            return resolve.border_radius(this.model.border_radius);
        }
        render() {
            super.render();
            this.text_el = document.createTextNode("");
            this.shadow_el.append(this.text_el);
        }
        _paint_text(ctx, text, sx, sy, angle) {
            const { el } = this;
            (0, dom_1.undisplay)(el);
            this.text_el.textContent = text;
            this.visuals.text.set_value(ctx);
            const { padding, border_radius } = this;
            this.position.replace(`
    :host {
      position: absolute;
      left: ${sx}px;
      top: ${sy}px;
    }
    `);
            this.style.replace(`
    :host {
      color: ${ctx.fillStyle};
      -webkit-text-stroke: 1px ${ctx.strokeStyle};
      font: ${ctx.font};
      white-space: pre;

      padding-left: ${padding.left}px;
      padding-right: ${padding.right}px;
      padding-top: ${padding.top}px;
      padding-bottom: ${padding.bottom}px;

      border-top-left-radius: ${border_radius.top_left}px;
      border-top-right-radius: ${border_radius.top_right}px;
      border-bottom-right-radius: ${border_radius.bottom_right}px;
      border-bottom-left-radius: ${border_radius.bottom_left}px;
    }
    `);
            const [x_anchor, x_t] = (() => {
                switch (this.visuals.text.text_align.get_value()) {
                    case "left": return ["left", "0%"];
                    case "center": return ["center", "-50%"];
                    case "right": return ["right", "-100%"];
                }
            })();
            const [y_anchor, y_t] = (() => {
                switch (this.visuals.text.text_baseline.get_value()) {
                    case "top": return ["top", "0%"];
                    case "middle": return ["center", "-50%"];
                    case "bottom": return ["bottom", "-100%"];
                    default: return ["center", "-50%"]; // "baseline"
                }
            })();
            let transform = `translate(${x_t}, ${y_t})`;
            if (angle != 0) {
                transform += ` rotate(${angle}rad)`;
            }
            this.style.append(`
    :host {
      transform-origin: ${x_anchor} ${y_anchor};
      transform: ${transform};
    }
    `);
            if (this.layout == null) {
                // const {bbox} = this.plot_view.frame
                // const {left, right, top, bottom} = bbox
                // el.style.clipPath = ???
            }
            if (this.visuals.background_fill.doit) {
                this.visuals.background_fill.set_value(ctx);
                this.style.append(`
      :host {
        background-color: ${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
                this.style.append(`
      :host {
        border-style: ${ctx.getLineDash().length < 2 ? "solid" : "dashed"};
        border-width: ${ctx.lineWidth}px;
        border-color: ${ctx.strokeStyle};
      }
      `);
            }
            (0, dom_1.display)(el);
        }
    }
    exports.TextAnnotationView = TextAnnotationView;
    TextAnnotationView.__name__ = "TextAnnotationView";
    class TextAnnotation extends annotation_1.Annotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TextAnnotation = TextAnnotation;
    _a = TextAnnotation;
    TextAnnotation.__name__ = "TextAnnotation";
    (() => {
        _a.define(() => ({
            padding: [kinds_1.Padding, 0],
            border_radius: [kinds_1.BorderRadius, 0],
        }));
    })();
},
/* models/annotations/html/label_set.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const data_annotation_1 = require(127) /* ../data_annotation */;
    const mixins = tslib_1.__importStar(require(80) /* ../../../core/property_mixins */);
    const enums_1 = require(20) /* ../../../core/enums */;
    const dom_1 = require(63) /* ../../../core/dom */;
    const p = tslib_1.__importStar(require(18) /* ../../../core/properties */);
    const types_1 = require(24) /* ../../../core/types */;
    const assert_1 = require(12) /* ../../../core/util/assert */;
    class HTMLLabelSetView extends data_annotation_1.DataAnnotationView {
        constructor() {
            super(...arguments);
            this.els = [];
        }
        set_data(source) {
            super.set_data(source);
            this.els.forEach((el) => el.remove());
            this.els = [...this.text.map(() => (0, dom_1.div)({ style: { display: "none" } }))];
            this.plot_view.canvas_view.overlays_el.append(...this.els);
        }
        remove() {
            this.els.forEach((el) => el.remove());
            this.els = [];
            super.remove();
        }
        _rerender() {
            this.paint();
        }
        map_data() {
            const { x_scale, y_scale } = this.coordinates;
            const panel = this.layout != null ? this.layout : this.plot_view.frame;
            this.sx = (() => {
                switch (this.model.x_units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._x);
                    case "screen":
                        return panel.bbox.xview.v_compute(this._x);
                    case "data":
                        return x_scale.v_compute(this._x);
                }
            })();
            this.sy = (() => {
                switch (this.model.y_units) {
                    case "canvas":
                        return new types_1.ScreenArray(this._y);
                    case "screen":
                        return panel.bbox.yview.v_compute(this._y);
                    case "data":
                        return y_scale.v_compute(this._y);
                }
            })();
        }
        _paint_data() {
            const { ctx } = this.layer;
            for (let i = 0, end = this.text.length; i < end; i++) {
                const x_offset_i = this.x_offset.get(i);
                const y_offset_i = this.y_offset.get(i);
                const sx_i = this.sx[i] + x_offset_i;
                const sy_i = this.sy[i] - y_offset_i;
                const angle_i = this.angle.get(i);
                const text_i = this.text.get(i);
                if (!isFinite(sx_i + sy_i + angle_i) || text_i == null) {
                    continue;
                }
                this._paint_text(ctx, i, text_i, sx_i, sy_i, angle_i);
            }
        }
        _paint_text(ctx, i, text, sx, sy, angle) {
            (0, assert_1.assert)(i in this.els);
            const el = this.els[i];
            el.textContent = text;
            this.visuals.text.set_vectorize(ctx, i);
            el.style.position = "absolute";
            el.style.left = `${sx}px`;
            el.style.top = `${sy}px`;
            el.style.color = ctx.fillStyle;
            el.style.webkitTextStroke = `1px ${ctx.strokeStyle}`;
            el.style.font = ctx.font;
            el.style.lineHeight = "normal"; // needed to prevent ipynb css override
            el.style.whiteSpace = "pre";
            const [x_anchor, x_t] = (() => {
                switch (this.visuals.text.text_align.get(i)) {
                    case "left": return ["left", "0%"];
                    case "center": return ["center", "-50%"];
                    case "right": return ["right", "-100%"];
                }
            })();
            const [y_anchor, y_t] = (() => {
                switch (this.visuals.text.text_baseline.get(i)) {
                    case "top": return ["top", "0%"];
                    case "middle": return ["center", "-50%"];
                    case "bottom": return ["bottom", "-100%"];
                    default: return ["center", "-50%"]; // "baseline"
                }
            })();
            let transform = `translate(${x_t}, ${y_t})`;
            if (angle != 0) {
                transform += `rotate(${angle}rad)`;
            }
            el.style.transformOrigin = `${x_anchor} ${y_anchor}`;
            el.style.transform = transform;
            if (this.layout == null) {
                // const {bbox} = this.plot_view.frame
                // const {left, right, top, bottom} = bbox
                // el.style.clipPath = ???
            }
            if (this.visuals.background_fill.doit) {
                this.visuals.background_fill.set_vectorize(ctx, i);
                el.style.backgroundColor = ctx.fillStyle;
            }
            if (this.visuals.border_line.doit) {
                this.visuals.border_line.set_vectorize(ctx, i);
                // attempt to support vector-style ("8 4 8") line dashing for css mode
                el.style.borderStyle = ctx.getLineDash().length < 2 ? "solid" : "dashed";
                el.style.borderWidth = `${ctx.lineWidth}px`;
                el.style.borderColor = ctx.strokeStyle;
            }
            (0, dom_1.display)(el);
        }
    }
    exports.HTMLLabelSetView = HTMLLabelSetView;
    HTMLLabelSetView.__name__ = "HTMLLabelSetView";
    class HTMLLabelSet extends data_annotation_1.DataAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HTMLLabelSet = HTMLLabelSet;
    _a = HTMLLabelSet;
    HTMLLabelSet.__name__ = "HTMLLabelSet";
    (() => {
        _a.prototype.default_view = HTMLLabelSetView;
        _a.mixins([
            mixins.TextVector,
            ["border_", mixins.LineVector],
            ["background_", mixins.FillVector],
        ]);
        _a.define(() => ({
            x: [p.XCoordinateSpec, { field: "x" }],
            y: [p.YCoordinateSpec, { field: "y" }],
            x_units: [enums_1.CoordinateUnits, "data"],
            y_units: [enums_1.CoordinateUnits, "data"],
            text: [p.NullStringSpec, { field: "text" }],
            angle: [p.AngleSpec, 0],
            x_offset: [p.NumberSpec, { value: 0 }],
            y_offset: [p.NumberSpec, { value: 0 }],
        }));
        _a.override({
            background_fill_color: null,
            border_line_color: null,
        });
    })();
},
/* models/annotations/html/title.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const text_annotation_1 = require(311) /* ./text_annotation */;
    const enums_1 = require(20) /* ../../../core/enums */;
    const graphics_1 = require(180) /* ../../../core/graphics */;
    const mixins = tslib_1.__importStar(require(80) /* ../../../core/property_mixins */);
    class HTMLTitleView extends text_annotation_1.TextAnnotationView {
        _get_location() {
            const hmargin = this.model.offset;
            const vmargin = this.model.standoff / 2;
            let sx, sy;
            const { bbox } = this.layout;
            switch (this.panel.side) {
                case "above":
                case "below": {
                    switch (this.model.vertical_align) {
                        case "top":
                            sy = bbox.top + vmargin;
                            break;
                        case "middle":
                            sy = bbox.vcenter;
                            break;
                        case "bottom":
                            sy = bbox.bottom - vmargin;
                            break;
                    }
                    switch (this.model.align) {
                        case "left":
                            sx = bbox.left + hmargin;
                            break;
                        case "center":
                            sx = bbox.hcenter;
                            break;
                        case "right":
                            sx = bbox.right - hmargin;
                            break;
                    }
                    break;
                }
                case "left": {
                    switch (this.model.vertical_align) {
                        case "top":
                            sx = bbox.left + vmargin;
                            break;
                        case "middle":
                            sx = bbox.hcenter;
                            break;
                        case "bottom":
                            sx = bbox.right - vmargin;
                            break;
                    }
                    switch (this.model.align) {
                        case "left":
                            sy = bbox.bottom - hmargin;
                            break;
                        case "center":
                            sy = bbox.vcenter;
                            break;
                        case "right":
                            sy = bbox.top + hmargin;
                            break;
                    }
                    break;
                }
                case "right": {
                    switch (this.model.vertical_align) {
                        case "top":
                            sx = bbox.right - vmargin;
                            break;
                        case "middle":
                            sx = bbox.hcenter;
                            break;
                        case "bottom":
                            sx = bbox.left + vmargin;
                            break;
                    }
                    switch (this.model.align) {
                        case "left":
                            sy = bbox.top + hmargin;
                            break;
                        case "center":
                            sy = bbox.vcenter;
                            break;
                        case "right":
                            sy = bbox.bottom - hmargin;
                            break;
                    }
                    break;
                }
            }
            return [sx, sy];
        }
        _paint() {
            const { text } = this.model;
            if (text.length == 0) {
                return;
            }
            this.model.text_baseline = this.model.vertical_align;
            this.model.text_align = this.model.align;
            const [sx, sy] = this._get_location();
            const angle = this.panel.get_label_angle_heuristic("parallel");
            this._paint_text(this.layer.ctx, text, sx, sy, angle);
        }
        // XXX: this needs to use CSS computed styles
        _get_size() {
            const { text } = this.model;
            const graphics = new graphics_1.TextBox({ text });
            graphics.visuals = this.visuals.text.values();
            const size = graphics.size();
            const { padding } = this;
            const width = size.width + padding.left + padding.right;
            const height = size.height + padding.top + padding.bottom;
            // XXX: The magic 2px is for backwards compatibility. This will be removed at
            // some point, but currently there is no point breaking half of visual tests.
            return { width, height: height == 0 ? 0 : 2 + height + this.model.standoff };
        }
    }
    exports.HTMLTitleView = HTMLTitleView;
    HTMLTitleView.__name__ = "HTMLTitleView";
    class HTMLTitle extends text_annotation_1.TextAnnotation {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HTMLTitle = HTMLTitle;
    _a = HTMLTitle;
    HTMLTitle.__name__ = "HTMLTitle";
    (() => {
        _a.prototype.default_view = HTMLTitleView;
        _a.mixins([
            mixins.Text,
            ["border_", mixins.Line],
            ["background_", mixins.Fill],
            ["background_", mixins.Hatch],
        ]);
        _a.define(({ Float, Str }) => ({
            text: [Str, ""],
            vertical_align: [enums_1.VerticalAlign, "bottom"],
            align: [enums_1.TextAlign, "left"],
            offset: [Float, 0],
            standoff: [Float, 10],
        }));
        _a.prototype._props.text_align.options.internal = true;
        _a.prototype._props.text_baseline.options.internal = true;
        _a.override({
            text_font_size: "13px",
            text_font_style: "bold",
            text_line_height: 1.0,
            background_fill_color: null,
            background_hatch_color: null,
            border_line_color: null,
        });
    })();
},
/* models/callbacks/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var customjs_1 = require(315) /* ./customjs */;
    __esExport("CustomJS", customjs_1.CustomJS);
    var open_url_1 = require(316) /* ./open_url */;
    __esExport("OpenURL", open_url_1.OpenURL);
    var set_value_1 = require(317) /* ./set_value */;
    __esExport("SetValue", set_value_1.SetValue);
    var toggle_visibility_1 = require(318) /* ./toggle_visibility */;
    __esExport("ToggleVisibility", toggle_visibility_1.ToggleVisibility);
    var open_dialog_1 = require(319) /* ./open_dialog */;
    __esExport("OpenDialog", open_dialog_1.OpenDialog);
    var close_dialog_1 = require(323) /* ./close_dialog */;
    __esExport("CloseDialog", close_dialog_1.CloseDialog);
},
/* models/callbacks/customjs.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const callback_1 = require(119) /* ./callback */;
    const object_1 = require(9) /* ../../core/util/object */;
    const array_1 = require(10) /* ../../core/util/array */;
    const string_1 = require(40) /* ../../core/util/string */;
    const logging_1 = require(19) /* ../../core/logging */;
    const types_1 = require(8) /* ../../core/util/types */;
    const standalone_1 = require(54) /* ../../embed/standalone */;
    class CustomJS extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
            this._state = null;
        }
        connect_signals() {
            super.connect_signals();
            const { args, code, module } = this.properties;
            this.on_change([args, code, module], () => this._state = null);
        }
        async _compile_module() {
            const url = URL.createObjectURL(new Blob([this.code], { type: "text/javascript" }));
            try {
                // XXX: eval() to work around transpilation to require()
                // https://github.com/microsoft/TypeScript/issues/43329
                const module = await eval(`import("${url}")`);
                if ((0, types_1.isFunction)(module.default)) {
                    return module.default;
                }
                else {
                    logging_1.logger.warn("custom ES module didn't export a default function");
                    return () => undefined;
                }
            }
            finally {
                URL.revokeObjectURL(url);
            }
        }
        async _compile_function() {
            const [names = [], values = []] = (0, array_1.unzip)((0, object_1.entries)(this.args));
            const code = (0, string_1.use_strict)(this.code);
            const func = new Function(...names, "cb_obj", "cb_data", "cb_context", code);
            return function (...args) {
                return func.call(this, ...values, ...args);
            };
        }
        _is_es_module(code) {
            return code.split("\n").some((line) => line.trimStart().startsWith("export default"));
        }
        async _compile() {
            const module = (() => {
                if (this.module == "auto") {
                    return this._is_es_module(this.code);
                }
                else {
                    return this.module;
                }
            })();
            if (module) {
                return { func: await this._compile_module(), module };
            }
            else {
                return { func: await this._compile_function(), module };
            }
        }
        async state() {
            if (this._state == null) {
                this._state = await this._compile();
            }
            return this._state;
        }
        async execute(obj, data = {}) {
            const { func, module } = await this.state();
            const context = { index: standalone_1.index };
            if (module) {
                return func((0, object_1.to_object)(this.args), obj, data, context);
            }
            else {
                return func.call(obj, obj, data, context);
            }
        }
    }
    exports.CustomJS = CustomJS;
    _a = CustomJS;
    CustomJS.__name__ = "CustomJS";
    (() => {
        _a.define(({ Unknown, Str, Dict, Auto, Or, Bool }) => ({
            args: [Dict(Unknown), {}],
            code: [Str],
            module: [Or(Auto, Bool), "auto"],
        }));
    })();
},
/* models/callbacks/open_url.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const callback_1 = require(119) /* ./callback */;
    const templating_1 = require(245) /* ../../core/util/templating */;
    const types_1 = require(8) /* ../../core/util/types */;
    class OpenURL extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        navigate(url) {
            if (this.same_tab) {
                window.location.href = url;
            }
            else {
                window.open(url);
            }
        }
        execute(_cb_obj, { source }) {
            const open_url = (i) => {
                const url = (0, templating_1.replace_placeholders)(this.url, source, i, undefined, undefined, encodeURI);
                if (!(0, types_1.isString)(url)) {
                    throw new Error("HTML output is not supported in this context");
                }
                this.navigate(url);
            };
            const { selected } = source;
            for (const i of selected.indices) {
                open_url(i);
            }
            for (const i of selected.line_indices) {
                open_url(i);
            }
            // TODO: multiline_indices: {[key: string]: number[]}
        }
    }
    exports.OpenURL = OpenURL;
    _a = OpenURL;
    OpenURL.__name__ = "OpenURL";
    (() => {
        _a.define(({ Bool, Str }) => ({
            url: [Str, "http://"],
            same_tab: [Bool, false],
        }));
    })();
},
/* models/callbacks/set_value.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const callback_1 = require(119) /* ./callback */;
    const has_props_1 = require(14) /* ../../core/has_props */;
    const logging_1 = require(19) /* ../../core/logging */;
    class SetValue extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        execute() {
            const { obj, attr, value } = this;
            if (attr in obj.properties) {
                obj.setv({ [attr]: value });
            }
            else {
                logging_1.logger.error(`${obj.type}.${attr} is not a property`);
            }
        }
    }
    exports.SetValue = SetValue;
    _a = SetValue;
    SetValue.__name__ = "SetValue";
    (() => {
        _a.define(({ Str, Unknown, Ref }) => ({
            obj: [Ref(has_props_1.HasProps)],
            attr: [Str],
            value: [Unknown],
        }));
    })();
},
/* models/callbacks/toggle_visibility.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const callback_1 = require(119) /* ./callback */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    class ToggleVisibility extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        execute() {
            const { target } = this;
            target.visible = !target.visible;
        }
    }
    exports.ToggleVisibility = ToggleVisibility;
    _a = ToggleVisibility;
    ToggleVisibility.__name__ = "ToggleVisibility";
    (() => {
        _a.define(({ Ref }) => ({
            target: [Ref(ui_element_1.UIElement)],
        }));
    })();
},
/* models/callbacks/open_dialog.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const callback_1 = require(119) /* ./callback */;
    const dialog_1 = require(320) /* ../ui/dialog */;
    class OpenDialog extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        async execute() {
            const { dialog } = this;
            const views = dialog.document?.views_manager;
            if (views != null) {
                let dialog_view = views.find_one(dialog);
                if (dialog_view == null) {
                    dialog_view = await views.build_view(dialog);
                }
                dialog_view.open();
            }
        }
    }
    exports.OpenDialog = OpenDialog;
    _a = OpenDialog;
    OpenDialog.__name__ = "OpenDialog";
    (() => {
        _a.define(({ Ref }) => ({
            dialog: [Ref(dialog_1.Dialog)],
        }));
    })();
},
/* models/ui/dialog.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    const dom_node_1 = require(125) /* ../dom/dom_node */;
    const text_1 = require(321) /* ../dom/text */;
    const dom_1 = require(63) /* ../../core/dom */;
    const types_1 = require(8) /* ../../core/util/types */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const array_1 = require(10) /* ../../core/util/array */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const Box = tslib_1.__importStar(require(264) /* ../common/box_kinds */);
    const coordinate_1 = require(60) /* ../coordinates/coordinate */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const dialogs_css_1 = tslib_1.__importStar(require(322) /* ../../styles/dialogs.css */), dialogs = dialogs_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(123) /* ../../styles/icons.css */);
    // Make sure this at least an order of magnitude lower than --bokeh-top-level.
    const base_z_index = 1000;
    const UIElementLike = (0, kinds_1.Or)((0, kinds_1.Ref)(ui_element_1.UIElement), (0, kinds_1.Ref)(dom_node_1.DOMNode));
    const _stacking_order = [];
    const _minimization_area = (() => {
        const el = (0, dom_1.div)();
        const shadow_el = el.attachShadow({ mode: "open" });
        const stylesheet = new dom_1.InlineStyleSheet(`
:host {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  position: fixed;
  left: 0;
  bottom: 0;
  width: max-content;
  height: max-content;
}
:host:empty {
  display: none;
}
`);
        stylesheet.install(shadow_el);
        void (0, dom_1.dom_ready)().then(() => document.body.append(el));
        return el;
    })();
    class DialogView extends ui_element_1.UIElementView {
        constructor() {
            super(...arguments);
            this._position = new dom_1.InlineStyleSheet();
            this._stacking = new dom_1.InlineStyleSheet();
            this._has_rendered = false;
            this._pinned = false;
            this._normal_bbox = null;
            this._collapsed = false;
            this._minimized = false;
            this._maximized = false;
        }
        *children() {
            yield* super.children();
            yield this._title;
            yield this._content;
        }
        stylesheets() {
            return [...super.stylesheets(), dialogs_css_1.default, icons_css_1.default, this._position, this._stacking];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const title = (() => {
                const { title } = this.model;
                return (0, types_1.isString)(title) || title == null ? new text_1.Text({ content: title ?? "" }) : title;
            })();
            const content = (() => {
                const { content } = this.model;
                return (0, types_1.isString)(content) ? new text_1.Text({ content }) : content;
            })();
            this._title = await (0, build_views_1.build_view)(title, { parent: this });
            this._content = await (0, build_views_1.build_view)(content, { parent: this });
        }
        connect_signals() {
            super.connect_signals();
            const { visible } = this.model.properties;
            this.connect(visible.change, () => this._toggle(this.model.visible));
        }
        remove() {
            (0, array_1.remove)(_stacking_order, this);
            this._content.remove();
            this._title.remove();
            super.remove();
        }
        _reposition(position) {
            this._position.replace(":host", {
                left: "left" in position ? (0, dom_1.px)(position.left) : "unset",
                right: "right" in position ? (0, dom_1.px)(position.right) : "unset",
                top: "top" in position ? (0, dom_1.px)(position.top) : "unset",
                bottom: "bottom" in position ? (0, dom_1.px)(position.bottom) : "unset",
                width: "width" in position ? (0, dom_1.px)(position.width) : "unset",
                height: "height" in position ? (0, dom_1.px)(position.height) : "unset",
            });
            this.update_bbox();
        }
        render() {
            super.render();
            this._title.render();
            this._content.render();
            const inner_el = (0, dom_1.div)({ class: dialogs.inner });
            this.shadow_el.append(inner_el);
            const header_el = (0, dom_1.div)({ class: dialogs.header });
            const content_el = (0, dom_1.div)({ class: dialogs.content }, this._content.el);
            const footer_el = (0, dom_1.div)({ class: dialogs.footer });
            inner_el.append(header_el);
            inner_el.append(content_el);
            inner_el.append(footer_el);
            const grip_el = (0, dom_1.div)({ class: dialogs.grip });
            const title_el = (0, dom_1.div)({ class: dialogs.title }, grip_el, this._title.el);
            const controls_el = (0, dom_1.div)({ class: dialogs.controls });
            header_el.append(title_el, controls_el);
            const pin_el = (0, dom_1.div)({ class: [dialogs.ctrl, dialogs.pin], title: "Pin" });
            pin_el.addEventListener("click", () => this.pin());
            this._pin_el = pin_el;
            const collapse_el = (0, dom_1.div)({ class: [dialogs.ctrl, dialogs.collapse], title: "Collapse" });
            collapse_el.addEventListener("click", () => this.collapse());
            this._collapse_el = collapse_el;
            const minimize_el = (0, dom_1.div)({ class: [dialogs.ctrl, dialogs.minimize], title: "Minimize" });
            minimize_el.addEventListener("click", () => this.minimize());
            this._minimize_el = minimize_el;
            const maximize_el = (0, dom_1.div)({ class: [dialogs.ctrl, dialogs.maximize], title: "Maximize" });
            maximize_el.addEventListener("click", () => this.maximize());
            this._maximize_el = maximize_el;
            const close_el = (0, dom_1.div)({ class: [dialogs.ctrl, dialogs.close], title: "Close" });
            close_el.addEventListener("click", () => this.close());
            this._close_el = close_el;
            if (this.model.pinnable) {
                controls_el.append(pin_el);
            }
            if (this.model.collapsible) {
                controls_el.append(collapse_el);
            }
            if (this.model.minimizable) {
                controls_el.append(minimize_el);
            }
            if (this.model.maximizable) {
                controls_el.append(maximize_el);
            }
            if (this.model.closable) {
                controls_el.append(close_el);
            }
            const handles = this._handles = {
                // area
                area: title_el,
                // edges
                top: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_top] }),
                bottom: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_bottom] }),
                left: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_left] }),
                right: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_right] }),
                // corners
                top_left: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_top_left] }),
                top_right: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_top_right] }),
                bottom_left: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_bottom_left] }),
                bottom_right: (0, dom_1.div)({ class: [dialogs.handle, dialogs.resize_bottom_right] }),
            };
            this.shadow_el.append(handles.top, handles.bottom, handles.left, handles.right, handles.top_left, handles.top_right, handles.bottom_left, handles.bottom_right);
            let state = null;
            const cancel = () => {
                state = null;
                document.removeEventListener("pointermove", pointer_move);
                document.removeEventListener("pointerup", pointer_up);
                document.removeEventListener("keydown", key_press);
                this.el.classList.remove(dialogs.interacting);
            };
            const pointer_move = (event) => {
                (0, assert_1.assert)(state != null);
                event.preventDefault();
                this.el.classList.add(dialogs.interacting);
                const dx = event.x - state.xy.x;
                const dy = event.y - state.xy.y;
                const { target, bbox } = state;
                const delta_bbox = this._move_bbox(target, bbox, dx, dy);
                this._reposition(delta_bbox);
            };
            const pointer_up = (event) => {
                (0, assert_1.assert)(state != null);
                event.preventDefault();
                cancel();
            };
            const key_press = (event) => {
                if (event.key == "Escape") {
                    (0, assert_1.assert)(state != null);
                    event.preventDefault();
                    const { left, top, width, height } = state.bbox;
                    this._reposition({ left, top, width, height });
                    cancel();
                }
            };
            this.el.addEventListener("pointerdown", (event) => {
                (0, assert_1.assert)(state == null);
                this.bring_to_front();
                const target = this._hit_target(event.composedPath());
                if (target == null || !this._can_hit(target)) {
                    return;
                }
                event.preventDefault();
                const { x, y } = event;
                state = {
                    bbox: (0, dom_1.bounding_box)(this.el),
                    xy: { x, y },
                    target,
                };
                document.addEventListener("pointermove", pointer_move);
                document.addEventListener("pointerup", pointer_up);
                document.addEventListener("keydown", key_press);
                const target_el = this._handles[target];
                target_el.setPointerCapture(event.pointerId);
            });
            title_el.addEventListener("wheel", (event) => {
                const dy = event.deltaY;
                if ((dy < 0 && !this._collapsed) || (dy > 0 && this._collapsed)) {
                    event.preventDefault();
                    event.stopPropagation();
                    this.collapse();
                }
            });
            this._has_rendered = true;
            if (this.model.visible) {
                this.bring_to_front();
            }
        }
        get resizable() {
            const { resizable } = this.model;
            return {
                left: resizable == "left" || resizable == "x" || resizable == "all",
                right: resizable == "right" || resizable == "x" || resizable == "all",
                top: resizable == "top" || resizable == "y" || resizable == "all",
                bottom: resizable == "bottom" || resizable == "y" || resizable == "all",
            };
        }
        _hit_target(path) {
            const { _handles } = this;
            for (const el of path) {
                switch (el) {
                    case _handles.area: return "area";
                    case _handles.top: return "top";
                    case _handles.bottom: return "bottom";
                    case _handles.left: return "left";
                    case _handles.right: return "right";
                    case _handles.top_left: return "top_left";
                    case _handles.top_right: return "top_right";
                    case _handles.bottom_left: return "bottom_left";
                    case _handles.bottom_right: return "bottom_right";
                }
            }
            return null;
        }
        _can_hit(target) {
            if (this._minimized || this._maximized) {
                return false;
            }
            const { left, right, top, bottom } = this.resizable;
            switch (target) {
                case "top_left": return top && left;
                case "top_right": return top && right;
                case "bottom_left": return bottom && left;
                case "bottom_right": return bottom && right;
                case "left": return left;
                case "right": return right;
                case "top": return top;
                case "bottom": return bottom;
                case "area": return this.model.movable != "none";
            }
        }
        _move_bbox(target, bbox, dx, dy) {
            const resolve = (dim, limit) => {
                if (limit instanceof coordinate_1.Coordinate) {
                    return this.resolve_as_scalar(limit, dim);
                }
                else {
                    return NaN;
                }
            };
            const slimits = bbox_1.BBox.from_lrtb({
                left: resolve("x", this.model.left_limit),
                right: resolve("x", this.model.right_limit),
                top: resolve("y", this.model.top_limit),
                bottom: resolve("y", this.model.bottom_limit),
            });
            const [dl, dr, dt, db] = (() => {
                const { symmetric } = this.model;
                const [Dx, Dy] = symmetric ? [-dx, -dy] : [0, 0];
                switch (target) {
                    // corners
                    case "top_left": return [dx, Dx, dy, Dy];
                    case "top_right": return [Dx, dx, dy, Dy];
                    case "bottom_left": return [dx, Dx, Dy, dy];
                    case "bottom_right": return [Dx, dx, Dy, dy];
                    // edges
                    case "left": return [dx, Dx, 0, 0];
                    case "right": return [Dx, dx, 0, 0];
                    case "top": return [0, 0, dy, Dy];
                    case "bottom": return [0, 0, Dy, dy];
                    // area
                    case "area": {
                        switch (this.model.movable) {
                            case "both": return [dx, dx, dy, dy];
                            case "x": return [dx, dx, 0, 0];
                            case "y": return [0, 0, dy, dy];
                            case "none": return [0, 0, 0, 0];
                        }
                    }
                }
            })();
            const min = (a, b) => (0, array_1.min)([a, b]);
            const sgn = (v) => v < 0 ? -1 : (v > 0 ? 1 : 0);
            let { left, right, left_sign, right_sign } = (() => {
                const left = bbox.left + dl;
                const right = bbox.right + dr;
                const left_sign = sgn(dl);
                const right_sign = sgn(dr);
                if (left <= right) {
                    return { left, right, left_sign, right_sign };
                }
                else {
                    return { left: right, right: left, left_sign: right_sign, right_sign: left_sign };
                }
            })();
            let { top, bottom, top_sign, bottom_sign } = (() => {
                const top = bbox.top + dt;
                const bottom = bbox.bottom + db;
                const top_sign = sgn(dt);
                const bottom_sign = sgn(db);
                if (top <= bottom) {
                    return { top, bottom, top_sign, bottom_sign };
                }
                else {
                    return { top: bottom, bottom: top, top_sign: bottom_sign, bottom_sign: top_sign };
                }
            })();
            const Dl = left - slimits.left;
            const Dr = slimits.right - right;
            const Dh = min(Dl < 0 ? Dl : NaN, Dr < 0 ? Dr : NaN);
            if (isFinite(Dh) && Dh < 0) {
                left += -left_sign * (-Dh);
                right += -right_sign * (-Dh);
            }
            const Dt = top - slimits.top;
            const Db = slimits.bottom - bottom;
            const Dv = min(Dt < 0 ? Dt : NaN, Db < 0 ? Db : NaN);
            if (isFinite(Dv) && Dv < 0) {
                top += -top_sign * (-Dv);
                bottom += -bottom_sign * (-Dv);
            }
            return bbox_1.BBox.from_lrtb({ left, right, top, bottom });
        }
        pin() {
            const { _pinned } = this;
            for (const dialog_view of _stacking_order) {
                if (dialog_view == this) {
                    this._pin(!_pinned);
                }
                else {
                    dialog_view._pin(false);
                }
            }
            if (!_pinned) {
                this.bring_to_front();
            }
        }
        _pin(value) {
            if (this._pinned != value) {
                this._pinned = value;
                this.el.classList.toggle(dialogs.pinned, this._pinned);
                this._pin_el.title = this._pinned ? "Unpin" : "Pin";
            }
        }
        collapse() {
            const position = (() => {
                if (!this._collapsed) {
                    this._minimize(false);
                    this._maximize(false);
                    if (this._normal_bbox == null) {
                        this._normal_bbox = (0, dom_1.bounding_box)(this.el);
                    }
                    const { left, top, width } = this._normal_bbox;
                    return { left, top, width, height: "max-content" };
                }
                else {
                    const { _normal_bbox } = this;
                    (0, assert_1.assert)(_normal_bbox != null);
                    this._normal_bbox = null;
                    return _normal_bbox;
                }
            })();
            this._reposition(position);
            this._collapse(!this._collapsed);
        }
        _collapse(value) {
            if (this._collapsed != value) {
                this._collapsed = value;
                this.el.classList.toggle(dialogs.collapsed, this._collapsed);
                this._collapse_el.title = this._collapsed ? "Restore" : "Collapse";
            }
        }
        minimize() {
            const position = (() => {
                if (!this._minimized) {
                    this._pin(false);
                    this._collapse(false);
                    this._maximize(false);
                    if (this._normal_bbox == null) {
                        this._normal_bbox = (0, dom_1.bounding_box)(this.el);
                    }
                    return { width: "auto", height: "max-content" };
                }
                else {
                    const { _normal_bbox } = this;
                    (0, assert_1.assert)(_normal_bbox != null);
                    this._normal_bbox = null;
                    return _normal_bbox;
                }
            })();
            this._reposition(position);
            this._minimize(!this._minimized);
        }
        _minimize(value) {
            if (this._minimized != value) {
                this._minimized = value;
                const target = value ? (_minimization_area.shadowRoot ?? _minimization_area) : document.body;
                target.append(this.el);
                this.el.classList.toggle(dialogs.minimized, this._minimized);
                this._minimize_el.title = this._minimized ? "Restore" : "Minimize";
            }
        }
        maximize() {
            const position = (() => {
                if (!this._maximized) {
                    this._collapse(false);
                    this._minimize(false);
                    if (this._normal_bbox == null) {
                        this._normal_bbox = (0, dom_1.bounding_box)(this.el);
                    }
                    return { left: 0, top: 0, width: "100%", height: "100%" };
                }
                else {
                    const { _normal_bbox } = this;
                    (0, assert_1.assert)(_normal_bbox != null);
                    this._normal_bbox = null;
                    return _normal_bbox;
                }
            })();
            this._reposition(position);
            this._maximize(!this._maximized);
        }
        _maximize(value) {
            if (this._maximized != value) {
                this._maximized = value;
                this.el.classList.toggle(dialogs.maximized, this._maximized);
                this._maximize_el.title = this._maximized ? "Restore" : "Maximize";
            }
        }
        restore() {
            this._collapse(false);
            this._minimize(false);
            this._maximize(false);
            const { _normal_bbox } = this;
            if (_normal_bbox != null) {
                this._reposition(_normal_bbox);
                this._normal_bbox = null;
            }
        }
        _toggle(show) {
            if (show) {
                if (!this._has_rendered) {
                    this.render_to(document.body);
                    this.r_after_render();
                }
                this.bring_to_front();
            }
            else {
                (0, array_1.remove)(_stacking_order, this);
                this.el.remove();
            }
        }
        open() {
            this.model.setv({ visible: true }, { check_eq: false });
        }
        close() {
            switch (this.model.close_action) {
                case "hide": {
                    this.model.visible = false;
                    break;
                }
                case "destroy": {
                    this.remove();
                    break;
                }
            }
        }
        bring_to_front() {
            if (!_stacking_order.includes(this)) {
                _stacking_order.push(this);
            }
            const pinned = (0, array_1.find)(_stacking_order, (view) => view._pinned);
            if (pinned != null) {
                (0, array_1.remove)(_stacking_order, pinned);
            }
            (0, array_1.remove)(_stacking_order, this);
            _stacking_order.push(this);
            if (pinned != null) {
                _stacking_order.push(pinned);
            }
            for (const [dialog_view, i] of (0, iterator_1.enumerate)(_stacking_order)) {
                dialog_view._stacking.replace(":host", {
                    "z-index": `${base_z_index + i}`,
                });
            }
        }
    }
    exports.DialogView = DialogView;
    DialogView.__name__ = "DialogView";
    class Dialog extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Dialog = Dialog;
    _a = Dialog;
    Dialog.__name__ = "Dialog";
    (() => {
        _a.prototype.default_view = DialogView;
        _a.define(({ Bool, Str, Ref, Or, Nullable, Enum }) => ({
            title: [Nullable(Or(Str, Ref(dom_node_1.DOMNode), Ref(ui_element_1.UIElement))), null],
            content: [Or(Str, Ref(dom_node_1.DOMNode), Ref(ui_element_1.UIElement))],
            pinnable: [Bool, true],
            collapsible: [Bool, true],
            minimizable: [Bool, true],
            maximizable: [Bool, true],
            closable: [Bool, true],
            close_action: [Enum("hide", "destroy"), "destroy"],
            resizable: [Box.Resizable, "all"],
            movable: [Box.Movable, "both"],
            symmetric: [Bool, false],
            top_limit: [Box.Limit, null],
            bottom_limit: [Box.Limit, null],
            left_limit: [Box.Limit, null],
            right_limit: [Box.Limit, null],
        }));
    })();
},
/* models/dom/text.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const dom_node_1 = require(125) /* ./dom_node */;
    class TextView extends dom_node_1.DOMNodeView {
        render() {
            this.el.textContent = this.model.content;
        }
        // TODO This shouldn't be here.
        after_render() {
            this.finish();
        }
        _create_element() {
            return document.createTextNode("");
        }
    }
    exports.TextView = TextView;
    TextView.__name__ = "TextView";
    class Text extends dom_node_1.DOMNode {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Text = Text;
    _a = Text;
    Text.__name__ = "Text";
    (() => {
        _a.prototype.default_view = TextView;
        _a.define(({ Str }) => ({
            content: [Str, ""],
        }));
    })();
},
/* styles/dialogs.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.interacting = "bk-interacting";
    exports.inner = "bk-inner";
    exports.header = "bk-header";
    exports.content = "bk-content";
    exports.collapsed = "bk-collapsed";
    exports.minimized = "bk-minimized";
    exports.footer = "bk-footer";
    exports.grip = "bk-grip";
    exports.title = "bk-title";
    exports.controls = "bk-controls";
    exports.ctrl = "bk-ctrl";
    exports.pin = "bk-pin";
    exports.pinned = "bk-pinned";
    exports.collapse = "bk-collapse";
    exports.minimize = "bk-minimize";
    exports.maximize = "bk-maximize";
    exports.maximized = "bk-maximized";
    exports.close = "bk-close";
    exports.handle = "bk-handle";
    exports.resize_top = "bk-resize-top";
    exports.resize_bottom = "bk-resize-bottom";
    exports.resize_left = "bk-resize-left";
    exports.resize_right = "bk-resize-right";
    exports.resize_top_left = "bk-resize-top-left";
    exports.resize_top_right = "bk-resize-top-right";
    exports.resize_bottom_left = "bk-resize-bottom-left";
    exports.resize_bottom_right = "bk-resize-bottom-right";
    exports.default = `:host{--bokeh-bg-color:white;--bokeh-border-color:#e5e5e5;--bokeh-shadow-color:#e5e5e5;--bokeh-ctrl-size:16px;--bokeh-ctrl-color:gray;}:host{position:fixed;left:200px;top:200px;width:600px;height:600px;width:80vw;height:60vh;}:host(.bk-interacting){opacity:0.9;}.bk-inner{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;width:100%;height:100%;overflow:hidden;border-radius:4px;background-color:var(--bokeh-bg-color);border:1px solid var(--bokeh-border-color);box-shadow:5px 5px 10px var(--bokeh-shadow-color);}.bk-header{position:relative;display:flex;flex:0;gap:1em;padding:5px;background-color:lightgray;}.bk-content{position:relative;display:flex;flex:1;overflow:auto;}:host(.bk-collapsed) .bk-content,:host(.bk-minimized) .bk-content,:host(.bk-collapsed) .bk-footer,:host(.bk-minimized) .bk-footer{display:none;}.bk-footer{position:relative;display:flex;flex:0;}.bk-grip{width:var(--bokeh-ctrl-size);height:var(--bokeh-ctrl-size);background-color:var(--bokeh-ctrl-color);background-color:var(--bokeh-icon-color);mask-image:var(--bokeh-icon-y-grip);-webkit-mask-image:var(--bokeh-icon-y-grip);mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;}.bk-title{position:relative;display:flex;flex:1;cursor:move;white-space:nowrap;}.bk-controls{position:relative;display:flex;flex:0;}.bk-ctrl{width:var(--bokeh-ctrl-size);height:var(--bokeh-ctrl-size);cursor:pointer;mask-size:100% 100%;-webkit-mask-size:100% 100%;mask-position:center center;-webkit-mask-position:center center;mask-repeat:no-repeat;-webkit-mask-repeat:no-repeat;background-color:var(--bokeh-ctrl-color);}.bk-ctrl:hover{background-color:red;}.bk-pin{mask-image:var(--bokeh-icon-pin);-webkit-mask-image:var(--bokeh-icon-pin);}:host(.bk-pinned) .bk-pin{mask-image:var(--bokeh-icon-unpin);-webkit-mask-image:var(--bokeh-icon-unpin);}.bk-collapse{mask-image:var(--bokeh-icon-chevron-up);-webkit-mask-image:var(--bokeh-icon-chevron-up);}:host(.bk-collapsed) .bk-collapse{mask-image:var(--bokeh-icon-chevron-down);-webkit-mask-image:var(--bokeh-icon-chevron-down);}.bk-minimize{mask-image:var(--bokeh-icon-arrow-down-to-bar);-webkit-mask-image:var(--bokeh-icon-arrow-down-to-bar);}:host(.bk-minimized) .bk-minimize{mask-image:var(--bokeh-icon-arrow-up-from-bar);-webkit-mask-image:var(--bokeh-icon-arrow-up-from-bar);}.bk-maximize{mask-image:var(--bokeh-icon-maximize);-webkit-mask-image:var(--bokeh-icon-maximize);}:host(.bk-maximized) .bk-maximize{mask-image:var(--bokeh-icon-minimize);-webkit-mask-image:var(--bokeh-icon-minimize);}.bk-close{mask-image:var(--bokeh-icon-x);-webkit-mask-image:var(--bokeh-icon-x);}:host{--resize-radius:3px;--resize-depth:calc(2*var(--resize-radius));}:host(.bk-minimized){position:relative;}:host(.bk-minimized) .bk-handle,:host(.bk-maximized) .bk-handle{display:none;}:host(.bk-minimized) .bk-title,:host(.bk-maximized) .bk-title{cursor:default;}.bk-resize-top{position:absolute;top:0;left:var(--resize-radius);width:calc(100% - var(--resize-depth));height:var(--resize-depth);transform:translate(0, -50%);cursor:ns-resize;}.bk-resize-bottom{position:absolute;bottom:0;left:var(--resize-radius);width:calc(100% - var(--resize-depth));height:var(--resize-depth);transform:translate(0, 50%);cursor:ns-resize;}.bk-resize-left{position:absolute;left:0;top:var(--resize-radius);width:var(--resize-depth);height:calc(100% - var(--resize-depth));transform:translate(-50%, 0);cursor:ew-resize;}.bk-resize-right{position:absolute;right:0;top:var(--resize-radius);width:var(--resize-depth);height:calc(100% - var(--resize-depth));transform:translate(50%, 0);cursor:ew-resize;}.bk-resize-top-left{position:absolute;top:0;left:0;width:var(--resize-depth);height:var(--resize-depth);transform:translate(-50%, -50%);cursor:nw-resize;}.bk-resize-top-right{position:absolute;top:0;right:0;width:var(--resize-depth);height:var(--resize-depth);transform:translate(50%, -50%);cursor:ne-resize;}.bk-resize-bottom-left{position:absolute;bottom:0;left:0;width:var(--resize-depth);height:var(--resize-depth);transform:translate(-50%, 50%);cursor:sw-resize;}.bk-resize-bottom-right{position:absolute;bottom:0;right:0;width:var(--resize-depth);height:var(--resize-depth);transform:translate(50%, 50%);cursor:se-resize;}`;
},
/* models/callbacks/close_dialog.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const callback_1 = require(119) /* ./callback */;
    const dialog_1 = require(320) /* ../ui/dialog */;
    class CloseDialog extends callback_1.Callback {
        constructor(attrs) {
            super(attrs);
        }
        async execute() {
            const { dialog } = this;
            dialog.document?.views_manager?.find_one(dialog)?.close();
        }
    }
    exports.CloseDialog = CloseDialog;
    _a = CloseDialog;
    CloseDialog.__name__ = "CloseDialog";
    (() => {
        _a.define(({ Ref }) => ({
            dialog: [Ref(dialog_1.Dialog)],
        }));
    })();
},
/* models/canvas/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var canvas_1 = require(325) /* ./canvas */;
    __esExport("Canvas", canvas_1.Canvas);
    var cartesian_frame_1 = require(188) /* ./cartesian_frame */;
    __esExport("CartesianFrame", cartesian_frame_1.CartesianFrame);
},
/* models/canvas/canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const settings_1 = require(29) /* ../../core/settings */;
    const logging_1 = require(19) /* ../../core/logging */;
    const dom_1 = require(63) /* ../../core/dom */;
    const enums_1 = require(20) /* ../../core/enums */;
    const ui_events_1 = require(326) /* ../../core/ui_events */;
    const modules_1 = require(183) /* ../../core/util/modules */;
    const canvas_1 = require(112) /* ../../core/util/canvas */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    const dom_2 = require(63) /* ../../core/dom */;
    const canvas_css = tslib_1.__importStar(require(328) /* ../../styles/canvas.css */);
    const icons_css_1 = tslib_1.__importDefault(require(123) /* ../../styles/icons.css */);
    async function init_webgl() {
        // We use a global invisible canvas and gl context. By having a global context,
        // we avoid the limitation of max 16 contexts that most browsers have.
        const canvas = document.createElement("canvas");
        const gl = canvas.getContext("webgl", { alpha: true, antialias: false, depth: false, premultipliedAlpha: true });
        // If WebGL is available, we store a reference to the ReGL wrapper on
        // the ctx object, because that's what gets passed everywhere.
        if (gl != null) {
            const webgl = await (0, modules_1.load_module)(Promise.resolve().then(() => tslib_1.__importStar(require(547) /* ../glyphs/webgl */)));
            if (webgl != null) {
                const regl_wrapper = webgl.get_regl(gl);
                if (regl_wrapper.has_webgl) {
                    return { canvas, regl_wrapper };
                }
                else {
                    logging_1.logger.trace("WebGL is supported, but not the required extensions");
                }
            }
            else {
                logging_1.logger.trace("WebGL is supported, but bokehjs(.min).js bundle is not available");
            }
        }
        else {
            logging_1.logger.trace("WebGL is not supported");
        }
        return null;
    }
    const global_webgl = (() => {
        let _global_webgl;
        return async () => {
            if (_global_webgl !== undefined) {
                return _global_webgl;
            }
            else {
                return _global_webgl = await init_webgl();
            }
        };
    })();
    class CanvasView extends ui_element_1.UIElementView {
        constructor() {
            super(...arguments);
            this.webgl = null;
            this._size = new dom_2.InlineStyleSheet();
            this.plot_views = [];
        }
        initialize() {
            super.initialize();
            this.underlays_el = (0, dom_1.div)({ class: canvas_css.layer });
            this.primary = this.create_layer();
            this.overlays = this.create_layer();
            this.overlays_el = (0, dom_1.div)({ class: canvas_css.layer });
            this.events_el = (0, dom_1.div)({ class: [canvas_css.layer, canvas_css.events] });
            this.ui_event_bus = new ui_events_1.UIEventBus(this);
        }
        get layers() {
            return [
                this.underlays_el,
                this.primary,
                this.overlays,
                this.overlays_el,
                this.events_el,
            ];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            if (this.model.output_backend == "webgl") {
                this.webgl = await global_webgl();
                if (settings_1.settings.force_webgl && this.webgl == null) {
                    throw new Error("webgl is not available");
                }
            }
        }
        remove() {
            this.ui_event_bus.remove();
            super.remove();
        }
        stylesheets() {
            return [...super.stylesheets(), canvas_css.default, icons_css_1.default, this._size];
        }
        render() {
            super.render();
            const elements = [
                this.underlays_el,
                this.primary.el,
                this.overlays.el,
                this.overlays_el,
                this.events_el,
            ];
            this.shadow_el.append(...elements);
        }
        get pixel_ratio() {
            return this.primary.pixel_ratio; // XXX: primary
        }
        _update_bbox() {
            const changed = super._update_bbox();
            if (changed) {
                const { width, height } = this.bbox;
                this._size.replace(`.${canvas_css.layer}`, {
                    width: (0, dom_1.px)(width),
                    height: (0, dom_1.px)(height),
                });
                this.primary.resize(width, height);
                this.overlays.resize(width, height);
            }
            return changed;
        }
        after_resize() {
            if (this.plot_views.length != 0) {
                // Canvas is being managed by a plot, thus it should not attempt
                // self-resize, as it would result in inconsistent state and
                // possibly invalid layout and/or lack of repaint of a plot.
                this.finish();
            }
            else {
                super.after_resize();
            }
        }
        _after_resize() {
            super._after_resize();
            const { width, height } = this.bbox;
            this.primary.resize(width, height);
            this.overlays.resize(width, height);
        }
        resize() {
            this._update_bbox();
            this._after_resize();
        }
        prepare_webgl(frame_box) {
            // Prepare WebGL for a drawing pass
            const { webgl } = this;
            if (webgl != null) {
                // Sync canvas size
                const { width, height } = this.bbox;
                webgl.canvas.width = this.pixel_ratio * width;
                webgl.canvas.height = this.pixel_ratio * height;
                const [sx, sy, w, h] = frame_box;
                const { xview, yview } = this.bbox;
                const vx = xview.compute(sx);
                const vy = yview.compute(sy + h);
                const ratio = this.pixel_ratio;
                webgl.regl_wrapper.set_scissor(ratio * vx, ratio * vy, ratio * w, ratio * h);
                this._clear_webgl();
            }
        }
        blit_webgl(ctx) {
            // This should be called when the ctx has no state except the HIDPI transform
            const { webgl } = this;
            if (webgl != null && webgl.canvas.width * webgl.canvas.height > 0) {
                // Blit gl canvas into the 2D canvas. To do 1-on-1 blitting, we need
                // to remove the hidpi transform, then blit, then restore.
                // ctx.globalCompositeOperation = "source-over"  -> OK; is the default
                logging_1.logger.debug("Blitting WebGL canvas");
                ctx.restore();
                ctx.drawImage(webgl.canvas, 0, 0);
                // Set back hidpi transform
                ctx.save();
                if (this.model.hidpi) {
                    const ratio = this.pixel_ratio;
                    ctx.scale(ratio, ratio);
                    ctx.translate(0.5, 0.5);
                }
                this._clear_webgl();
            }
        }
        _clear_webgl() {
            const { webgl } = this;
            if (webgl != null) {
                // Prepare GL for drawing
                const { regl_wrapper, canvas } = webgl;
                regl_wrapper.clear(canvas.width, canvas.height);
            }
        }
        compose() {
            const composite = this.create_layer();
            const { width, height } = this.bbox;
            composite.resize(width, height);
            composite.ctx.drawImage(this.primary.canvas, 0, 0);
            composite.ctx.drawImage(this.overlays.canvas, 0, 0);
            return composite;
        }
        create_layer() {
            const { output_backend, hidpi } = this.model;
            return new canvas_1.CanvasLayer(output_backend, hidpi);
        }
        to_blob() {
            return this.compose().to_blob();
        }
    }
    exports.CanvasView = CanvasView;
    CanvasView.__name__ = "CanvasView";
    class Canvas extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Canvas = Canvas;
    _a = Canvas;
    Canvas.__name__ = "Canvas";
    (() => {
        _a.prototype.default_view = CanvasView;
        _a.define(({ Bool }) => ({
            hidpi: [Bool, true],
            output_backend: [enums_1.OutputBackend, "canvas"],
        }));
    })();
},
/* core/ui_events.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.is_Tapable = is_Tapable;
    exports.is_Moveable = is_Moveable;
    exports.is_Pannable = is_Pannable;
    exports.is_Pinchable = is_Pinchable;
    exports.is_Rotatable = is_Rotatable;
    exports.is_Scrollable = is_Scrollable;
    exports.is_Keyable = is_Keyable;
    const tslib_1 = require(1) /* tslib */;
    const ui_gestures_1 = require(296) /* ./ui_gestures */;
    const signaling_1 = require(15) /* ./signaling */;
    const dom_1 = require(63) /* ./dom */;
    const events = tslib_1.__importStar(require(53) /* ./bokeh_events */);
    const wheel_1 = require(327) /* ./util/wheel */;
    const array_1 = require(10) /* ./util/array */;
    const types_1 = require(8) /* ./util/types */;
    const tool_proxy_1 = require(294) /* ../models/tools/tool_proxy */;
    function is_Tapable(obj) {
        return (0, types_1.isObject)(obj) && "on_tap" in obj;
    }
    function is_Moveable(obj) {
        return (0, types_1.isObject)(obj) && "on_enter" in obj && "on_move" in obj && "on_leave" in obj;
    }
    function is_Pannable(obj) {
        return (0, types_1.isObject)(obj) && "on_pan_start" in obj && "on_pan" in obj && "on_pan_end" in obj;
    }
    function is_Pinchable(obj) {
        return (0, types_1.isObject)(obj) && "on_pinch_start" in obj && "on_pinch" in obj && "on_pinch_end" in obj;
    }
    function is_Rotatable(obj) {
        return (0, types_1.isObject)(obj) && "on_rotate_start" in obj && "on_rotate" in obj && "on_rotate_end" in obj;
    }
    function is_Scrollable(obj) {
        return (0, types_1.isObject)(obj) && "on_scroll" in obj;
    }
    function is_Keyable(obj) {
        return (0, types_1.isObject)(obj) && "on_keydown" in obj && "on_keyup" in obj;
    }
    class UIEventBus {
        constructor(canvas_view) {
            this.pan_start = new signaling_1.Signal(this, "pan:start");
            this.pan = new signaling_1.Signal(this, "pan");
            this.pan_end = new signaling_1.Signal(this, "pan:end");
            this.pinch_start = new signaling_1.Signal(this, "pinch:start");
            this.pinch = new signaling_1.Signal(this, "pinch");
            this.pinch_end = new signaling_1.Signal(this, "pinch:end");
            this.rotate_start = new signaling_1.Signal(this, "rotate:start");
            this.rotate = new signaling_1.Signal(this, "rotate");
            this.rotate_end = new signaling_1.Signal(this, "rotate:end");
            this.tap = new signaling_1.Signal(this, "tap");
            this.doubletap = new signaling_1.Signal(this, "doubletap");
            this.press = new signaling_1.Signal(this, "press");
            this.pressup = new signaling_1.Signal(this, "pressup");
            this.move_enter = new signaling_1.Signal(this, "move:enter");
            this.move = new signaling_1.Signal(this, "move");
            this.move_exit = new signaling_1.Signal(this, "move:exit");
            this.scroll = new signaling_1.Signal(this, "scroll");
            this.keydown = new signaling_1.Signal(this, "keydown");
            this.keyup = new signaling_1.Signal(this, "keyup");
            this._tools = new Map();
            this._prev_move = null;
            this._curr_pan = null;
            this._curr_pinch = null;
            this._curr_rotate = null;
            this._current_pan_view = null;
            this._current_pinch_view = null;
            this._current_rotate_view = null;
            this._current_move_views = [];
            this.canvas_view = canvas_view;
            this.hit_area = canvas_view.events_el;
            this.on_tap = this.on_tap.bind(this);
            this.on_doubletap = this.on_doubletap.bind(this);
            this.on_press = this.on_press.bind(this);
            this.on_pressup = this.on_pressup.bind(this);
            this.on_enter = this.on_enter.bind(this);
            this.on_move = this.on_move.bind(this);
            this.on_leave = this.on_leave.bind(this);
            this.on_pan_start = this.on_pan_start.bind(this);
            this.on_pan = this.on_pan.bind(this);
            this.on_pan_end = this.on_pan_end.bind(this);
            this.on_pinch_start = this.on_pinch_start.bind(this);
            this.on_pinch = this.on_pinch.bind(this);
            this.on_pinch_end = this.on_pinch_end.bind(this);
            this.on_rotate_start = this.on_rotate_start.bind(this);
            this.on_rotate = this.on_rotate.bind(this);
            this.on_rotate_end = this.on_rotate_end.bind(this);
            this.ui_gestures = new ui_gestures_1.UIGestures(this.hit_area, this, { must_be_target: true });
            this.ui_gestures.connect_signals();
            this.on_context_menu = this.on_context_menu.bind(this);
            this.on_mouse_wheel = this.on_mouse_wheel.bind(this);
            this.on_key_down = this.on_key_down.bind(this);
            this.on_key_up = this.on_key_up.bind(this);
            this.hit_area.addEventListener("contextmenu", this.on_context_menu);
            this.hit_area.addEventListener("wheel", this.on_mouse_wheel);
            document.addEventListener("keydown", this.on_key_down);
            document.addEventListener("keyup", this.on_key_up);
        }
        remove() {
            this.ui_gestures.remove();
            this.hit_area.removeEventListener("contextmenu", this.on_context_menu);
            this.hit_area.removeEventListener("wheel", this.on_mouse_wheel);
            document.removeEventListener("keydown", this.on_key_down);
            document.removeEventListener("keyup", this.on_key_up);
        }
        register_tool(tool_view) {
            const { model: tool } = tool_view;
            if (this._tools.has(tool)) {
                throw new Error(`${tool} already registered`);
            }
            else {
                this._tools.set(tool, tool_view);
            }
        }
        hit_test_renderers(plot_view, sx, sy) {
            const collected = [];
            for (const view of (0, array_1.reversed)(plot_view.all_renderer_views)) {
                if (view.interactive_hit?.(sx, sy) ?? false) {
                    collected.push(view);
                }
            }
            return collected;
        }
        set_cursor(cursor) {
            this.hit_area.style.cursor = cursor ?? "default";
        }
        hit_test_frame(plot_view, sx, sy) {
            return plot_view.frame.bbox.contains(sx, sy);
        }
        hit_test_plot(sx, sy) {
            // TODO: z-index
            for (const plot_view of this.canvas_view.plot_views) {
                if (plot_view.bbox.relative() /*XXX*/.contains(sx, sy)) {
                    return plot_view;
                }
            }
            return null;
        }
        _trigger(signal, e) {
            if (!this.hit_area.isConnected) {
                return;
            }
            const { sx, sy, native: srcEvent } = 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 { ...e, sx: rel_sx, sy: rel_sy };
            };
            if (e.type == "pan_start" || e.type == "pan" || e.type == "pan_end") {
                let pan_view;
                if (e.type == "pan_start" && 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 == "pan_end" && 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 == "pinch_start" || e.type == "pinch" || e.type == "pinch_end") {
                let pinch_view;
                if (e.type == "pinch_start" && 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 == "pinch_end" && 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 == "rotate_start" || e.type == "rotate" || e.type == "rotate_end") {
                let rotate_view;
                if (e.type == "rotate_start" && 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 == "rotate_end" && 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 == "enter" || e.type == "move" || e.type == "leave") {
                const prev_view = this._prev_move?.plot_view;
                if (prev_view != null && (e.type == "leave" || prev_view != curr_view)) {
                    const { sx, sy } = relativize_event(prev_view);
                    this.__trigger(prev_view, this.move_exit, { type: "leave", sx, sy, modifiers: { shift: false, ctrl: false, alt: false }, native: srcEvent }, srcEvent);
                }
                if (curr_view != null && (e.type == "enter" || prev_view != curr_view)) {
                    const { sx, sy } = relativize_event(curr_view);
                    this.__trigger(curr_view, this.move_enter, { type: "enter", sx, sy, modifiers: { shift: false, ctrl: false, alt: false }, native: srcEvent }, srcEvent);
                }
                if (curr_view != null && e.type == "move") {
                    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) {
            const gestures = plot_view.model.toolbar.gestures;
            const event_type = signal.name;
            const base_type = event_type.split(":")[0];
            const views = this.hit_test_renderers(plot_view, e.sx, e.sy);
            if (base_type == "pan") {
                const event = e;
                if (this._current_pan_view == null) {
                    if (event_type == "pan:start") {
                        for (const view of views) {
                            if (!is_Pannable(view)) {
                                continue;
                            }
                            if (view.on_pan_start(event)) {
                                this._current_pan_view = view;
                                srcEvent.preventDefault();
                                return;
                            }
                        }
                    }
                }
                else {
                    if (event_type == "pan") {
                        this._current_pan_view.on_pan(event);
                    }
                    else if (event_type == "pan:end") {
                        this._current_pan_view.on_pan_end(event);
                        this._current_pan_view = null;
                    }
                    srcEvent.preventDefault();
                    return;
                }
            }
            else if (base_type == "pinch") {
                const event = e;
                if (this._current_pinch_view == null) {
                    if (event_type == "pinch:start") {
                        for (const view of views) {
                            if (!is_Pinchable(view)) {
                                continue;
                            }
                            if (view.on_pinch_start(event)) {
                                this._current_pinch_view = view;
                                srcEvent.preventDefault();
                                return;
                            }
                        }
                    }
                }
                else {
                    if (event_type == "pinch") {
                        this._current_pinch_view.on_pinch(event);
                    }
                    else if (event_type == "pinch:end") {
                        this._current_pinch_view.on_pinch_end(event);
                        this._current_pinch_view = null;
                    }
                    srcEvent.preventDefault();
                    return;
                }
            }
            else if (base_type == "rotate") {
                const event = e;
                if (this._current_rotate_view == null) {
                    if (event_type == "rotate:start") {
                        for (const view of views) {
                            if (!is_Rotatable(view)) {
                                continue;
                            }
                            if (view.on_rotate_start(event)) {
                                this._current_rotate_view = view;
                                srcEvent.preventDefault();
                                return;
                            }
                        }
                    }
                }
                else {
                    if (event_type == "rotate") {
                        this._current_rotate_view.on_rotate(event);
                    }
                    else if (event_type == "rotate:end") {
                        this._current_rotate_view.on_rotate_end(event);
                        this._current_rotate_view = null;
                    }
                    srcEvent.preventDefault();
                    return;
                }
            }
            else if (base_type == "move") {
                const event = e;
                const new_views = new Set(views);
                const current_views = new Set(this._current_move_views);
                this._current_move_views = [];
                for (const view of current_views) {
                    if (!new_views.has(view)) {
                        current_views.delete(view);
                        view.on_leave(event);
                    }
                }
                for (const view of views) {
                    if (!is_Moveable(view)) {
                        continue;
                    }
                    if (!current_views.has(view)) {
                        if (view.on_enter(e)) {
                            this._current_move_views.push(view);
                        }
                    }
                    else {
                        this._current_move_views.push(view);
                        view.on_move(event);
                    }
                }
            }
            function get_tool_view(tool_like) {
                if (tool_like != null) {
                    const tool = tool_like instanceof tool_proxy_1.ToolProxy ? tool_like.tools[0] : tool_like;
                    return plot_view.tool_views.get(tool) ?? null;
                }
                else {
                    return null;
                }
            }
            const top_view = views.at(0);
            switch (base_type) {
                case "move": {
                    const active_gesture = gestures.move.active;
                    if (active_gesture != null) {
                        this.trigger(signal, e, active_gesture);
                    }
                    const active_inspectors = plot_view.model.toolbar.inspectors.filter(t => t.active);
                    const cursor = (() => {
                        const current_view = this._current_pan_view ??
                            this._current_pinch_view ??
                            this._current_rotate_view ??
                            this._current_move_views.at(0) ??
                            top_view ??
                            get_tool_view(active_gesture);
                        if (current_view != null) {
                            const cursor = current_view.cursor(e.sx, e.sy);
                            if (cursor != null) {
                                return cursor;
                            }
                        }
                        if (this.hit_test_frame(plot_view, e.sx, e.sy) && !(0, array_1.is_empty)(active_inspectors)) {
                            // the event happened on the plot frame but off a renderer
                            return "crosshair";
                        }
                        return null;
                    })();
                    this.set_cursor(cursor);
                    if (top_view != null && !top_view.model.propagate_hover && !(0, array_1.is_empty)(active_inspectors)) {
                        // override event_type to cause inspectors to clear overlays
                        signal = this.move_exit; // XXX
                    }
                    active_inspectors.map((inspector) => this.trigger(signal, e, inspector));
                    break;
                }
                case "tap": {
                    const path = srcEvent.composedPath();
                    if (path.length != 0 && path[0] != this.hit_area) {
                        return; // don't trigger bokeh events
                    }
                    top_view?.on_hit?.(e.sx, e.sy);
                    if (this.hit_test_frame(plot_view, e.sx, e.sy)) {
                        const active_gesture = gestures.tap.active;
                        if (active_gesture != null) {
                            this.trigger(signal, e, active_gesture);
                        }
                    }
                    break;
                }
                case "doubletap": {
                    if (this.hit_test_frame(plot_view, e.sx, e.sy)) {
                        const active_gesture = gestures.doubletap.active ?? gestures.tap.active;
                        if (active_gesture != null) {
                            this.trigger(signal, e, active_gesture);
                        }
                    }
                    break;
                }
                case "press": {
                    if (this.hit_test_frame(plot_view, e.sx, e.sy)) {
                        const active_gesture = gestures.press.active ?? gestures.tap.active;
                        if (active_gesture != null) {
                            this.trigger(signal, e, active_gesture);
                        }
                    }
                    break;
                }
                case "pinch": {
                    const active_gesture = gestures.pinch.active ?? gestures.scroll.active;
                    if (active_gesture != null) {
                        if (this.trigger(signal, e, active_gesture)) {
                            srcEvent.preventDefault();
                            srcEvent.stopPropagation();
                        }
                    }
                    break;
                }
                case "scroll": {
                    const active_gesture = gestures.scroll.active;
                    if (active_gesture != null) {
                        if (this.trigger(signal, e, active_gesture)) {
                            srcEvent.preventDefault();
                            srcEvent.stopPropagation();
                        }
                    }
                    break;
                }
                case "pan": {
                    const active_gesture = gestures.pan.active;
                    if (active_gesture != null) {
                        if (this.trigger(signal, e, active_gesture)) {
                            srcEvent.preventDefault();
                            srcEvent.stopPropagation();
                        }
                    }
                    /* TODO this requires knowledge of the current interactive
                            tool (similar to _current_pan_view, etc.)
                    const active_pan_view = get_tool_view(active_gesture)
                    if (active_pan_view != null) {
                      const cursor = active_pan_view.cursor(e.sx, e.sy)
                      this.set_cursor(cursor)
                    }
                    */
                    break;
                }
                default: {
                    const active_gesture = gestures[base_type].active;
                    if (active_gesture != null) {
                        this.trigger(signal, e, active_gesture);
                    }
                }
            }
            this._trigger_bokeh_event(plot_view, e);
        }
        trigger(signal, e, tool = null) {
            const emit = (tool) => {
                const tool_view = this._tools.get(tool);
                if (tool_view == null) {
                    return false;
                }
                const fn = (() => {
                    switch (signal) {
                        case this.pan_start: return tool_view._pan_start;
                        case this.pan: return tool_view._pan;
                        case this.pan_end: return tool_view._pan_end;
                        case this.pinch_start: return tool_view._pinch_start;
                        case this.pinch: return tool_view._pinch;
                        case this.pinch_end: return tool_view._pinch_end;
                        case this.rotate_start: return tool_view._rotate_start;
                        case this.rotate: return tool_view._rotate;
                        case this.rotate_end: return tool_view._rotate_end;
                        case this.move_enter: return tool_view._move_enter;
                        case this.move: return tool_view._move;
                        case this.move_exit: return tool_view._move_exit;
                        case this.tap: return tool_view._tap;
                        case this.doubletap: return tool_view._doubletap;
                        case this.press: return tool_view._press;
                        case this.pressup: return tool_view._pressup;
                        case this.scroll: return tool_view._scroll;
                        case this.keydown: return tool_view._keydown;
                        case this.keyup: return tool_view._keyup;
                        default: return null;
                    }
                })();
                if (fn == null) {
                    return false;
                }
                const val = fn.bind(tool_view)(e);
                if ((0, types_1.isBoolean)(val)) {
                    return val;
                }
                else {
                    return true;
                }
            };
            if (tool != null) {
                return emit(tool);
            }
            else {
                let result = false;
                for (const tool of this._tools.keys()) {
                    // don't conflate these lines because of short circuiting nature of ||= operator
                    const emitted = emit(tool);
                    result || (result = emitted);
                }
                return result;
            }
        }
        /*protected*/ _trigger_bokeh_event(plot_view, ev) {
            const bokeh_event = (() => {
                const { sx, sy, modifiers } = ev;
                const x = plot_view.frame.x_scale.invert(sx);
                const y = plot_view.frame.y_scale.invert(sy);
                switch (ev.type) {
                    case "wheel": return new events.MouseWheel(sx, sy, x, y, ev.delta, modifiers);
                    case "enter": return new events.MouseEnter(sx, sy, x, y, modifiers);
                    case "move": return new events.MouseMove(sx, sy, x, y, modifiers);
                    case "leave": return new events.MouseLeave(sx, sy, x, y, modifiers);
                    case "tap": return new events.Tap(sx, sy, x, y, modifiers);
                    case "double_tap": return new events.DoubleTap(sx, sy, x, y, modifiers);
                    case "press": return new events.Press(sx, sy, x, y, modifiers);
                    case "press_up": return new events.PressUp(sx, sy, x, y, modifiers);
                    case "pan_start": return new events.PanStart(sx, sy, x, y, modifiers);
                    case "pan": return new events.Pan(sx, sy, x, y, ev.dx, ev.dy, modifiers);
                    case "pan_end": return new events.PanEnd(sx, sy, x, y, modifiers);
                    case "pinch_start": return new events.PinchStart(sx, sy, x, y, modifiers);
                    case "pinch": return new events.Pinch(sx, sy, x, y, ev.scale, modifiers);
                    case "pinch_end": return new events.PinchEnd(sx, sy, x, y, modifiers);
                    case "rotate_start": return new events.RotateStart(sx, sy, x, y, modifiers);
                    case "rotate": return new events.Rotate(sx, sy, x, y, ev.rotation, modifiers);
                    case "rotate_end": return new events.RotateEnd(sx, sy, x, y, modifiers);
                    default: return null;
                }
            })();
            if (bokeh_event != null) {
                plot_view.model.trigger_event(bokeh_event);
            }
        }
        _get_sxy(event) {
            const { pageX, pageY } = event;
            const { left, top } = (0, dom_1.offset_bbox)(this.hit_area);
            return {
                sx: pageX - left,
                sy: pageY - top,
            };
        }
        _get_modifiers(event) {
            return {
                shift: event.shiftKey,
                ctrl: event.ctrlKey,
                alt: event.altKey,
            };
        }
        _scroll_event(event) {
            return {
                type: event.type,
                ...this._get_sxy(event),
                delta: (0, wheel_1.getDeltaY)(event),
                modifiers: this._get_modifiers(event),
                native: event,
            };
        }
        _key_event(event) {
            return {
                type: event.type,
                key: event.key,
                modifiers: this._get_modifiers(event),
                native: event,
            };
        }
        on_tap(event) {
            this._trigger(this.tap, event);
        }
        on_doubletap(event) {
            this._trigger(this.doubletap, event);
        }
        on_press(event) {
            this._trigger(this.press, event);
        }
        on_pressup(event) {
            this._trigger(this.pressup, event);
        }
        on_enter(event) {
            this._trigger(this.move_enter, event);
        }
        on_move(event) {
            this._trigger(this.move, event);
        }
        on_leave(event) {
            this._trigger(this.move_exit, event);
        }
        on_pan_start(event) {
            this._trigger(this.pan_start, event);
        }
        on_pan(event) {
            this._trigger(this.pan, event);
        }
        on_pan_end(event) {
            this._trigger(this.pan_end, event);
        }
        on_pinch_start(event) {
            this._trigger(this.pinch_start, event);
        }
        on_pinch(event) {
            this._trigger(this.pinch, event);
        }
        on_pinch_end(event) {
            this._trigger(this.pinch_end, event);
        }
        on_rotate_start(event) {
            this._trigger(this.rotate_start, event);
        }
        on_rotate(event) {
            this._trigger(this.rotate, event);
        }
        on_rotate_end(event) {
            this._trigger(this.rotate_end, event);
        }
        on_mouse_wheel(event) {
            this._trigger(this.scroll, this._scroll_event(event));
        }
        on_context_menu(_event) {
            // TODO
        }
        on_key_down(event) {
            // NOTE: keyup event triggered unconditionally
            this.trigger(this.keydown, this._key_event(event));
        }
        on_key_up(event) {
            // NOTE: keyup event triggered unconditionally
            this.trigger(this.keyup, this._key_event(event));
        }
    }
    exports.UIEventBus = UIEventBus;
    UIEventBus.__name__ = "UIEventBus";
},
/* core/util/wheel.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.getDeltaY = getDeltaY;
    /*!
     * jQuery Mousewheel 3.1.13
     *
     * Copyright jQuery Foundation and other contributors
     * Released under the MIT license
     * http://jquery.org/license
     */
    function fontSize(element) {
        const value = getComputedStyle(element).fontSize;
        const size = parseInt(value, 10);
        return isNaN(size) ? null : size;
    }
    function lineHeight(element) {
        const parent = element.offsetParent ?? document.body;
        return fontSize(parent) ?? fontSize(element) ?? 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;
    }
},
/* styles/canvas.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.layer = "bk-layer";
    exports.events = "bk-events";
    exports.default = `.bk-layer{position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;}.bk-events{touch-action:none;overflow:visible;}`;
},
/* models/comparisons/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var comparison_1 = require(330) /* ./comparison */;
    __esExport("Comparison", comparison_1.Comparison);
    var customjs_compare_1 = require(331) /* ./customjs_compare */;
    __esExport("CustomJSCompare", customjs_compare_1.CustomJSCompare);
    var nan_compare_1 = require(332) /* ./nan_compare */;
    __esExport("NanCompare", nan_compare_1.NanCompare);
},
/* models/comparisons/comparison.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(51) /* ../../model */;
    class Comparison extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Comparison = Comparison;
    Comparison.__name__ = "Comparison";
},
/* models/comparisons/customjs_compare.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const comparison_1 = require(330) /* ./comparison */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(40) /* ../../core/util/string */;
    class CustomJSCompare extends comparison_1.Comparison {
        constructor(attrs) {
            super(attrs);
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        _make_func() {
            const code = (0, string_1.use_strict)(this.code);
            return new Function("x", "y", ...this.names, code);
        }
        compute(x, y) {
            const func = this._make_func();
            return func(x, y, this.values);
        }
    }
    exports.CustomJSCompare = CustomJSCompare;
    _a = CustomJSCompare;
    CustomJSCompare.__name__ = "CustomJSCompare";
    (() => {
        _a.define(({ Unknown, Str, Dict }) => ({
            args: [Dict(Unknown), {}],
            code: [Str, ""],
        }));
    })();
},
/* models/comparisons/nan_compare.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const comparison_1 = require(330) /* ./comparison */;
    const types_1 = require(8) /* ../../core/util/types */;
    class NanCompare extends comparison_1.Comparison {
        constructor(attrs) {
            super(attrs);
        }
        compute(x, y) {
            if ((0, types_1.isNumber)(x) && isNaN(x)) {
                return this.ascending_first ? -1 : 1;
            }
            if ((0, types_1.isNumber)(y) && isNaN(y)) {
                return this.ascending_first ? 1 : -1;
            }
            if ((0, types_1.isNumber)(x) && (0, types_1.isNumber)(y)) {
                return x == y ? 0 : x < y ? -1 : 1;
            }
            return 0;
        }
    }
    exports.NanCompare = NanCompare;
    _a = NanCompare;
    NanCompare.__name__ = "NanCompare";
    (() => {
        _a.define(({ Bool }) => ({
            ascending_first: [Bool, false],
        }));
    })();
},
/* models/coordinates/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var coordinate_mapping_1 = require(95) /* ./coordinate_mapping */;
    __esExport("CoordinateMapping", coordinate_mapping_1.CoordinateMapping);
    var node_1 = require(59) /* ./node */;
    __esExport("Node", node_1.Node);
    var xy_1 = require(61) /* ./xy */;
    __esExport("XY", xy_1.XY);
    var indexed_1 = require(62) /* ./indexed */;
    __esExport("Indexed", indexed_1.Indexed);
},
/* models/expressions/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var expression_1 = require(335) /* ./expression */;
    __esExport("Expression", expression_1.Expression);
    var customjs_expr_1 = require(336) /* ./customjs_expr */;
    __esExport("CustomJSExpr", customjs_expr_1.CustomJSExpr);
    var stack_1 = require(337) /* ./stack */;
    __esExport("Stack", stack_1.Stack);
    var cumsum_1 = require(338) /* ./cumsum */;
    __esExport("CumSum", cumsum_1.CumSum);
    var expression_2 = require(335) /* ./expression */;
    __esExport("ScalarExpression", expression_2.ScalarExpression);
    var minimum_1 = require(339) /* ./minimum */;
    __esExport("Minimum", minimum_1.Minimum);
    var maximum_1 = require(340) /* ./maximum */;
    __esExport("Maximum", maximum_1.Maximum);
    var coordinate_transform_1 = require(341) /* ./coordinate_transform */;
    __esExport("XComponent", coordinate_transform_1.XComponent);
    __esExport("YComponent", coordinate_transform_1.YComponent);
    var polar_1 = require(342) /* ./polar */;
    __esExport("PolarTransform", polar_1.PolarTransform);
},
/* models/expressions/expression.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(51) /* ../../model */;
    class Expression extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this._result = new Map();
        }
        v_compute(source) {
            let result = this._result.get(source);
            if (result === undefined || source.changed_for(this)) {
                result = this._v_compute(source);
                this._result.set(source, result);
            }
            return result;
        }
    }
    exports.Expression = Expression;
    Expression.__name__ = "Expression";
    class ScalarExpression extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this._result = new Map();
        }
        compute(source) {
            let result = this._result.get(source);
            if (result === undefined || source.changed_for(this)) {
                result = this._compute(source);
                this._result.set(source, result);
            }
            return result;
        }
    }
    exports.ScalarExpression = ScalarExpression;
    ScalarExpression.__name__ = "ScalarExpression";
},
/* models/expressions/customjs_expr.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const has_props_1 = require(14) /* ../../core/has_props */;
    const expression_1 = require(335) /* ./expression */;
    const types_1 = require(24) /* ../../core/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(40) /* ../../core/util/string */;
    const types_2 = require(8) /* ../../core/util/types */;
    class CustomJSExpr extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        connect_signals() {
            super.connect_signals();
            for (const value of (0, object_1.values)(this.args)) {
                if (value instanceof has_props_1.HasProps) {
                    value.change.connect(() => {
                        this._result.clear();
                        this.change.emit();
                    });
                }
            }
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        get func() {
            const code = (0, string_1.use_strict)(this.code);
            return new types_1.GeneratorFunction(...this.names, code);
        }
        _v_compute(source) {
            const generator = this.func.apply(source, this.values);
            let result = generator.next();
            if ((result.done ?? false) && result.value !== undefined) {
                const { value } = result;
                if ((0, types_2.isArray)(value) || (0, types_2.isTypedArray)(value)) {
                    return value;
                }
                else if ((0, types_2.isIterable)(value)) {
                    return [...value];
                }
                else {
                    return (0, array_1.repeat)(value, source.length);
                }
            }
            else {
                const array = [];
                do {
                    array.push(result.value);
                    result = generator.next();
                } while (!(result.done ?? false));
                return array;
            }
        }
    }
    exports.CustomJSExpr = CustomJSExpr;
    _a = CustomJSExpr;
    CustomJSExpr.__name__ = "CustomJSExpr";
    (() => {
        _a.define(({ Unknown, Str, Dict }) => ({
            args: [Dict(Unknown), {}],
            code: [Str, ""],
        }));
    })();
},
/* models/expressions/stack.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const expression_1 = require(335) /* ./expression */;
    const object_1 = require(9) /* ../../core/util/object */;
    class Stack extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            const n = source.get_length() ?? 0;
            const result = new Float64Array(n);
            for (const f of this.fields) {
                const column = (0, object_1.dict)(source.data).get(f);
                if (column != null) {
                    const k = Math.min(n, column.length);
                    for (let i = 0; i < k; i++) {
                        result[i] += column[i];
                    }
                }
            }
            return result;
        }
    }
    exports.Stack = Stack;
    _a = Stack;
    Stack.__name__ = "Stack";
    (() => {
        _a.define(({ Str, List }) => ({
            fields: [List(Str), []],
        }));
    })();
},
/* models/expressions/cumsum.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const expression_1 = require(335) /* ./expression */;
    const object_1 = require(9) /* ../../core/util/object */;
    class CumSum extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            const result = new Float64Array(source.get_length() ?? 0);
            const column = ((0, object_1.dict)(source.data).get(this.field) ?? []);
            const offset = this.include_zero ? 1 : 0;
            result[0] = this.include_zero ? 0 : column[0];
            for (let i = 1; i < result.length; i++) {
                result[i] = result[i - 1] + column[i - offset];
            }
            return result;
        }
    }
    exports.CumSum = CumSum;
    _a = CumSum;
    CumSum.__name__ = "CumSum";
    (() => {
        _a.define(({ Bool, Str }) => ({
            field: [Str],
            include_zero: [Bool, false],
        }));
    })();
},
/* models/expressions/minimum.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const expression_1 = require(335) /* ./expression */;
    const object_1 = require(9) /* ../../core/util/object */;
    const array_1 = require(10) /* ../../core/util/array */;
    class Minimum extends expression_1.ScalarExpression {
        constructor(attrs) {
            super(attrs);
        }
        _compute(source) {
            const column = (0, object_1.dict)(source.data).get(this.field) ?? [];
            return Math.min(this.initial, (0, array_1.min)(column));
        }
    }
    exports.Minimum = Minimum;
    _a = Minimum;
    Minimum.__name__ = "Minimum";
    (() => {
        _a.define(({ Float, Str }) => ({
            field: [Str],
            initial: [Float, Infinity],
        }));
    })();
},
/* models/expressions/maximum.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const expression_1 = require(335) /* ./expression */;
    const object_1 = require(9) /* ../../core/util/object */;
    const array_1 = require(10) /* ../../core/util/array */;
    class Maximum extends expression_1.ScalarExpression {
        constructor(attrs) {
            super(attrs);
        }
        _compute(source) {
            const column = (0, object_1.dict)(source.data).get(this.field) ?? [];
            return Math.max(this.initial, (0, array_1.max)(column));
        }
    }
    exports.Maximum = Maximum;
    _a = Maximum;
    Maximum.__name__ = "Maximum";
    (() => {
        _a.define(({ Float, Str }) => ({
            field: [Str],
            initial: [Float, -Infinity],
        }));
    })();
},
/* models/expressions/coordinate_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const expression_1 = require(335) /* ../expressions/expression */;
    class CoordinateTransform extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
        get x() {
            return new XComponent({ transform: this });
        }
        get y() {
            return new YComponent({ transform: this });
        }
    }
    exports.CoordinateTransform = CoordinateTransform;
    CoordinateTransform.__name__ = "CoordinateTransform";
    class XYComponent extends expression_1.Expression {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.XYComponent = XYComponent;
    _a = XYComponent;
    XYComponent.__name__ = "XYComponent";
    (() => {
        _a.define(({ Ref }) => ({
            transform: [Ref(CoordinateTransform)],
        }));
    })();
    class XComponent extends XYComponent {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            return this.transform.v_compute(source).x;
        }
    }
    exports.XComponent = XComponent;
    XComponent.__name__ = "XComponent";
    class YComponent extends XYComponent {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            return this.transform.v_compute(source).y;
        }
    }
    exports.YComponent = YComponent;
    YComponent.__name__ = "YComponent";
},
/* models/expressions/polar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const coordinate_transform_1 = require(341) /* ../expressions/coordinate_transform */;
    const enums_1 = require(20) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class PolarTransform extends coordinate_transform_1.CoordinateTransform {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            const radius = this.properties.radius.uniform(source);
            const angle = this.properties.angle.uniform(source);
            const coeff = this.direction == "anticlock" ? -1 : 1;
            const n = Math.min(radius.length, angle.length);
            const x = new Float64Array(n);
            const y = new Float64Array(n);
            for (let i = 0; i < n; i++) {
                const radius_i = radius.get(i);
                const angle_i = angle.get(i) * coeff;
                x[i] = radius_i * Math.cos(angle_i);
                y[i] = radius_i * Math.sin(angle_i);
            }
            return { x, y };
        }
    }
    exports.PolarTransform = PolarTransform;
    _a = PolarTransform;
    PolarTransform.__name__ = "PolarTransform";
    (() => {
        _a.define(({}) => ({
            radius: [p.DistanceSpec, { field: "radius" }],
            angle: [p.AngleSpec, { field: "angle" }],
            direction: [enums_1.Direction, "anticlock"],
        }));
    })();
},
/* models/filters/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var boolean_filter_1 = require(344) /* ./boolean_filter */;
    __esExport("BooleanFilter", boolean_filter_1.BooleanFilter);
    var customjs_filter_1 = require(345) /* ./customjs_filter */;
    __esExport("CustomJSFilter", customjs_filter_1.CustomJSFilter);
    var filter_1 = require(238) /* ./filter */;
    __esExport("Filter", filter_1.Filter);
    var group_filter_1 = require(346) /* ./group_filter */;
    __esExport("GroupFilter", group_filter_1.GroupFilter);
    var index_filter_1 = require(347) /* ./index_filter */;
    __esExport("IndexFilter", index_filter_1.IndexFilter);
    var all_indices_1 = require(239) /* ./all_indices */;
    __esExport("AllIndices", all_indices_1.AllIndices);
    var inversion_filter_1 = require(348) /* ./inversion_filter */;
    __esExport("InversionFilter", inversion_filter_1.InversionFilter);
    var intersection_filter_1 = require(240) /* ./intersection_filter */;
    __esExport("IntersectionFilter", intersection_filter_1.IntersectionFilter);
    var union_filter_1 = require(349) /* ./union_filter */;
    __esExport("UnionFilter", union_filter_1.UnionFilter);
    var difference_filter_1 = require(350) /* ./difference_filter */;
    __esExport("DifferenceFilter", difference_filter_1.DifferenceFilter);
    var symmetric_difference_filter_1 = require(351) /* ./symmetric_difference_filter */;
    __esExport("SymmetricDifferenceFilter", symmetric_difference_filter_1.SymmetricDifferenceFilter);
},
/* models/filters/boolean_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(238) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    class BooleanFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            const size = source.get_length() ?? 1;
            const { booleans } = this;
            if (booleans == null) {
                return types_1.Indices.all_set(size);
            }
            else {
                return types_1.Indices.from_booleans(size, booleans);
            }
        }
    }
    exports.BooleanFilter = BooleanFilter;
    _a = BooleanFilter;
    BooleanFilter.__name__ = "BooleanFilter";
    (() => {
        _a.define(({ Bool, Iterable, Nullable }) => ({
            booleans: [Nullable(Iterable(Bool)), null],
        }));
    })();
},
/* models/filters/customjs_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(238) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    const object_1 = require(9) /* ../../core/util/object */;
    const types_2 = require(8) /* ../../core/util/types */;
    const string_1 = require(40) /* ../../core/util/string */;
    class CustomJSFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        get func() {
            const code = (0, string_1.use_strict)(this.code);
            return new Function(...this.names, "source", code);
        }
        compute_indices(source) {
            const size = source.get_length() ?? 1;
            const filter = this.func(...this.values, source);
            if (filter == null) {
                return types_1.Indices.all_set(size);
            }
            else if ((0, types_2.isArrayOf)(filter, types_2.isInteger)) {
                return types_1.Indices.from_indices(size, filter);
            }
            else if ((0, types_2.isArrayOf)(filter, types_2.isBoolean)) {
                return types_1.Indices.from_booleans(size, filter);
            }
            else {
                throw new Error(`expect an array of integers or booleans, or null, got ${filter}`);
            }
        }
    }
    exports.CustomJSFilter = CustomJSFilter;
    _a = CustomJSFilter;
    CustomJSFilter.__name__ = "CustomJSFilter";
    (() => {
        _a.define(({ Unknown, Str, Dict }) => ({
            args: [Dict(Unknown), {}],
            code: [Str, ""],
        }));
    })();
},
/* models/filters/group_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(238) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    const logging_1 = require(19) /* ../../core/logging */;
    const eq_1 = require(26) /* ../../core/util/eq */;
    class GroupFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            const column = source.get_column(this.column_name);
            const size = source.get_length() ?? 1;
            if (column == null) {
                logging_1.logger.warn(`${this}: groupby column '${this.column_name}' not found in the data source`);
                return types_1.Indices.all_set(size);
            }
            else {
                const indices = new types_1.Indices(size, 0);
                const cmp = new eq_1.Comparator();
                for (let i = 0; i < indices.size; i++) {
                    if (cmp.eq(column[i], this.group)) {
                        indices.set(i);
                    }
                }
                return indices;
            }
        }
    }
    exports.GroupFilter = GroupFilter;
    _a = GroupFilter;
    GroupFilter.__name__ = "GroupFilter";
    (() => {
        _a.define(({ Str, Unknown }) => ({
            column_name: [Str],
            group: [Unknown],
        }));
    })();
},
/* models/filters/index_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(238) /* ./filter */;
    const types_1 = require(24) /* ../../core/types */;
    class IndexFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        compute_indices(source) {
            const size = source.get_length() ?? 1;
            const { indices } = this;
            if (indices == null) {
                return types_1.Indices.all_set(size);
            }
            else {
                return types_1.Indices.from_indices(size, indices);
            }
        }
    }
    exports.IndexFilter = IndexFilter;
    _a = IndexFilter;
    IndexFilter.__name__ = "IndexFilter";
    (() => {
        _a.define(({ Int, Iterable, Nullable }) => ({
            indices: [Nullable(Iterable(Int)), null],
        }));
    })();
},
/* models/filters/inversion_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const filter_1 = require(238) /* ./filter */;
    class InversionFilter extends filter_1.Filter {
        constructor(attrs) {
            super(attrs);
        }
        connect_signals() {
            super.connect_signals();
            const emit_changed = () => {
                this.change.emit();
            };
            const connect_operands = (operands) => {
                for (const operand of operands) {
                    this.connect(operand.change, emit_changed);
                }
            };
            const disconnect_operands = (operands) => {
                for (const operand of operands) {
                    this.disconnect(operand.change, emit_changed);
                }
            };
            let operands = (() => {
                const { operand } = this.properties;
                return operand.is_unset ? [] : [operand.get_value()];
            })();
            connect_operands(operands);
            this.on_change(this.properties.operand, () => {
                disconnect_operands(operands);
                operands = [this.operand];
                connect_operands(operands);
            });
        }
        compute_indices(source) {
            const index = this.operand.compute_indices(source);
            index.invert();
            return index;
        }
    }
    exports.InversionFilter = InversionFilter;
    _a = InversionFilter;
    InversionFilter.__name__ = "InversionFilter";
    (() => {
        _a.define(({ Ref }) => ({
            operand: [Ref(filter_1.Filter)],
        }));
    })();
},
/* models/filters/union_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const composite_filter_1 = require(241) /* ./composite_filter */;
    class UnionFilter extends composite_filter_1.CompositeFilter {
        constructor(attrs) {
            super(attrs);
        }
        _inplace_op(index, op) {
            index.add(op);
        }
    }
    exports.UnionFilter = UnionFilter;
    UnionFilter.__name__ = "UnionFilter";
},
/* models/filters/difference_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const composite_filter_1 = require(241) /* ./composite_filter */;
    class DifferenceFilter extends composite_filter_1.CompositeFilter {
        constructor(attrs) {
            super(attrs);
        }
        _inplace_op(index, op) {
            index.subtract(op);
        }
    }
    exports.DifferenceFilter = DifferenceFilter;
    DifferenceFilter.__name__ = "DifferenceFilter";
},
/* models/filters/symmetric_difference_filter.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const composite_filter_1 = require(241) /* ./composite_filter */;
    class SymmetricDifferenceFilter extends composite_filter_1.CompositeFilter {
        constructor(attrs) {
            super(attrs);
        }
        _inplace_op(index, op) {
            index.symmetric_subtract(op);
        }
    }
    exports.SymmetricDifferenceFilter = SymmetricDifferenceFilter;
    SymmetricDifferenceFilter.__name__ = "SymmetricDifferenceFilter";
},
/* models/glyphs/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var annular_wedge_1 = require(353) /* ./annular_wedge */;
    __esExport("AnnularWedge", annular_wedge_1.AnnularWedge);
    var annulus_1 = require(354) /* ./annulus */;
    __esExport("Annulus", annulus_1.Annulus);
    var arc_1 = require(355) /* ./arc */;
    __esExport("Arc", arc_1.Arc);
    var bezier_1 = require(356) /* ./bezier */;
    __esExport("Bezier", bezier_1.Bezier);
    var block_1 = require(358) /* ./block */;
    __esExport("Block", block_1.Block);
    var circle_1 = require(360) /* ./circle */;
    __esExport("Circle", circle_1.Circle);
    var ellipse_1 = require(362) /* ./ellipse */;
    __esExport("Ellipse", ellipse_1.Ellipse);
    var glyph_1 = require(222) /* ./glyph */;
    __esExport("Glyph", glyph_1.Glyph);
    var harea_1 = require(234) /* ./harea */;
    __esExport("HArea", harea_1.HArea);
    var harea_step_1 = require(231) /* ./harea_step */;
    __esExport("HAreaStep", harea_step_1.HAreaStep);
    var hbar_1 = require(364) /* ./hbar */;
    __esExport("HBar", hbar_1.HBar);
    var hex_tile_1 = require(365) /* ./hex_tile */;
    __esExport("HexTile", hex_tile_1.HexTile);
    var hspan_1 = require(366) /* ./hspan */;
    __esExport("HSpan", hspan_1.HSpan);
    var hstrip_1 = require(367) /* ./hstrip */;
    __esExport("HStrip", hstrip_1.HStrip);
    var image_1 = require(368) /* ./image */;
    __esExport("Image", image_1.Image);
    var image_rgba_1 = require(370) /* ./image_rgba */;
    __esExport("ImageRGBA", image_rgba_1.ImageRGBA);
    var image_stack_1 = require(371) /* ./image_stack */;
    __esExport("ImageStack", image_stack_1.ImageStack);
    var image_url_1 = require(372) /* ./image_url */;
    __esExport("ImageURL", image_url_1.ImageURL);
    var line_1 = require(220) /* ./line */;
    __esExport("Line", line_1.Line);
    var mathml_glyph_1 = require(373) /* ./mathml_glyph */;
    __esExport("MathMLGlyph", mathml_glyph_1.MathMLGlyph);
    var multi_line_1 = require(376) /* ./multi_line */;
    __esExport("MultiLine", multi_line_1.MultiLine);
    var multi_polygons_1 = require(377) /* ./multi_polygons */;
    __esExport("MultiPolygons", multi_polygons_1.MultiPolygons);
    var ngon_1 = require(378) /* ./ngon */;
    __esExport("Ngon", ngon_1.Ngon);
    var patch_1 = require(230) /* ./patch */;
    __esExport("Patch", patch_1.Patch);
    var patches_1 = require(379) /* ./patches */;
    __esExport("Patches", patches_1.Patches);
    var quad_1 = require(380) /* ./quad */;
    __esExport("Quad", quad_1.Quad);
    var quadratic_1 = require(381) /* ./quadratic */;
    __esExport("Quadratic", quadratic_1.Quadratic);
    var ray_1 = require(382) /* ./ray */;
    __esExport("Ray", ray_1.Ray);
    var rect_1 = require(383) /* ./rect */;
    __esExport("Rect", rect_1.Rect);
    var scatter_1 = require(384) /* ./scatter */;
    __esExport("Scatter", scatter_1.Scatter);
    var segment_1 = require(387) /* ./segment */;
    __esExport("Segment", segment_1.Segment);
    var spline_1 = require(388) /* ./spline */;
    __esExport("Spline", spline_1.Spline);
    var step_1 = require(390) /* ./step */;
    __esExport("Step", step_1.Step);
    var tex_glyph_1 = require(391) /* ./tex_glyph */;
    __esExport("TeXGlyph", tex_glyph_1.TeXGlyph);
    var text_1 = require(375) /* ./text */;
    __esExport("Text", text_1.Text);
    var varea_1 = require(236) /* ./varea */;
    __esExport("VArea", varea_1.VArea);
    var varea_step_1 = require(235) /* ./varea_step */;
    __esExport("VAreaStep", varea_step_1.VAreaStep);
    var vbar_1 = require(392) /* ./vbar */;
    __esExport("VBar", vbar_1.VBar);
    var vspan_1 = require(393) /* ./vspan */;
    __esExport("VSpan", vspan_1.VSpan);
    var vstrip_1 = require(394) /* ./vstrip */;
    __esExport("VStrip", vstrip_1.VStrip);
    var wedge_1 = require(395) /* ./wedge */;
    __esExport("Wedge", wedge_1.Wedge);
},
/* models/glyphs/annular_wedge.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const types_1 = require(24) /* ../../core/types */;
    const enums_1 = require(20) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const math_1 = require(11) /* ../../core/util/math */;
    const selection_1 = require(130) /* ../selections/selection */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    class AnnularWedgeView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { AnnularWedgeGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(560) /* ./webgl/annular_wedge */));
            return AnnularWedgeGL;
        }
        _map_data() {
            this._define_or_inherit_attr("sinner_radius", () => {
                if (this.model.properties.inner_radius.units == "data") {
                    if (this.inherited_x && this.inherited_inner_radius) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.inner_radius);
                    }
                }
                else {
                    return this.inherited_inner_radius ? glyph_1.inherit : (0, types_1.to_screen)(this.inner_radius);
                }
            });
            this._define_or_inherit_attr("souter_radius", () => {
                if (this.model.properties.outer_radius.units == "data") {
                    if (this.inherited_x && this.inherited_outer_radius) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.outer_radius);
                    }
                }
                else {
                    return this.inherited_outer_radius ? glyph_1.inherit : (0, types_1.to_screen)(this.outer_radius);
                }
            });
            this._define_or_inherit_attr("max_souter_radius", () => (0, arrayable_1.max)(this.souter_radius));
        }
        _paint(ctx, indices, data) {
            const { sx, sy, start_angle, end_angle, sinner_radius, souter_radius } = { ...this, ...data };
            const anticlock = this.model.direction == "anticlock";
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sinner_radius_i = sinner_radius[i];
                const souter_radius_i = souter_radius[i];
                const start_angle_i = start_angle.get(i);
                const end_angle_i = end_angle.get(i);
                if (!isFinite(sx_i + sy_i + sinner_radius_i + souter_radius_i + start_angle_i + end_angle_i)) {
                    continue;
                }
                const angle_i = end_angle_i - start_angle_i;
                ctx.translate(sx_i, sy_i);
                ctx.rotate(start_angle_i);
                ctx.beginPath();
                ctx.moveTo(souter_radius_i, 0);
                ctx.arc(0, 0, souter_radius_i, 0, angle_i, anticlock);
                ctx.rotate(angle_i);
                ctx.lineTo(sinner_radius_i, 0);
                ctx.arc(0, 0, sinner_radius_i, 0, -angle_i, !anticlock);
                ctx.closePath();
                ctx.rotate(-angle_i - start_angle_i);
                ctx.translate(-sx_i, -sy_i);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            // check radius first
            const sx0 = sx - this.max_souter_radius;
            const sx1 = sx + this.max_souter_radius;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const sy0 = sy - this.max_souter_radius;
            const sy1 = sy + this.max_souter_radius;
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const candidates = [];
            for (const i of this.index.indices({ x0, x1, y0, y1 })) {
                const or2 = this.souter_radius[i] ** 2;
                const ir2 = this.sinner_radius[i] ** 2;
                const [sx0, sx1] = this.renderer.xscale.r_compute(x, this.x[i]);
                const [sy0, sy1] = this.renderer.yscale.r_compute(y, this.y[i]);
                const dist = (sx0 - sx1) ** 2 + (sy0 - sy1) ** 2;
                if (dist <= or2 && dist >= ir2) {
                    candidates.push(i);
                }
            }
            const anticlock = this.model.direction == "anticlock";
            const indices = [];
            for (const i of candidates) {
                // NOTE: minus the angle because JS uses non-mathy convention for angles
                const angle = Math.atan2(sy - this.sy[i], sx - this.sx[i]);
                const is_full_circle = Math.abs(this.start_angle.get(i) - this.end_angle.get(i)) >= 2 * Math.PI;
                if (is_full_circle || (0, math_1.angle_between)(-angle, -this.start_angle.get(i), -this.end_angle.get(i), anticlock)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy(i) {
            const r = (this.sinner_radius[i] + this.souter_radius[i]) / 2;
            const a = (this.start_angle.get(i) + this.end_angle.get(i)) / 2;
            const scx = this.sx[i] + r * Math.cos(a);
            const scy = this.sy[i] + r * Math.sin(a);
            return [scx, scy];
        }
    }
    exports.AnnularWedgeView = AnnularWedgeView;
    AnnularWedgeView.__name__ = "AnnularWedgeView";
    class AnnularWedge extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.AnnularWedge = AnnularWedge;
    _a = AnnularWedge;
    AnnularWedge.__name__ = "AnnularWedge";
    (() => {
        _a.prototype.default_view = AnnularWedgeView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(({}) => ({
            direction: [enums_1.Direction, "anticlock"],
            inner_radius: [p.DistanceSpec, { field: "inner_radius" }],
            outer_radius: [p.DistanceSpec, { field: "outer_radius" }],
            start_angle: [p.AngleSpec, { field: "start_angle" }],
            end_angle: [p.AngleSpec, { field: "end_angle" }],
        }));
    })();
},
/* models/glyphs/annulus.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const glyph_1 = require(222) /* ./glyph */;
    const types_1 = require(24) /* ../../core/types */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(130) /* ../selections/selection */;
    class AnnulusView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { AnnulusGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(567) /* ./webgl/annulus */));
            return AnnulusGL;
        }
        _map_data() {
            this._define_or_inherit_attr("sinner_radius", () => {
                if (this.model.properties.inner_radius.units == "data") {
                    if (this.inherited_x && this.inherited_inner_radius) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.inner_radius);
                    }
                }
                else {
                    return this.inherited_inner_radius ? glyph_1.inherit : (0, types_1.to_screen)(this.inner_radius);
                }
            });
            this._define_or_inherit_attr("souter_radius", () => {
                if (this.model.properties.outer_radius.units == "data") {
                    if (this.inherited_x && this.inherited_outer_radius) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.outer_radius);
                    }
                }
                else {
                    return this.inherited_outer_radius ? glyph_1.inherit : (0, types_1.to_screen)(this.outer_radius);
                }
            });
        }
        _paint(ctx, indices, data) {
            const { sx, sy, sinner_radius, souter_radius } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sinner_radius_i = sinner_radius[i];
                const souter_radius_i = souter_radius[i];
                if (!isFinite(sx_i + sy_i + sinner_radius_i + souter_radius_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.arc(sx_i, sy_i, sinner_radius_i, 0, 2 * Math.PI, true);
                ctx.moveTo(sx_i + souter_radius_i, sy_i);
                ctx.arc(sx_i, sy_i, souter_radius_i, 2 * Math.PI, 0, false);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            let x0, y0;
            let x1, y1;
            if (this.model.properties.outer_radius.units == "data") {
                x0 = x - this.max_outer_radius;
                x1 = x + this.max_outer_radius;
                y0 = y - this.max_outer_radius;
                y1 = y + this.max_outer_radius;
            }
            else {
                const sx0 = sx - this.max_outer_radius;
                const sx1 = sx + this.max_outer_radius;
                [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                const sy0 = sy - this.max_outer_radius;
                const sy1 = sy + this.max_outer_radius;
                [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            }
            const indices = [];
            for (const i of this.index.indices({ x0, x1, y0, y1 })) {
                const or2 = this.souter_radius[i] ** 2;
                const ir2 = this.sinner_radius[i] ** 2;
                const [sx0, sx1] = this.renderer.xscale.r_compute(x, this.x[i]);
                const [sy0, sy1] = this.renderer.yscale.r_compute(y, this.y[i]);
                const dist = (sx0 - sx1) ** 2 + (sy0 - sy1) ** 2;
                if (dist <= or2 && dist >= ir2) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, { x0, y0, x1, y1 }, index) {
            const len = index + 1;
            const sx = new Array(len);
            sx[index] = (x0 + x1) / 2;
            const sy = new Array(len);
            sy[index] = (y0 + y1) / 2;
            const r = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.5;
            const sinner_radius = new Array(len);
            sinner_radius[index] = r * 0.4;
            const souter_radius = new Array(len);
            souter_radius[index] = r * 0.8;
            this._paint(ctx, [index], { sx, sy, sinner_radius, souter_radius });
        }
    }
    exports.AnnulusView = AnnulusView;
    AnnulusView.__name__ = "AnnulusView";
    class Annulus extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Annulus = Annulus;
    _a = Annulus;
    Annulus.__name__ = "Annulus";
    (() => {
        _a.prototype.default_view = AnnulusView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(({}) => ({
            inner_radius: [p.DistanceSpec, { field: "inner_radius" }],
            outer_radius: [p.DistanceSpec, { field: "outer_radius" }],
        }));
    })();
},
/* models/glyphs/arc.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const property_mixins_1 = require(80) /* ../../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() {
            this._define_or_inherit_attr("sradius", () => {
                if (this.model.properties.radius.units == "data") {
                    if (this.inherited_x && this.inherited_radius) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.radius);
                    }
                }
                else {
                    return this.inherited_radius ? glyph_1.inherit : (0, types_1.to_screen)(this.radius);
                }
            });
        }
        _paint(ctx, indices, data) {
            if (!this.visuals.line.doit) {
                return;
            }
            const { sx, sy, sradius, start_angle, end_angle } = { ...this, ...data };
            const anticlock = this.model.direction == "anticlock";
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sradius_i = sradius[i];
                const start_angle_i = start_angle.get(i);
                const end_angle_i = end_angle.get(i);
                if (!isFinite(sx_i + sy_i + sradius_i + start_angle_i + end_angle_i)) {
                    continue;
                }
                this._render_decorations(ctx, i, sx_i, sy_i, sradius_i, start_angle_i, end_angle_i, anticlock);
                ctx.beginPath();
                ctx.arc(sx_i, sy_i, sradius_i, start_angle_i, end_angle_i, anticlock);
                this.visuals.line.apply(ctx, i);
            }
        }
        _render_decorations(ctx, i, sx, sy, sradius, start_angle, end_angle, _anticlock) {
            const { sin, cos, PI } = Math;
            for (const decoration of this.decorations.values()) {
                ctx.save();
                if (decoration.model.node == "start") {
                    const x = sradius * cos(start_angle) + sx;
                    const y = sradius * sin(start_angle) + sy;
                    ctx.translate(x, y);
                    ctx.rotate(start_angle + PI);
                }
                else if (decoration.model.node == "end") {
                    const x = sradius * Math.cos(end_angle) + sx;
                    const y = sradius * Math.sin(end_angle) + sy;
                    ctx.translate(x, y);
                    ctx.rotate(end_angle);
                }
                decoration.marking.paint(ctx, i);
                ctx.restore();
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.ArcView = ArcView;
    ArcView.__name__ = "ArcView";
    class Arc extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Arc = Arc;
    _a = Arc;
    Arc.__name__ = "Arc";
    (() => {
        _a.prototype.default_view = ArcView;
        _a.mixins(property_mixins_1.LineVector);
        _a.define(({}) => ({
            direction: [enums_1.Direction, "anticlock"],
            radius: [p.DistanceSpec, { field: "radius" }],
            start_angle: [p.AngleSpec, { field: "start_angle" }],
            end_angle: [p.AngleSpec, { field: "end_angle" }],
        }));
    })();
},
/* models/glyphs/bezier.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const algorithms_1 = require(357) /* ../../core/util/algorithms */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class BezierView extends glyph_1.GlyphView {
        _project_data() {
            this._project_xy("x0", this.x0, "y0", this.y0);
            this._project_xy("x1", this.x1, "y1", this.y1);
        }
        _index_data(index) {
            const { data_size, x0, y0, x1, y1, cx0, cy0, cx1, cy1 } = this;
            for (let i = 0; i < data_size; i++) {
                const x0_i = x0[i];
                const y0_i = y0[i];
                const x1_i = x1[i];
                const y1_i = y1[i];
                const cx0_i = cx0[i];
                const cy0_i = cy0[i];
                const cx1_i = cx1[i];
                const cy1_i = cy1[i];
                if (!isFinite(x0_i + x1_i + y0_i + y1_i + cx0_i + cy0_i + cx1_i + cy1_i)) {
                    index.add_empty();
                }
                else {
                    const { x0, y0, x1, y1 } = (0, algorithms_1.cbb)(x0_i, y0_i, cx0_i, cy0_i, cx1_i, cy1_i, x1_i, y1_i);
                    index.add_rect(x0, y0, x1, y1);
                }
            }
        }
        _paint(ctx, indices, data) {
            if (!this.visuals.line.doit) {
                return;
            }
            const { sx0, sy0, sx1, sy1, scx0, scy0, scx1, scy1 } = { ...this, ...data };
            for (const i of indices) {
                const sx0_i = sx0[i];
                const sy0_i = sy0[i];
                const sx1_i = sx1[i];
                const sy1_i = sy1[i];
                const scx0_i = scx0[i];
                const scy0_i = scy0[i];
                const scx1_i = scx1[i];
                const scy1_i = scy1[i];
                if (!isFinite(sx0_i + sy0_i + sx1_i + sy1_i + scx0_i + scy0_i + scx1_i + scy1_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.moveTo(sx0_i, sy0_i);
                ctx.bezierCurveTo(scx0_i, scy0_i, scx1_i, scy1_i, sx1_i, sy1_i);
                this.visuals.line.apply(ctx, i);
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy() {
            throw new Error(`${this}.scenterxy() is not implemented`);
        }
    }
    exports.BezierView = BezierView;
    BezierView.__name__ = "BezierView";
    class Bezier extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Bezier = Bezier;
    _a = Bezier;
    Bezier.__name__ = "Bezier";
    (() => {
        _a.prototype.default_view = BezierView;
        _a.define(({}) => ({
            x0: [p.XCoordinateSpec, { field: "x0" }],
            y0: [p.YCoordinateSpec, { field: "y0" }],
            x1: [p.XCoordinateSpec, { field: "x1" }],
            y1: [p.YCoordinateSpec, { field: "y1" }],
            cx0: [p.XCoordinateSpec, { field: "cx0" }],
            cy0: [p.YCoordinateSpec, { field: "cy0" }],
            cx1: [p.XCoordinateSpec, { field: "cx1" }],
            cy1: [p.YCoordinateSpec, { field: "cy1" }],
        }));
        _a.mixins(property_mixins_1.LineVector);
    })();
},
/* core/util/algorithms.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.qbb = qbb;
    exports.cbb = cbb;
    const arrayable_1 = require(13) /* ./arrayable */;
    const { abs, sqrt, min, max } = Math;
    /**
     * Formula from: http://pomax.nihongoresources.com/pages/bezier/
     *
     * if segment is quadratic bezier do:
     *   for both directions do:
     *     if control between start and end, compute linear bounding box
     *     otherwise, compute
     *       bound = u(1-t)^2 + 2v(1-t)t + wt^2
     *         (with t = ((u-v) / (u-2v+w)), with {u = start, v = control, w = end})
     *       if control precedes start, min = bound, otherwise max = bound
     */
    function qbb(x0, y0, cx, cy, x1, y1) {
        function _qbb(u, v, w) {
            if (v == (u + w) / 2) {
                return [u, w];
            }
            else {
                const t = (u - v) / (u - 2 * v + w);
                const bd = u * (1 - t) ** 2 + 2 * v * (1 - t) * t + w * t ** 2;
                return [min(u, w, bd), max(u, w, bd)];
            }
        }
        const [x_min, x_max] = _qbb(x0, cx, x1);
        const [y_min, y_max] = _qbb(y0, cy, y1);
        return {
            x0: x_min, x1: x_max,
            y0: y_min, y1: y_max,
        };
    }
    // algorithm adapted from http://stackoverflow.com/a/14429749/3406693
    function cbb(x0, y0, cx0, cy0, cx1, cy1, x1, y1) {
        const x3 = x1;
        const y3 = y1;
        x1 = cx0;
        y1 = cy0;
        const x2 = cx1;
        const y2 = cy1;
        const tvalues = [];
        for (let i = 0; i <= 2; i++) {
            let a, b, c;
            if (i == 0) {
                b = 6 * x0 - 12 * x1 + 6 * x2;
                a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
                c = 3 * x1 - 3 * x0;
            }
            else {
                b = 6 * y0 - 12 * y1 + 6 * y2;
                a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
                c = 3 * y1 - 3 * y0;
            }
            // Numerical robustness
            if (abs(a) < 1e-12) {
                if (abs(b) < 1e-12) {
                    continue;
                }
                const t = -c / b;
                if (0 < t && t < 1) {
                    tvalues.push(t);
                }
                continue;
            }
            const b2ac = b ** 2 - 4 * c * a;
            const sqrtb2ac = sqrt(b2ac);
            if (b2ac < 0) {
                continue;
            }
            const t1 = (-b + sqrtb2ac) / (2 * a);
            if (0 < t1 && t1 < 1) {
                tvalues.push(t1);
            }
            const t2 = (-b - sqrtb2ac) / (2 * a);
            if (0 < t2 && t2 < 1) {
                tvalues.push(t2);
            }
        }
        const n = tvalues.length;
        let j = n;
        const x_bounds = Array(n + 2);
        const y_bounds = Array(n + 2);
        while (j-- > 0) {
            const t = tvalues[j];
            const mt = 1 - t;
            const x = mt ** 3 * x0 + 3 * mt ** 2 * t * x1 + 3 * mt * t ** 2 * x2 + t ** 3 * x3;
            const y = mt ** 3 * y0 + 3 * mt ** 2 * t * y1 + 3 * mt * t ** 2 * y2 + t ** 3 * y3;
            x_bounds[j] = x;
            y_bounds[j] = y;
        }
        x_bounds[n] = x0;
        y_bounds[n] = y0;
        x_bounds[n + 1] = x3;
        y_bounds[n + 1] = y3;
        const [x_min, x_max, y_min, y_max] = (0, arrayable_1.minmax2)(x_bounds, y_bounds);
        return { x0: x_min, x1: x_max, y0: y_min, y1: y_max };
    }
},
/* models/glyphs/block.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const lrtb_1 = require(359) /* ./lrtb */;
    const math_1 = require(11) /* ../../core/util/math */;
    const types_1 = require(24) /* ../../core/types */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class BlockView extends lrtb_1.LRTBView {
        scenterxy(i) {
            const scx = this.sleft[i] / 2 + this.sright[i] / 2;
            const scy = this.stop[i] / 2 + this.sbottom[i] / 2;
            return [scx, scy];
        }
        _lrtb(i) {
            const x_i = this.x[i];
            const y_i = this.y[i];
            const width_i = this.width.get(i);
            const height_i = this.height.get(i);
            const [l, r] = (0, math_1.minmax)(x_i, x_i + width_i);
            const [b, t] = (0, math_1.minmax)(y_i, y_i + height_i);
            return { l, r, t, b };
        }
        _map_data() {
            const { sx, sy } = this;
            const n = sx.length;
            if (this.inherited_x && this.inherited_width) {
                this._inherit_attr("sleft");
                this._inherit_attr("sright");
            }
            else {
                const sw = this.sdist(this.renderer.xscale, this.x, this.width, "edge");
                const sleft = new types_1.ScreenArray(n);
                const sright = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    sleft[i] = sx[i];
                    sright[i] = sx[i] + sw[i];
                }
                this._define_attr("sleft", sleft);
                this._define_attr("sright", sright);
            }
            if (this.inherited_y && this.inherited_height) {
                this._inherit_attr("stop");
                this._inherit_attr("sbottom");
            }
            else {
                const sh = this.sdist(this.renderer.yscale, this.y, this.height, "edge");
                const stop = new types_1.ScreenArray(n);
                const sbottom = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    stop[i] = sy[i] - sh[i];
                    sbottom[i] = sy[i];
                }
                this._define_attr("stop", stop);
                this._define_attr("sbottom", sbottom);
            }
            this._clamp_to_viewport();
        }
    }
    exports.BlockView = BlockView;
    BlockView.__name__ = "BlockView";
    class Block extends lrtb_1.LRTB {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Block = Block;
    _a = Block;
    Block.__name__ = "Block";
    (() => {
        _a.prototype.default_view = BlockView;
        _a.define(({}) => ({
            x: [p.XCoordinateSpec, { field: "x" }],
            y: [p.YCoordinateSpec, { field: "y" }],
            width: [p.DistanceSpec, { value: 1 }],
            height: [p.DistanceSpec, { value: 1 }],
        }));
    })();
},
/* models/glyphs/lrtb.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const selection_1 = require(130) /* ../selections/selection */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const kinds_1 = require(185) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(186) /* ../common/resolve */);
    const painting_1 = require(187) /* ../common/painting */;
    class LRTBView extends glyph_1.GlyphView {
        async load_glglyph() {
            const { LRTBGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(575) /* ./webgl/lrtb */));
            return LRTBGL;
        }
        get_anchor_point(anchor, i, _spt) {
            const left = Math.min(this.sleft[i], this.sright[i]);
            const right = Math.max(this.sright[i], this.sleft[i]);
            const top = Math.min(this.stop[i], this.sbottom[i]); // screen coordinates !!!
            const bottom = Math.max(this.sbottom[i], this.stop[i]); //
            switch (anchor) {
                case "top_left": return { x: left, y: top };
                case "top":
                case "top_center": return { x: (left + right) / 2, y: top };
                case "top_right": return { x: right, y: top };
                case "bottom_left": return { x: left, y: bottom };
                case "bottom":
                case "bottom_center": return { x: (left + right) / 2, y: bottom };
                case "bottom_right": return { x: right, y: bottom };
                case "left":
                case "center_left": return { x: left, y: (top + bottom) / 2 };
                case "center":
                case "center_center": return { x: (left + right) / 2, y: (top + bottom) / 2 };
                case "right":
                case "center_right": return { x: right, y: (top + bottom) / 2 };
            }
        }
        _set_data(indices) {
            super._set_data(indices);
            this.border_radius = resolve.border_radius(this.model.border_radius);
        }
        _index_data(index) {
            const { min, max } = Math;
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const { l, r, t, b } = this._lrtb(i);
                index.add_rect(min(l, r), min(t, b), max(r, l), max(t, b));
            }
        }
        _paint(ctx, indices, data) {
            const { sleft, sright, stop, sbottom, border_radius } = { ...this, ...data };
            for (const i of indices) {
                const sleft_i = sleft[i];
                const stop_i = stop[i];
                const sright_i = sright[i];
                const sbottom_i = sbottom[i];
                if (!isFinite(sleft_i + stop_i + sright_i + sbottom_i)) {
                    continue;
                }
                ctx.beginPath();
                const box = bbox_1.BBox.from_lrtb({ left: sleft_i, right: sright_i, top: stop_i, bottom: sbottom_i });
                (0, painting_1.round_rect)(ctx, box, border_radius);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        // We need to clamp the endpoints inside the viewport, because various browser canvas
        // implementations have issues drawing rects with enpoints far outside the viewport
        _clamp_to_viewport() {
            const { min, max } = Math;
            const { h_range, v_range } = this.renderer.plot_view.frame.bbox;
            if (!this.inherited_sleft) {
                (0, arrayable_1.inplace_map)(this.sleft, (left) => max(left, h_range.start));
            }
            if (!this.inherited_sright) {
                (0, arrayable_1.inplace_map)(this.sright, (right) => min(right, h_range.end));
            }
            if (!this.inherited_stop) {
                (0, arrayable_1.inplace_map)(this.stop, (top) => max(top, v_range.start));
            }
            if (!this.inherited_sbottom) {
                (0, arrayable_1.inplace_map)(this.sbottom, (bottom) => min(bottom, v_range.end));
            }
        }
        _hit_rect(geometry) {
            return this._hit_rect_against_index(geometry);
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const indices = [...this.index.indices({ x0: x, y0: y, x1: x, y1: y })];
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            let indices;
            if (geometry.direction == "v") {
                const y = this.renderer.yscale.invert(sy);
                const hr = this.renderer.plot_view.frame.bbox.h_range;
                const [x0, x1] = this.renderer.xscale.r_invert(hr.start, hr.end);
                indices = [...this.index.indices({ x0, y0: y, x1, y1: y })];
            }
            else {
                const x = this.renderer.xscale.invert(sx);
                const vr = this.renderer.plot_view.frame.bbox.v_range;
                const [y0, y1] = this.renderer.yscale.r_invert(vr.start, vr.end);
                indices = [...this.index.indices({ x0: x, y0, x1: x, y1 })];
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.LRTBView = LRTBView;
    LRTBView.__name__ = "LRTBView";
    class LRTB extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LRTB = LRTB;
    _a = LRTB;
    LRTB.__name__ = "LRTB";
    (() => {
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(() => ({
            border_radius: [kinds_1.BorderRadius, 0],
        }));
    })();
},
/* models/glyphs/circle.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const radial_glyph_1 = require(361) /* ./radial_glyph */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const selection_1 = require(130) /* ../selections/selection */;
    class CircleView extends radial_glyph_1.RadialGlyphView {
        async load_glglyph() {
            const { CircleGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(569) /* ./webgl/circle */));
            return CircleGL;
        }
        _paint(ctx, indices, data) {
            const { sx, sy, sradius } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sradius_i = sradius[i];
                if (!isFinite(sx_i + sy_i + sradius_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.arc(sx_i, sy_i, sradius_i, 0, 2 * Math.PI, false);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const { hit_dilation } = this.model;
            const [x0, x1, y0, y1] = (() => {
                if (this.model.properties.radius.units == "data") {
                    const dr = this.max_radius * hit_dilation;
                    const x0 = x - dr;
                    const x1 = x + dr;
                    const y0 = y - dr;
                    const y1 = y + dr;
                    return [x0, x1, y0, y1];
                }
                else {
                    const ds = this.max_radius * hit_dilation;
                    const sx0 = sx - ds;
                    const sx1 = sx + ds;
                    const sy0 = sy - ds;
                    const sy1 = sy + ds;
                    const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                    const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
                    return [x0, x1, y0, y1];
                }
            })();
            const candidates = this.index.indices({ x0, x1, y0, y1 });
            const indices = [];
            if (this.model.properties.radius.units == "data") {
                for (const i of candidates) {
                    const r2 = (this.sradius[i] * hit_dilation) ** 2;
                    const [sx0, sx1] = this.renderer.xscale.r_compute(x, this.x[i]);
                    const [sy0, sy1] = this.renderer.yscale.r_compute(y, this.y[i]);
                    const dist = (sx0 - sx1) ** 2 + (sy0 - sy1) ** 2;
                    if (dist <= r2) {
                        indices.push(i);
                    }
                }
            }
            else {
                for (const i of candidates) {
                    const r2 = (this.sradius[i] * hit_dilation) ** 2;
                    const dist = (this.sx[i] - sx) ** 2 + (this.sy[i] - sy) ** 2;
                    if (dist <= r2) {
                        indices.push(i);
                    }
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            const bounds = this.bounds();
            const [x0, x1, y0, y1] = (() => {
                const dr = this.max_radius;
                if (geometry.direction == "h") {
                    // use circle bounds instead of current pointer y coordinates
                    const sx0 = sx - dr;
                    const sx1 = sx + dr;
                    const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                    const { y0, y1 } = bounds;
                    return [x0, x1, y0, y1];
                }
                else {
                    // use circle bounds instead of current pointer x coordinates
                    const sy0 = sy - dr;
                    const sy1 = sy + dr;
                    const { x0, x1 } = bounds;
                    const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
                    return [x0, x1, y0, y1];
                }
            })();
            const indices = [...this.index.indices({ x0, x1, y0, y1 })];
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const candidates = this.index.indices({ x0, x1, y0, y1 });
            const indices = [];
            for (const i of candidates) {
                const sx_i = this.sx[i];
                const sy_i = this.sy[i];
                if (sx0 <= sx_i && sx_i <= sx1 && sy0 <= sy_i && sy_i <= sy1) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_poly(geometry) {
            const { sx: sxs, sy: sys } = geometry;
            const candidates = (() => {
                const [sx0, sx1, sy0, sy1] = (0, arrayable_1.minmax2)(sxs, sys);
                const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const i of candidates) {
                if (hittest.point_in_poly(this.sx[i], this.sy[i], sxs, sys)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
    }
    exports.CircleView = CircleView;
    CircleView.__name__ = "CircleView";
    class Circle extends radial_glyph_1.RadialGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Circle = Circle;
    _a = Circle;
    Circle.__name__ = "Circle";
    (() => {
        _a.prototype.default_view = CircleView;
        _a.define(({ Float }) => ({
            hit_dilation: [Float, 1.0],
        }));
    })();
},
/* models/glyphs/radial_glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const glyph_1 = require(222) /* ./glyph */;
    const property_mixins_1 = require(80) /* ../../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 array_1 = require(10) /* ../../core/util/array */;
    class RadialGlyphView extends xy_glyph_1.XYGlyphView {
        _index_data(index) {
            const { x, y, radius, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x_i = x[i];
                const y_i = y[i];
                const r_i = radius.get(i);
                index.add_rect(x_i - r_i, y_i - r_i, x_i + r_i, y_i + r_i);
            }
        }
        _map_data() {
            this._define_or_inherit_attr("sradius", () => {
                if (this.model.properties.radius.units == "data") {
                    const sradius_x = () => this.sdist(this.renderer.xscale, this.x, this.radius);
                    const sradius_y = () => this.sdist(this.renderer.yscale, this.y, this.radius);
                    const { radius_dimension } = this.model;
                    switch (radius_dimension) {
                        case "x": {
                            return this.inherited_x && this.inherited_radius ? glyph_1.inherit : sradius_x();
                        }
                        case "y": {
                            return this.inherited_y && this.inherited_radius ? glyph_1.inherit : sradius_y();
                        }
                        case "min":
                        case "max": {
                            if (this.inherited_x && this.inherited_y && this.inherited_radius) {
                                return glyph_1.inherit;
                            }
                            else {
                                return (0, array_1.elementwise)(sradius_x(), sradius_y(), Math[radius_dimension]);
                            }
                        }
                    }
                }
                else {
                    return this.inherited_sradius ? glyph_1.inherit : (0, types_1.to_screen)(this.radius);
                }
            });
        }
        _mask_data() {
            const { frame } = this.renderer.plot_view;
            const shr = frame.x_target;
            const svr = frame.y_target;
            let hr;
            let vr;
            if (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_radius).map((x) => this.renderer.xscale.invert(x));
                vr = svr.widen(this.max_radius).map((y) => this.renderer.yscale.invert(y));
            }
            return this.index.indices({
                x0: hr.start, x1: hr.end,
                y0: vr.start, y1: vr.end,
            });
        }
        draw_legend_for_index(ctx, { x0, y0, x1, y1 }, index) {
            // using objects like this is wonky, since the keys are coerced to strings, 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._paint(ctx, [index], { sx, sy, sradius });
        }
    }
    exports.RadialGlyphView = RadialGlyphView;
    RadialGlyphView.__name__ = "RadialGlyphView";
    class RadialGlyph extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.RadialGlyph = RadialGlyph;
    _a = RadialGlyph;
    RadialGlyph.__name__ = "RadialGlyph";
    (() => {
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(() => ({
            radius: [p.DistanceSpec, { field: "radius" }],
            radius_dimension: [enums_1.RadiusDimension, "x"],
        }));
    })();
},
/* models/glyphs/ellipse.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const center_rotatable_1 = require(363) /* ./center_rotatable */;
    const glyph_1 = require(222) /* ./glyph */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const types_1 = require(24) /* ../../core/types */;
    const selection_1 = require(130) /* ../selections/selection */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class EllipseView extends center_rotatable_1.CenterRotatableView {
        _map_data() {
            this._define_or_inherit_attr("swidth", () => {
                if (this.model.properties.width.units == "data") {
                    if (this.inherited_x && this.inherited_width) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.width, "center");
                    }
                }
                else {
                    return this.inherited_width ? glyph_1.inherit : (0, types_1.to_screen)(this.width);
                }
            });
            this._define_or_inherit_attr("sheight", () => {
                if (this.model.properties.height.units == "data") {
                    if (this.inherited_y && this.inherited_height) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.yscale, this.y, this.height, "center");
                    }
                }
                else {
                    return this.inherited_height ? glyph_1.inherit : (0, types_1.to_screen)(this.height);
                }
            });
        }
        _paint(ctx, indices, data) {
            const { sx, sy, swidth, sheight, angle } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const swidth_i = swidth[i];
                const sheight_i = sheight[i];
                const angle_i = angle.get(i);
                if (!isFinite(sx_i + sy_i + swidth_i + sheight_i + angle_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.ellipse(sx_i, sy_i, swidth_i / 2, sheight_i / 2, angle_i, 0, 2 * Math.PI);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_point(geometry) {
            let x0, x1, y0, y1, cond, sx0, sx1, sy0, sy1;
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            if (this.model.properties.width.units == "data") {
                x0 = x - this.max_width;
                x1 = x + this.max_width;
            }
            else {
                sx0 = sx - this.max_width;
                sx1 = sx + this.max_width;
                [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            }
            if (this.model.properties.height.units == "data") {
                y0 = y - this.max_height;
                y1 = y + this.max_height;
            }
            else {
                sy0 = sy - this.max_height;
                sy1 = sy + this.max_height;
                [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            }
            const candidates = this.index.indices({ x0, x1, y0, y1 });
            const indices = [];
            for (const i of candidates) {
                cond = hittest.point_in_ellipse(sx, sy, this.angle.get(i), this.sheight[i] / 2, this.swidth[i] / 2, this.sx[i], this.sy[i]);
                if (cond) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, { x0, y0, x1, y1 }, index) {
            const n = index + 1;
            const sx = new Array(n);
            sx[index] = (x0 + x1) / 2;
            const sy = new Array(n);
            sy[index] = (y0 + y1) / 2;
            const scale = this.swidth[index] / this.sheight[index];
            const d = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.8;
            const swidth = new Array(n);
            const sheight = new Array(n);
            if (scale > 1) {
                swidth[index] = d;
                sheight[index] = d / scale;
            }
            else {
                swidth[index] = d * scale;
                sheight[index] = d;
            }
            const angle = new p.UniformScalar(0, n); // don't attempt to match glyph angle
            this._paint(ctx, [index], { sx, sy, swidth, sheight, angle });
        }
    }
    exports.EllipseView = EllipseView;
    EllipseView.__name__ = "EllipseView";
    class Ellipse extends center_rotatable_1.CenterRotatable {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Ellipse = Ellipse;
    _a = Ellipse;
    Ellipse.__name__ = "Ellipse";
    (() => {
        _a.prototype.default_view = EllipseView;
    })();
},
/* models/glyphs/center_rotatable.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class CenterRotatableView extends xy_glyph_1.XYGlyphView {
        get max_w2() {
            return this.model.properties.width.units == "data" ? this.max_width / 2 : 0;
        }
        get max_h2() {
            return this.model.properties.height.units == "data" ? this.max_height / 2 : 0;
        }
        _bounds({ x0, x1, y0, y1 }) {
            const { max_w2, max_h2 } = this;
            return {
                x0: x0 - max_w2,
                x1: x1 + max_w2,
                y0: y0 - max_h2,
                y1: y1 + max_h2,
            };
        }
    }
    exports.CenterRotatableView = CenterRotatableView;
    CenterRotatableView.__name__ = "CenterRotatableView";
    class CenterRotatable extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.CenterRotatable = CenterRotatable;
    _a = CenterRotatable;
    CenterRotatable.__name__ = "CenterRotatable";
    (() => {
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(({}) => ({
            angle: [p.AngleSpec, 0],
            width: [p.DistanceSpec, { field: "width" }],
            height: [p.DistanceSpec, { field: "height" }],
        }));
    })();
},
/* models/glyphs/hbar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const lrtb_1 = require(359) /* ./lrtb */;
    const types_1 = require(24) /* ../../core/types */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class HBarView extends lrtb_1.LRTBView {
        scenterxy(i) {
            const scx = (this.sleft[i] + this.sright[i]) / 2;
            const scy = this.sy[i];
            return [scx, scy];
        }
        _lrtb(i) {
            const left_i = this.left[i];
            const right_i = this.right[i];
            const y_i = this.y[i];
            const half_height_i = this.height.get(i) / 2;
            const l = Math.min(left_i, right_i);
            const r = Math.max(left_i, right_i);
            const t = y_i + half_height_i;
            const b = y_i - half_height_i;
            return { l, r, t, b };
        }
        _map_data() {
            if (this.inherited_y && this.inherited_height) {
                this._inherit_attr("sheight");
                this._inherit_attr("stop");
                this._inherit_attr("sbottom");
            }
            else {
                const sheight = this.sdist(this.renderer.yscale, this.y, this.height, "center");
                const { sy } = this;
                const n = this.sy.length;
                const stop = new types_1.ScreenArray(n);
                const sbottom = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    const sy_i = sy[i];
                    const sheight_i = sheight[i];
                    stop[i] = sy_i - sheight_i / 2;
                    sbottom[i] = sy_i + sheight_i / 2;
                }
                this._define_attr("sheight", sheight);
                this._define_attr("stop", stop);
                this._define_attr("sbottom", sbottom);
            }
            this._clamp_to_viewport();
        }
    }
    exports.HBarView = HBarView;
    HBarView.__name__ = "HBarView";
    class HBar extends lrtb_1.LRTB {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HBar = HBar;
    _a = HBar;
    HBar.__name__ = "HBar";
    (() => {
        _a.prototype.default_view = HBarView;
        _a.define(({}) => ({
            left: [p.XCoordinateSpec, { value: 0 }],
            y: [p.YCoordinateSpec, { field: "y" }],
            height: [p.DistanceSpec, { value: 1 }],
            right: [p.XCoordinateSpec, { field: "right" }],
        }));
    })();
},
/* models/glyphs/hex_tile.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(222) /* ./glyph */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const enums_1 = require(20) /* ../../core/enums */;
    const utils_1 = require(228) /* ./utils */;
    const selection_1 = require(130) /* ../selections/selection */;
    class HexTileView extends glyph_1.GlyphView {
        async load_glglyph() {
            const { HexTileGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(571) /* ./webgl/hex_tile */));
            return HexTileGL;
        }
        scenterxy(i) {
            const scx = this.sx[i];
            const scy = this.sy[i];
            return [scx, scy];
        }
        _set_data() {
            const { orientation, size, aspect_scale } = this.model;
            const { q, r } = this;
            const n = this.q.length;
            const x = new Float64Array(n);
            const y = new Float64Array(n);
            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;
                }
            }
            this._define_attr("x", x);
            this._define_attr("y", y);
        }
        _project_data() {
            this._project_xy("x", this.x, "y", 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 { x, y, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x_i = x[i];
                const y_i = y[i];
                index.add_rect(x_i - xsize, y_i - ysize, x_i + xsize, y_i + ysize);
            }
        }
        // overriding map_data instead of _map_data because the default automatic mappings
        // for other glyphs (with cartesian coordinates) is not useful
        map_data() {
            const [sx, sy] = this.renderer.coordinates.map_to_screen(this.x, this.y);
            const [svx, svy] = this._get_unscaled_vertices();
            this._define_attr("sx", sx);
            this._define_attr("sy", sy);
            this._define_attr("svx", svx);
            this._define_attr("svy", svy);
            // From overridden GlyphView.map_data()
            this.glglyph?.set_data_mapped();
        }
        _get_unscaled_vertices() {
            const size = this.model.size;
            const aspect_scale = this.model.aspect_scale;
            if (this.model.orientation == "pointytop") {
                const rscale = this.renderer.yscale;
                const hscale = this.renderer.xscale;
                const r = Math.abs(rscale.compute(0) - rscale.compute(size)); // assumes linear scale
                const h = Math.sqrt(3) / 2 * Math.abs(hscale.compute(0) - hscale.compute(size)) / aspect_scale; // assumes linear scale
                const r2 = r / 2.0;
                const svx = [0, -h, -h, 0, h, h];
                const svy = [r, r2, -r2, -r, -r2, r2];
                return [svx, svy];
            }
            else {
                const rscale = this.renderer.xscale;
                const hscale = this.renderer.yscale;
                const r = Math.abs(rscale.compute(0) - rscale.compute(size)); // assumes linear scale
                const h = Math.sqrt(3) / 2 * Math.abs(hscale.compute(0) - hscale.compute(size)) * aspect_scale; // assumes linear scale
                const r2 = r / 2.0;
                const svx = [r, r2, -r2, -r, -r2, r2];
                const svy = [0, -h, -h, 0, h, h];
                return [svx, svy];
            }
        }
        _paint(ctx, indices, data) {
            const { sx, sy, svx, svy, scale } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const scale_i = scale.get(i);
                if (!isFinite(sx_i + sy_i + scale_i)) {
                    continue;
                }
                ctx.translate(sx_i, sy_i);
                ctx.beginPath();
                for (let j = 0; j < 6; j++) {
                    ctx.lineTo(svx[j] * scale_i, svy[j] * scale_i);
                }
                ctx.closePath();
                ctx.translate(-sx_i, -sy_i);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            const indices = [];
            for (const i of candidates) {
                if (hittest.point_in_poly(sx - this.sx[i], sy - this.sy[i], this.svx, this.svy)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const rect = (() => {
                if (geometry.direction == "v") {
                    const { sy } = geometry;
                    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);
                    return { x0, y0: y, x1, y1: y };
                }
                else {
                    const { sx } = geometry;
                    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);
                    return { x0: x, y0, x1: x, y1 };
                }
            })();
            const indices = [...this.index.indices(rect)];
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const indices = [...this.index.indices({ x0, x1, y0, y1 })];
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.HexTileView = HexTileView;
    HexTileView.__name__ = "HexTileView";
    class HexTile extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HexTile = HexTile;
    _a = HexTile;
    HexTile.__name__ = "HexTile";
    (() => {
        _a.prototype.default_view = HexTileView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(({ Float }) => ({
            r: [p.NumberSpec, { field: "r" }],
            q: [p.NumberSpec, { field: "q" }],
            scale: [p.NumberSpec, 1.0],
            size: [Float, 1.0],
            aspect_scale: [Float, 1.0],
            orientation: [enums_1.HexTileOrientation, "pointytop"],
        }));
        _a.override({ line_color: null });
    })();
},
/* models/glyphs/hspan.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const selection_1 = require(130) /* ../selections/selection */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const uniforms = tslib_1.__importStar(require(39) /* ../../core/uniforms */);
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const array_1 = require(10) /* ../../core/util/array */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const { abs, max } = Math;
    const UNUSED = 0;
    class HSpanView extends glyph_1.GlyphView {
        after_visuals() {
            super.after_visuals();
            this.max_line_width = uniforms.max(this.line_width);
        }
        _index_data(index) {
            for (const y_i of this.y) {
                index.add_point(UNUSED, y_i);
            }
        }
        _bounds(bounds) {
            const { y0, y1 } = bounds;
            return { x0: NaN, x1: NaN, y0, y1 };
        }
        _map_data() {
            super._map_data();
            const { round } = Math;
            if (!this.inherited_sy) {
                const sy = (0, arrayable_1.map)(this.sy, (yi) => round(yi));
                this._define_attr("sy", sy);
            }
        }
        scenterxy(i) {
            const { hcenter } = this.renderer.plot_view.frame.bbox;
            return [hcenter, this.sy[i]];
        }
        _paint(ctx, indices, data) {
            const { sy } = { ...this, ...data };
            const { left, right } = this.renderer.plot_view.frame.bbox;
            for (const i of indices) {
                const sy_i = sy[i];
                if (!isFinite(sy_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.moveTo(left, sy_i);
                ctx.lineTo(right, sy_i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _get_candidates(sy0, sy1) {
            const { max_line_width } = this;
            const [y0, y1] = this.renderer.yscale.r_invert(sy0 - max_line_width, (sy1 ?? sy0) + max_line_width);
            return this.index.indices({ x0: 0, x1: 0, y0, y1 });
        }
        _find_spans(candidates, fn) {
            const { sy, line_width } = this;
            const indices = [];
            for (const i of candidates) {
                const sy_i = sy[i];
                const line_width_i = line_width.get(i);
                if (fn(sy_i, line_width_i)) {
                    indices.push(i);
                }
            }
            return indices;
        }
        _hit_point(geometry) {
            const { sy: gsy } = geometry;
            const candidates = this._get_candidates(gsy);
            const indices = this._find_spans(candidates, (sy, line_width) => {
                return abs(sy - gsy) <= max(line_width / 2, 2 /*px*/);
            });
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const indices = (() => {
                if (geometry.direction == "v") {
                    return (0, array_1.range)(0, this.data_size);
                }
                else {
                    const { sy: gsy } = geometry;
                    const candidates = this._get_candidates(gsy);
                    return this._find_spans(candidates, (sy, line_width) => {
                        return abs(sy - gsy) <= max(line_width / 2, 2 /*px*/);
                    });
                }
            })();
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const indices = (() => {
                const { sy0: gsy0, sy1: gsy1 } = geometry;
                const candidates = this._get_candidates(gsy0, gsy1);
                return this._find_spans(candidates, (sy, line_width) => {
                    return gsy0 - line_width / 2 <= sy && sy <= gsy1 + line_width / 2;
                });
            })();
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.HSpanView = HSpanView;
    HSpanView.__name__ = "HSpanView";
    class HSpan extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HSpan = HSpan;
    _a = HSpan;
    HSpan.__name__ = "HSpan";
    (() => {
        _a.prototype.default_view = HSpanView;
        _a.mixins([property_mixins_1.LineVector]);
        _a.define(() => ({
            y: [p.YCoordinateSpec, { field: "y" }],
        }));
    })();
},
/* models/glyphs/hstrip.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const selection_1 = require(130) /* ../selections/selection */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const types_1 = require(24) /* ../../core/types */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const iter = tslib_1.__importStar(require(34) /* ../../core/util/iterator */);
    const array_1 = require(10) /* ../../core/util/array */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const UNUSED = 0;
    class HStripView extends glyph_1.GlyphView {
        async lazy_initialize() {
            await super.lazy_initialize();
            const { webgl } = this.renderer.plot_view.canvas_view;
            if (webgl != null && webgl.regl_wrapper.has_webgl) {
                const { LRTBGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(575) /* ./webgl/lrtb */));
                this.glglyph = new LRTBGL(webgl.regl_wrapper, this);
            }
        }
        get sleft() {
            const { left } = this.renderer.plot_view.frame.bbox;
            const n = this.data_size;
            const sleft = new types_1.ScreenArray(n);
            sleft.fill(left);
            return sleft;
        }
        get sright() {
            const { right } = this.renderer.plot_view.frame.bbox;
            const n = this.data_size;
            const sright = new types_1.ScreenArray(n);
            sright.fill(right);
            return sright;
        }
        get stop() {
            return this.sy0;
        }
        get sbottom() {
            return this.sy1;
        }
        _set_data(indices) {
            super._set_data(indices);
            const { abs } = Math;
            const { max, map, zip } = iter;
            const { y0, y1 } = this;
            if (this.inherited_y0 && this.inherited_y1) {
                this._inherit_attr("max_height");
            }
            else {
                const max_height = max(map(zip(y0, y1), ([y0_i, y1_i]) => abs(y0_i - y1_i)));
                this._define_attr("max_height", max_height);
            }
        }
        _index_data(index) {
            const { y0, y1, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const y0_i = y0[i];
                const y1_i = y1[i];
                index.add_rect(UNUSED, y0_i, UNUSED, y1_i);
            }
        }
        _bounds(bounds) {
            const { y0, y1 } = bounds;
            return { x0: NaN, x1: NaN, y0, y1 };
        }
        _map_data() {
            super._map_data();
            const { round } = Math;
            if (!this.inherited_sy0) {
                const sy0 = (0, arrayable_1.map)(this.sy0, (yi) => round(yi));
                this._define_attr("sy0", sy0);
            }
            if (!this.inherited_sy1) {
                const sy1 = (0, arrayable_1.map)(this.sy1, (yi) => round(yi));
                this._define_attr("sy1", sy1);
            }
        }
        scenterxy(i) {
            const { hcenter } = this.renderer.plot_view.frame.bbox;
            return [hcenter, (this.sy0[i] + this.sy1[i]) / 2];
        }
        _paint(ctx, indices, data) {
            const { sy0, sy1 } = { ...this, ...data };
            const { left, right, width } = this.renderer.plot_view.frame.bbox;
            for (const i of indices) {
                const sy0_i = sy0[i];
                const sy1_i = sy1[i];
                if (!isFinite(sy0_i + sy1_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.rect(left, sy0_i, width, sy1_i - sy0_i);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                ctx.beginPath();
                ctx.moveTo(left, sy0_i);
                ctx.lineTo(right, sy0_i);
                ctx.moveTo(left, sy1_i);
                ctx.lineTo(right, sy1_i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _get_candidates(sy0, sy1) {
            const { max_height } = this;
            const [dy0, dy1] = this.renderer.yscale.r_invert(sy0, sy1 ?? sy0);
            const y0 = dy0 - max_height;
            const y1 = dy1 + max_height;
            return this.index.indices({ x0: 0, x1: 0, y0, y1 });
        }
        _find_strips(candidates, fn) {
            function contains(sy0, sy1) {
                return sy0 <= sy1 ? fn(sy0, sy1) : fn(sy1, sy0);
            }
            const { sy0, sy1 } = this;
            const indices = [];
            for (const i of candidates) {
                const sy0_i = sy0[i];
                const sy1_i = sy1[i];
                if (contains(sy0_i, sy1_i)) {
                    indices.push(i);
                }
            }
            return indices;
        }
        _hit_point(geometry) {
            const { sy } = geometry;
            const candidates = this._get_candidates(sy);
            const indices = this._find_strips(candidates, (sy0, sy1) => sy0 <= sy && sy <= sy1);
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const indices = (() => {
                if (geometry.direction == "v") {
                    return (0, array_1.range)(0, this.data_size);
                }
                else {
                    const { sy } = geometry;
                    const candidates = this._get_candidates(sy);
                    return this._find_strips(candidates, (sy0, sy1) => sy0 <= sy && sy <= sy1);
                }
            })();
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const indices = (() => {
                const { sy0: gsy0, sy1: gsy1 } = geometry;
                const candidates = this._get_candidates(gsy0, gsy1);
                return this._find_strips(candidates, (sy0, sy1) => {
                    return gsy0 <= sy0 && sy0 <= gsy1 && gsy0 <= sy1 && sy1 <= gsy1;
                });
            })();
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.HStripView = HStripView;
    HStripView.__name__ = "HStripView";
    class HStrip extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HStrip = HStrip;
    _a = HStrip;
    HStrip.__name__ = "HStrip";
    (() => {
        _a.prototype.default_view = HStripView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(() => ({
            y0: [p.YCoordinateSpec, { field: "y0" }],
            y1: [p.YCoordinateSpec, { field: "y1" }],
        }));
    })();
},
/* models/glyphs/image.js */ function _(require, module, exports, __esModule, __esExport) {
    var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    }));
    var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    });
    var __importStar = (this && this.__importStar) || function (mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k in mod)
                if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
                    __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    };
    var _a;
    __esModule();
    const image_base_1 = require(369) /* ./image_base */;
    const color_mapper_1 = require(216) /* ../mappers/color_mapper */;
    const linear_color_mapper_1 = require(276) /* ../mappers/linear_color_mapper */;
    class ImageView extends image_base_1.ImageBaseView {
        async load_glglyph() {
            const { ImageGL } = await Promise.resolve().then(() => __importStar(require(572) /* ./webgl/image */));
            return ImageGL;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.color_mapper.change, () => this._update_image());
        }
        _update_image() {
            if (this.glglyph != null) {
                this.glglyph.set_image_changed();
            }
            // Only reset image_data if already initialized
            if (this.image_data != null) {
                this._set_data(null);
                this.renderer.request_paint();
            }
        }
        get _can_inherit_image_data() {
            return super._can_inherit_image_data &&
                this._can_inherit_from(this.model.properties.color_mapper, this.base);
        }
        _flat_img_to_buf8(img) {
            const cmap = this.model.color_mapper.rgba_mapper;
            return cmap.v_compute(img);
        }
    }
    exports.ImageView = ImageView;
    ImageView.__name__ = "ImageView";
    // NOTE: this needs to be redefined here, because palettes are located in bokeh-api.js bundle
    const Greys9 = () => ["#000000", "#252525", "#525252", "#737373", "#969696", "#bdbdbd", "#d9d9d9", "#f0f0f0", "#ffffff"];
    class Image extends image_base_1.ImageBase {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Image = Image;
    _a = Image;
    Image.__name__ = "Image";
    (() => {
        _a.prototype.default_view = ImageView;
        _a.define(({ Ref }) => ({
            color_mapper: [Ref(color_mapper_1.ColorMapper), () => new linear_color_mapper_1.LinearColorMapper({ palette: Greys9() })],
        }));
    })();
},
/* models/glyphs/image_base.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const glyph_1 = require(222) /* ./glyph */;
    const types_1 = require(24) /* ../../core/types */;
    const enums_1 = require(20) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const selection_1 = require(130) /* ../selections/selection */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const kinds_1 = require(185) /* ../common/kinds */;
    const resolve_1 = require(186) /* ../common/resolve */;
    class ImageBaseView extends xy_glyph_1.XYGlyphView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.global_alpha.change, () => this.renderer.request_paint());
        }
        get image_dimension() {
            return 2;
        }
        get xy_scale() {
            switch (this.model.origin) {
                case "bottom_left": return { x: 1, y: -1 };
                case "top_left": return { x: 1, y: 1 };
                case "bottom_right": return { x: -1, y: -1 };
                case "top_right": return { x: -1, y: 1 };
            }
        }
        get xy_offset() {
            switch (this.model.origin) {
                case "bottom_left": return { x: 0.0, y: 1.0 };
                case "top_left": return { x: 0.0, y: 0.0 };
                case "bottom_right": return { x: 1.0, y: 1.0 };
                case "top_right": return { x: 1.0, y: 0.0 };
            }
        }
        get xy_anchor() {
            return (0, resolve_1.anchor)(this.model.anchor);
        }
        get xy_sign() {
            const xr = this.renderer.xscale.source_range;
            const yr = this.renderer.yscale.source_range;
            return {
                x: xr.is_reversed ? -1 : 1,
                y: yr.is_reversed ? -1 : 1,
            };
        }
        _paint(ctx, indices, data) {
            const { image_data, sx, sy, sdw, sdh } = { ...this, ...data };
            const { xy_sign, xy_scale, xy_offset, xy_anchor } = this;
            (0, assert_1.assert)(image_data != null);
            ctx.save();
            ctx.imageSmoothingEnabled = false;
            if (this.visuals.image.doit) {
                for (const i of indices) {
                    const image_data_i = image_data[i];
                    const sx_i = sx[i];
                    const sy_i = sy[i];
                    const sdw_i = sdw[i];
                    const sdh_i = sdh[i];
                    if (image_data_i == null || !isFinite(sx_i + sy_i + sdw_i + sdh_i)) {
                        continue;
                    }
                    const tx_i = xy_sign.x * xy_anchor.x * sdw_i;
                    const ty_i = xy_sign.y * xy_anchor.y * sdh_i;
                    ctx.save();
                    ctx.translate(sx_i - tx_i, sy_i - ty_i);
                    ctx.scale(xy_sign.x * xy_scale.x, xy_sign.y * xy_scale.y);
                    this.visuals.image.set_vectorize(ctx, i);
                    ctx.drawImage(image_data_i, -xy_offset.x * sdw_i, -xy_offset.y * sdh_i, sdw_i, sdh_i);
                    ctx.restore();
                }
            }
            ctx.restore();
        }
        get _can_inherit_image_data() {
            return this.inherited_image;
        }
        _set_data(indices) {
            const n = this.data_size;
            if (!this._can_inherit_image_data) {
                if (typeof this.image_data === "undefined" || this.image_data.length != n) {
                    this._define_attr("image_data", new Array(n).fill(null));
                    this._define_attr("image_width", new Uint32Array(n));
                    this._define_attr("image_height", new Uint32Array(n));
                }
                const { image_dimension } = this;
                for (let i = 0; i < n; i++) {
                    if (indices != null && !indices.includes(i)) {
                        continue;
                    }
                    const img = this.image.get(i);
                    (0, assert_1.assert)(img.dimension == image_dimension, `expected a ${image_dimension}D array, not ${img.dimension}D`);
                    const [height, width] = img.shape;
                    this.image_width[i] = width;
                    this.image_height[i] = height;
                    const buf8 = this._flat_img_to_buf8(img);
                    this._set_image_data_from_buffer(i, buf8);
                }
            }
            else {
                this._inherit_attr("image_data");
                this._inherit_attr("image_width");
                this._inherit_attr("image_height");
            }
        }
        _index_data(index) {
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const [l, r, t, b] = this._lrtb(i);
                index.add_rect(l, b, r, t);
            }
        }
        _lrtb(i) {
            const dw_i = this.dw.get(i);
            const dh_i = this.dh.get(i);
            const x_i = this.x[i];
            const y_i = this.y[i];
            const { xy_anchor } = this;
            const [x0, x1] = [x_i - xy_anchor.x * dw_i, x_i + (1 - xy_anchor.x) * dw_i];
            const [y0, y1] = [y_i + xy_anchor.y * dh_i, y_i - (1 - xy_anchor.y) * dh_i];
            const [l, r] = x0 <= x1 ? [x0, x1] : [x1, x0];
            const [b, t] = y0 <= y1 ? [y0, y1] : [y1, y0];
            return [l, r, t, b];
        }
        _get_or_create_canvas(i) {
            (0, assert_1.assert)(this.image_data != null);
            const image_data_i = this.image_data[i];
            if (image_data_i != null && image_data_i.width == this.image_width[i]
                && image_data_i.height == this.image_height[i]) {
                return image_data_i;
            }
            else {
                const canvas = document.createElement("canvas");
                canvas.width = this.image_width[i];
                canvas.height = this.image_height[i];
                return canvas;
            }
        }
        _set_image_data_from_buffer(i, buf8) {
            (0, assert_1.assert)(this.image_data != null);
            const canvas = this._get_or_create_canvas(i);
            const ctx = canvas.getContext("2d");
            const image_data = ctx.getImageData(0, 0, this.image_width[i], this.image_height[i]);
            image_data.data.set(buf8);
            ctx.putImageData(image_data, 0, 0);
            this.image_data[i] = canvas;
        }
        _map_data() {
            this._define_or_inherit_attr("sdw", () => {
                if (this.model.properties.dw.units == "data") {
                    if (this.inherited_x && this.inherited_dw) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.dw, "edge", this.model.dilate);
                    }
                }
                else {
                    return this.inherited_dw ? glyph_1.inherit : (0, types_1.to_screen)(this.dw);
                }
            });
            this._define_or_inherit_attr("sdh", () => {
                if (this.model.properties.dh.units == "data") {
                    if (this.inherited_y && this.inherited_dh) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.yscale, this.y, this.dh, "edge", this.model.dilate);
                    }
                }
                else {
                    return this.inherited_dh ? glyph_1.inherit : (0, types_1.to_screen)(this.dh);
                }
            });
        }
        _image_index(index, x, y) {
            const [l, r, t, b] = this._lrtb(index);
            const width = this.image_width[index];
            const height = this.image_height[index];
            const dx = (r - l) / width;
            const dy = (t - b) / height;
            const i = Math.floor((x - l) / dx);
            const j = Math.floor((y - b) / dy);
            return { index, i, j, flat_index: j * width + i };
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const candidates = this.index.indices({ x0: x, x1: x, y0: y, y1: y });
            const result = new selection_1.Selection();
            const indices = [];
            for (const index of candidates) {
                if (isFinite(sx) && isFinite(sy)) {
                    indices.push(index);
                    result.image_indices.push(this._image_index(index, x, y));
                }
            }
            result.indices = indices;
            return result;
        }
    }
    exports.ImageBaseView = ImageBaseView;
    ImageBaseView.__name__ = "ImageBaseView";
    class ImageBase extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ImageBase = ImageBase;
    _a = ImageBase;
    ImageBase.__name__ = "ImageBase";
    (() => {
        _a.mixins(mixins.ImageVector);
        _a.define(({ Bool }) => ({
            image: [p.NDArraySpec, { field: "image" }],
            dw: [p.DistanceSpec, { field: "dw" }],
            dh: [p.DistanceSpec, { field: "dh" }],
            dilate: [Bool, false],
            origin: [enums_1.ImageOrigin, "bottom_left"],
            anchor: [kinds_1.Anchor, "bottom_left"],
        }));
    })();
},
/* models/glyphs/image_rgba.js */ function _(require, module, exports, __esModule, __esExport) {
    var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    }));
    var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    });
    var __importStar = (this && this.__importStar) || function (mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k in mod)
                if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
                    __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    };
    var _a;
    __esModule();
    const image_base_1 = require(369) /* ./image_base */;
    const types_1 = require(8) /* ../../core/util/types */;
    class ImageRGBAView extends image_base_1.ImageBaseView {
        async load_glglyph() {
            const { ImageGL } = await Promise.resolve().then(() => __importStar(require(572) /* ./webgl/image */));
            return ImageGL;
        }
        _flat_img_to_buf8(img) {
            const array = (0, types_1.isTypedArray)(img) ? img : new Uint32Array(img);
            return new Uint8ClampedArray(array.buffer);
        }
    }
    exports.ImageRGBAView = ImageRGBAView;
    ImageRGBAView.__name__ = "ImageRGBAView";
    class ImageRGBA extends image_base_1.ImageBase {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ImageRGBA = ImageRGBA;
    _a = ImageRGBA;
    ImageRGBA.__name__ = "ImageRGBA";
    (() => {
        _a.prototype.default_view = ImageRGBAView;
    })();
},
/* models/glyphs/image_stack.js */ function _(require, module, exports, __esModule, __esExport) {
    var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    }));
    var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    });
    var __importStar = (this && this.__importStar) || function (mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k in mod)
                if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
                    __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    };
    var _a;
    __esModule();
    const image_base_1 = require(369) /* ./image_base */;
    const stack_color_mapper_1 = require(279) /* ../mappers/stack_color_mapper */;
    class ImageStackView extends image_base_1.ImageBaseView {
        async load_glglyph() {
            const { ImageGL } = await Promise.resolve().then(() => __importStar(require(572) /* ./webgl/image */));
            return ImageGL;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.color_mapper.change, () => this._update_image());
        }
        get image_dimension() {
            return 3;
        }
        _update_image() {
            if (this.glglyph != null) {
                this.glglyph.set_image_changed();
            }
            // Only reset image_data if already initialized
            if (this.image_data != null) {
                this._set_data(null);
                this.renderer.request_paint();
            }
        }
        get _can_inherit_image_data() {
            return super._can_inherit_image_data &&
                this._can_inherit_from(this.model.properties.color_mapper, this.base);
        }
        _flat_img_to_buf8(img) {
            const cmap = this.model.color_mapper.rgba_mapper;
            return cmap.v_compute(img);
        }
    }
    exports.ImageStackView = ImageStackView;
    ImageStackView.__name__ = "ImageStackView";
    class ImageStack extends image_base_1.ImageBase {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ImageStack = ImageStack;
    _a = ImageStack;
    ImageStack.__name__ = "ImageStack";
    (() => {
        _a.prototype.default_view = ImageStackView;
        _a.define(({ Ref }) => ({
            color_mapper: [Ref(stack_color_mapper_1.StackColorMapper)],
        }));
    })();
},
/* models/glyphs/image_url.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const glyph_1 = require(222) /* ./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 array_1 = require(10) /* ../../core/util/array */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const image_1 = require(179) /* ../../core/util/image */;
    const resolve = tslib_1.__importStar(require(186) /* ../common/resolve */);
    class ImageURLView extends xy_glyph_1.XYGlyphView {
        constructor() {
            super(...arguments);
            this._images_rendered = false;
            /*protected*/ this.image = new Array(0);
            this._set_data_iteration = 0;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.properties.global_alpha.change, () => this.renderer.request_paint());
        }
        _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() {
            if (this.inherited_url) {
                return;
            }
            this._set_data_iteration++;
            const { url } = this;
            const n_url = url.length;
            this.image = (0, array_1.resize)(this.image, n_url, null);
            this.loaders = new Array(n_url).fill(null);
            this.resolved = new types_1.Indices(n_url);
            const { retry_attempts, retry_timeout } = this.model;
            const { _set_data_iteration } = this;
            for (let i = 0; i < n_url; i++) {
                const url_i = url.get(i);
                if (url_i == "") {
                    continue;
                }
                const loader = new image_1.ImageLoader(url_i, {
                    loaded: (image_i) => {
                        if (this._set_data_iteration == _set_data_iteration && !this.resolved.get(i)) {
                            this.resolved.set(i);
                            this.image[i] = image_i;
                            this.loaders[i] = null;
                            this.renderer.request_paint();
                        }
                    },
                    failed: () => {
                        if (this._set_data_iteration == _set_data_iteration) {
                            this.resolved.set(i);
                            this.loaders[i] = null;
                            const image_i = this.image[i];
                            if (image_i != null) {
                                this.image[i] = null;
                                this.renderer.request_paint();
                            }
                        }
                    },
                    attempts: retry_attempts + 1,
                    timeout: retry_timeout,
                });
                this.loaders[i] = loader;
            }
            const w_data = this.model.properties.w.units == "data";
            const h_data = this.model.properties.h.units == "data";
            const n = this.data_size;
            const xs = new types_1.ScreenArray(w_data ? 2 * n : n);
            const ys = new types_1.ScreenArray(h_data ? 2 * n : n);
            this.anchor = resolve.anchor(this.model.anchor);
            const { x: x_anchor, y: y_anchor } = this.anchor;
            function x0x1(x, w) {
                const x0 = x - x_anchor * w;
                return [x0, x0 + w];
            }
            function y0y1(y, h) {
                const y0 = y + y_anchor * h;
                return [y0, y0 - h];
            }
            // if the width/height are in screen units, don't try to include them in bounds
            if (w_data) {
                for (let i = 0; i < n; i++) {
                    [xs[i], xs[n + i]] = x0x1(this.x[i], this.w.get(i) ?? 0);
                }
            }
            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) ?? 0);
                }
            }
            else {
                ys.set(this.y, 0);
            }
            const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
            this._bounds_rect = { x0, x1, y0, y1 };
        }
        has_finished() {
            return super.has_finished() && this._images_rendered;
        }
        _map_data() {
            const w = () => this.w.map((w_i) => w_i ?? NaN);
            const h = () => this.h.map((h_i) => h_i ?? NaN);
            this._define_or_inherit_attr("sw", () => {
                if (this.model.properties.w.units == "data") {
                    if (this.inherited_x && this.inherited_w) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, w(), "edge", this.model.dilate);
                    }
                }
                else {
                    return this.inherited_w ? glyph_1.inherit : (0, types_1.to_screen)(w());
                }
            });
            this._define_or_inherit_attr("sh", () => {
                if (this.model.properties.h.units == "data") {
                    if (this.inherited_y && this.inherited_h) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.yscale, this.y, h(), "edge", this.model.dilate);
                    }
                }
                else {
                    return this.inherited_h ? glyph_1.inherit : (0, types_1.to_screen)(h());
                }
            });
        }
        _paint(ctx, indices, data) {
            const { sx, sy, sw, sh, angle, global_alpha } = { ...this, ...data };
            const { image, loaders, resolved } = this;
            // TODO (bev): take actual border width into account when clipping
            const { frame } = this.renderer.plot_view;
            const { left, top, width, height } = frame.bbox;
            ctx.beginPath();
            ctx.rect(left + 1, top + 1, width - 2, height - 2);
            ctx.clip();
            let finished = true;
            for (const i of indices) {
                const loader_i = loaders[i];
                if (!isFinite(sx[i] + sy[i] + angle.get(i) + global_alpha.get(i))) {
                    continue;
                }
                if (!resolved.get(i)) {
                    if (loader_i != null && loader_i.image.complete) {
                        image[i] = loader_i.image;
                        loaders[i] = null;
                        resolved.set(i);
                    }
                    else {
                        finished = false;
                    }
                }
                const image_i = image[i];
                if (image_i == null) {
                    continue;
                }
                if (image_i.naturalWidth == 0 && image_i.naturalHeight == 0) { // dumb way of detecting broken images
                    continue;
                }
                this._render_image(ctx, i, image_i, sx, sy, sw, sh, angle, global_alpha);
            }
            if (finished && !this._images_rendered) {
                this._images_rendered = true;
                this.notify_finished();
            }
        }
        _render_image(ctx, i, image, sx, sy, sw, sh, angle, alpha) {
            if (!isFinite(sw[i])) {
                sw[i] = image.width;
            }
            if (!isFinite(sh[i])) {
                sh[i] = image.height;
            }
            const sw_i = sw[i];
            const sh_i = sh[i];
            const { anchor } = this;
            const dx_i = anchor.x * sw_i;
            const dy_i = anchor.y * sh_i;
            const sx_i = sx[i] - dx_i;
            const sy_i = sy[i] - dy_i;
            const angle_i = angle.get(i);
            const alpha_i = alpha.get(i);
            ctx.save();
            ctx.globalAlpha = alpha_i;
            const sw2 = sw_i / 2;
            const sh2 = sh_i / 2;
            if (angle_i != 0) {
                ctx.translate(sx_i, sy_i);
                //rotation about center of image
                ctx.translate(sw2, sh2);
                ctx.rotate(angle_i);
                ctx.translate(-sw2, -sh2);
                ctx.drawImage(image, 0, 0, sw_i, sh_i);
                ctx.translate(sw2, sh2);
                ctx.rotate(-angle_i);
                ctx.translate(-sw2, -sh2);
                ctx.translate(-sx_i, -sy_i);
            }
            else {
                ctx.drawImage(image, sx_i, sy_i, sw_i, sh_i);
            }
            ctx.restore();
        }
        bounds() {
            return this._bounds_rect;
        }
    }
    exports.ImageURLView = ImageURLView;
    ImageURLView.__name__ = "ImageURLView";
    class ImageURL extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ImageURL = ImageURL;
    _a = ImageURL;
    ImageURL.__name__ = "ImageURL";
    (() => {
        _a.prototype.default_view = ImageURLView;
        _a.define(({ Bool, Int }) => ({
            url: [p.StringSpec, { field: "url" }],
            anchor: [enums_1.Anchor, "top_left"],
            global_alpha: [p.NumberSpec, { value: 1.0 }],
            angle: [p.AngleSpec, 0],
            w: [p.NullDistanceSpec, null],
            h: [p.NullDistanceSpec, null],
            dilate: [Bool, false],
            retry_attempts: [Int, 0],
            retry_timeout: [Int, 0],
        }));
    })();
},
/* models/glyphs/mathml_glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const math_text_glyph_1 = require(374) /* ./math_text_glyph */;
    const math_text_1 = require(178) /* ../text/math_text */;
    class MathMLGlyphView extends math_text_glyph_1.MathTextGlyphView {
        _build_label(text) {
            return new math_text_1.MathML({ text });
        }
    }
    exports.MathMLGlyphView = MathMLGlyphView;
    MathMLGlyphView.__name__ = "MathMLGlyphView";
    class MathMLGlyph extends math_text_glyph_1.MathTextGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MathMLGlyph = MathMLGlyph;
    _a = MathMLGlyph;
    MathMLGlyph.__name__ = "MathMLGlyph";
    (() => {
        _a.prototype.default_view = MathMLGlyphView;
    })();
},
/* models/glyphs/math_text_glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const text_1 = require(375) /* ./text */;
    const math_text_1 = require(178) /* ../text/math_text */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    class MathTextGlyphView extends text_1.TextView {
        constructor() {
            super(...arguments);
            this._label_views = new Map();
        }
        remove() {
            (0, build_views_1.remove_views)(this._label_views);
            super.remove();
        }
        *children() {
            yield* super.children();
            yield* this._label_views.values();
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            for (const view of this._label_views.values()) {
                if (!view.has_finished()) {
                    return false;
                }
            }
            return true;
        }
        async _build_labels(text) {
            const labels = Array.from(text, (text_i) => {
                return text_i == null ? null : this._build_label(text_i);
            });
            await (0, build_views_1.build_views)(this._label_views, labels.filter((v) => v != null), { parent: this.renderer });
            return labels.map((label_i) => {
                return label_i == null ? null : this._label_views.get(label_i).graphics();
            });
        }
        async after_lazy_visuals() {
            await super.after_lazy_visuals();
            const promises = [...this._label_views.values()].map((label_view) => {
                if (label_view instanceof math_text_1.MathTextView) {
                    return label_view.request_image();
                }
                else {
                    return null;
                }
            });
            await Promise.allSettled(promises);
            const { left, right, top, bottom } = this.padding;
            for (const [label, i] of (0, iterator_1.enumerate)(this.labels)) {
                if (label == null) {
                    continue;
                }
                if (!(label instanceof math_text_1.MathTextView)) {
                    continue;
                }
                const size = label.size();
                const width = left + size.width + right;
                const height = top + size.height + bottom;
                this.swidth[i] = width;
                this.sheight[i] = height;
            }
        }
    }
    exports.MathTextGlyphView = MathTextGlyphView;
    MathTextGlyphView.__name__ = "MathTextGlyphView";
    class MathTextGlyph extends text_1.Text {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MathTextGlyph = MathTextGlyph;
    MathTextGlyph.__name__ = "MathTextGlyph";
},
/* models/glyphs/text.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const uniforms_1 = require(39) /* ../../core/uniforms */;
    const selection_1 = require(130) /* ../selections/selection */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const affine_1 = require(114) /* ../../core/util/affine */;
    const graphics_1 = require(180) /* ../../core/graphics */;
    const kinds_1 = require(185) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(186) /* ../common/resolve */);
    const painting_1 = require(187) /* ../common/painting */;
    const math_1 = require(11) /* ../../core/util/math */;
    class TextAnchorSpec extends p.DataSpec {
    }
    TextAnchorSpec.__name__ = "TextAnchorSpec";
    class OutlineShapeSpec extends p.DataSpec {
    }
    OutlineShapeSpec.__name__ = "OutlineShapeSpec";
    class TextView extends xy_glyph_1.XYGlyphView {
        async _build_labels(text) {
            return Array.from(text, (value) => {
                if (value == null) {
                    return null;
                }
                else {
                    const text = `${value}`; // TODO: guarantee correct types earlier
                    return new graphics_1.TextBox({ text });
                }
            });
        }
        async _set_lazy_data() {
            if (this.inherited_text) {
                this._inherit_attr("labels");
            }
            else {
                this._define_attr("labels", await this._build_labels(this.text));
            }
        }
        after_visuals() {
            super.after_visuals();
            const n = this.data_size;
            const { anchor } = this.base ?? this;
            const { padding, border_radius } = this.model;
            const { text_align, text_baseline } = this.visuals.text;
            if (anchor.is_Scalar() && anchor.value != "auto") {
                this.anchor_ = new uniforms_1.UniformScalar(resolve.anchor(anchor.value), n);
            }
            else if (anchor.is_Scalar() && text_align.is_Scalar() && text_baseline.is_Scalar()) {
                this.anchor_ = new uniforms_1.UniformScalar(resolve.text_anchor(anchor.value, text_align.value, text_baseline.value), n);
            }
            else {
                const anchors = new Array(n);
                for (let i = 0; i < n; i++) {
                    const anchor_i = anchor.get(i);
                    const align_i = text_align.get(i);
                    const baseline_i = text_baseline.get(i);
                    anchors[i] = resolve.text_anchor(anchor_i, align_i, baseline_i);
                }
                this.anchor_ = new uniforms_1.UniformVector(anchors);
            }
            this.padding = resolve.padding(padding);
            this.border_radius = resolve.border_radius(border_radius);
            this.swidth = new Float32Array(n);
            this.sheight = new Float32Array(n);
            const { left, right, top, bottom } = this.padding;
            for (const [label, i] of (0, iterator_1.enumerate)(this.labels)) {
                if (label == null) {
                    continue;
                }
                label.visuals = this.visuals.text.values(i);
                label.position = { sx: 0, sy: 0, x_anchor: "left", y_anchor: "top" };
                label.align = "auto";
                const size = label.size();
                const width = left + size.width + right;
                const height = top + size.height + bottom;
                this.swidth[i] = width;
                this.sheight[i] = height;
            }
        }
        _paint(ctx, indices, data) {
            const { sx, sy, x_offset, y_offset, angle, outline_shape } = { ...this, ...data };
            const { text, background_fill, background_hatch, border_line } = this.visuals;
            const { anchor_: anchor, border_radius, padding } = this;
            const { labels, swidth, sheight } = this;
            for (const i of indices) {
                const sx_i = sx[i] + x_offset.get(i);
                const sy_i = sy[i] + y_offset.get(i);
                const angle_i = angle.get(i);
                const label_i = labels[i];
                const shape_i = outline_shape.get(i);
                if (!isFinite(sx_i + sy_i + angle_i) || label_i == null) {
                    continue;
                }
                const swidth_i = swidth[i];
                const sheight_i = sheight[i];
                const anchor_i = anchor.get(i);
                const dx_i = anchor_i.x * swidth_i;
                const dy_i = anchor_i.y * sheight_i;
                ctx.translate(sx_i, sy_i);
                ctx.rotate(angle_i);
                ctx.translate(-dx_i, -dy_i);
                if (shape_i != "none" && (background_fill.v_doit(i) || background_hatch.v_doit(i) || border_line.v_doit(i))) {
                    const bbox = new bbox_1.BBox({ x: 0, y: 0, width: swidth_i, height: sheight_i });
                    const visuals = {
                        fill: background_fill,
                        hatch: background_hatch,
                        line: border_line,
                    };
                    this._paint_shape(ctx, i, shape_i, bbox, visuals, border_radius);
                }
                if (text.v_doit(i)) {
                    const { left, top } = padding;
                    ctx.translate(left, top);
                    label_i.visuals = text.values(i);
                    label_i.paint(ctx);
                    ctx.translate(-left, -top);
                }
                ctx.translate(dx_i, dy_i);
                ctx.rotate(-angle_i);
                ctx.translate(-sx_i, -sy_i);
            }
        }
        _paint_shape(ctx, i, shape, bbox, visuals, border_radius) {
            ctx.beginPath();
            switch (shape) {
                case "none": {
                    break;
                }
                case "box":
                case "rectangle": {
                    (0, painting_1.round_rect)(ctx, bbox, border_radius);
                    break;
                }
                case "square": {
                    const square = (() => {
                        const { x, y, width, height } = bbox;
                        if (width > height) {
                            const dy = (width - height) / 2;
                            return new bbox_1.BBox({ x, y: y - dy, width, height: width });
                        }
                        else {
                            const dx = (height - width) / 2;
                            return new bbox_1.BBox({ x: x - dx, y, width: height, height });
                        }
                    })();
                    (0, painting_1.round_rect)(ctx, square, border_radius);
                    break;
                }
                case "circle": {
                    const cx = bbox.x_center;
                    const cy = bbox.y_center;
                    const radius = (0, math_1.sqrt)(bbox.width ** 2 + bbox.height ** 2) / 2;
                    ctx.arc(cx, cy, radius, 0, 2 * math_1.PI, false);
                    break;
                }
                case "ellipse": {
                    const cx = bbox.x_center;
                    const cy = bbox.y_center;
                    const rx = bbox.width / 2;
                    const ry = bbox.height / 2;
                    const n = 1.5;
                    const x_0 = rx;
                    const y_0 = ry;
                    const a = (0, math_1.sqrt)(x_0 ** 2 + x_0 ** (2 / n) * y_0 ** (2 - 2 / n));
                    const b = (0, math_1.sqrt)(y_0 ** 2 + y_0 ** (2 / n) * x_0 ** (2 - 2 / n));
                    ctx.ellipse(cx, cy, a, b, 0, 0, 2 * math_1.PI);
                    break;
                }
                case "trapezoid": {
                    const { left, right, top, bottom, width } = bbox;
                    const ext = 0.2 * width;
                    ctx.moveTo(left, top);
                    ctx.lineTo(right, top);
                    ctx.lineTo(right + ext, bottom);
                    ctx.lineTo(left - ext, bottom);
                    ctx.closePath();
                    break;
                }
                case "parallelogram": {
                    const { left, right, top, bottom, width } = bbox;
                    const ext = 0.2 * width;
                    ctx.moveTo(left, top);
                    ctx.lineTo(right + ext, top);
                    ctx.lineTo(right, bottom);
                    ctx.lineTo(left - ext, bottom);
                    ctx.closePath();
                    break;
                }
                case "diamond": {
                    const { x_center, y_center, width, height } = bbox;
                    ctx.moveTo(x_center, y_center - height);
                    ctx.lineTo(width + width / 2, y_center);
                    ctx.lineTo(x_center, y_center + height);
                    ctx.lineTo(-width / 2, y_center);
                    ctx.closePath();
                    break;
                }
                case "triangle": {
                    const w = bbox.width;
                    const h = bbox.height;
                    const l = (0, math_1.sqrt)(3) / 2 * w;
                    const H = h + l;
                    ctx.translate(w / 2, -l);
                    ctx.moveTo(0, 0);
                    ctx.lineTo(H / 2, H);
                    ctx.lineTo(-H / 2, H);
                    ctx.closePath();
                    ctx.translate(-w / 2, l);
                    break;
                }
            }
            visuals.fill.apply(ctx, i);
            visuals.hatch.apply(ctx, i);
            visuals.line.apply(ctx, i);
        }
        _hit_point(geometry) {
            const hit_xy = { x: geometry.sx, y: geometry.sy };
            const { sx, sy, x_offset, y_offset, angle, labels } = this;
            const { anchor_: anchor } = this;
            const { swidth, sheight } = this;
            const n = this.data_size;
            const indices = [];
            for (let i = 0; i < n; i++) {
                const sx_i = sx[i] + x_offset.get(i);
                const sy_i = sy[i] + y_offset.get(i);
                const angle_i = angle.get(i);
                const label_i = labels[i];
                if (!isFinite(sx_i + sy_i + angle_i) || label_i == null) {
                    continue;
                }
                const swidth_i = swidth[i];
                const sheight_i = sheight[i];
                const anchor_i = anchor.get(i);
                const dx_i = anchor_i.x * swidth_i;
                const dy_i = anchor_i.y * sheight_i;
                const { x, y } = (0, affine_1.rotate_around)(hit_xy, { x: sx_i, y: sy_i }, -angle_i);
                const left = sx_i - dx_i;
                const top = sy_i - dy_i;
                const right = left + swidth_i;
                const bottom = top + sheight_i;
                // TODO: consider round corners
                if (left <= x && x <= right && top <= y && y <= bottom) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        rect_i(i) {
            const { sx, sy, x_offset, y_offset, angle, labels } = this;
            const { anchor_: anchor } = this;
            const { swidth, sheight } = this;
            const sx_i = sx[i] + x_offset.get(i);
            const sy_i = sy[i] + y_offset.get(i);
            const angle_i = angle.get(i);
            const label_i = labels[i];
            if (!isFinite(sx_i + sy_i + angle_i) || label_i == null) {
                return {
                    p0: { x: NaN, y: NaN },
                    p1: { x: NaN, y: NaN },
                    p2: { x: NaN, y: NaN },
                    p3: { x: NaN, y: NaN },
                };
            }
            const swidth_i = swidth[i];
            const sheight_i = sheight[i];
            const anchor_i = anchor.get(i);
            const dx_i = anchor_i.x * swidth_i;
            const dy_i = anchor_i.y * sheight_i;
            const bbox = new bbox_1.BBox({
                x: sx_i - dx_i,
                y: sy_i - dy_i,
                width: swidth_i,
                height: sheight_i,
            });
            const { rect } = bbox;
            if (angle_i == 0) {
                return rect;
            }
            else {
                const tr = new affine_1.AffineTransform();
                tr.rotate_around(sx_i, sy_i, angle_i);
                return tr.apply_rect(rect);
            }
        }
        scenterxy(i) {
            const { p0, p1, p2, p3 } = this.rect_i(i);
            const sx = (p0.x + p1.x + p2.x + p3.x) / 4;
            const sy = (p0.y + p1.y + p2.y + p3.y) / 4;
            return [sx, sy];
        }
    }
    exports.TextView = TextView;
    TextView.__name__ = "TextView";
    class Text extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Text = Text;
    _a = Text;
    Text.__name__ = "Text";
    (() => {
        _a.prototype.default_view = TextView;
        _a.mixins([
            mixins.TextVector,
            ["border_", mixins.LineVector],
            ["background_", mixins.FillVector],
            ["background_", mixins.HatchVector],
        ]);
        _a.define(() => ({
            text: [p.NullStringSpec, { field: "text" }],
            angle: [p.AngleSpec, 0],
            x_offset: [p.NumberSpec, 0],
            y_offset: [p.NumberSpec, 0],
            anchor: [TextAnchorSpec, { value: "auto" }],
            padding: [kinds_1.Padding, 0],
            border_radius: [kinds_1.BorderRadius, 0],
            outline_shape: [OutlineShapeSpec, "box"],
        }));
        _a.override({
            border_line_color: null,
            background_fill_color: null,
            background_hatch_color: null,
        });
    })();
},
/* models/glyphs/multi_line.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const selection_1 = require(130) /* ../selections/selection */;
    class MultiLineView extends glyph_1.GlyphView {
        async load_glglyph() {
            const { MultiLineGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(576) /* ./webgl/multi_line */));
            return MultiLineGL;
        }
        _project_data() {
            this._project_xy("xs", this.xs.data, "ys", this.ys.data);
        }
        _index_data(index) {
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const xsi = this.xs.get(i);
                const ysi = this.ys.get(i);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xsi, ysi);
                index.add_rect(x0, y0, x1, y1);
            }
        }
        _paint(ctx, indices, data) {
            const { sxs, sys } = { ...this, ...data };
            for (const i of indices) {
                const sx = sxs.get(i);
                const sy = sys.get(i);
                const n = Math.min(sx.length, sy.length);
                let move = true;
                ctx.beginPath();
                for (let j = 0; j < n; j++) {
                    const sx_j = sx[j];
                    const sy_j = sy[j];
                    if (!isFinite(sx_j + sy_j)) {
                        move = true;
                    }
                    else {
                        if (move) {
                            ctx.moveTo(sx_j, sy_j);
                            move = false;
                        }
                        else {
                            ctx.lineTo(sx_j, sy_j);
                        }
                    }
                }
                this.visuals.line.set_vectorize(ctx, i);
                ctx.stroke();
            }
        }
        _hit_point(geometry) {
            const point = { x: geometry.sx, y: geometry.sy };
            let shortest = 9999;
            const hits = new Map();
            for (let i = 0, end = this.sxs.length; i < end; i++) {
                const threshold = Math.max(2, this.line_width.get(i) / 2);
                const sxsi = this.sxs.get(i);
                const sysi = this.sys.get(i);
                let points = null;
                for (let j = 0, endj = sxsi.length - 1; j < endj; j++) {
                    const p0 = { x: sxsi[j], y: sysi[j] };
                    const p1 = { x: sxsi[j + 1], y: sysi[j + 1] };
                    const dist = hittest.dist_to_segment(point, p0, p1);
                    if (dist < threshold && dist < shortest) {
                        shortest = dist;
                        points = [j];
                    }
                }
                if (points != null) {
                    hits.set(i, points);
                }
            }
            return new selection_1.Selection({
                indices: [...hits.keys()],
                multiline_indices: 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: 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 (0, utils_1.line_interpolation)(this.renderer, geometry, x2, y2, x3, y3);
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy() {
            throw new Error(`${this}.scenterxy() is not implemented`);
        }
    }
    exports.MultiLineView = MultiLineView;
    MultiLineView.__name__ = "MultiLineView";
    class MultiLine extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MultiLine = MultiLine;
    _a = MultiLine;
    MultiLine.__name__ = "MultiLine";
    (() => {
        _a.prototype.default_view = MultiLineView;
        _a.define(({}) => ({
            xs: [p.XCoordinateSeqSpec, { field: "xs" }],
            ys: [p.YCoordinateSeqSpec, { field: "ys" }],
        }));
        _a.mixins(property_mixins_1.LineVector);
    })();
},
/* models/glyphs/multi_polygons.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const spatial_1 = require(224) /* ../../core/util/spatial */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const arrayable_2 = require(13) /* ../../core/util/arrayable */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(130) /* ../selections/selection */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class MultiPolygonsView extends glyph_1.GlyphView {
        _project_data() {
            // TODO
        }
        _index_data(index) {
            const { min, max } = Math;
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const xsi = this.xs[i];
                const ysi = this.ys[i];
                if (xsi.length == 0 || ysi.length == 0) {
                    index.add_empty();
                    continue;
                }
                let xi0 = +Infinity;
                let xi1 = -Infinity;
                let yi0 = +Infinity;
                let yi1 = -Infinity;
                for (let j = 0, endj = xsi.length; j < endj; j++) {
                    const xsij = xsi[j][0]; // do not use holes
                    const ysij = ysi[j][0]; // do not use holes
                    if (xsij.length != 0 && ysij.length != 0) {
                        const [xij0, xij1, yij0, yij1] = (0, arrayable_1.minmax2)(xsij, ysij);
                        xi0 = min(xi0, xij0);
                        xi1 = max(xi1, xij1);
                        yi0 = min(yi0, yij0);
                        yi1 = max(yi1, yij1);
                    }
                }
                index.add_rect(xi0, yi0, xi1, yi1);
            }
            this._hole_index = this._index_hole_data();
        }
        _index_hole_data() {
            const { min, max } = Math;
            const { data_size } = this;
            const index = new spatial_1.SpatialIndex(data_size);
            for (let i = 0; i < data_size; i++) {
                const xsi = this.xs[i];
                const ysi = this.ys[i];
                if (xsi.length == 0 || ysi.length == 0) {
                    index.add_empty();
                    continue;
                }
                let xi0 = +Infinity;
                let xi1 = -Infinity;
                let yi0 = +Infinity;
                let yi1 = -Infinity;
                for (let j = 0, endj = xsi.length; j < endj; j++) {
                    const xsij = xsi[j];
                    const ysij = ysi[j];
                    if (xsij.length > 1 && ysij.length > 1) {
                        for (let k = 1, endk = xsij.length; k < endk; k++) {
                            const [xij0, xij1, yij0, yij1] = (0, arrayable_1.minmax2)(xsij[k], ysij[k]);
                            xi0 = min(xi0, xij0);
                            xi1 = max(xi1, xij1);
                            yi0 = min(yi0, yij0);
                            yi1 = max(yi1, yij1);
                        }
                    }
                }
                index.add_rect(xi0, yi0, xi1, yi1);
            }
            index.finish();
            return index;
        }
        _mask_data() {
            const { x_source, y_source } = this.renderer.coordinates;
            return this.index.indices({
                x0: x_source.min, x1: x_source.max,
                y0: y_source.min, y1: y_source.max,
            });
        }
        _paint(ctx, indices, data) {
            if (!this.visuals.fill.doit && !this.visuals.line.doit) {
                return;
            }
            const { sxs, sys } = { ...this, ...data };
            for (const i of indices) {
                ctx.beginPath();
                const sx_i = sxs[i];
                const sy_i = sys[i];
                const nj = Math.min(sx_i.length, sy_i.length);
                for (let j = 0; j < nj; j++) {
                    const sx_ij = sx_i[j];
                    const sy_ij = sy_i[j];
                    const nk = Math.min(sx_ij.length, sy_ij.length);
                    for (let k = 0; k < nk; k++) {
                        const sx_ijk = sx_ij[k];
                        const sy_ijk = sy_ij[k];
                        const nl = Math.min(sx_ijk.length, sy_ijk.length);
                        for (let l = 0; l < nl; l++) {
                            const sx_ijkl = sx_ijk[l];
                            const sy_ijkl = sy_ijk[l];
                            if (l == 0) {
                                ctx.moveTo(sx_ijkl, sy_ijkl);
                            }
                            else {
                                ctx.lineTo(sx_ijkl, sy_ijkl);
                            }
                        }
                        ctx.closePath();
                    }
                }
                this.visuals.fill.apply(ctx, i, "evenodd");
                this.visuals.hatch.apply(ctx, i, "evenodd");
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_poly(geometry) {
            const { sx: sxs, sy: sys, greedy = false } = geometry;
            const candidates = (() => {
                const xs = this.renderer.xscale.v_invert(sxs);
                const ys = this.renderer.yscale.v_invert(sys);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const i of candidates) {
                const sxs_i = this.sxs[i];
                const sys_i = this.sys[i];
                let hit = !greedy;
                const nj = sxs_i.length;
                for (let j = 0; j < nj; j++) {
                    const sxs_ij0 = sxs_i[j][0];
                    const sys_ij0 = sys_i[j][0];
                    const nk = sxs_ij0.length;
                    for (let k = 0; k < nk; k++) {
                        const sxs_ij0k = sxs_ij0[k];
                        const sys_ij0k = sys_ij0[k];
                        if (!hittest.point_in_poly(sxs_ij0k, sys_ij0k, sxs, sys)) {
                            if (!greedy) {
                                hit = false;
                                break;
                            }
                        }
                        else {
                            if (greedy) {
                                hit = true;
                                break;
                            }
                        }
                    }
                    if (!greedy) {
                        if (!hit) {
                            break;
                        }
                    }
                    else {
                        if (hit) {
                            break;
                        }
                    }
                }
                if (hit) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1, greedy } = geometry;
            const sxs = [sx0, sx1, sx1, sx0];
            const sys = [sy0, sy0, sy1, sy1];
            return this._hit_poly({ type: "poly", sx: sxs, sy: sys, greedy });
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            const hole_candidates = this._hole_index.indices({ x0: x, y0: y, x1: x, y1: y });
            const indices = [];
            for (const index of candidates) {
                const sxs = this.sxs[index];
                const sys = this.sys[index];
                for (let j = 0, endj = sxs.length; j < endj; j++) {
                    const nk = sxs[j].length;
                    if (hittest.point_in_poly(sx, sy, sxs[j][0], sys[j][0])) {
                        if (nk == 1) {
                            indices.push(index);
                        }
                        else if (!hole_candidates.get(index)) {
                            indices.push(index);
                        }
                        else if (nk > 1) {
                            let in_a_hole = false;
                            for (let k = 1; k < nk; k++) {
                                const sxs_k = sxs[j][k];
                                const sys_k = sys[j][k];
                                if (hittest.point_in_poly(sx, sy, sxs_k, sys_k)) {
                                    in_a_hole = true;
                                    break;
                                }
                                else {
                                    continue;
                                }
                            }
                            if (!in_a_hole) {
                                indices.push(index);
                            }
                        }
                    }
                }
            }
            return new selection_1.Selection({ indices });
        }
        _get_snap_coord(array) {
            return (0, arrayable_2.sum)(array) / array.length;
        }
        scenterxy(i, sx, sy) {
            if (this.sxs[i].length == 1) {
                // We don't have discontinuous objects so we're ok
                const scx = this._get_snap_coord(this.sxs[i][0][0]);
                const scy = this._get_snap_coord(this.sys[i][0][0]);
                return [scx, scy];
            }
            else {
                // We have discontinuous objects, so we need to find which
                // one we're in, we can use point_in_poly again
                const sxs = this.sxs[i];
                const sys = this.sys[i];
                for (let j = 0, end = sxs.length; j < end; j++) {
                    if (hittest.point_in_poly(sx, sy, sxs[j][0], sys[j][0])) {
                        const scx = this._get_snap_coord(sxs[j][0]);
                        const scy = this._get_snap_coord(sys[j][0]);
                        return [scx, scy];
                    }
                }
            }
            (0, assert_1.unreachable)();
        }
        map_data() {
            if (this.inherited_xs && this.inherited_ys) {
                this._inherit_attr("sxs");
                this._inherit_attr("sys");
            }
            else {
                const { xs, ys } = this;
                const n_i = xs.length;
                const sxs = new Array(n_i);
                const sys = new Array(n_i);
                for (let i = 0; i < n_i; i++) {
                    const n_j = xs[i].length;
                    sxs[i] = new Array(n_j);
                    sys[i] = new Array(n_j);
                    for (let j = 0; j < n_j; j++) {
                        const n_k = xs[i][j].length;
                        sxs[i][j] = new Array(n_k);
                        sys[i][j] = new Array(n_k);
                        for (let k = 0; k < n_k; k++) {
                            const [sx, sy] = this.renderer.coordinates.map_to_screen(xs[i][j][k], ys[i][j][k]);
                            sxs[i][j][k] = sx;
                            sys[i][j][k] = sy;
                        }
                    }
                }
                this._define_attr("sxs", sxs);
                this._define_attr("sys", sys);
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.MultiPolygonsView = MultiPolygonsView;
    MultiPolygonsView.__name__ = "MultiPolygonsView";
    class MultiPolygons extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MultiPolygons = MultiPolygons;
    _a = MultiPolygons;
    MultiPolygons.__name__ = "MultiPolygons";
    (() => {
        _a.prototype.default_view = MultiPolygonsView;
        _a.define(({}) => ({
            xs: [p.XCoordinateSeqSeqSeqSpec, { field: "xs" }],
            ys: [p.YCoordinateSeqSeqSeqSpec, { field: "ys" }],
        }));
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
    })();
},
/* models/glyphs/ngon.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const radial_glyph_1 = require(361) /* ./radial_glyph */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const hittest_1 = require(229) /* ../../core/hittest */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(130) /* ../selections/selection */;
    function ngon(x, y, r, n, angle) {
        const xs = new Float32Array(n);
        const ys = new Float32Array(n);
        const alpha_i = 2 * Math.PI / n;
        for (let i = 0; i < n; i++) {
            const alpha = i * alpha_i + angle;
            xs[i] = x + r * Math.sin(alpha);
            ys[i] = y + r * -Math.cos(alpha);
        }
        return [xs, ys];
    }
    class NgonView extends radial_glyph_1.RadialGlyphView {
        async load_glglyph() {
            const { NgonGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(578) /* ./webgl/ngon */));
            return NgonGL;
        }
        _paint(ctx, indices, data) {
            const { sx, sy, sradius, angle, n } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sradius_i = sradius[i];
                const angle_i = angle.get(i);
                const n_i = n.get(i);
                if (n_i < 3 || !isFinite(sx_i + sy_i + sradius_i + angle_i + n_i)) {
                    continue;
                }
                const [sxs, sys] = ngon(sx_i, sy_i, sradius_i, n_i, angle_i);
                ctx.beginPath();
                ctx.moveTo(sxs[0], sys[0]);
                for (let i = 1; i <= n_i; i++) {
                    ctx.lineTo(sxs[i], sys[i]);
                }
                ctx.closePath();
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _ngon(index) {
            const { sx, sy, sradius, angle, n } = { ...this };
            const sx_i = sx[index];
            const sy_i = sy[index];
            const sradius_i = sradius[index];
            const angle_i = angle.get(index);
            const n_i = n.get(index);
            return ngon(sx_i, sy_i, sradius_i, n_i, angle_i);
        }
        _hit_point(geometry) {
            const x = this.renderer.xscale.invert(geometry.sx);
            const y = this.renderer.yscale.invert(geometry.sy);
            const candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            const indices = [];
            for (const index of candidates) {
                const [sxs, sys] = this._ngon(index);
                if ((0, hittest_1.point_in_poly)(geometry.sx, geometry.sy, sxs, sys)) {
                    indices.push(index);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            const { x0, x1, y0, y1 } = this.bounds();
            const [val, dim, candidates] = (() => {
                switch (geometry.direction) {
                    case "v": {
                        const y = this.renderer.yscale.invert(sy);
                        const candidates = this.index.indices({ x0, y0: y, x1, y1: y });
                        return [sy, 1, candidates];
                    }
                    case "h": {
                        const x = this.renderer.xscale.invert(sx);
                        const candidates = this.index.indices({ x0: x, y0, x1: x, y1 });
                        return [sx, 0, candidates];
                    }
                }
            })();
            const indices = [];
            for (const index of candidates) {
                const coords = this._ngon(index)[dim];
                for (let i = 0; i < coords.length - 1; i++) {
                    if ((coords[i] <= val && val <= coords[i + 1]) || (coords[i + 1] <= val && val <= coords[i])) {
                        indices.push(index);
                        break;
                    }
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_poly(geometry) {
            const { sx: gsx, sy: gsy } = geometry;
            const candidates = (() => {
                const xs = this.renderer.xscale.v_invert(gsx);
                const ys = this.renderer.yscale.v_invert(gsy);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const index of candidates) {
                const [sxs, sys] = this._ngon(index);
                if ((0, hittest_1.vertex_overlap)(sxs, sys, gsx, gsy)) {
                    indices.push(index);
                    continue;
                }
                if ((0, hittest_1.edge_intersection)(sxs, sys, gsx, gsy)) {
                    indices.push(index);
                    continue;
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const sxs = [sx0, sx1, sx1, sx0];
            const sys = [sy0, sy0, sy1, sy1];
            return this._hit_poly({ type: "poly", sx: sxs, sy: sys });
        }
    }
    exports.NgonView = NgonView;
    NgonView.__name__ = "NgonView";
    class Ngon extends radial_glyph_1.RadialGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Ngon = Ngon;
    _a = Ngon;
    Ngon.__name__ = "Ngon";
    (() => {
        _a.prototype.default_view = NgonView;
        _a.define(() => ({
            angle: [p.AngleSpec, 0],
            n: [p.NumberSpec, { field: "n" }],
        }));
    })();
},
/* models/glyphs/patches.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const selection_1 = require(130) /* ../selections/selection */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class PatchesView extends glyph_1.GlyphView {
        _project_data() {
            this._project_xy("xs", this.xs.data, "ys", this.ys.data);
        }
        _index_data(index) {
            const { data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const xsi = this.xs.get(i);
                const ysi = this.ys.get(i);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xsi, ysi);
                index.add_rect(x0, y0, x1, y1);
            }
        }
        _mask_data() {
            const { x_source, y_source } = this.renderer.coordinates;
            return this.index.indices({
                x0: x_source.min, x1: x_source.max,
                y0: y_source.min, y1: y_source.max,
            });
        }
        _paint(ctx, indices, data) {
            const { sxs, sys } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sxs.get(i);
                const sy_i = sys.get(i);
                let move = true;
                ctx.beginPath();
                const n = Math.min(sx_i.length, sy_i.length);
                for (let j = 0; j < n; j++) {
                    const sx_j = sx_i[j];
                    const sy_j = sy_i[j];
                    if (!isFinite(sx_j + sy_j)) {
                        ctx.closePath();
                        move = true;
                    }
                    else {
                        if (move) {
                            ctx.moveTo(sx_j, sy_j);
                            move = false;
                        }
                        else {
                            ctx.lineTo(sx_j, sy_j);
                        }
                    }
                }
                ctx.closePath();
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_poly(geometry) {
            const { sx: sxs, sy: sys, greedy = false } = geometry;
            const candidates = (() => {
                const xs = this.renderer.xscale.v_invert(sxs);
                const ys = this.renderer.yscale.v_invert(sys);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const i of candidates) {
                const sxs_i = this.sxs.get(i);
                const sys_i = this.sys.get(i);
                const n = sxs_i.length;
                if (n == 0) {
                    continue;
                }
                let hit = !greedy;
                for (let j = 0; j < n; j++) {
                    const sx = sxs_i[j];
                    const sy = sys_i[j];
                    if (!hittest.point_in_poly(sx, sy, sxs, sys)) {
                        if (!greedy) {
                            hit = false;
                            break;
                        }
                    }
                    else {
                        if (greedy) {
                            hit = true;
                            break;
                        }
                    }
                }
                if (hit) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1, greedy } = geometry;
            const sxs = [sx0, sx1, sx1, sx0];
            const sys = [sy0, sy0, sy1, sy1];
            return this._hit_poly({ type: "poly", sx: sxs, sy: sys, greedy });
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            const candidates = this.index.indices({ x0: x, y0: y, x1: x, y1: y });
            const indices = [];
            for (const index of candidates) {
                const sxsi = this.sxs.get(index);
                const sysi = this.sys.get(index);
                const n = sxsi.length;
                for (let k = 0, j = 0;; j++) {
                    if (isNaN(sxsi[j]) || j == n) {
                        const sxsi_kj = sxsi.subarray(k, j);
                        const sysi_kj = sysi.subarray(k, j);
                        if (hittest.point_in_poly(sx, sy, sxsi_kj, sysi_kj)) {
                            indices.push(index);
                            break;
                        }
                        k = j + 1;
                    }
                    if (j == n) {
                        break;
                    }
                }
            }
            return new selection_1.Selection({ indices });
        }
        _get_snap_coord(array) {
            return (0, arrayable_1.sum)(array) / array.length;
        }
        scenterxy(i, sx, sy) {
            const sxsi = this.sxs.get(i);
            const sysi = this.sys.get(i);
            const n = sxsi.length;
            let has_nan = false;
            for (let k = 0, j = 0;; j++) {
                const this_nan = isNaN(sxsi[j]);
                has_nan = has_nan || this_nan;
                if (j == n && !has_nan) {
                    const scx = this._get_snap_coord(sxsi);
                    const scy = this._get_snap_coord(sysi);
                    return [scx, scy];
                }
                if (this_nan || j == n) {
                    const sxsi_kj = sxsi.subarray(k, j);
                    const sysi_kj = sysi.subarray(k, j);
                    if (hittest.point_in_poly(sx, sy, sxsi_kj, sysi_kj)) {
                        const scx = this._get_snap_coord(sxsi_kj);
                        const scy = this._get_snap_coord(sysi_kj);
                        return [scx, scy];
                    }
                    k = j + 1;
                }
                if (j == n) {
                    break;
                }
            }
            (0, assert_1.unreachable)();
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.PatchesView = PatchesView;
    PatchesView.__name__ = "PatchesView";
    class Patches extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Patches = Patches;
    _a = Patches;
    Patches.__name__ = "Patches";
    (() => {
        _a.prototype.default_view = PatchesView;
        _a.define(({}) => ({
            xs: [p.XCoordinateSeqSpec, { field: "xs" }],
            ys: [p.YCoordinateSeqSpec, { field: "ys" }],
        }));
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
    })();
},
/* models/glyphs/quad.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const lrtb_1 = require(359) /* ./lrtb */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class QuadView extends lrtb_1.LRTBView {
        scenterxy(i) {
            const scx = this.sleft[i] / 2 + this.sright[i] / 2;
            const scy = this.stop[i] / 2 + this.sbottom[i] / 2;
            return [scx, scy];
        }
        _lrtb(i) {
            const l = this.left[i];
            const r = this.right[i];
            const t = this.top[i];
            const b = this.bottom[i];
            return { l, r, t, b };
        }
    }
    exports.QuadView = QuadView;
    QuadView.__name__ = "QuadView";
    class Quad extends lrtb_1.LRTB {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Quad = Quad;
    _a = Quad;
    Quad.__name__ = "Quad";
    (() => {
        _a.prototype.default_view = QuadView;
        _a.define(({}) => ({
            right: [p.XCoordinateSpec, { field: "right" }],
            bottom: [p.YCoordinateSpec, { field: "bottom" }],
            left: [p.XCoordinateSpec, { field: "left" }],
            top: [p.YCoordinateSpec, { field: "top" }],
        }));
    })();
},
/* models/glyphs/quadratic.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const algorithms_1 = require(357) /* ../../core/util/algorithms */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class QuadraticView extends glyph_1.GlyphView {
        _project_data() {
            this._project_xy("x0", this.x0, "y0", this.y0);
            this._project_xy("x1", this.x1, "y1", this.y1);
        }
        _index_data(index) {
            const { x0, x1, y0, y1, cx, cy, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x0_i = x0[i];
                const x1_i = x1[i];
                const y0_i = y0[i];
                const y1_i = y1[i];
                const cx_i = cx[i];
                const cy_i = cy[i];
                if (!isFinite(x0_i + x1_i + y0_i + y1_i + cx_i + cy_i)) {
                    index.add_empty();
                }
                else {
                    const { x0, y0, x1, y1 } = (0, algorithms_1.qbb)(x0_i, y0_i, cx_i, cy_i, x1_i, y1_i);
                    index.add_rect(x0, y0, x1, y1);
                }
            }
        }
        _paint(ctx, indices, data) {
            if (!this.visuals.line.doit) {
                return;
            }
            const { sx0, sy0, sx1, sy1, scx, scy } = { ...this, ...data };
            for (const i of indices) {
                const sx0_i = sx0[i];
                const sy0_i = sy0[i];
                const sx1_i = sx1[i];
                const sy1_i = sy1[i];
                const scx_i = scx[i];
                const scy_i = scy[i];
                if (!isFinite(sx0_i + sy0_i + sx1_i + sy1_i + scx_i + scy_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.moveTo(sx0_i, sy0_i);
                ctx.quadraticCurveTo(scx_i, scy_i, sx1_i, sy1_i);
                this.visuals.line.apply(ctx, i);
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy() {
            throw new Error(`${this}.scenterxy() is not implemented`);
        }
    }
    exports.QuadraticView = QuadraticView;
    QuadraticView.__name__ = "QuadraticView";
    class Quadratic extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Quadratic = Quadratic;
    _a = Quadratic;
    Quadratic.__name__ = "Quadratic";
    (() => {
        _a.prototype.default_view = QuadraticView;
        _a.define(({}) => ({
            x0: [p.XCoordinateSpec, { field: "x0" }],
            y0: [p.YCoordinateSpec, { field: "y0" }],
            x1: [p.XCoordinateSpec, { field: "x1" }],
            y1: [p.YCoordinateSpec, { field: "y1" }],
            cx: [p.XCoordinateSpec, { field: "cx" }],
            cy: [p.YCoordinateSpec, { field: "cy" }],
        }));
        _a.mixins(property_mixins_1.LineVector);
    })();
},
/* models/glyphs/ray.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const property_mixins_1 = require(80) /* ../../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() {
            this._define_or_inherit_attr("slength", () => {
                if (this.model.properties.length.units == "data") {
                    if (this.inherited_x && this.inherited_length) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.length);
                    }
                }
                else {
                    return this.inherited_length ? glyph_1.inherit : (0, types_1.to_screen)(this.length);
                }
            });
            if (!this.inherited_slength) {
                const { width, height } = this.renderer.plot_view.frame.bbox;
                const inf_len = 2 * (width + height);
                const { slength } = this;
                const n = slength.length;
                for (let i = 0; i < n; i++) {
                    if (slength[i] == 0) {
                        slength[i] = inf_len;
                    }
                }
            }
        }
        _paint(ctx, indices, data) {
            if (!this.visuals.line.doit) {
                return;
            }
            const { sx, sy, slength, angle } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const angle_i = angle.get(i);
                const slength_i = slength[i];
                if (!isFinite(sx_i + sy_i + angle_i + slength_i)) {
                    continue;
                }
                ctx.translate(sx_i, sy_i);
                ctx.rotate(angle_i);
                ctx.beginPath();
                ctx.moveTo(0, 0);
                ctx.lineTo(slength_i, 0);
                this.visuals.line.apply(ctx, i);
                ctx.rotate(-angle_i);
                ctx.translate(-sx_i, -sy_i);
            }
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.RayView = RayView;
    RayView.__name__ = "RayView";
    class Ray extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Ray = Ray;
    _a = Ray;
    Ray.__name__ = "Ray";
    (() => {
        _a.prototype.default_view = RayView;
        _a.mixins(property_mixins_1.LineVector);
        _a.define(({}) => ({
            length: [p.DistanceSpec, 0],
            angle: [p.AngleSpec, 0],
        }));
    })();
},
/* models/glyphs/rect.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const center_rotatable_1 = require(363) /* ./center_rotatable */;
    const utils_1 = require(228) /* ./utils */;
    const types_1 = require(24) /* ../../core/types */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const selection_1 = require(130) /* ../selections/selection */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const affine_1 = require(114) /* ../../core/util/affine */;
    const kinds_1 = require(185) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(186) /* ../common/resolve */);
    const painting_1 = require(187) /* ../common/painting */;
    const { abs, sqrt } = Math;
    class RectView extends center_rotatable_1.CenterRotatableView {
        async load_glglyph() {
            const { RectGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(579) /* ./webgl/rect */));
            return RectGL;
        }
        _set_data(indices) {
            super._set_data(indices);
            this.border_radius = resolve.border_radius(this.model.border_radius);
        }
        _map_data() {
            const n = this.data_size;
            if (this.inherited_x && this.inherited_width) {
                this._inherit_attr("swidth");
                this._inherit_attr("sx0");
            }
            else {
                let swidth;
                let sx0;
                if (this.model.properties.width.units == "data") {
                    [swidth, sx0] = this._map_dist_corner_for_data_side_length(this.x, this.width, this.renderer.xscale);
                }
                else {
                    swidth = (0, types_1.to_screen)(this.width);
                    sx0 = new types_1.ScreenArray(n);
                    const { sx } = this;
                    for (let i = 0; i < n; i++) {
                        sx0[i] = sx[i] - swidth[i] / 2;
                    }
                }
                this._define_attr("swidth", swidth);
                this._define_attr("sx0", sx0);
            }
            if (this.inherited_y && this.inherited_height) {
                this._inherit_attr("sheight");
                this._inherit_attr("sy1");
            }
            else {
                let sheight;
                let sy1;
                if (this.model.properties.height.units == "data") {
                    [sheight, sy1] = this._map_dist_corner_for_data_side_length(this.y, this.height, this.renderer.yscale);
                }
                else {
                    sheight = (0, types_1.to_screen)(this.height);
                    sy1 = new types_1.ScreenArray(n);
                    const { sy } = this;
                    for (let i = 0; i < n; i++) {
                        sy1[i] = sy[i] - sheight[i] / 2;
                    }
                }
                this._define_attr("sheight", sheight);
                this._define_attr("sy1", sy1);
            }
            if (this.inherited_swidth && this.inherited_sheight) {
                this._inherit_attr("max_x2_ddist");
                this._inherit_attr("max_y2_ddist");
            }
            else {
                const { sx0, sy1, swidth, sheight } = this;
                const ssemi_diag = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    const swidth_i = swidth[i];
                    const sheight_i = sheight[i];
                    ssemi_diag[i] = sqrt(swidth_i ** 2 + sheight_i ** 2) / 2;
                }
                const scenter_x = new types_1.ScreenArray(n);
                const scenter_y = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    scenter_x[i] = sx0[i] + swidth[i] / 2;
                    scenter_y[i] = sy1[i] + sheight[i] / 2;
                }
                const max_x2_ddist = (0, arrayable_1.max)(this._ddist(0, scenter_x, ssemi_diag));
                const max_y2_ddist = (0, arrayable_1.max)(this._ddist(1, scenter_y, ssemi_diag));
                this._define_attr("max_x2_ddist", max_x2_ddist);
                this._define_attr("max_y2_ddist", max_y2_ddist);
            }
        }
        _paint(ctx, indices, data) {
            const { sx, sy, sx0, sy1, swidth, sheight, angle, border_radius } = { ...this, ...data };
            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 swidth_i = swidth[i];
                const sheight_i = sheight[i];
                const angle_i = angle.get(i);
                if (!isFinite(sx_i + sy_i + sx0_i + sy1_i + swidth_i + sheight_i + angle_i)) {
                    continue;
                }
                if (swidth_i == 0 || sheight_i == 0) {
                    continue;
                }
                ctx.beginPath();
                if (angle_i != 0) {
                    ctx.translate(sx_i, sy_i);
                    ctx.rotate(angle_i);
                    const box = new bbox_1.BBox({ x: -swidth_i / 2, y: -sheight_i / 2, width: swidth_i, height: sheight_i });
                    (0, painting_1.round_rect)(ctx, box, border_radius);
                    ctx.rotate(-angle_i);
                    ctx.translate(-sx_i, -sy_i);
                }
                else {
                    const box = new bbox_1.BBox({ x: sx0_i, y: sy1_i, width: swidth_i, height: sheight_i });
                    (0, painting_1.round_rect)(ctx, box, border_radius);
                }
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_rect(geometry) {
            return this._hit_rect_against_index(geometry);
        }
        _hit_point(geometry) {
            const hit_xy = { x: geometry.sx, y: geometry.sy };
            const x = this.renderer.xscale.invert(hit_xy.x);
            const y = this.renderer.yscale.invert(hit_xy.y);
            const candidates = this.index.indices({
                x0: x - this.max_x2_ddist,
                x1: x + this.max_x2_ddist,
                y0: y - this.max_y2_ddist,
                y1: y + this.max_y2_ddist,
            });
            const { sx, sy, sx0, sy1, swidth: sw, sheight: sh, angle } = this;
            const indices = [];
            for (const i of candidates) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sx0_i = sx0[i];
                const sy1_i = sy1[i];
                const sw_i = sw[i];
                const sh_i = sh[i];
                const angle_i = angle.get(i);
                const hit_rxy = (0, affine_1.rotate_around)(hit_xy, { x: sx_i, y: sy_i }, -angle_i);
                const x = hit_rxy.x - sx0_i;
                const y = hit_rxy.y - sy1_i;
                // TODO: consider round corners
                if (0 <= x && x <= sw_i && 0 <= y && y <= sh_i) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _map_dist_corner_for_data_side_length(coord, side_length, scale) {
            const n = coord.length;
            const pt0 = new Float64Array(n);
            const pt1 = new Float64Array(n);
            for (let i = 0; i < n; i++) {
                const coord_i = coord[i];
                const half_side_length_i = side_length.get(i) / 2;
                pt0[i] = coord_i - half_side_length_i;
                pt1[i] = coord_i + half_side_length_i;
            }
            const spt0 = scale.v_compute(pt0);
            const spt1 = scale.v_compute(pt1);
            const sside_length = this.sdist(scale, pt0, side_length, "edge", this.model.dilate);
            let spt_corner = spt0;
            for (let i = 0; i < n; i++) {
                const spt0i = spt0[i];
                const spt1i = spt1[i];
                if (!isNaN(spt0i + spt1i) && spt0i != spt1i) {
                    spt_corner = spt0i < spt1i ? spt0 : spt1;
                    break;
                }
            }
            return [sside_length, spt_corner];
        }
        _ddist(dim, spts, spans) {
            const ArrayType = (0, types_1.infer_type)(spts, spans);
            const scale = dim == 0 ? this.renderer.xscale : this.renderer.yscale;
            const spt0 = spts;
            const m = spt0.length;
            const spt1 = new ArrayType(m);
            for (let i = 0; i < m; i++) {
                spt1[i] = spt0[i] + spans[i];
            }
            const pt0 = scale.v_invert(spt0);
            const pt1 = scale.v_invert(spt1);
            const n = pt0.length;
            const ddist = new ArrayType(n);
            for (let i = 0; i < n; i++) {
                ddist[i] = abs(pt1[i] - pt0[i]);
            }
            return ddist;
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.RectView = RectView;
    RectView.__name__ = "RectView";
    class Rect extends center_rotatable_1.CenterRotatable {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Rect = Rect;
    _a = Rect;
    Rect.__name__ = "Rect";
    (() => {
        _a.prototype.default_view = RectView;
        _a.define(({ Bool }) => ({
            border_radius: [kinds_1.BorderRadius, 0],
            dilate: [Bool, false],
        }));
    })();
},
/* models/glyphs/scatter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const marker_1 = require(385) /* ./marker */;
    const defs_1 = require(386) /* ./defs */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class ScatterView extends marker_1.MarkerView {
        async load_glglyph() {
            const { MultiMarkerGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(577) /* ./webgl/multi_marker */));
            return MultiMarkerGL;
        }
        _paint(ctx, indices, data) {
            const { sx, sy, size, angle, marker } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const size_i = size.get(i);
                const angle_i = angle.get(i);
                const marker_i = marker.get(i);
                if (!isFinite(sx_i + sy_i + size_i + angle_i) || marker_i == null) {
                    continue;
                }
                const r = size_i / 2;
                ctx.beginPath();
                ctx.translate(sx_i, sy_i);
                if (angle_i != 0) {
                    ctx.rotate(angle_i);
                }
                defs_1.marker_funcs[marker_i](ctx, i, r, this.visuals);
                if (angle_i != 0) {
                    ctx.rotate(-angle_i);
                }
                ctx.translate(-sx_i, -sy_i);
            }
        }
        draw_legend_for_index(ctx, { x0, x1, y0, y1 }, index) {
            const n = index + 1;
            const marker = this.marker.get(index);
            const args = {
                ...this._get_legend_args({ x0, x1, y0, y1 }, index),
                marker: new p.UniformScalar(marker, n),
            };
            this._paint(ctx, [index], args);
        }
    }
    exports.ScatterView = ScatterView;
    ScatterView.__name__ = "ScatterView";
    class Scatter extends marker_1.Marker {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Scatter = Scatter;
    _a = Scatter;
    Scatter.__name__ = "Scatter";
    (() => {
        _a.prototype.default_view = ScatterView;
        _a.define(() => ({
            marker: [p.MarkerSpec, { value: "circle" }],
        }));
    })();
},
/* models/glyphs/marker.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const selection_1 = require(130) /* ../selections/selection */;
    class MarkerView extends xy_glyph_1.XYGlyphView {
        _paint(ctx, indices, data) {
            const { sx, sy, size, angle } = { ...this, ...data };
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const size_i = size.get(i);
                const angle_i = angle.get(i);
                if (!isFinite(sx_i + sy_i + size_i + angle_i)) {
                    continue;
                }
                const r = size_i / 2;
                ctx.beginPath();
                ctx.translate(sx_i, sy_i);
                if (angle_i != 0) {
                    ctx.rotate(angle_i);
                }
                this._render_one(ctx, i, r, this.visuals);
                if (angle_i != 0) {
                    ctx.rotate(-angle_i);
                }
                ctx.translate(-sx_i, -sy_i);
            }
        }
        _mask_data() {
            // dilate the inner screen region by max_size and map back to data space for use in spatial query
            const { x_target, y_target } = this.renderer.plot_view.frame;
            const hr = x_target.widen(this.max_size).map((x) => this.renderer.xscale.invert(x));
            const vr = y_target.widen(this.max_size).map((y) => this.renderer.yscale.invert(y));
            return this.index.indices({
                x0: hr.start, x1: hr.end,
                y0: vr.start, y1: vr.end,
            });
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const { max_size } = this;
            const { hit_dilation } = this.model;
            const sx0 = sx - max_size * hit_dilation;
            const sx1 = sx + max_size * hit_dilation;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const sy0 = sy - max_size * hit_dilation;
            const sy1 = sy + max_size * hit_dilation;
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const candidates = this.index.indices({ x0, x1, y0, y1 });
            const indices = [];
            for (const i of candidates) {
                const s2 = this.size.get(i) / 2 * hit_dilation;
                if (Math.abs(this.sx[i] - sx) <= s2 && Math.abs(this.sy[i] - sy) <= s2) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const { sx, sy } = geometry;
            const bounds = this.bounds();
            const half_size = this.max_size / 2;
            const [x0, x1, y0, y1] = (() => {
                if (geometry.direction == "h") {
                    const { y0, y1 } = bounds;
                    const sx0 = sx - half_size;
                    const sx1 = sx + half_size;
                    const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
                    return [x0, x1, y0, y1];
                }
                else {
                    const { x0, x1 } = bounds;
                    const sy0 = sy - half_size;
                    const sy1 = sy + half_size;
                    const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
                    return [x0, x1, y0, y1];
                }
            })();
            const indices = [...this.index.indices({ x0, x1, y0, y1 })];
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const { sx0, sx1, sy0, sy1 } = geometry;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const indices = [...this.index.indices({ x0, x1, y0, y1 })];
            return new selection_1.Selection({ indices });
        }
        _hit_poly(geometry) {
            const { sx: sxs, sy: sys } = geometry;
            const candidates = (() => {
                const xs = this.renderer.xscale.v_invert(sxs);
                const ys = this.renderer.yscale.v_invert(sys);
                const [x0, x1, y0, y1] = (0, arrayable_1.minmax2)(xs, ys);
                return this.index.indices({ x0, x1, y0, y1 });
            })();
            const indices = [];
            for (const i of candidates) {
                if (hittest.point_in_poly(this.sx[i], this.sy[i], sxs, sys)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _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._paint(ctx, [index], args);
        }
    }
    exports.MarkerView = MarkerView;
    MarkerView.__name__ = "MarkerView";
    class Marker extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Marker = Marker;
    _a = Marker;
    Marker.__name__ = "Marker";
    (() => {
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(({ Float }) => ({
            size: [p.ScreenSizeSpec, { value: 4 }],
            angle: [p.AngleSpec, 0],
            hit_dilation: [Float, 1.0],
        }));
    })();
},
/* models/glyphs/defs.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const SQ3 = Math.sqrt(3);
    const SQ5 = Math.sqrt(5);
    const c36 = (SQ5 + 1) / 4;
    const s36 = Math.sqrt((5 - SQ5) / 8);
    const c72 = (SQ5 - 1) / 4;
    const s72 = Math.sqrt((5 + SQ5) / 8);
    function _one_line(ctx, r) {
        ctx.moveTo(-r, 0);
        ctx.lineTo(r, 0);
    }
    function _one_x(ctx, r) {
        ctx.rotate(Math.PI / 4);
        _one_cross(ctx, r);
        ctx.rotate(-Math.PI / 4);
    }
    function _one_y(ctx, r) {
        const h = r * SQ3;
        const a = h / 3;
        ctx.moveTo(-h / 2, -a);
        ctx.lineTo(0, 0);
        ctx.lineTo(h / 2, -a);
        ctx.lineTo(0, 0);
        ctx.lineTo(0, r);
    }
    function _one_cross(ctx, r) {
        ctx.moveTo(0, r);
        ctx.lineTo(0, -r);
        ctx.moveTo(-r, 0);
        ctx.lineTo(r, 0);
    }
    function _one_dot(ctx, r) {
        ctx.beginPath();
        ctx.arc(0, 0, r / 4, 0, 2 * Math.PI, false);
        ctx.closePath();
    }
    function _one_diamond(ctx, r) {
        ctx.moveTo(0, r);
        ctx.lineTo(r / 1.5, 0);
        ctx.lineTo(0, -r);
        ctx.lineTo(-r / 1.5, 0);
        ctx.closePath();
    }
    function _one_hex(ctx, r) {
        const r2 = r / 2;
        const h = SQ3 * r2;
        ctx.moveTo(r, 0);
        ctx.lineTo(r2, -h);
        ctx.lineTo(-r2, -h);
        ctx.lineTo(-r, 0);
        ctx.lineTo(-r2, h);
        ctx.lineTo(r2, h);
        ctx.closePath();
    }
    function _one_star(ctx, r) {
        const a = Math.sqrt(5 - 2 * SQ5) * r;
        ctx.moveTo(0, -r);
        ctx.lineTo(a * c72, -r + a * s72);
        ctx.lineTo(a * (1 + c72), -r + a * s72);
        ctx.lineTo(a * (1 + c72 - c36), -r + a * (s72 + s36));
        ctx.lineTo(a * (1 + 2 * c72 - c36), -r + a * (2 * s72 + s36));
        ctx.lineTo(0, -r + a * 2 * s72);
        ctx.lineTo(-a * (1 + 2 * c72 - c36), -r + a * (2 * s72 + s36));
        ctx.lineTo(-a * (1 + c72 - c36), -r + a * (s72 + s36));
        ctx.lineTo(-a * (1 + c72), -r + a * s72);
        ctx.lineTo(-a * c72, -r + a * s72);
        ctx.closePath();
    }
    function _one_tri(ctx, r) {
        const h = r * SQ3;
        const a = h / 3;
        ctx.moveTo(-r, a);
        ctx.lineTo(r, a);
        ctx.lineTo(0, a - h);
        ctx.closePath();
    }
    function asterisk(ctx, i, r, visuals) {
        _one_cross(ctx, r);
        _one_x(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function circle(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function circle_cross(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        _one_cross(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function circle_dot(ctx, i, r, visuals) {
        circle(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function circle_y(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        _one_y(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function circle_x(ctx, i, r, visuals) {
        ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        _one_x(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function cross(ctx, i, r, visuals) {
        _one_cross(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function diamond(ctx, i, r, visuals) {
        _one_diamond(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function diamond_cross(ctx, i, r, visuals) {
        _one_diamond(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        ctx.moveTo(0, r);
        ctx.lineTo(0, -r);
        ctx.moveTo(-r / 1.5, 0);
        ctx.lineTo(r / 1.5, 0);
        visuals.line.apply(ctx, i);
    }
    function diamond_dot(ctx, i, r, visuals) {
        diamond(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function dot(ctx, i, r, visuals) {
        _one_dot(ctx, r);
        visuals.line.set_vectorize(ctx, i);
        ctx.fillStyle = ctx.strokeStyle; // NOTE: dots use line color for fill to match
        ctx.fill();
    }
    function hex(ctx, i, r, visuals) {
        _one_hex(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function hex_dot(ctx, i, r, visuals) {
        hex(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function inverted_triangle(ctx, i, r, visuals) {
        ctx.rotate(Math.PI);
        _one_tri(ctx, r);
        ctx.rotate(-Math.PI);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function plus(ctx, i, r, visuals) {
        const a = 3 * r / 8;
        const b = r;
        const xs = [a, a, b, b, a, a, -a, -a, -b, -b, -a, -a];
        const ys = [b, a, a, -a, -a, -b, -b, -a, -a, a, a, b];
        ctx.beginPath();
        for (let j = 0; j < 12; j++) {
            ctx.lineTo(xs[j], ys[j]);
        }
        ctx.closePath();
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function square(ctx, i, r, visuals) {
        const size = 2 * r;
        ctx.rect(-r, -r, size, size);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function square_pin(ctx, i, r, visuals) {
        const a = 3 * r / 8;
        ctx.moveTo(-r, -r);
        /* eslint-disable space-in-parens */
        ctx.quadraticCurveTo(0, -a, r, -r);
        ctx.quadraticCurveTo(a, 0, r, r);
        ctx.quadraticCurveTo(0, a, -r, r);
        ctx.quadraticCurveTo(-a, 0, -r, -r);
        /* eslint-ensable space-in-parens */
        ctx.closePath();
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function square_cross(ctx, i, r, visuals) {
        const size = 2 * r;
        ctx.rect(-r, -r, size, size);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        _one_cross(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function square_dot(ctx, i, r, visuals) {
        square(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function square_x(ctx, i, r, visuals) {
        const size = 2 * r;
        ctx.rect(-r, -r, size, size);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        ctx.moveTo(-r, r);
        ctx.lineTo(r, -r);
        ctx.moveTo(-r, -r);
        ctx.lineTo(r, r);
        visuals.line.apply(ctx, i);
    }
    function star(ctx, i, r, visuals) {
        _one_star(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function star_dot(ctx, i, r, visuals) {
        star(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function triangle(ctx, i, r, visuals) {
        _one_tri(ctx, r);
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function triangle_dot(ctx, i, r, visuals) {
        triangle(ctx, i, r, visuals);
        dot(ctx, i, r, visuals);
    }
    function triangle_pin(ctx, i, r, visuals) {
        const h = r * SQ3;
        const a = h / 3;
        const b = 3 * a / 8;
        ctx.moveTo(-r, a);
        ctx.quadraticCurveTo(0, b, r, a);
        ctx.quadraticCurveTo(SQ3 * b / 2, b / 2, 0, a - h);
        ctx.quadraticCurveTo(-SQ3 * b / 2, b / 2, -r, a);
        ctx.closePath();
        visuals.fill.apply(ctx, i);
        visuals.hatch.apply(ctx, i);
        visuals.line.apply(ctx, i);
    }
    function dash(ctx, i, r, visuals) {
        _one_line(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function x(ctx, i, r, visuals) {
        _one_x(ctx, r);
        visuals.line.apply(ctx, i);
    }
    function y(ctx, i, r, visuals) {
        _one_y(ctx, r);
        visuals.line.apply(ctx, i);
    }
    exports.marker_funcs = {
        asterisk,
        circle,
        circle_cross,
        circle_dot,
        circle_y,
        circle_x,
        cross,
        diamond,
        diamond_dot,
        diamond_cross,
        dot,
        hex,
        hex_dot,
        inverted_triangle,
        plus,
        square,
        square_cross,
        square_dot,
        square_pin,
        square_x,
        star,
        star_dot,
        triangle,
        triangle_dot,
        triangle_pin,
        dash,
        x,
        y,
    };
},
/* models/glyphs/segment.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const hittest = tslib_1.__importStar(require(229) /* ../../core/hittest */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const math_1 = require(11) /* ../../core/util/math */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const selection_1 = require(130) /* ../selections/selection */;
    class SegmentView extends glyph_1.GlyphView {
        _project_data() {
            this._project_xy("x0", this.x0, "y0", this.y0);
            this._project_xy("x1", this.x1, "y1", 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_i = x0[i];
                const x1_i = x1[i];
                const y0_i = y0[i];
                const y1_i = y1[i];
                index.add_rect(min(x0_i, x1_i), min(y0_i, y1_i), max(x0_i, x1_i), max(y0_i, y1_i));
            }
        }
        _paint(ctx, indices, data) {
            if (!this.visuals.line.doit) {
                return;
            }
            const { sx0, sy0, sx1, sy1 } = { ...this, ...data };
            for (const i of indices) {
                const sx0_i = sx0[i];
                const sy0_i = sy0[i];
                const sx1_i = sx1[i];
                const sy1_i = sy1[i];
                if (!isFinite(sx0_i + sy0_i + sx1_i + sy1_i)) {
                    continue;
                }
                this._render_decorations(ctx, i, sx0_i, sy0_i, sx1_i, sy1_i);
                ctx.beginPath();
                ctx.moveTo(sx0_i, sy0_i);
                ctx.lineTo(sx1_i, sy1_i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _render_decorations(ctx, i, sx0, sy0, sx1, sy1) {
            const { PI } = Math;
            const angle = (0, math_1.atan2)([sx0, sy0], [sx1, sy1]) + PI / 2;
            for (const decoration of this.decorations.values()) {
                ctx.save();
                if (decoration.model.node == "start") {
                    ctx.translate(sx0, sy0);
                    ctx.rotate(angle + PI);
                }
                else if (decoration.model.node == "end") {
                    ctx.translate(sx1, sy1);
                    ctx.rotate(angle);
                }
                decoration.marking.paint(ctx, i);
                ctx.restore();
            }
        }
        _hit_point(geometry) {
            const { sx, sy } = geometry;
            const point = { x: sx, y: sy };
            const lw_voffset = 2; // FIXME: Use maximum of segments line_width/2 instead of magic constant 2
            const [x0, x1] = this.renderer.xscale.r_invert(sx - lw_voffset, sx + lw_voffset);
            const [y0, y1] = this.renderer.yscale.r_invert(sy - lw_voffset, sy + lw_voffset);
            const candidates = this.index.indices({ x0, y0, x1, y1 });
            const indices = [];
            for (const i of candidates) {
                const threshold2 = Math.max(2, this.line_width.get(i) / 2) ** 2;
                const p0 = { x: this.sx0[i], y: this.sy0[i] };
                const p1 = { x: this.sx1[i], y: this.sy1[i] };
                const dist2 = hittest.dist_to_segment_squared(point, p0, p1);
                if (dist2 < threshold2) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const [hr, vr] = this.renderer.plot_view.frame.bbox.ranges;
            const { sx, sy } = geometry;
            let v0;
            let v1;
            let val;
            if (geometry.direction == "v") {
                val = this.renderer.yscale.invert(sy);
                [v0, v1] = [this.y0, this.y1];
            }
            else {
                val = this.renderer.xscale.invert(sx);
                [v0, v1] = [this.x0, this.x1];
            }
            const indices = [];
            const [x0, x1] = this.renderer.xscale.r_invert(hr.start, hr.end);
            const [y0, y1] = this.renderer.yscale.r_invert(vr.start, vr.end);
            const candidates = this.index.indices({ x0, y0, x1, y1 });
            for (const i of candidates) {
                if ((v0[i] <= val && val <= v1[i]) || (v1[i] <= val && val <= v0[i])) {
                    indices.push(i);
                }
                const threshold = 1.5 + (this.line_width.get(i) / 2); // Maximum pixel difference to detect hit
                if (v0[i] == v1[i]) {
                    if (geometry.direction == "h") {
                        if (Math.abs(this.sx0[i] - sx) <= threshold) {
                            indices.push(i);
                        }
                    }
                    else {
                        if (Math.abs(this.sy0[i] - sy) <= threshold) {
                            indices.push(i);
                        }
                    }
                }
            }
            return new selection_1.Selection({ indices });
        }
        scenterxy(i) {
            const scx = this.sx0[i] / 2 + this.sx1[i] / 2;
            const scy = this.sy0[i] / 2 + this.sy1[i] / 2;
            return [scx, scy];
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.SegmentView = SegmentView;
    SegmentView.__name__ = "SegmentView";
    class Segment extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Segment = Segment;
    _a = Segment;
    Segment.__name__ = "Segment";
    (() => {
        _a.prototype.default_view = SegmentView;
        _a.define(({}) => ({
            x0: [p.XCoordinateSpec, { field: "x0" }],
            y0: [p.YCoordinateSpec, { field: "y0" }],
            x1: [p.XCoordinateSpec, { field: "x1" }],
            y1: [p.YCoordinateSpec, { field: "y1" }],
        }));
        _a.mixins(property_mixins_1.LineVector);
    })();
},
/* models/glyphs/spline.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const interpolation_1 = require(389) /* ../../core/util/interpolation */;
    class SplineView extends xy_glyph_1.XYGlyphView {
        _set_data() {
            const { tension, closed } = this.model;
            const [xt, yt] = (0, interpolation_1.catmullrom_spline)(this.x, this.y, 20, tension, closed);
            this._define_attr("xt", xt);
            this._define_attr("yt", yt);
        }
        _map_data() {
            const { x_scale, y_scale } = this.renderer.coordinates;
            const sxt = x_scale.v_compute(this.xt);
            const syt = y_scale.v_compute(this.yt);
            this._define_attr("sxt", sxt);
            this._define_attr("syt", syt);
        }
        _paint(ctx, _indices, data) {
            const { sxt, syt } = { ...this, ...data };
            let move = true;
            ctx.beginPath();
            const n = sxt.length;
            for (let j = 0; j < n; j++) {
                const sx_i = sxt[j];
                const sy_i = syt[j];
                if (!isFinite(sx_i + sy_i)) {
                    move = true;
                }
                else {
                    if (move) {
                        ctx.moveTo(sx_i, sy_i);
                        move = false;
                    }
                    else {
                        ctx.lineTo(sx_i, sy_i);
                    }
                }
            }
            this.visuals.line.set_value(ctx);
            ctx.stroke();
        }
    }
    exports.SplineView = SplineView;
    SplineView.__name__ = "SplineView";
    class Spline extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Spline = Spline;
    _a = Spline;
    Spline.__name__ = "Spline";
    (() => {
        _a.prototype.default_view = SplineView;
        _a.mixins(mixins.LineScalar);
        _a.define(({ Bool, Float }) => ({
            tension: [Float, 0.5],
            closed: [Bool, false],
        }));
    })();
},
/* core/util/interpolation.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.catmullrom_spline = catmullrom_spline;
    const types_1 = require(24) /* ../types */;
    const assert_1 = require(12) /* ./assert */;
    function catmullrom_spline(x, y, T = 10, tension = 0.5, closed = false) {
        /** Centripetal Catmull-Rom spline. */
        (0, assert_1.assert)(x.length == y.length);
        const n = x.length;
        const N = closed ? n + 1 : n;
        const ArrayType = (0, types_1.infer_type)(x, y);
        const xx = new ArrayType(N + 2);
        const yy = new ArrayType(N + 2);
        xx.set(x, 1);
        yy.set(y, 1);
        if (closed) {
            xx[0] = x[n - 1];
            yy[0] = y[n - 1];
            xx[N] = x[0];
            yy[N] = y[0];
            xx[N + 1] = x[1];
            yy[N + 1] = y[1];
        }
        else {
            xx[0] = x[0];
            yy[0] = y[0];
            xx[N + 1] = x[n - 1];
            yy[N + 1] = y[n - 1];
        }
        const basis = new ArrayType(4 * (T + 1));
        for (let j = 0, k = 0; j <= T; j++) {
            const t = j / T;
            const t_2 = t ** 2;
            const t_3 = t * t_2;
            basis[k++] = 2 * t_3 - 3 * t_2 + 1; // h00
            basis[k++] = -2 * t_3 + 3 * t_2; // h01
            basis[k++] = t_3 - 2 * t_2 + t; // h10
            basis[k++] = t_3 - t_2; // h11
        }
        const xt = new ArrayType((N - 1) * (T + 1));
        const yt = new ArrayType((N - 1) * (T + 1));
        for (let i = 1, k = 0; i < N; i++) {
            const t0x = (xx[i + 1] - xx[i - 1]) * tension;
            const t0y = (yy[i + 1] - yy[i - 1]) * tension;
            const t1x = (xx[i + 2] - xx[i]) * tension;
            const t1y = (yy[i + 2] - yy[i]) * tension;
            for (let j = 0; j <= 4 * T; k++) {
                const h00 = basis[j++];
                const h01 = basis[j++];
                const h10 = basis[j++];
                const h11 = basis[j++];
                xt[k] = h00 * xx[i] + h01 * xx[i + 1] + h10 * t0x + h11 * t1x;
                yt[k] = h00 * yy[i] + h01 * yy[i + 1] + h10 * t0y + h11 * t1y;
            }
        }
        return [xt, yt];
    }
},
/* models/glyphs/step.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const utils_1 = require(228) /* ./utils */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const enums_1 = require(20) /* ../../core/enums */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class StepView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { StepGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(580) /* ./webgl/step */));
            return StepGL;
        }
        _paint(ctx, indices, data) {
            const npoints = indices.length;
            if (npoints < 2) {
                return;
            }
            const { sx, sy } = { ...this, ...data };
            const mode = this.model.mode;
            this.visuals.line.set_value(ctx);
            let drawing = false;
            let prev_finite = false;
            const i = indices[0];
            let is_finite = isFinite(sx[i] + sy[i]);
            if (mode == "center") {
                drawing = this._render_xy(ctx, drawing, is_finite ? sx[i] : NaN, sy[i]);
            }
            for (const i of indices) {
                const next_finite = isFinite(sx[i + 1] + sy[i + 1]);
                switch (mode) {
                    case "before":
                        drawing = this._render_xy(ctx, drawing, is_finite ? sx[i] : NaN, sy[i]);
                        if (i < sx.length - 1) {
                            drawing = this._render_xy(ctx, drawing, is_finite && next_finite ? sx[i] : NaN, sy[i + 1]);
                        }
                        break;
                    case "after":
                        drawing = this._render_xy(ctx, drawing, is_finite ? sx[i] : NaN, sy[i]);
                        if (i < sx.length - 1) {
                            drawing = this._render_xy(ctx, drawing, is_finite && next_finite ? sx[i + 1] : NaN, sy[i]);
                        }
                        break;
                    case "center":
                        if (is_finite && next_finite) {
                            const midx = (sx[i] + sx[i + 1]) / 2;
                            drawing = this._render_xy(ctx, drawing, midx, sy[i]);
                            drawing = this._render_xy(ctx, drawing, midx, sy[i + 1]);
                        }
                        else {
                            if (prev_finite) {
                                drawing = this._render_xy(ctx, drawing, is_finite ? sx[i] : NaN, sy[i]);
                            }
                            drawing = this._render_xy(ctx, drawing, next_finite ? sx[i + 1] : NaN, sy[i + 1]);
                        }
                        break;
                    default:
                        (0, assert_1.unreachable)();
                }
                prev_finite = is_finite;
                is_finite = next_finite;
            }
            if (drawing) {
                const i = indices[npoints - 1];
                if (this._render_xy(ctx, drawing, is_finite ? sx[i] : NaN, sy[i])) {
                    ctx.stroke();
                }
            }
        }
        _render_xy(ctx, drawing, x, y) {
            if (isFinite(x + y)) {
                if (drawing) {
                    // Continue with current line
                    ctx.lineTo(x, y);
                }
                else {
                    // Start new line
                    ctx.beginPath();
                    ctx.moveTo(x, y);
                    drawing = true;
                }
            }
            else if (drawing) {
                // End current line
                ctx.stroke();
                drawing = false;
            }
            return drawing;
        }
        draw_legend_for_index(ctx, bbox, _index) {
            (0, utils_1.generic_line_scalar_legend)(this.visuals, ctx, bbox);
        }
    }
    exports.StepView = StepView;
    StepView.__name__ = "StepView";
    class Step extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Step = Step;
    _a = Step;
    Step.__name__ = "Step";
    (() => {
        _a.prototype.default_view = StepView;
        _a.mixins(mixins.LineScalar);
        _a.define(() => ({
            mode: [enums_1.StepMode, "before"],
        }));
    })();
},
/* models/glyphs/tex_glyph.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const math_text_glyph_1 = require(374) /* ./math_text_glyph */;
    const math_text_1 = require(178) /* ../text/math_text */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const utils_1 = require(177) /* ../text/utils */;
    exports.DisplayMode = (0, kinds_1.Or)((0, kinds_1.Enum)("inline", "block"), kinds_1.Auto);
    class TeXGlyphView extends math_text_glyph_1.MathTextGlyphView {
        _build_label(text) {
            const { macros, display } = this.model;
            if (display == "auto") {
                const obj = (0, utils_1.parse_delimited_string)(text);
                if (obj instanceof math_text_1.TeX) {
                    obj.macros = macros;
                }
                return obj;
            }
            else {
                return new math_text_1.TeX({ text, macros, inline: display == "inline" });
            }
        }
    }
    exports.TeXGlyphView = TeXGlyphView;
    TeXGlyphView.__name__ = "TeXGlyphView";
    class TeXGlyph extends math_text_glyph_1.MathTextGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TeXGlyph = TeXGlyph;
    _a = TeXGlyph;
    TeXGlyph.__name__ = "TeXGlyph";
    (() => {
        _a.prototype.default_view = TeXGlyphView;
        _a.define(({ Float, Str, Dict, Tuple, Or }) => ({
            macros: [Dict(Or(Str, Tuple(Str, Float))), {}],
            display: [exports.DisplayMode, "auto"],
        }));
    })();
},
/* models/glyphs/vbar.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const lrtb_1 = require(359) /* ./lrtb */;
    const types_1 = require(24) /* ../../core/types */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    class VBarView extends lrtb_1.LRTBView {
        scenterxy(i) {
            const scx = this.sx[i];
            const scy = (this.stop[i] + this.sbottom[i]) / 2;
            return [scx, scy];
        }
        _lrtb(i) {
            const half_width_i = this.width.get(i) / 2;
            const x_i = this.x[i];
            const top_i = this.top[i];
            const bottom_i = this.bottom[i];
            const l = x_i - half_width_i;
            const r = x_i + half_width_i;
            const t = Math.max(top_i, bottom_i);
            const b = Math.min(top_i, bottom_i);
            return { l, r, t, b };
        }
        _map_data() {
            if (this.inherited_x && this.inherited_width) {
                this._inherit_attr("swidth");
                this._inherit_attr("sleft");
                this._inherit_attr("sright");
            }
            else {
                const swidth = this.sdist(this.renderer.xscale, this.x, this.width, "center");
                const { sx } = this;
                const n = sx.length;
                const sleft = new types_1.ScreenArray(n);
                const sright = new types_1.ScreenArray(n);
                for (let i = 0; i < n; i++) {
                    const sx_i = sx[i];
                    const swidth_i = swidth[i];
                    sleft[i] = sx_i - swidth_i / 2;
                    sright[i] = sx_i + swidth_i / 2;
                }
                this._define_attr("swidth", swidth);
                this._define_attr("sleft", sleft);
                this._define_attr("sright", sright);
            }
            this._clamp_to_viewport();
        }
    }
    exports.VBarView = VBarView;
    VBarView.__name__ = "VBarView";
    class VBar extends lrtb_1.LRTB {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VBar = VBar;
    _a = VBar;
    VBar.__name__ = "VBar";
    (() => {
        _a.prototype.default_view = VBarView;
        _a.define(({}) => ({
            x: [p.XCoordinateSpec, { field: "x" }],
            bottom: [p.YCoordinateSpec, { value: 0 }],
            width: [p.DistanceSpec, { value: 1 }],
            top: [p.YCoordinateSpec, { field: "top" }],
        }));
    })();
},
/* models/glyphs/vspan.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const selection_1 = require(130) /* ../selections/selection */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const uniforms = tslib_1.__importStar(require(39) /* ../../core/uniforms */);
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const array_1 = require(10) /* ../../core/util/array */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const { abs, max } = Math;
    const UNUSED = 0;
    class VSpanView extends glyph_1.GlyphView {
        after_visuals() {
            super.after_visuals();
            this.max_line_width = uniforms.max(this.line_width);
        }
        _index_data(index) {
            for (const x_i of this.x) {
                index.add_point(x_i, UNUSED);
            }
        }
        _bounds(bounds) {
            const { x0, x1 } = bounds;
            return { x0, x1, y0: NaN, y1: NaN };
        }
        _map_data() {
            super._map_data();
            const { round } = Math;
            if (!this.inherited_sx) {
                const sx = (0, arrayable_1.map)(this.sx, (xi) => round(xi));
                this._define_attr("sx", sx);
            }
        }
        scenterxy(i) {
            const { vcenter } = this.renderer.plot_view.frame.bbox;
            return [this.sx[i], vcenter];
        }
        _paint(ctx, indices, data) {
            const { sx } = { ...this, ...data };
            const { top, bottom } = this.renderer.plot_view.frame.bbox;
            for (const i of indices) {
                const sx_i = sx[i];
                if (!isFinite(sx_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.moveTo(sx_i, top);
                ctx.lineTo(sx_i, bottom);
                this.visuals.line.apply(ctx, i);
            }
        }
        _get_candidates(sx0, sx1) {
            const { max_line_width } = this;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0 - max_line_width, (sx1 ?? sx0) + max_line_width);
            return this.index.indices({ x0, x1, y0: 0, y1: 0 });
        }
        _find_spans(candidates, fn) {
            const { sx, line_width } = this;
            const indices = [];
            for (const i of candidates) {
                const sx_i = sx[i];
                const line_width_i = line_width.get(i);
                if (fn(sx_i, line_width_i)) {
                    indices.push(i);
                }
            }
            return indices;
        }
        _hit_point(geometry) {
            const { sx: gsx } = geometry;
            const candidates = this._get_candidates(gsx);
            const indices = this._find_spans(candidates, (sx, line_width) => {
                return abs(sx - gsx) <= max(line_width, 2 /*px*/);
            });
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const indices = (() => {
                if (geometry.direction == "h") {
                    return (0, array_1.range)(0, this.data_size);
                }
                else {
                    const { sx: gsx } = geometry;
                    const candidates = this._get_candidates(gsx);
                    return this._find_spans(candidates, (sx, line_width) => {
                        return abs(sx - gsx) <= max(line_width / 2, 2 /*px*/);
                    });
                }
            })();
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const indices = (() => {
                const { sx0: gsx0, sx1: gsx1 } = geometry;
                const candidates = this._get_candidates(gsx0, gsx1);
                return this._find_spans(candidates, (sx, line_width) => {
                    return gsx0 - line_width / 2 <= sx && sx <= gsx1 + line_width / 2;
                });
            })();
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_line_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.VSpanView = VSpanView;
    VSpanView.__name__ = "VSpanView";
    class VSpan extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VSpan = VSpan;
    _a = VSpan;
    VSpan.__name__ = "VSpan";
    (() => {
        _a.prototype.default_view = VSpanView;
        _a.mixins([property_mixins_1.LineVector]);
        _a.define(() => ({
            x: [p.XCoordinateSpec, { field: "x" }],
        }));
    })();
},
/* models/glyphs/vstrip.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const selection_1 = require(130) /* ../selections/selection */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const types_1 = require(24) /* ../../core/types */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const iter = tslib_1.__importStar(require(34) /* ../../core/util/iterator */);
    const array_1 = require(10) /* ../../core/util/array */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const UNUSED = 0;
    class VStripView extends glyph_1.GlyphView {
        async lazy_initialize() {
            await super.lazy_initialize();
            const { webgl } = this.renderer.plot_view.canvas_view;
            if (webgl != null && webgl.regl_wrapper.has_webgl) {
                const { LRTBGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(575) /* ./webgl/lrtb */));
                this.glglyph = new LRTBGL(webgl.regl_wrapper, this);
            }
        }
        get sleft() {
            return this.sx0;
        }
        get sright() {
            return this.sx1;
        }
        get stop() {
            const { top } = this.renderer.plot_view.frame.bbox;
            const n = this.data_size;
            const stop = new types_1.ScreenArray(n);
            stop.fill(top);
            return stop;
        }
        get sbottom() {
            const { bottom } = this.renderer.plot_view.frame.bbox;
            const n = this.data_size;
            const sbottom = new types_1.ScreenArray(n);
            sbottom.fill(bottom);
            return sbottom;
        }
        _set_data(indices) {
            super._set_data(indices);
            const { abs } = Math;
            const { max, map, zip } = iter;
            const { x0, x1 } = this;
            if (this.inherited_x0 && this.inherited_x1) {
                this._inherit_attr("max_width");
            }
            else {
                const max_width = max(map(zip(x0, x1), ([x0_i, x1_i]) => abs(x0_i - x1_i)));
                this._define_attr("max_width", max_width);
            }
        }
        _index_data(index) {
            const { x0, x1, data_size } = this;
            for (let i = 0; i < data_size; i++) {
                const x0_i = x0[i];
                const x1_i = x1[i];
                index.add_rect(x0_i, UNUSED, x1_i, UNUSED);
            }
        }
        _bounds(bounds) {
            const { x0, x1 } = bounds;
            return { x0, x1, y0: NaN, y1: NaN };
        }
        _map_data() {
            super._map_data();
            const { round } = Math;
            if (!this.inherited_sx0) {
                const sx0 = (0, arrayable_1.map)(this.sx0, (xi) => round(xi));
                this._define_attr("sx0", sx0);
            }
            if (!this.inherited_sx1) {
                const sx1 = (0, arrayable_1.map)(this.sx1, (xi) => round(xi));
                this._define_attr("sx1", sx1);
            }
        }
        scenterxy(i) {
            const { vcenter } = this.renderer.plot_view.frame.bbox;
            return [(this.sx0[i] + this.sx1[i]) / 2, vcenter];
        }
        _paint(ctx, indices, data) {
            const { sx0, sx1 } = { ...this, ...data };
            const { top, bottom, height } = this.renderer.plot_view.frame.bbox;
            for (const i of indices) {
                const sx0_i = sx0[i];
                const sx1_i = sx1[i];
                if (!isFinite(sx0_i + sx1_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.rect(sx0_i, top, sx1_i - sx0_i, height);
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                ctx.beginPath();
                ctx.moveTo(sx0_i, top);
                ctx.lineTo(sx0_i, bottom);
                ctx.moveTo(sx1_i, top);
                ctx.lineTo(sx1_i, bottom);
                this.visuals.line.apply(ctx, i);
            }
        }
        _get_candidates(sx0, sx1) {
            const { max_width } = this;
            const [dx0, dx1] = this.renderer.xscale.r_invert(sx0, sx1 ?? sx0);
            const x0 = dx0 - max_width;
            const x1 = dx1 + max_width;
            return this.index.indices({ x0, x1, y0: 0, y1: 0 });
        }
        _find_strips(candidates, fn) {
            function contains(sx0, sx1) {
                return sx0 <= sx1 ? fn(sx0, sx1) : fn(sx1, sx0);
            }
            const { sx0, sx1 } = this;
            const indices = [];
            for (const i of candidates) {
                const sx0_i = sx0[i];
                const sx1_i = sx1[i];
                if (contains(sx0_i, sx1_i)) {
                    indices.push(i);
                }
            }
            return indices;
        }
        _hit_point(geometry) {
            const { sx } = geometry;
            const candidates = this._get_candidates(sx);
            const indices = this._find_strips(candidates, (sx0, sx1) => sx0 <= sx && sx <= sx1);
            return new selection_1.Selection({ indices });
        }
        _hit_span(geometry) {
            const indices = (() => {
                if (geometry.direction == "h") {
                    return (0, array_1.range)(0, this.data_size);
                }
                else {
                    const { sx } = geometry;
                    const candidates = this._get_candidates(sx);
                    return this._find_strips(candidates, (sx0, sx1) => sx0 <= sx && sx <= sx1);
                }
            })();
            return new selection_1.Selection({ indices });
        }
        _hit_rect(geometry) {
            const indices = (() => {
                const { sx0: gsx0, sx1: gsx1 } = geometry;
                const candidates = this._get_candidates(gsx0, gsx1);
                return this._find_strips(candidates, (sx0, sx1) => {
                    return gsx0 <= sx0 && sx0 <= gsx1 && gsx0 <= sx1 && sx1 <= gsx1;
                });
            })();
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
    }
    exports.VStripView = VStripView;
    VStripView.__name__ = "VStripView";
    class VStrip extends glyph_1.Glyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VStrip = VStrip;
    _a = VStrip;
    VStrip.__name__ = "VStrip";
    (() => {
        _a.prototype.default_view = VStripView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(() => ({
            x0: [p.XCoordinateSpec, { field: "x0" }],
            x1: [p.XCoordinateSpec, { field: "x1" }],
        }));
    })();
},
/* models/glyphs/wedge.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const xy_glyph_1 = require(221) /* ./xy_glyph */;
    const glyph_1 = require(222) /* ./glyph */;
    const utils_1 = require(228) /* ./utils */;
    const property_mixins_1 = require(80) /* ../../core/property_mixins */;
    const types_1 = require(24) /* ../../core/types */;
    const enums_1 = require(20) /* ../../core/enums */;
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const math_1 = require(11) /* ../../core/util/math */;
    const selection_1 = require(130) /* ../selections/selection */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    class WedgeView extends xy_glyph_1.XYGlyphView {
        async load_glglyph() {
            const { WedgeGL } = await Promise.resolve().then(() => tslib_1.__importStar(require(581) /* ./webgl/wedge */));
            return WedgeGL;
        }
        _map_data() {
            this._define_or_inherit_attr("sradius", () => {
                if (this.model.properties.radius.units == "data") {
                    if (this.inherited_x && this.inherited_radius) {
                        return glyph_1.inherit;
                    }
                    else {
                        return this.sdist(this.renderer.xscale, this.x, this.radius);
                    }
                }
                else {
                    return this.inherited_radius ? glyph_1.inherit : (0, types_1.to_screen)(this.radius);
                }
            });
            this._define_or_inherit_attr("max_sradius", () => (0, arrayable_1.max)(this.sradius));
        }
        _paint(ctx, indices, data) {
            const { sx, sy, sradius, start_angle, end_angle } = { ...this, ...data };
            const anticlock = this.model.direction == "anticlock";
            for (const i of indices) {
                const sx_i = sx[i];
                const sy_i = sy[i];
                const sradius_i = sradius[i];
                const start_angle_i = start_angle.get(i);
                const end_angle_i = end_angle.get(i);
                if (!isFinite(sx_i + sy_i + sradius_i + start_angle_i + end_angle_i)) {
                    continue;
                }
                ctx.beginPath();
                ctx.arc(sx_i, sy_i, sradius_i, start_angle_i, end_angle_i, anticlock);
                ctx.lineTo(sx_i, sy_i);
                ctx.closePath();
                this.visuals.fill.apply(ctx, i);
                this.visuals.hatch.apply(ctx, i);
                this.visuals.line.apply(ctx, i);
            }
        }
        _hit_point(geometry) {
            let dist, sx0, sx1, sy0, sy1;
            const { sx, sy } = geometry;
            const x = this.renderer.xscale.invert(sx);
            const y = this.renderer.yscale.invert(sy);
            // check diameter first
            sx0 = sx - this.max_sradius;
            sx1 = sx + this.max_sradius;
            const [x0, x1] = this.renderer.xscale.r_invert(sx0, sx1);
            sy0 = sy - this.max_sradius;
            sy1 = sy + this.max_sradius;
            const [y0, y1] = this.renderer.yscale.r_invert(sy0, sy1);
            const candidates = [];
            for (const i of this.index.indices({ x0, x1, y0, y1 })) {
                const r2 = this.sradius[i] ** 2;
                [sx0, sx1] = this.renderer.xscale.r_compute(x, this.x[i]);
                [sy0, sy1] = this.renderer.yscale.r_compute(y, this.y[i]);
                dist = (sx0 - sx1) ** 2 + (sy0 - sy1) ** 2;
                if (dist <= r2) {
                    candidates.push(i);
                }
            }
            const anticlock = this.model.direction == "anticlock";
            const indices = [];
            for (const i of candidates) {
                // NOTE: minus the angle because JS uses non-mathy convention for angles
                const angle = Math.atan2(sy - this.sy[i], sx - this.sx[i]);
                const is_full_circle = Math.abs(this.start_angle.get(i) - this.end_angle.get(i)) >= 2 * Math.PI;
                if (is_full_circle || (0, math_1.angle_between)(-angle, -this.start_angle.get(i), -this.end_angle.get(i), anticlock)) {
                    indices.push(i);
                }
            }
            return new selection_1.Selection({ indices });
        }
        draw_legend_for_index(ctx, bbox, index) {
            (0, utils_1.generic_area_vector_legend)(this.visuals, ctx, bbox, index);
        }
        scenterxy(i) {
            const r = this.sradius[i] / 2;
            const a = (this.start_angle.get(i) + this.end_angle.get(i)) / 2;
            const scx = this.sx[i] + r * Math.cos(a);
            const scy = this.sy[i] + r * Math.sin(a);
            return [scx, scy];
        }
    }
    exports.WedgeView = WedgeView;
    WedgeView.__name__ = "WedgeView";
    class Wedge extends xy_glyph_1.XYGlyph {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Wedge = Wedge;
    _a = Wedge;
    Wedge.__name__ = "Wedge";
    (() => {
        _a.prototype.default_view = WedgeView;
        _a.mixins([property_mixins_1.LineVector, property_mixins_1.FillVector, property_mixins_1.HatchVector]);
        _a.define(({}) => ({
            direction: [enums_1.Direction, "anticlock"],
            radius: [p.DistanceSpec, { field: "radius" }],
            start_angle: [p.AngleSpec, { field: "start_angle" }],
            end_angle: [p.AngleSpec, { field: "end_angle" }],
        }));
    })();
},
/* models/graphics/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var decoration_1 = require(227) /* ./decoration */;
    __esExport("Decoration", decoration_1.Decoration);
    var marking_1 = require(169) /* ./marking */;
    __esExport("Marking", marking_1.Marking);
},
/* models/graphs/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(398) /* ./graph_hit_test_policy */, exports);
    tslib_1.__exportStar(require(399) /* ./layout_provider */, exports);
    tslib_1.__exportStar(require(400) /* ./static_layout_provider */, exports);
},
/* models/graphs/graph_hit_test_policy.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    const selection_1 = require(130) /* ../selections/selection */;
    class GraphHitTestPolicy extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        _hit_test(geometry, graph_view, renderer_view) {
            if (!graph_view.model.visible) {
                return null;
            }
            const hit_test_result = renderer_view.glyph.hit_test(geometry);
            if (hit_test_result == null) {
                return null;
            }
            else {
                return renderer_view.model.view.convert_selection_from_subset(hit_test_result);
            }
        }
    }
    exports.GraphHitTestPolicy = GraphHitTestPolicy;
    GraphHitTestPolicy.__name__ = "GraphHitTestPolicy";
    class EdgesOnly extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.edge_view);
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const edge_selection = graph.edge_renderer.data_source.selected;
            edge_selection.update(hit_test_result, final, mode);
            graph.edge_renderer.data_source._select.emit();
            return !edge_selection.is_empty();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const { edge_renderer } = graph_view.model;
            const edge_inspection = edge_renderer.get_selection_manager().get_or_create_inspector(graph_view.edge_view.model);
            edge_inspection.update(hit_test_result, final, mode);
            // silently set inspected attr to avoid triggering data_source.change event and rerender
            graph_view.edge_view.model.data_source.setv({ inspected: edge_inspection }, { silent: true });
            graph_view.edge_view.model.data_source.inspect.emit([graph_view.edge_view.model, { geometry }]);
            return !edge_inspection.is_empty();
        }
    }
    exports.EdgesOnly = EdgesOnly;
    EdgesOnly.__name__ = "EdgesOnly";
    class NodesOnly extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.node_view);
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const node_selection = graph.node_renderer.data_source.selected;
            node_selection.update(hit_test_result, final, mode);
            graph.node_renderer.data_source._select.emit();
            return !node_selection.is_empty();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const { node_renderer } = graph_view.model;
            const node_inspection = node_renderer.get_selection_manager().get_or_create_inspector(graph_view.node_view.model);
            node_inspection.update(hit_test_result, final, mode);
            // silently set inspected attr to avoid triggering data_source.change event and rerender
            graph_view.node_view.model.data_source.setv({ inspected: node_inspection }, { silent: true });
            graph_view.node_view.model.data_source.inspect.emit([graph_view.node_view.model, { geometry }]);
            return !node_inspection.is_empty();
        }
    }
    exports.NodesOnly = NodesOnly;
    NodesOnly.__name__ = "NodesOnly";
    class NodesAndLinkedEdges extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.node_view);
        }
        get_linked_edges(node_source, edge_source, mode) {
            const node_data = (0, object_1.dict)(node_source.data);
            const index = node_data.get("index") ?? [];
            const node_indices = (() => {
                switch (mode) {
                    case "selection": return (0, arrayable_1.map)(node_source.selected.indices, (i) => index[i]);
                    case "inspection": return (0, arrayable_1.map)(node_source.inspected.indices, (i) => index[i]);
                }
            })();
            const edge_data = (0, object_1.dict)(edge_source.data);
            const start = edge_data.get("start") ?? [];
            const end = edge_data.get("end") ?? [];
            const edge_indices = [];
            const n = start.length;
            for (let i = 0; i < n; i++) {
                if ((0, array_1.contains)(node_indices, start[i]) || (0, array_1.contains)(node_indices, end[i])) {
                    edge_indices.push(i);
                }
            }
            const linked_edges = new selection_1.Selection();
            for (const i of edge_indices) {
                linked_edges.multiline_indices.set(i, [0]); //currently only supports 2-element multilines, so this is all of it
            }
            linked_edges.indices = edge_indices;
            return linked_edges;
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const node_selection = graph.node_renderer.data_source.selected;
            node_selection.update(hit_test_result, final, mode);
            const edge_selection = graph.edge_renderer.data_source.selected;
            const linked_edges_selection = this.get_linked_edges(graph.node_renderer.data_source, graph.edge_renderer.data_source, "selection");
            edge_selection.update(linked_edges_selection, final, mode);
            graph.node_renderer.data_source._select.emit();
            return !node_selection.is_empty();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const node_inspection = graph_view.node_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.node_view.model);
            node_inspection.update(hit_test_result, final, mode);
            graph_view.node_view.model.data_source.setv({ inspected: node_inspection }, { silent: true });
            const edge_inspection = graph_view.edge_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.edge_view.model);
            const linked_edges = this.get_linked_edges(graph_view.node_view.model.data_source, graph_view.edge_view.model.data_source, "inspection");
            edge_inspection.update(linked_edges, final, mode);
            //silently set inspected attr to avoid triggering data_source.change event and rerender
            graph_view.edge_view.model.data_source.setv({ inspected: edge_inspection }, { silent: true });
            graph_view.node_view.model.data_source.inspect.emit([graph_view.node_view.model, { geometry }]);
            return !node_inspection.is_empty();
        }
    }
    exports.NodesAndLinkedEdges = NodesAndLinkedEdges;
    NodesAndLinkedEdges.__name__ = "NodesAndLinkedEdges";
    class EdgesAndLinkedNodes extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.edge_view);
        }
        get_linked_nodes(node_source, edge_source, mode) {
            const edge_indices = (() => {
                switch (mode) {
                    case "selection": return edge_source.selected.indices;
                    case "inspection": return edge_source.inspected.indices;
                }
            })();
            const edge_data = (0, object_1.dict)(edge_source.data);
            const start = edge_data.get("start") ?? [];
            const end = edge_data.get("end") ?? [];
            const nodes = [];
            for (const i of edge_indices) {
                nodes.push(start[i], end[i]);
            }
            const node_data = (0, object_1.dict)(node_source.data);
            const index = node_data.get("index") ?? [];
            const node_indices = (0, array_1.uniq)(nodes).map((i) => (0, arrayable_1.index_of)(index, i));
            return new selection_1.Selection({ indices: node_indices });
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const edge_selection = graph.edge_renderer.data_source.selected;
            edge_selection.update(hit_test_result, final, mode);
            const node_selection = graph.node_renderer.data_source.selected;
            const linked_nodes = this.get_linked_nodes(graph.node_renderer.data_source, graph.edge_renderer.data_source, "selection");
            node_selection.update(linked_nodes, final, mode);
            graph.edge_renderer.data_source._select.emit();
            return !edge_selection.is_empty();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const edge_inspection = graph_view.edge_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.edge_view.model);
            edge_inspection.update(hit_test_result, final, mode);
            graph_view.edge_view.model.data_source.setv({ inspected: edge_inspection }, { silent: true });
            const node_inspection = graph_view.node_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.node_view.model);
            const linked_nodes = this.get_linked_nodes(graph_view.node_view.model.data_source, graph_view.edge_view.model.data_source, "inspection");
            node_inspection.update(linked_nodes, final, mode);
            // silently set inspected attr to avoid triggering data_source.change event and rerender
            graph_view.node_view.model.data_source.setv({ inspected: node_inspection }, { silent: true });
            graph_view.edge_view.model.data_source.inspect.emit([graph_view.edge_view.model, { geometry }]);
            return !edge_inspection.is_empty();
        }
    }
    exports.EdgesAndLinkedNodes = EdgesAndLinkedNodes;
    EdgesAndLinkedNodes.__name__ = "EdgesAndLinkedNodes";
    class NodesAndAdjacentNodes extends GraphHitTestPolicy {
        constructor(attrs) {
            super(attrs);
        }
        hit_test(geometry, graph_view) {
            return this._hit_test(geometry, graph_view, graph_view.node_view);
        }
        get_adjacent_nodes(node_source, edge_source, mode) {
            const node_data = (0, object_1.dict)(node_source.data);
            const index = node_data.get("index") ?? [];
            const selected_node_indices = (() => {
                switch (mode) {
                    case "selection": return (0, arrayable_1.map)(node_source.selected.indices, (i) => index[i]);
                    case "inspection": return (0, arrayable_1.map)(node_source.inspected.indices, (i) => index[i]);
                }
            })();
            const edge_data = (0, object_1.dict)(edge_source.data);
            const start = edge_data.get("start") ?? [];
            const end = edge_data.get("end") ?? [];
            const adjacent_nodes = [];
            const selected_nodes = [];
            for (let i = 0; i < start.length; i++) {
                if ((0, array_1.contains)(selected_node_indices, start[i])) {
                    adjacent_nodes.push(end[i]);
                    selected_nodes.push(start[i]);
                }
                if ((0, array_1.contains)(selected_node_indices, end[i])) {
                    adjacent_nodes.push(start[i]);
                    selected_nodes.push(end[i]);
                }
            }
            for (let i = 0; i < selected_nodes.length; i++) {
                adjacent_nodes.push(selected_nodes[i]);
            }
            const adjacent_node_indices = (0, array_1.uniq)(adjacent_nodes).map((i) => (0, arrayable_1.index_of)(index, i));
            return new selection_1.Selection({ indices: adjacent_node_indices });
        }
        do_selection(hit_test_result, graph, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const node_selection = graph.node_renderer.data_source.selected;
            node_selection.update(hit_test_result, final, mode);
            const adjacent_nodes_selection = this.get_adjacent_nodes(graph.node_renderer.data_source, graph.edge_renderer.data_source, "selection");
            if (!adjacent_nodes_selection.is_empty()) {
                node_selection.update(adjacent_nodes_selection, final, mode);
            }
            graph.node_renderer.data_source._select.emit();
            return !node_selection.is_empty();
        }
        do_inspection(hit_test_result, geometry, graph_view, final, mode) {
            if (hit_test_result == null) {
                return false;
            }
            const node_inspection = graph_view.node_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.node_view.model);
            node_inspection.update(hit_test_result, final, mode);
            graph_view.node_view.model.data_source.setv({ inspected: node_inspection }, { silent: true });
            const adjacent_nodes_inspection = this.get_adjacent_nodes(graph_view.node_view.model.data_source, graph_view.edge_view.model.data_source, "inspection");
            if (!adjacent_nodes_inspection.is_empty()) {
                node_inspection.update(adjacent_nodes_inspection, final, mode);
                graph_view.node_view.model.data_source.setv({ inspected: node_inspection }, { silent: true });
            }
            graph_view.node_view.model.data_source.inspect.emit([graph_view.node_view.model, { geometry }]);
            return !node_inspection.is_empty();
        }
    }
    exports.NodesAndAdjacentNodes = NodesAndAdjacentNodes;
    NodesAndAdjacentNodes.__name__ = "NodesAndAdjacentNodes";
},
/* models/graphs/layout_provider.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const coordinate_transform_1 = require(341) /* ../expressions/coordinate_transform */;
    class LayoutProvider extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        get node_coordinates() {
            return new NodeCoordinates({ layout: this });
        }
        get edge_coordinates() {
            return new EdgeCoordinates({ layout: this });
        }
    }
    exports.LayoutProvider = LayoutProvider;
    LayoutProvider.__name__ = "LayoutProvider";
    class GraphCoordinates extends coordinate_transform_1.CoordinateTransform {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GraphCoordinates = GraphCoordinates;
    _a = GraphCoordinates;
    GraphCoordinates.__name__ = "GraphCoordinates";
    (() => {
        _a.define(({ Ref }) => ({
            layout: [Ref(LayoutProvider)],
        }));
    })();
    class NodeCoordinates extends GraphCoordinates {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            const [x, y] = this.layout.get_node_coordinates(source);
            return { x, y };
        }
    }
    exports.NodeCoordinates = NodeCoordinates;
    NodeCoordinates.__name__ = "NodeCoordinates";
    class EdgeCoordinates extends GraphCoordinates {
        constructor(attrs) {
            super(attrs);
        }
        _v_compute(source) {
            const [x, y] = this.layout.get_edge_coordinates(source);
            return { x, y };
        }
    }
    exports.EdgeCoordinates = EdgeCoordinates;
    EdgeCoordinates.__name__ = "EdgeCoordinates";
},
/* models/graphs/static_layout_provider.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const layout_provider_1 = require(399) /* ./layout_provider */;
    const object_1 = require(9) /* ../../core/util/object */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    exports.GraphLayout = (0, kinds_1.Or)((0, kinds_1.Dict)((0, kinds_1.Arrayable)(kinds_1.Float)), (0, kinds_1.Mapping)((0, kinds_1.Or)(kinds_1.Int, kinds_1.Str), (0, kinds_1.Arrayable)(kinds_1.Float)));
    class StaticLayoutProvider extends layout_provider_1.LayoutProvider {
        constructor(attrs) {
            super(attrs);
        }
        get_node_coordinates(node_source) {
            const data = (0, object_1.dict)(node_source.data);
            const index = data.get("index") ?? [];
            const n = index.length;
            const xs = new Float64Array(n);
            const ys = new Float64Array(n);
            const graph_layout = (0, object_1.dict)(this.graph_layout);
            for (let i = 0; i < n; i++) {
                const j = index[i];
                const [x, y] = graph_layout.get(j) ?? [NaN, NaN];
                xs[i] = x;
                ys[i] = y;
            }
            return [xs, ys];
        }
        get_edge_coordinates(edge_source) {
            const data = (0, object_1.dict)(edge_source.data);
            const starts = (data.get("start") ?? []);
            const ends = (data.get("end") ?? []);
            const n = Math.min(starts.length, ends.length);
            const xs = [];
            const ys = [];
            const edge_xs = data.get("xs");
            const edge_ys = data.get("ys");
            const has_paths = edge_xs != null && edge_ys != null;
            const graph_layout = (0, object_1.dict)(this.graph_layout);
            for (let i = 0; i < n; i++) {
                const in_layout = graph_layout.has(starts[i]) && graph_layout.has(ends[i]);
                if (has_paths && in_layout) {
                    xs.push(edge_xs[i]);
                    ys.push(edge_ys[i]);
                }
                else {
                    const start = graph_layout.get(starts[i]) ?? [NaN, NaN];
                    const end = graph_layout.get(ends[i]) ?? [NaN, NaN];
                    xs.push([start[0], end[0]]);
                    ys.push([start[1], end[1]]);
                }
            }
            return [xs, ys];
        }
    }
    exports.StaticLayoutProvider = StaticLayoutProvider;
    _a = StaticLayoutProvider;
    StaticLayoutProvider.__name__ = "StaticLayoutProvider";
    (() => {
        _a.define(() => ({
            graph_layout: [exports.GraphLayout, new Map()], // TODO: length == 2
        }));
    })();
},
/* models/grids/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var grid_1 = require(402) /* ./grid */;
    __esExport("Grid", grid_1.Grid);
},
/* models/grids/grid.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const axes_1 = require(266) /* ../axes */;
    const guide_renderer_1 = require(190) /* ../renderers/guide_renderer */;
    const ticker_1 = require(191) /* ../tickers/ticker */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const types_1 = require(8) /* ../../core/util/types */;
    class GridView extends guide_renderer_1.GuideRendererView {
        _paint() {
            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_paint());
        }
        _draw_regions(ctx) {
            if (!this.visuals.band_fill.doit && !this.visuals.band_hatch.doit) {
                return;
            }
            const [xs, ys] = this.grid_coords("major", false);
            for (let i = 0; i < xs.length - 1; i++) {
                if (i % 2 != 1) {
                    continue;
                }
                const [sx0, sy0] = this.coordinates.map_to_screen(xs[i], ys[i]);
                const [sx1, sy1] = this.coordinates.map_to_screen(xs[i + 1], ys[i + 1]);
                ctx.beginPath();
                ctx.rect(sx0[0], sy0[0], sx1[1] - sx0[0], sy1[1] - sy0[0]);
                this.visuals.band_fill.apply(ctx);
                this.visuals.band_hatch.apply(ctx);
            }
        }
        _draw_grids(ctx) {
            if (!this.visuals.grid_line.doit) {
                return;
            }
            const [xs, ys] = this.grid_coords("major");
            this._draw_grid_helper(ctx, this.visuals.grid_line, xs, ys);
        }
        _draw_minor_grids(ctx) {
            if (!this.visuals.minor_grid_line.doit) {
                return;
            }
            const [xs, ys] = this.grid_coords("minor");
            this._draw_grid_helper(ctx, this.visuals.minor_grid_line, xs, ys);
        }
        _draw_grid_helper(ctx, visuals, xs, ys) {
            visuals.set_value(ctx);
            ctx.beginPath();
            for (let i = 0; i < xs.length; i++) {
                const [sx, sy] = this.coordinates.map_to_screen(xs[i], ys[i]);
                ctx.moveTo(Math.round(sx[0]), Math.round(sy[0]));
                for (let i = 1; i < sx.length; i++) {
                    ctx.lineTo(Math.round(sx[i]), Math.round(sy[i]));
                }
            }
            ctx.stroke();
        }
        // {{{ TODO: state
        ranges() {
            const i = this.model.dimension;
            const j = 1 - i;
            const { ranges } = this.coordinates;
            return [ranges[i], ranges[j]];
        }
        computed_bounds() {
            const [range] = this.ranges();
            const user_bounds = this.model.bounds;
            const range_bounds = [range.min, range.max];
            let start;
            let end;
            if ((0, types_1.isArray)(user_bounds)) {
                start = Math.min(user_bounds[0], user_bounds[1]);
                end = Math.max(user_bounds[0], user_bounds[1]);
                if (start < range_bounds[0]) {
                    start = range_bounds[0];
                }
                // XXX:
                //else if (start > range_bounds[1])
                //  start = null
                if (end > range_bounds[1]) {
                    end = range_bounds[1];
                }
                // XXX:
                //else if (end < range_bounds[0])
                //  end = null
            }
            else {
                [start, end] = range_bounds;
                for (const axis_view of this.plot_view.axis_views) {
                    if (axis_view.dimension == this.model.dimension
                        && axis_view.model.x_range_name == this.model.x_range_name
                        && axis_view.model.y_range_name == this.model.y_range_name) {
                        [start, end] = axis_view.computed_bounds;
                    }
                }
            }
            return [start, end];
        }
        grid_coords(location, exclude_ends = true) {
            const i = this.model.dimension;
            const j = 1 - i;
            const [range, cross_range] = this.ranges();
            const [start, end] = (() => {
                const [start, end] = this.computed_bounds();
                return [Math.min(start, end), Math.max(start, end)];
            })();
            const coords = [[], []];
            // TODO: (bev) using cross_range.min for cross_loc is a bit of a cheat. Since we
            // currently only support "straight line" grids, this should be OK for now. If
            // we ever want to support "curved" grids, e.g. for some projections, we may
            // have to communicate more than just a single cross location.
            const ticker = this.model.get_ticker();
            if (ticker == null) {
                return coords;
            }
            const ticks = ticker.get_ticks(start, end, range, cross_range.min)[location];
            const min = range.min;
            const max = range.max;
            const [cmin, cmax] = (() => {
                const { cross_bounds } = this.model;
                if (cross_bounds == "auto") {
                    return [cross_range.min, cross_range.max];
                }
                else {
                    return cross_bounds;
                }
            })();
            if (!exclude_ends) {
                if (ticks[0] != min) {
                    ticks.splice(0, 0, min);
                }
                if (ticks[ticks.length - 1] != max) {
                    ticks.push(max);
                }
            }
            for (let ii = 0; ii < ticks.length; ii++) {
                if ((ticks[ii] == min || ticks[ii] == max) && exclude_ends) {
                    continue;
                }
                const dim_i = [];
                const dim_j = [];
                const N = 2;
                for (let n = 0; n < N; n++) {
                    const loc = cmin + (cmax - cmin) / (N - 1) * n;
                    dim_i.push(ticks[ii]);
                    dim_j.push(loc);
                }
                coords[i].push(dim_i);
                coords[j].push(dim_j);
            }
            return coords;
        }
    }
    exports.GridView = GridView;
    GridView.__name__ = "GridView";
    class Grid extends guide_renderer_1.GuideRenderer {
        constructor(attrs) {
            super(attrs);
        }
        get_ticker() {
            if (this.ticker != null) {
                return this.ticker;
            }
            if (this.axis != null) {
                return this.axis.ticker;
            }
            return null;
        }
    }
    exports.Grid = Grid;
    _a = Grid;
    Grid.__name__ = "Grid";
    (() => {
        _a.prototype.default_view = GridView;
        _a.mixins([
            ["grid_", mixins.Line],
            ["minor_grid_", mixins.Line],
            ["band_", mixins.Fill],
            ["band_", mixins.Hatch],
        ]);
        _a.define(({ Float, Auto, Enum, Ref, Tuple, Or, Nullable }) => ({
            bounds: [Or(Tuple(Float, Float), Auto), "auto"],
            cross_bounds: [Or(Tuple(Float, Float), Auto), "auto"],
            dimension: [Enum(0, 1), 0],
            axis: [Nullable(Ref(axes_1.Axis)), null],
            ticker: [Nullable(Ref(ticker_1.Ticker)), null],
        }));
        _a.override({
            level: "underlay",
            band_fill_color: null,
            band_fill_alpha: 0,
            grid_line_color: "#e5e5e5",
            minor_grid_line_color: null,
        });
    })();
},
/* models/layouts/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var column_1 = require(404) /* ./column */;
    __esExport("Column", column_1.Column);
    var flex_box_1 = require(405) /* ./flex_box */;
    __esExport("FlexBox", flex_box_1.FlexBox);
    var grid_box_1 = require(411) /* ./grid_box */;
    __esExport("GridBox", grid_box_1.GridBox);
    var group_box_1 = require(413) /* ./group_box */;
    __esExport("GroupBox", group_box_1.GroupBox);
    var hbox_1 = require(415) /* ./hbox */;
    __esExport("HBox", hbox_1.HBox);
    var layout_dom_1 = require(406) /* ./layout_dom */;
    __esExport("LayoutDOM", layout_dom_1.LayoutDOM);
    var row_1 = require(416) /* ./row */;
    __esExport("Row", row_1.Row);
    var scroll_box_1 = require(417) /* ./scroll_box */;
    __esExport("ScrollBox", scroll_box_1.ScrollBox);
    var spacer_1 = require(418) /* ./spacer */;
    __esExport("Spacer", spacer_1.Spacer);
    var tab_panel_1 = require(419) /* ./tab_panel */;
    __esExport("TabPanel", tab_panel_1.TabPanel);
    var tabs_1 = require(423) /* ./tabs */;
    __esExport("Tabs", tabs_1.Tabs);
    var vbox_1 = require(425) /* ./vbox */;
    __esExport("VBox", vbox_1.VBox);
},
/* models/layouts/column.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const flex_box_1 = require(405) /* ./flex_box */;
    class ColumnView extends flex_box_1.FlexBoxView {
        constructor() {
            super(...arguments);
            this._direction = "column";
        }
    }
    exports.ColumnView = ColumnView;
    ColumnView.__name__ = "ColumnView";
    class Column extends flex_box_1.FlexBox {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Column = Column;
    _a = Column;
    Column.__name__ = "Column";
    (() => {
        _a.prototype.default_view = ColumnView;
    })();
},
/* models/layouts/flex_box.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const layout_dom_1 = require(406) /* ./layout_dom */;
    const alignments_1 = require(410) /* ./alignments */;
    const grid_1 = require(259) /* ../../core/layout/grid */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    const dom_1 = require(63) /* ../../core/dom */;
    class FlexBoxView extends layout_dom_1.LayoutDOMView {
        connect_signals() {
            super.connect_signals();
            const { children } = this.model.properties;
            this.on_change(children, () => this.update_children());
        }
        get child_models() {
            return this.model.children;
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "flex" };
        }
        _update_layout() {
            super._update_layout();
            this.style.append(":host", {
                flex_direction: this._direction,
                gap: (0, dom_1.px)(this.model.spacing),
            });
            const layoutable = new grid_1.Container();
            let r0 = 0;
            let c0 = 0;
            for (const view of this.child_views) {
                if (!(view instanceof layout_dom_1.LayoutDOMView)) {
                    continue;
                }
                const sizing = view.box_sizing();
                const flex = (() => {
                    const policy = this._direction == "row" ? sizing.width_policy : sizing.height_policy;
                    const size = this._direction == "row" ? sizing.width : sizing.height;
                    const basis = size != null ? (0, dom_1.px)(size) : "auto";
                    switch (policy) {
                        case "auto":
                        case "fixed": return `0 0 ${basis}`;
                        case "fit": return "1 1 auto";
                        case "min": return "0 1 auto";
                        case "max": return "1 0 0px";
                    }
                })();
                const align_self = (() => {
                    const policy = this._direction == "row" ? sizing.height_policy : sizing.width_policy;
                    switch (policy) {
                        case "auto":
                        case "fixed":
                        case "fit":
                        case "min": return this._direction == "row" ? sizing.valign : sizing.halign;
                        case "max": return "stretch";
                    }
                })();
                view.style.append(":host", { flex, align_self });
                // undo `width/height: 100%` and let `align-self: strech` do the work
                if (this._direction == "row") {
                    if (sizing.height_policy == "max") {
                        view.style.append(":host", { height: "auto" });
                    }
                }
                else {
                    if (sizing.width_policy == "max") {
                        view.style.append(":host", { width: "auto" });
                    }
                }
                if (view.layout != null) {
                    layoutable.add({ r0, c0, r1: r0 + 1, c1: c0 + 1 }, view);
                    if (this._direction == "row") {
                        c0 += 1;
                    }
                    else {
                        r0 += 1;
                    }
                }
            }
            if (layoutable.size != 0) {
                this.layout = new alignments_1.GridAlignmentLayout(layoutable);
                this.layout.set_sizing();
            }
            else {
                delete this.layout;
            }
        }
    }
    exports.FlexBoxView = FlexBoxView;
    FlexBoxView.__name__ = "FlexBoxView";
    class FlexBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.FlexBox = FlexBox;
    _a = FlexBox;
    FlexBox.__name__ = "FlexBox";
    (() => {
        _a.define(({ Float, List, Ref }) => ({
            children: [List(Ref(ui_element_1.UIElement)), []],
            spacing: [Float, 0],
        }));
    })();
},
/* models/layouts/layout_dom.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const pane_1 = require(407) /* ../ui/pane */;
    const logging_1 = require(19) /* ../../core/logging */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const enums_1 = require(20) /* ../../core/enums */;
    const dom_1 = require(63) /* ../../core/dom */;
    const types_1 = require(8) /* ../../core/util/types */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const layout_1 = require(257) /* ../../core/layout */;
    const canvas_1 = require(112) /* ../../core/util/canvas */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class LayoutDOMView extends pane_1.PaneView {
        constructor() {
            super(...arguments);
            this._child_views = new Map();
            this.mouseenter = new signaling_1.Signal(this, "mouseenter");
            this.mouseleave = new signaling_1.Signal(this, "mouseleave");
            this.disabled = new signaling_1.Signal(this, "disabled");
            this._auto_width = "fit-content";
            this._auto_height = "fit-content";
            this._layout_computed = false;
        }
        get is_layout_root() {
            return this.is_root || !(this.parent instanceof LayoutDOMView);
        }
        _after_resize() {
            super._after_resize();
            if (this.is_layout_root && !this._was_built) {
                // This can happen only in pathological cases primarily in tests.
                logging_1.logger.warn(`${this} wasn't built properly`);
                this.render();
                this.r_after_render();
            }
            else {
                this.compute_layout();
            }
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this.build_child_views();
        }
        remove() {
            for (const child_view of this.child_views) {
                child_view.remove();
            }
            this._child_views.clear();
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            this.el.addEventListener("mouseenter", (event) => {
                this.mouseenter.emit(event);
            });
            this.el.addEventListener("mouseleave", (event) => {
                this.mouseleave.emit(event);
            });
            if (this.parent instanceof LayoutDOMView) {
                this.connect(this.parent.disabled, (disabled) => {
                    this.disabled.emit(disabled || this.model.disabled);
                });
            }
            const p = this.model.properties;
            this.on_change(p.disabled, () => {
                this.disabled.emit(this.model.disabled);
            });
            this.on_change([
                p.css_classes,
                p.stylesheets,
                p.width, p.height,
                p.min_width, p.min_height,
                p.max_width, p.max_height,
                p.margin,
                p.width_policy, p.height_policy,
                p.flow_mode, p.sizing_mode,
                p.aspect_ratio,
                p.visible,
            ], () => this.invalidate_layout());
        }
        *children() {
            yield* super.children();
            yield* this.child_views;
        }
        get child_views() {
            // TODO In case of a race condition somewhere between layout, resize and children updates,
            // child_models and _child_views may be temporarily inconsistent, resulting in undefined
            // values. Eventually this shouldn't happen and undefined should be treated as a bug.
            return this.child_models.map((child) => this._child_views.get(child)).filter((view) => view != null);
        }
        get layoutable_views() {
            return this.child_views.filter((c) => c instanceof LayoutDOMView);
        }
        async build_child_views() {
            const { created, removed } = await (0, build_views_1.build_views)(this._child_views, this.child_models, { parent: this });
            for (const view of removed) {
                this._resize_observer.unobserve(view.el);
            }
            for (const view of created) {
                this._resize_observer.observe(view.el, { box: "border-box" });
            }
            return created;
        }
        render() {
            super.render();
            for (const child_view of this.child_views) {
                const target = child_view.rendering_target() ?? this.shadow_el;
                child_view.render_to(target);
            }
        }
        _update_children() { }
        async update_children() {
            const created = await this.build_child_views();
            const created_children = new Set(created);
            // First remove and then either reattach existing elements or render and
            // attach new elements, so that the order of children is consistent, while
            // avoiding expensive re-rendering of existing views.
            for (const child_view of this.child_views) {
                child_view.el.remove();
            }
            for (const child_view of this.child_views) {
                const is_new = created_children.has(child_view);
                const target = child_view.rendering_target() ?? this.shadow_el;
                if (is_new) {
                    child_view.render_to(target);
                }
                else {
                    target.append(child_view.el);
                }
            }
            this.r_after_render();
            this._update_children();
            this.invalidate_layout();
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "flow" };
        }
        _update_layout() {
            function css_sizing(policy, size, auto_size, margin) {
                switch (policy) {
                    case "auto":
                        return size != null ? (0, dom_1.px)(size) : auto_size;
                    case "fixed":
                        return size != null ? (0, dom_1.px)(size) : "fit-content";
                    case "fit":
                        return "fit-content";
                    case "min":
                        return "min-content";
                    case "max":
                        return margin == null ? "100%" : `calc(100% - ${margin})`;
                }
            }
            function css_display(display) {
                // Convert to legacy values due to limitted browser support.
                const { inner, outer } = display;
                switch (`${inner} ${outer}`) {
                    case "block flow": return "block";
                    case "inline flow": return "inline";
                    case "block flow-root": return "flow-root";
                    case "inline flow-root": return "inline-block";
                    case "block flex": return "flex";
                    case "inline flex": return "inline-flex";
                    case "block grid": return "grid";
                    case "inline grid": return "inline-grid";
                    case "block table": return "table";
                    case "inline table": return "inline-table";
                    default: (0, assert_1.unreachable)();
                }
            }
            function to_css(value) {
                return (0, types_1.isNumber)(value) ? (0, dom_1.px)(value) : `${value.percent}%`;
            }
            const styles = {};
            const display = this._intrinsic_display();
            styles.display = css_display(display);
            const sizing = this.box_sizing();
            const { width_policy, height_policy, width, height, aspect_ratio } = sizing;
            const computed_aspect = (() => {
                if (aspect_ratio == "auto") {
                    if (width != null && height != null) {
                        return width / height;
                    }
                }
                else if ((0, types_1.isNumber)(aspect_ratio)) {
                    return aspect_ratio;
                }
                return null;
            })();
            if (aspect_ratio == "auto") {
                if (width != null && height != null) {
                    styles.aspect_ratio = `${width} / ${height}`;
                }
                else {
                    styles.aspect_ratio = "auto";
                }
            }
            else if ((0, types_1.isNumber)(aspect_ratio)) {
                styles.aspect_ratio = `${aspect_ratio}`;
            }
            const { margin } = this.model;
            const margins = (() => {
                if (margin != null) {
                    if ((0, types_1.isNumber)(margin)) {
                        styles.margin = (0, dom_1.px)(margin);
                        return { width: (0, dom_1.px)(2 * margin), height: (0, dom_1.px)(2 * margin) };
                    }
                    else if (margin.length == 2) {
                        const [vertical, horizontal] = margin;
                        styles.margin = `${(0, dom_1.px)(vertical)} ${(0, dom_1.px)(horizontal)}`;
                        return { width: (0, dom_1.px)(2 * horizontal), height: (0, dom_1.px)(2 * vertical) };
                    }
                    else {
                        const [top, right, bottom, left] = margin;
                        styles.margin = `${(0, dom_1.px)(top)} ${(0, dom_1.px)(right)} ${(0, dom_1.px)(bottom)} ${(0, dom_1.px)(left)}`;
                        return { width: (0, dom_1.px)(left + right), height: (0, dom_1.px)(top + bottom) };
                    }
                }
                else {
                    return { width: null, height: null };
                }
            })();
            const [css_width, css_height] = (() => {
                const css_width = css_sizing(width_policy, width, this._auto_width, margins.width);
                const css_height = css_sizing(height_policy, height, this._auto_height, margins.height);
                if (aspect_ratio != null) {
                    if (width_policy != height_policy) {
                        if (width_policy == "fixed") {
                            return [css_width, "auto"];
                        }
                        if (height_policy == "fixed") {
                            return ["auto", css_height];
                        }
                        if (width_policy == "max") {
                            return [css_width, "auto"];
                        }
                        if (height_policy == "max") {
                            return ["auto", css_height];
                        }
                        return ["auto", "auto"];
                    }
                    else {
                        if (width_policy != "fixed" && height_policy != "fixed") {
                            if (computed_aspect != null) {
                                if (computed_aspect >= 1) {
                                    return [css_width, "auto"];
                                }
                                else {
                                    return ["auto", css_height];
                                }
                            }
                        }
                    }
                }
                return [css_width, css_height];
            })();
            styles.width = css_width;
            styles.height = css_height;
            const { min_width, max_width } = this.model;
            const { min_height, max_height } = this.model;
            styles.min_width = min_width == null ? "0px" : to_css(min_width);
            styles.min_height = min_height == null ? "0px" : to_css(min_height);
            if (this.is_layout_root) {
                if (max_width != null) {
                    styles.max_width = to_css(max_width);
                }
                if (max_height != null) {
                    styles.max_height = to_css(max_height);
                }
            }
            else {
                if (max_width != null) {
                    styles.max_width = `min(${to_css(max_width)}, 100%)`;
                }
                else if (width_policy != "fixed") {
                    styles.max_width = "100%";
                }
                if (max_height != null) {
                    styles.max_height = `min(${to_css(max_height)}, 100%)`;
                }
                else if (height_policy != "fixed") {
                    styles.max_height = "100%";
                }
            }
            const { resizable } = this.model;
            if (resizable !== false) {
                const resize = (() => {
                    switch (resizable) {
                        case "width": return "horizontal";
                        case "height": return "vertical";
                        case true:
                        case "both": return "both";
                    }
                })();
                styles.resize = resize;
                styles.overflow = "auto";
            }
            this.style.append(":host", styles);
        }
        update_layout() {
            this.update_style();
            for (const child_view of this.layoutable_views) {
                child_view.update_layout();
            }
            this._update_layout();
        }
        get is_managed() {
            return this.parent instanceof LayoutDOMView;
        }
        /**
         * Update CSS layout with computed values from canvas layout.
         * This can be done more frequently than `_update_layout()`.
         */
        _measure_layout() { }
        measure_layout() {
            for (const child_view of this.layoutable_views) {
                child_view.measure_layout();
            }
            this._measure_layout();
        }
        compute_layout() {
            if (this.parent instanceof LayoutDOMView) { // TODO: this.is_managed
                this.parent.compute_layout();
            }
            else {
                this.measure_layout();
                this.update_bbox();
                this._compute_layout();
                this.after_layout();
            }
            this._layout_computed = true;
        }
        _compute_layout() {
            if (this.layout != null) {
                this.layout.compute(this.bbox.size);
                for (const child_view of this.layoutable_views) {
                    if (child_view.layout == null) {
                        child_view._compute_layout();
                    }
                    else {
                        child_view._propagate_layout();
                    }
                }
            }
            else {
                for (const child_view of this.layoutable_views) {
                    child_view._compute_layout();
                }
            }
        }
        _propagate_layout() {
            for (const child_view of this.layoutable_views) {
                if (child_view.layout == null) {
                    child_view._compute_layout();
                }
            }
        }
        update_bbox() {
            for (const child_view of this.layoutable_views) {
                child_view.update_bbox();
            }
            const changed = super.update_bbox();
            if (this.layout != null) {
                this.layout.visible = this.is_displayed;
            }
            return changed;
        }
        _after_layout() { }
        after_layout() {
            for (const child_view of this.layoutable_views) {
                child_view.after_layout();
            }
            this._after_layout();
        }
        _after_render() {
            // XXX no super
            if (!this.is_managed) {
                this.invalidate_layout();
            }
        }
        invalidate_layout() {
            // TODO: it would be better and more efficient to do a localized
            // update, but for now this guarantees consistent state of layout.
            if (this.parent instanceof LayoutDOMView) {
                this.parent.invalidate_layout();
            }
            else {
                this.update_layout();
                this.compute_layout();
            }
        }
        invalidate_render() {
            this.render();
            this.invalidate_layout();
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            if (this.is_layout_root && !this._layout_computed) {
                return false;
            }
            for (const child_view of this.child_views) {
                if (!child_view.has_finished()) {
                    return false;
                }
            }
            return true;
        }
        box_sizing() {
            let { width_policy, height_policy, aspect_ratio } = this.model;
            const { sizing_mode } = this.model;
            if (sizing_mode != null) {
                if (sizing_mode == "inherit") {
                    if (this.parent instanceof LayoutDOMView) {
                        const sizing = this.parent.box_sizing();
                        width_policy = sizing.width_policy;
                        height_policy = sizing.height_policy;
                        if (aspect_ratio == null) {
                            aspect_ratio = sizing.aspect_ratio;
                        }
                    }
                }
                else if (sizing_mode == "fixed") {
                    width_policy = height_policy = "fixed";
                }
                else if (sizing_mode == "stretch_both") {
                    width_policy = height_policy = "max";
                }
                else if (sizing_mode == "stretch_width") {
                    width_policy = "max";
                }
                else if (sizing_mode == "stretch_height") {
                    height_policy = "max";
                }
                else {
                    if (aspect_ratio == null) {
                        aspect_ratio = "auto";
                    }
                    switch (sizing_mode) {
                        case "scale_width":
                            width_policy = "max";
                            height_policy = "min";
                            break;
                        case "scale_height":
                            width_policy = "min";
                            height_policy = "max";
                            break;
                        case "scale_both":
                            width_policy = "max";
                            height_policy = "max";
                            break;
                    }
                }
            }
            const [halign, valign] = (() => {
                const { align } = this.model;
                if (align == "auto") {
                    return [undefined, undefined];
                }
                else if ((0, types_1.isArray)(align)) {
                    return align;
                }
                else {
                    return [align, align];
                }
            })();
            const { width, height } = this.model;
            return {
                width_policy,
                height_policy,
                width,
                height,
                aspect_ratio,
                halign,
                valign,
            };
        }
        export(type = "auto", hidpi = true) {
            const output_backend = (() => {
                switch (type) {
                    case "auto": // TODO: actually infer the best type
                    case "png": return "canvas";
                    case "svg": return "svg";
                }
            })();
            const composite = new canvas_1.CanvasLayer(output_backend, hidpi);
            const { x, y, width, height } = this.bbox;
            composite.resize(width, height);
            const bg_color = getComputedStyle(this.el).backgroundColor;
            composite.ctx.fillStyle = bg_color;
            composite.ctx.fillRect(x, y, width, height);
            for (const view of this.child_views) {
                const region = view.export(type, hidpi);
                const { x, y } = view.bbox.scale(composite.pixel_ratio);
                composite.ctx.drawImage(region.canvas, x, y);
            }
            return composite;
        }
    }
    exports.LayoutDOMView = LayoutDOMView;
    LayoutDOMView.__name__ = "LayoutDOMView";
    class LayoutDOM extends pane_1.Pane {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.LayoutDOM = LayoutDOM;
    _a = LayoutDOM;
    LayoutDOM.__name__ = "LayoutDOM";
    (() => {
        _a.define((types) => {
            const { Bool, Float, Auto, Tuple, Or, Null, Nullable } = types;
            const Number2 = Tuple(Float, Float);
            const Number4 = Tuple(Float, Float, Float, Float);
            return {
                width: [Nullable(Float), null],
                height: [Nullable(Float), null],
                min_width: [Nullable(Float), null],
                min_height: [Nullable(Float), null],
                max_width: [Nullable(Float), null],
                max_height: [Nullable(Float), null],
                margin: [Nullable(Or(Float, Number2, Number4)), null],
                width_policy: [Or(layout_1.SizingPolicy, Auto), "auto"],
                height_policy: [Or(layout_1.SizingPolicy, Auto), "auto"],
                aspect_ratio: [Or(Float, Auto, Null), null],
                flow_mode: [enums_1.FlowMode, "block"],
                sizing_mode: [Nullable(enums_1.SizingMode), null],
                disabled: [Bool, false],
                align: [Or(enums_1.Align, Tuple(enums_1.Align, enums_1.Align), Auto), "auto"],
                resizable: [Or(Bool, enums_1.Dimensions), false],
            };
        });
    })();
},
/* models/ui/pane.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const ui_element_1 = require(111) /* ./ui_element */;
    const dom_node_1 = require(125) /* ../dom/dom_node */;
    const html_1 = require(408) /* ../dom/html */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    // TODO UIElement needs to inherit from DOMNode
    exports.ElementLike = (0, kinds_1.Or)((0, kinds_1.Ref)(ui_element_1.UIElement), (0, kinds_1.Ref)(dom_node_1.DOMNode), (0, kinds_1.Ref)(html_1.HTML));
    class PaneView extends ui_element_1.UIElementView {
        constructor() {
            super(...arguments);
            this._element_views = new Map();
        }
        get elements() {
            return this.model.elements;
        }
        get element_views() {
            return this.elements.map((element) => this._element_views.get(element));
        }
        *children() {
            yield* super.children();
            yield* this.element_views;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._build_elements();
        }
        async _build_elements() {
            return await (0, build_views_1.build_views)(this._element_views, this.elements, { parent: this });
        }
        async _update_elements() {
            const { created } = await this._build_elements();
            const created_elements = new Set(created);
            // First remove and then either reattach existing elements or render and
            // attach new elements, so that the order of children is consistent, while
            // avoiding expensive re-rendering of existing views.
            for (const element_view of this.element_views) {
                element_view.el.remove();
            }
            for (const element_view of this.element_views) {
                const is_new = created_elements.has(element_view);
                const target = element_view.rendering_target() ?? this.shadow_el;
                if (is_new) {
                    element_view.render_to(target);
                }
                else {
                    target.append(element_view.el);
                }
            }
            this.r_after_render();
        }
        remove() {
            (0, build_views_1.remove_views)(this._element_views);
            super.remove();
        }
        connect_signals() {
            super.connect_signals();
            const { elements } = this.model.properties;
            this.on_change(elements, async () => {
                await this._update_elements();
            });
        }
        render() {
            super.render();
            for (const element_view of this.element_views) {
                const target = element_view.rendering_target() ?? this.shadow_el;
                element_view.render_to(target);
            }
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            for (const element_view of this.element_views) {
                if (!element_view.has_finished()) {
                    return false;
                }
            }
            return true;
        }
    }
    exports.PaneView = PaneView;
    PaneView.__name__ = "PaneView";
    class Pane extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Pane = Pane;
    _a = Pane;
    Pane.__name__ = "Pane";
    (() => {
        _a.prototype.default_view = PaneView;
        _a.define(({ List }) => ({
            elements: [List(exports.ElementLike), []],
        }));
    })();
},
/* models/dom/html.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const dom_element_1 = require(409) /* ./dom_element */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const dom_1 = require(63) /* ../../core/dom */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const types_1 = require(8) /* ../../core/util/types */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    const HTMLRef = (0, kinds_1.Or)((0, kinds_1.Ref)(dom_element_1.DOMElement), (0, kinds_1.Ref)(ui_element_1.UIElement));
    const HTMLMarkup = kinds_1.Str;
    class HTMLView extends dom_element_1.DOMElementView {
        constructor() {
            super(...arguments);
            this._refs = new Map();
        }
        get refs() {
            const { html, refs } = this.model;
            return [
                ...(0, types_1.isArray)(html) ? html.filter((item) => !(0, types_1.isString)(item)) : [],
                ...refs,
            ];
        }
        *children() {
            yield* super.children();
            yield* this._refs.values();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await (0, build_views_1.build_views)(this._refs, this.refs);
        }
        remove() {
            (0, build_views_1.remove_views)(this._refs);
            super.remove();
        }
        render() {
            super.render();
            const html = (() => {
                const { html } = this.model;
                if ((0, types_1.isArray)(html)) {
                    return html.map((item) => (0, types_1.isString)(item) ? item : `<ref id="${item.id}"></ref>`).join("");
                }
                else {
                    return html;
                }
            })();
            const nodes = (() => {
                if ((0, types_1.isString)(html)) {
                    return this.parse_html(html);
                }
                else {
                    return [html];
                }
            })();
            this.el.append(...nodes);
            this.finish();
        }
        parse_html(html) {
            const parser = new DOMParser();
            const document = parser.parseFromString(html, "text/html");
            const iter = document.createNodeIterator(document, NodeFilter.SHOW_ELEMENT, (node) => {
                return node.nodeName.toLowerCase() == "ref" ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
            });
            let node;
            next_node: while ((node = iter.nextNode()) != null) {
                (0, assert_1.assert)(node instanceof Element);
                const id = node.getAttribute("id");
                if (id != null) {
                    for (const [model, view] of this._refs) {
                        if (model.id == id) {
                            view.render();
                            node.replaceWith(view.el);
                            continue next_node;
                        }
                    }
                    node.replaceWith((0, dom_1.span)(`<not found: id=${id}>`));
                    continue;
                }
                const name = node.getAttribute("name");
                if (name != null) {
                    for (const [model, view] of this._refs) {
                        if (model.name == name) {
                            view.render();
                            node.replaceWith(view.el);
                            continue next_node;
                        }
                    }
                    node.replaceWith((0, dom_1.span)(`<not found: name=${name}>`));
                    continue;
                }
            }
            return [...document.body.childNodes];
        }
    }
    exports.HTMLView = HTMLView;
    HTMLView.__name__ = "HTMLView";
    class HTML extends dom_element_1.DOMElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HTML = HTML;
    _a = HTML;
    HTML.__name__ = "HTML";
    (() => {
        _a.prototype.default_view = HTMLView;
        _a.define(({ Node, List, Or }) => ({
            html: [Or(Node, HTMLMarkup, List(Or(HTMLMarkup, HTMLRef)))],
            refs: [List(HTMLRef), []],
        }));
    })();
},
/* models/dom/dom_element.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const dom_node_1 = require(125) /* ./dom_node */;
    const styled_element_1 = require(84) /* ../ui/styled_element */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const types_1 = require(8) /* ../../core/util/types */;
    const css_1 = require(65) /* ../../core/css */;
    const dom_1 = require(63) /* ../../core/dom */;
    class DOMElementView extends dom_node_1.DOMNodeView {
        constructor() {
            super(...arguments);
            this.child_views = new Map();
        }
        *children() {
            yield* super.children();
            yield* this.child_views.values();
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const children = this.model.children.filter((obj) => !(0, types_1.isString)(obj));
            await (0, build_views_1.build_views)(this.child_views, children, { parent: this });
        }
        remove() {
            (0, build_views_1.remove_views)(this.child_views);
            super.remove();
        }
        render() {
            (0, dom_1.empty)(this.el);
            (0, css_1.apply_styles)(this.el.style, this.model.style);
            for (const child of this.model.children) {
                if ((0, types_1.isString)(child)) {
                    const node = document.createTextNode(child);
                    this.el.appendChild(node);
                }
                else {
                    const child_view = this.child_views.get(child);
                    child_view.render_to(this.el);
                }
            }
            this.finish();
        }
    }
    exports.DOMElementView = DOMElementView;
    DOMElementView.__name__ = "DOMElementView";
    class DOMElement extends dom_node_1.DOMNode {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.DOMElement = DOMElement;
    _a = DOMElement;
    DOMElement.__name__ = "DOMElement";
    (() => {
        _a.define(({ Str, List, Or, Ref }) => {
            return {
                style: [styled_element_1.StylesLike, {}],
                children: [List(Or(Str, Ref(dom_node_1.DOMNode), Ref(ui_element_1.UIElement))), []],
            };
        });
    })();
},
/* models/layouts/alignments.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const layoutable_1 = require(175) /* ../../core/layout/layoutable */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const { max } = Math;
    class GridAlignmentLayout extends layoutable_1.Layoutable {
        constructor(children) {
            super();
            this.children = children;
        }
        _measure(_viewport) {
            return { width: 0, height: 0 };
        }
        compute(viewport = {}) {
            const { width, height } = viewport;
            (0, assert_1.assert)(width != null && height != null);
            const size_hint = { width, height };
            const outer = new bbox_1.BBox({ left: 0, top: 0, width, height });
            let inner = undefined;
            if (size_hint.inner != null) {
                const { left, top, right, bottom } = size_hint.inner;
                inner = new bbox_1.BBox({ left, top, right: width - right, bottom: height - bottom });
            }
            this.set_geometry(outer, inner);
        }
        _set_geometry(outer, inner) {
            super._set_geometry(outer, inner);
            const items = this.children.map((_, child) => {
                const { layout, bbox } = child;
                (0, assert_1.assert)(layout != null);
                const size_hint = layout.measure(bbox);
                return { child, layout, bbox, size_hint };
            });
            const row_extents = Array(items.nrows).fill(null).map(() => ({ top: 0, bottom: 0 }));
            const col_extents = Array(items.ncols).fill(null).map(() => ({ left: 0, right: 0 }));
            items.foreach(({ r0, c0, r1, c1 }, { size_hint }) => {
                const { inner } = size_hint;
                if (inner != null) {
                    col_extents[c0].left = max(col_extents[c0].left, inner.left);
                    col_extents[c1].right = max(col_extents[c1].right, inner.right);
                    row_extents[r0].top = max(row_extents[r0].top, inner.top);
                    row_extents[r1].bottom = max(row_extents[r1].bottom, inner.bottom);
                }
            });
            items.foreach(({ r0, c0, r1, c1 }, { layout, size_hint, bbox }) => {
                const outer_bbox = bbox;
                const inner_bbox = size_hint.inner == null ? undefined : (() => {
                    const { inner, align } = size_hint;
                    const align_left = align?.left ?? true;
                    const align_right = align?.right ?? true;
                    const align_top = align?.top ?? true;
                    const align_bottom = align?.bottom ?? true;
                    const fixed_width = align?.fixed_width ?? false;
                    const fixed_height = align?.fixed_height ?? false;
                    const { left, right } = (() => {
                        if (fixed_width) {
                            const inner_width = outer_bbox.width - inner.right - inner.left;
                            if (align_left) {
                                const left = col_extents[c0].left;
                                const right = outer_bbox.width - (left + inner_width);
                                return { left, right };
                            }
                            else if (align_right) {
                                const right = col_extents[c1].right;
                                const left = outer_bbox.width - (right + inner_width);
                                return { left, right };
                            }
                            else {
                                const left = inner.left;
                                const right = inner.right;
                                return { left, right };
                            }
                        }
                        else {
                            const left = align_left ? col_extents[c0].left : inner.left;
                            const right = align_right ? col_extents[c1].right : inner.right;
                            return { left, right };
                        }
                    })();
                    const { top, bottom } = (() => {
                        if (fixed_height) {
                            const inner_height = outer_bbox.height - inner.bottom - inner.top;
                            if (align_top) {
                                const top = row_extents[r0].top;
                                const bottom = outer_bbox.height - (top + inner_height);
                                return { top, bottom };
                            }
                            else if (align_bottom) {
                                const bottom = row_extents[r1].bottom;
                                const top = outer_bbox.height - (bottom + inner_height);
                                return { top, bottom };
                            }
                            else {
                                const top = inner.top;
                                const bottom = inner.bottom;
                                return { top, bottom };
                            }
                        }
                        else {
                            const top = align_top ? row_extents[r0].top : inner.top;
                            const bottom = align_bottom ? row_extents[r1].bottom : inner.bottom;
                            return { top, bottom };
                        }
                    })();
                    const { width, height } = outer_bbox;
                    return bbox_1.BBox.from_lrtb({ left, top, right: width - right, bottom: height - bottom });
                })();
                layout.set_geometry(outer_bbox, inner_bbox);
            });
        }
    }
    exports.GridAlignmentLayout = GridAlignmentLayout;
    GridAlignmentLayout.__name__ = "GridAlignmentLayout";
},
/* models/layouts/grid_box.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const css_grid_box_1 = require(412) /* ./css_grid_box */;
    const kinds_1 = require(185) /* ../common/kinds */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    class GridBoxView extends css_grid_box_1.CSSGridBoxView {
        connect_signals() {
            super.connect_signals();
            const { children, rows, cols } = this.model.properties;
            this.on_change(children, () => this.update_children());
            this.on_change([rows, cols], () => this.invalidate_layout());
        }
        get _children() {
            return this.model.children;
        }
        get _rows() {
            return this.model.rows;
        }
        get _cols() {
            return this.model.cols;
        }
    }
    exports.GridBoxView = GridBoxView;
    GridBoxView.__name__ = "GridBoxView";
    class GridBox extends css_grid_box_1.CSSGridBox {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GridBox = GridBox;
    _a = GridBox;
    GridBox.__name__ = "GridBox";
    (() => {
        _a.prototype.default_view = GridBoxView;
        _a.define(({ List, Nullable }) => {
            return {
                children: [List((0, kinds_1.GridChild)(ui_element_1.UIElement)), []],
                rows: [Nullable(kinds_1.TracksSizing), null],
                cols: [Nullable(kinds_1.TracksSizing), null],
            };
        });
    })();
},
/* models/layouts/css_grid_box.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const layout_dom_1 = require(406) /* ./layout_dom */;
    const alignments_1 = require(410) /* ./alignments */;
    const kinds_1 = require(185) /* ../common/kinds */;
    const dom_1 = require(63) /* ../../core/dom */;
    const grid_1 = require(259) /* ../../core/layout/grid */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const types_1 = require(8) /* ../../core/util/types */;
    const { max } = Math;
    class CSSGridBoxView extends layout_dom_1.LayoutDOMView {
        connect_signals() {
            super.connect_signals();
            const { spacing } = this.model.properties;
            this.on_change(spacing, () => this.invalidate_layout());
        }
        get child_models() {
            return this._children.map(([child]) => child);
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "grid" };
        }
        _update_layout() {
            super._update_layout();
            const styles = {};
            const [row_gap, column_gap] = (() => {
                const { spacing } = this.model;
                return (0, types_1.isNumber)(spacing) ? [spacing, spacing] : spacing;
            })();
            styles.row_gap = (0, dom_1.px)(row_gap);
            styles.column_gap = (0, dom_1.px)(column_gap);
            let nrows = 0;
            let ncols = 0;
            const layoutable = new grid_1.Container();
            for (const [[, row, col, row_span = 1, col_span = 1], i] of (0, iterator_1.enumerate)(this._children)) {
                const view = this.child_views[i];
                nrows = max(nrows, row + row_span);
                ncols = max(ncols, col + col_span);
                // CSS grid is 1-based, but layout is 0-based
                const styles = {};
                styles.grid_row_start = `${row + 1}`;
                styles.grid_row_end = `span ${row_span}`;
                styles.grid_column_start = `${col + 1}`;
                styles.grid_column_end = `span ${col_span}`;
                view.style.append(":host", styles);
                if (view instanceof layout_dom_1.LayoutDOMView && view.layout != null) {
                    const r0 = row;
                    const c0 = col;
                    const r1 = row + row_span - 1;
                    const c1 = col + col_span - 1;
                    layoutable.add({ r0, c0, r1, c1 }, view);
                }
            }
            const { _rows: rows, _cols: cols } = this;
            if (rows instanceof Map) {
                nrows = max(nrows, ...rows.keys());
            }
            else if ((0, types_1.isArray)(rows)) {
                nrows = max(nrows, rows.length);
            }
            if (cols instanceof Map) {
                ncols = max(ncols, ...cols.keys());
            }
            else if ((0, types_1.isArray)(cols)) {
                ncols = max(ncols, cols.length);
            }
            function parse_sizing(tracks, template) {
                if (tracks instanceof Map) {
                    for (const [i, spec] of tracks.entries()) {
                        if ((0, types_1.isString)(spec)) {
                            template[i].size = spec;
                        }
                        else {
                            template[i] = spec;
                        }
                    }
                }
                else if ((0, types_1.isArray)(tracks)) {
                    for (const [spec, i] of (0, iterator_1.enumerate)(tracks)) {
                        if ((0, types_1.isString)(spec)) {
                            template[i].size = spec;
                        }
                        else {
                            template[i] = spec;
                        }
                    }
                }
                else if (tracks != null) {
                    for (const row of template) {
                        if ((0, types_1.isString)(tracks)) {
                            row.size = tracks;
                        }
                        else {
                            row.size = tracks.size;
                            row.align = tracks.align;
                        }
                    }
                }
            }
            const rows_template = Array(nrows).fill(null).map(() => ({}));
            const cols_template = Array(ncols).fill(null).map(() => ({}));
            parse_sizing(rows, rows_template);
            parse_sizing(cols, cols_template);
            for (const [[, row, col], i] of (0, iterator_1.enumerate)(this._children)) {
                const child = this.child_views[i];
                const { halign, valign } = child.box_sizing();
                child.style.append(":host", {
                    justify_self: halign ?? cols_template[col].align,
                    align_self: valign ?? rows_template[row].align,
                });
            }
            const default_size = "auto";
            styles.grid_template_rows = rows_template.map(({ size }) => size ?? default_size).join(" ");
            styles.grid_template_columns = cols_template.map(({ size }) => size ?? default_size).join(" ");
            this.style.append(":host", styles);
            if (layoutable.size != 0) {
                this.layout = new alignments_1.GridAlignmentLayout(layoutable);
                this.layout.set_sizing();
            }
            else {
                delete this.layout;
            }
        }
    }
    exports.CSSGridBoxView = CSSGridBoxView;
    CSSGridBoxView.__name__ = "CSSGridBoxView";
    class CSSGridBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.CSSGridBox = CSSGridBox;
    _a = CSSGridBox;
    CSSGridBox.__name__ = "CSSGridBox";
    (() => {
        _a.define(() => ({
            spacing: [kinds_1.GridSpacing, 0],
        }));
    })();
},
/* models/layouts/group_box.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const layout_dom_1 = require(406) /* ./layout_dom */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    const dom_1 = require(63) /* ../../core/dom */;
    const group_box_css_1 = tslib_1.__importDefault(require(414) /* ../../styles/group_box.css */);
    class GroupBoxView extends layout_dom_1.LayoutDOMView {
        stylesheets() {
            return [...super.stylesheets(), group_box_css_1.default];
        }
        connect_signals() {
            super.connect_signals();
            const { child } = this.model.properties;
            this.on_change(child, () => this.update_children());
            const { checkable, disabled } = this.model.properties;
            this.on_change(checkable, () => {
                (0, dom_1.display)(this.checkbox_el, this.model.checkable);
            });
            this.on_change(disabled, () => {
                this.checkbox_el.checked = !this.model.disabled;
            });
        }
        get child_models() {
            return [this.model.child];
        }
        render() {
            super.render();
            const { checkable, disabled, title } = this.model;
            this.checkbox_el = (0, dom_1.input)({ type: "checkbox", checked: !disabled });
            this.checkbox_el.addEventListener("change", () => {
                this.model.disabled = !this.checkbox_el.checked;
            });
            (0, dom_1.display)(this.checkbox_el, checkable);
            const title_el = (0, dom_1.legend)({}, this.checkbox_el, title);
            const child_els = this.child_views.map((child) => child.el);
            this.fieldset_el = (0, dom_1.fieldset)({}, title_el, ...child_els);
            this.shadow_el.appendChild(this.fieldset_el);
        }
        _update_children() {
            const child_els = this.child_views.map((child) => child.el);
            this.fieldset_el.append(...child_els);
        }
    }
    exports.GroupBoxView = GroupBoxView;
    GroupBoxView.__name__ = "GroupBoxView";
    class GroupBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GroupBox = GroupBox;
    _a = GroupBox;
    GroupBox.__name__ = "GroupBox";
    (() => {
        _a.prototype.default_view = GroupBoxView;
        _a.define(({ Bool, Str, Nullable, Ref }) => ({
            title: [Nullable(Str), null],
            child: [Ref(ui_element_1.UIElement)],
            checkable: [Bool, false],
        }));
    })();
},
/* styles/group_box.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `legend{display:flex;gap:0.5em;padding:0 calc(var(--padding-horizontal) / 2);}fieldset{border:1px solid #ccc;}`;
},
/* models/layouts/hbox.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const css_grid_box_1 = require(412) /* ./css_grid_box */;
    const kinds_1 = require(185) /* ../common/kinds */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    const kinds_2 = require(21) /* ../../core/kinds */;
    const HBoxChild = (0, kinds_2.Struct)({ child: (0, kinds_2.Ref)(ui_element_1.UIElement), col: (0, kinds_2.Opt)(kinds_1.Index), span: (0, kinds_2.Opt)(kinds_1.Span) });
    class HBoxView extends css_grid_box_1.CSSGridBoxView {
        connect_signals() {
            super.connect_signals();
            const { children, cols } = this.model.properties;
            this.on_change(children, () => this.update_children());
            this.on_change(cols, () => this.invalidate_layout());
        }
        get _children() {
            return this.model.children.map(({ child, col, span }, i) => [child, 0, col ?? i, 1, span ?? 1]);
        }
        get _rows() {
            return null;
        }
        get _cols() {
            return this.model.cols;
        }
    }
    exports.HBoxView = HBoxView;
    HBoxView.__name__ = "HBoxView";
    class HBox extends css_grid_box_1.CSSGridBox {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.HBox = HBox;
    _a = HBox;
    HBox.__name__ = "HBox";
    (() => {
        _a.prototype.default_view = HBoxView;
        _a.define(({ List, Nullable }) => ({
            children: [List(HBoxChild), []],
            cols: [Nullable(kinds_1.TracksSizing), null],
        }));
    })();
},
/* models/layouts/row.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const flex_box_1 = require(405) /* ./flex_box */;
    class RowView extends flex_box_1.FlexBoxView {
        constructor() {
            super(...arguments);
            this._direction = "row";
        }
    }
    exports.RowView = RowView;
    RowView.__name__ = "RowView";
    class Row extends flex_box_1.FlexBox {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Row = Row;
    _a = Row;
    Row.__name__ = "Row";
    (() => {
        _a.prototype.default_view = RowView;
    })();
},
/* models/layouts/scroll_box.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const layout_dom_1 = require(406) /* ./layout_dom */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    const enums_1 = require(20) /* ../../core/enums */;
    class ScrollBoxView extends layout_dom_1.LayoutDOMView {
        stylesheets() {
            return [...super.stylesheets()];
        }
        connect_signals() {
            super.connect_signals();
            const { child, horizontal_scrollbar, vertical_scrollbar } = this.model.properties;
            this.on_change(child, () => this.update_children());
            this.on_change([horizontal_scrollbar, vertical_scrollbar], () => this.invalidate_layout());
        }
        get child_models() {
            return [this.model.child];
        }
        _update_layout() {
            super._update_layout();
            function to_overflow(policy) {
                switch (policy) {
                    case "auto": return "auto";
                    case "visible": return "scroll";
                    case "hidden": return "hidden";
                }
            }
            const { horizontal_scrollbar, vertical_scrollbar } = this.model;
            this.style.append(":host", {
                overflow_x: to_overflow(horizontal_scrollbar),
                overflow_y: to_overflow(vertical_scrollbar),
            });
        }
    }
    exports.ScrollBoxView = ScrollBoxView;
    ScrollBoxView.__name__ = "ScrollBoxView";
    class ScrollBox extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.ScrollBox = ScrollBox;
    _a = ScrollBox;
    ScrollBox.__name__ = "ScrollBox";
    (() => {
        _a.prototype.default_view = ScrollBoxView;
        _a.define(({ Ref }) => ({
            child: [Ref(ui_element_1.UIElement)],
            horizontal_scrollbar: [enums_1.ScrollbarPolicy, "auto"],
            vertical_scrollbar: [enums_1.ScrollbarPolicy, "auto"],
        }));
    })();
},
/* models/layouts/spacer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const layout_dom_1 = require(406) /* ./layout_dom */;
    class SpacerView extends layout_dom_1.LayoutDOMView {
        constructor() {
            super(...arguments);
            this._auto_width = "auto";
            this._auto_height = "auto";
        }
        get child_models() {
            return [];
        }
    }
    exports.SpacerView = SpacerView;
    SpacerView.__name__ = "SpacerView";
    class Spacer extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Spacer = Spacer;
    _a = Spacer;
    Spacer.__name__ = "Spacer";
    (() => {
        _a.prototype.default_view = SpacerView;
    })();
},
/* models/layouts/tab_panel.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tooltip_1 = require(420) /* ../ui/tooltip */;
    const model_1 = require(51) /* ../../model */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    class TabPanel extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TabPanel = TabPanel;
    _a = TabPanel;
    TabPanel.__name__ = "TabPanel";
    (() => {
        _a.define(({ Bool, Str, Ref, Nullable }) => ({
            title: [Str, ""],
            tooltip: [Nullable(Ref(tooltip_1.Tooltip)), null],
            child: [Ref(ui_element_1.UIElement)],
            closable: [Bool, false],
            disabled: [Bool, false],
        }));
    })();
},
/* models/ui/tooltip.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const ui_element_1 = require(111) /* ./ui_element */;
    const dom_node_1 = require(125) /* ../dom/dom_node */;
    const coordinate_1 = require(60) /* ../coordinates/coordinate */;
    const selector_1 = require(421) /* ../selectors/selector */;
    const enums_1 = require(20) /* ../../core/enums */;
    const dom_1 = require(63) /* ../../core/dom */;
    const dom_view_1 = require(57) /* ../../core/dom_view */;
    const types_1 = require(8) /* ../../core/util/types */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const logging_1 = require(19) /* ../../core/logging */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const model_1 = require(51) /* ../../model */;
    const NativeNode = globalThis.Node;
    const tooltips_css_1 = tslib_1.__importStar(require(422) /* ../../styles/tooltips.css */), tooltips = tooltips_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(123) /* ../../styles/icons.css */);
    class TooltipView extends ui_element_1.UIElementView {
        constructor() {
            super(...arguments);
            this._element_view = null;
            this._has_rendered = false;
        }
        get target() {
            return this._target;
        }
        set target(el) {
            this._target = el;
        }
        _init_target() {
            const { target } = this.model;
            const el = (() => {
                if (target instanceof ui_element_1.UIElement) {
                    return this.owner.find_one(target)?.el ?? null;
                }
                else if (target instanceof selector_1.Selector) {
                    return target.find_one(document);
                }
                else if (target instanceof NativeNode) {
                    return target;
                }
                else {
                    const { parent } = this;
                    return parent instanceof dom_view_1.DOMElementView ? parent.el : null;
                }
            })();
            if (el instanceof Element) {
                this._target = el;
            }
            else {
                logging_1.logger.warn(`unable to resolve target '${target}' for '${this}'`);
                this._target = document.body;
            }
        }
        initialize() {
            super.initialize();
            this._init_target();
        }
        *children() {
            yield* super.children();
            if (this._element_view != null) {
                yield this._element_view;
            }
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this._build_content();
        }
        async _build_content() {
            if (this._element_view != null) {
                this._element_view.remove();
                this._element_view = null;
            }
            const { content } = this.model;
            if (content instanceof model_1.Model) {
                this._element_view = await (0, build_views_1.build_view)(content, { parent: this });
            }
        }
        connect_signals() {
            super.connect_signals();
            this._observer = new ResizeObserver(() => {
                this._reposition();
            });
            this._observer.observe(this.target);
            let throttle = false;
            document.addEventListener("scroll", this._scroll_listener = () => {
                if (!throttle) {
                    requestAnimationFrame(() => {
                        this._reposition();
                        throttle = false;
                    });
                    throttle = true;
                }
            }, { capture: true });
            const { target, content, closable, interactive, position, attachment, visible } = this.model.properties;
            this.on_change(target, () => {
                this._init_target();
                this._observer.disconnect();
                this._observer.observe(this.target);
                this.render();
                this.after_render();
            });
            this.on_change(content, async () => {
                await this._build_content();
                this.render();
                this.after_render();
            });
            this.on_change([closable, interactive], () => {
                this.render();
                this.after_render();
            });
            this.on_change([position, attachment, visible], () => {
                this._reposition();
            });
        }
        disconnect_signals() {
            if (this._scroll_listener != null) {
                document.removeEventListener("scroll", this._scroll_listener, { capture: true });
                delete this._scroll_listener;
            }
            super.disconnect_signals();
        }
        remove() {
            this._element_view?.remove();
            this._observer.disconnect();
            super.remove();
        }
        stylesheets() {
            return [...super.stylesheets(), tooltips_css_1.default, icons_css_1.default];
        }
        get content() {
            const { content } = this.model;
            if ((0, types_1.isString)(content)) {
                return document.createTextNode(content);
            }
            else if (content instanceof model_1.Model) {
                (0, assert_1.assert)(this._element_view != null);
                return this._element_view.el;
            }
            else {
                return content;
            }
        }
        render() {
            super.render();
            const { _element_view } = this;
            if (_element_view != null) {
                _element_view.render();
                _element_view.r_after_render();
            }
            this.arrow_el = (0, dom_1.div)({ class: [tooltips.arrow] });
            this.content_el = (0, dom_1.div)({ class: tooltips.tooltip_content }, this.content);
            this.shadow_el.append(this.arrow_el, this.content_el);
            this.class_list.toggle(tooltips.closable, this.model.closable);
            const close_el = (0, dom_1.div)({ class: tooltips.close });
            this.shadow_el.append(close_el);
            close_el.addEventListener("click", () => {
                this.model.visible = false;
            });
            this.el.classList.toggle(tooltips.show_arrow, this.model.show_arrow);
            this.el.classList.toggle(tooltips.non_interactive, !this.model.interactive);
            this._has_rendered = true;
        }
        _after_render() {
            super._after_render();
            this._reposition();
        }
        _after_resize() {
            super._after_resize();
            this._reposition();
        }
        _anchor_to_align(anchor) {
            anchor = (() => {
                switch (anchor) {
                    case "top": return "top_center";
                    case "bottom": return "bottom_center";
                    case "left": return "center_left";
                    case "right": return "center_right";
                    default: return anchor;
                }
            })();
            const [v, h] = anchor.split("_");
            return { v, h };
        }
        _reposition() {
            // Append to `body` to deal with CSS' `contain` interaction
            // with `position: fixed`. We assume initial containment
            // block in this function, but `contain` can introduce a
            // new containment block and offset tooltip's position.
            const target = document.body.shadowRoot ?? document.body;
            if (!this._has_rendered) {
                this.render_to(target);
                this.after_render();
                return; // render() calls _reposition()
            }
            const { position, visible } = this.model;
            if (position == null || !visible) {
                this.el.remove();
                return;
            }
            target.append(this.el);
            const bbox = (0, dom_1.bounding_box)(this.target);
            const [sx, sy] = (() => {
                if ((0, types_1.isString)(position)) {
                    const { v: v_align, h: h_align } = this._anchor_to_align(position);
                    const sx = (() => {
                        switch (h_align) {
                            case "left": return bbox.left;
                            case "center": return bbox.hcenter;
                            case "right": return bbox.right;
                        }
                    })();
                    const sy = (() => {
                        switch (v_align) {
                            case "top": return bbox.top;
                            case "center": return bbox.vcenter;
                            case "bottom": return bbox.bottom;
                        }
                    })();
                    return [sx, sy];
                }
                else if ((0, types_1.isArray)(position)) {
                    const [x, y] = position;
                    return [bbox.left + x, bbox.top + y];
                }
                else {
                    // XXX this assumes position is resolved relative to this.target
                    const { x, y } = this.resolve_as_xy(position);
                    return [bbox.left + x, bbox.top + y];
                }
            })();
            const viewport = new bbox_1.BBox({
                x: 0,
                y: 0,
                width: window.innerWidth,
                height: window.innerHeight,
            });
            const arrow_size = (0, dom_1.box_size)(this.arrow_el);
            const side = (() => {
                const attachment = (() => {
                    const { attachment } = this.model;
                    if (attachment == "auto") {
                        if ((0, types_1.isString)(position)) {
                            const { v: v_align, h: h_align } = this._anchor_to_align(position);
                            if (h_align != "center") {
                                return h_align == "left" ? "left" : "right";
                            }
                            if (v_align != "center") {
                                return v_align == "top" ? "above" : "below";
                            }
                        }
                        return "horizontal";
                    }
                    else {
                        return attachment;
                    }
                })();
                const el_size = (0, dom_1.box_size)(this.el);
                const width = el_size.width + arrow_size.width;
                const height = el_size.height + arrow_size.height;
                switch (attachment) {
                    case "horizontal": {
                        if (sx < bbox.hcenter) {
                            return sx + width <= viewport.right ? "right" : "left";
                        }
                        else {
                            return sx - width >= viewport.left ? "left" : "right";
                        }
                    }
                    case "vertical": {
                        if (sy < bbox.vcenter) {
                            return sy + height <= viewport.bottom ? "below" : "above";
                        }
                        else {
                            return sy - height >= viewport.top ? "above" : "below";
                        }
                    }
                    default:
                        return attachment;
                }
            })();
            // slightly confusing: side "left" (for example) is relative to point that
            // is being annotated but CS class ".bk-left" is relative to the tooltip itself
            this.class_list.remove(tooltips.right, tooltips.left, tooltips.above, tooltips.below);
            this.class_list.add((() => {
                switch (side) {
                    case "left": return tooltips.right;
                    case "right": return tooltips.left;
                    case "above": return tooltips.below;
                    case "below": return tooltips.above;
                }
            })());
            this.arrow_el.style.left = `${sx}px`;
            this.arrow_el.style.top = `${sy}px`;
            const { left, top } = (() => {
                const { width, height } = (0, dom_1.box_size)(this.el);
                function adjust_top(top) {
                    if (top < viewport.top) {
                        return viewport.top;
                    }
                    else if (top + height > viewport.bottom) {
                        return viewport.bottom - height;
                    }
                    else {
                        return top;
                    }
                }
                function adjust_left(left) {
                    if (left < viewport.left) {
                        return viewport.left;
                    }
                    else if (left + width > viewport.right) {
                        return viewport.right - width;
                    }
                    else {
                        return left;
                    }
                }
                switch (side) {
                    case "left": {
                        return {
                            left: sx - width - arrow_size.width,
                            top: adjust_top(sy - height / 2),
                        };
                    }
                    case "right": {
                        return {
                            left: sx + arrow_size.width,
                            top: adjust_top(sy - height / 2),
                        };
                    }
                    case "above": {
                        return {
                            left: adjust_left(sx - width / 2),
                            top: sy - height - arrow_size.height,
                        };
                    }
                    case "below": {
                        return {
                            left: adjust_left(sx - width / 2),
                            top: sy + arrow_size.height,
                        };
                    }
                }
            })();
            this.el.style.top = `${top}px`;
            this.el.style.left = `${left}px`;
        }
    }
    exports.TooltipView = TooltipView;
    TooltipView.__name__ = "TooltipView";
    class Tooltip extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
        show({ x, y }) {
            this.setv({ position: [x, y], visible: true }, { check_eq: false }); // XXX: force update
        }
        clear() {
            this.position = null;
        }
    }
    exports.Tooltip = Tooltip;
    _a = Tooltip;
    Tooltip.__name__ = "Tooltip";
    (() => {
        _a.prototype.default_view = TooltipView;
        _a.define(({ Bool, Float, Str, Tuple, Or, Ref, Nullable, Auto }) => ({
            target: [Or(Ref(ui_element_1.UIElement), Ref(selector_1.Selector), Ref(NativeNode), Auto), "auto"],
            position: [Nullable(Or(enums_1.Anchor, Tuple(Float, Float), Ref(coordinate_1.Coordinate))), null],
            content: [Or(Str, Ref(dom_node_1.DOMNode), Ref(ui_element_1.UIElement), Ref(NativeNode))],
            attachment: [Or(enums_1.TooltipAttachment, Auto), "auto"],
            show_arrow: [Bool, true],
            closable: [Bool, false],
            interactive: [Bool, true],
        }));
        _a.override({
            visible: false,
        });
    })();
},
/* models/selectors/selector.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    class Selector extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Selector = Selector;
    _a = Selector;
    Selector.__name__ = "Selector";
    (() => {
        _a.define(({ Str }) => ({
            query: [Str],
        }));
    })();
},
/* styles/tooltips.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.non_interactive = "bk-non-interactive";
    exports.arrow = "bk-arrow";
    exports.show_arrow = "bk-show-arrow";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.tooltip_content = "bk-tooltip-content";
    exports.tooltip_row_label = "bk-tooltip-row-label";
    exports.tooltip_row_value = "bk-tooltip-row-value";
    exports.tooltip_color_block = "bk-tooltip-color-block";
    exports.closable = "bk-closable";
    exports.close = "bk-close";
    exports.default = `:host{--tooltip-border:#e5e5e5;--tooltip-color:white;--tooltip-text:#2f2f2f;--tooltip-arrow-color:#909599;--tooltip-arrow-width:10px;--tooltip-arrow-height:10px;--tooltip-arrow-half-width:7px;--tooltip-arrow-half-height:7px;}:host{width:max-content;font-size:var(--font-size);position:fixed;padding:5px;border:1px solid var(--tooltip-border);color:var(--tooltip-text);background-color:var(--tooltip-color);opacity:0.95;z-index:var(--bokeh-top-level);}:host(.bk-non-interactive){pointer-events:none;}.bk-arrow{pointer-events:none;position:fixed;width:0;height:0;content:" ";border-style:solid;border-color:transparent;}:host(:not(.bk-show-arrow)) .bk-arrow{display:none;}:host(.bk-left) .bk-arrow,:host(.bk-right) .bk-arrow{border-width:var(--tooltip-arrow-half-height) 0 var(--tooltip-arrow-half-height) 0;}:host(.bk-above) .bk-arrow,:host(.bk-below) .bk-arrow{border-width:0 var(--tooltip-arrow-half-width) 0 var(--tooltip-arrow-half-width);}:host(.bk-left) .bk-arrow{transform:translate(0%, -50%);border-right-width:var(--tooltip-arrow-width);border-right-color:var(--tooltip-arrow-color);}:host(.bk-right) .bk-arrow{transform:translate(-100%, -50%);border-left-width:var(--tooltip-arrow-width);border-left-color:var(--tooltip-arrow-color);}:host(.bk-above) .bk-arrow{transform:translate(-50%, 0%);border-bottom-width:var(--tooltip-arrow-height);border-bottom-color:var(--tooltip-arrow-color);}:host(.bk-below) .bk-arrow{transform:translate(-50%, -100%);border-top-width:var(--tooltip-arrow-height);border-top-color:var(--tooltip-arrow-color);}.bk-tooltip-content > div:not(:first-child){margin-top:5px;border-top:var(--tooltip-border) 1px dashed;}.bk-tooltip-row-label{text-align:right;color:#26aae1;}.bk-tooltip-row-value{color:none;}.bk-tooltip-color-block{width:12px;height:12px;margin-left:5px;margin-right:5px;outline:#dddddd solid 1px;display:inline-block;}:host(:not(.bk-closable)) .bk-close{display:none;}.bk-close{position:absolute;top:2px;right:2px;width:12px;height:12px;cursor:pointer;background-color:gray;mask-image:var(--bokeh-icon-x);mask-size:contain;mask-repeat:no-repeat;-webkit-mask-image:var(--bokeh-icon-x);-webkit-mask-size:contain;-webkit-mask-repeat:no-repeat;}.bk-close:hover{background-color:red;}`;
},
/* models/layouts/tabs.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const dom_1 = require(63) /* ../../core/dom */;
    const array_1 = require(10) /* ../../core/util/array */;
    const grid_1 = require(259) /* ../../core/layout/grid */;
    const enums_1 = require(20) /* ../../core/enums */;
    const layout_dom_1 = require(406) /* ./layout_dom */;
    const tab_panel_1 = require(419) /* ./tab_panel */;
    const alignments_1 = require(410) /* ./alignments */;
    const tabs_css_1 = tslib_1.__importStar(require(424) /* ../../styles/tabs.css */), tabs = tabs_css_1;
    const icons_css_1 = tslib_1.__importDefault(require(123) /* ../../styles/icons.css */);
    class TabsView extends layout_dom_1.LayoutDOMView {
        constructor() {
            super(...arguments);
            this.tooltip_views = new Map();
        }
        connect_signals() {
            super.connect_signals();
            const { tabs, active } = this.model.properties;
            this.on_change(tabs, async () => {
                this._update_headers();
                await this.update_children();
            });
            this.on_change(active, () => {
                this.update_active();
            });
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { tabs } = this.model;
            const tooltips = tabs.map((tab) => tab.tooltip).filter((tt) => tt != null);
            await (0, build_views_1.build_views)(this.tooltip_views, tooltips, { parent: this });
        }
        stylesheets() {
            return [...super.stylesheets(), tabs_css_1.default, icons_css_1.default];
        }
        get child_models() {
            return this.model.tabs.map((tab) => tab.child);
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "grid" };
        }
        _update_layout() {
            super._update_layout();
            const loc = this.model.tabs_location;
            this.class_list.remove([...enums_1.Location].map((loc) => tabs[loc]));
            this.class_list.add(tabs[loc]);
            const layoutable = new grid_1.Container();
            for (const view of this.child_views) {
                view.style.append(":host", { grid_area: "stack" });
                if (view instanceof layout_dom_1.LayoutDOMView && view.layout != null) {
                    layoutable.add({ r0: 0, c0: 0, r1: 1, c1: 1 }, view);
                }
            }
            if (layoutable.size != 0) {
                this.layout = new alignments_1.GridAlignmentLayout(layoutable);
                this.layout.set_sizing();
            }
            else {
                delete this.layout;
            }
        }
        _after_layout() {
            super._after_layout();
            const { child_views } = this;
            for (const child_view of child_views) {
                (0, dom_1.hide)(child_view.el);
            }
            const { active } = this.model;
            if (active in child_views) {
                const tab = child_views[active];
                (0, dom_1.show)(tab.el);
            }
        }
        render() {
            super.render();
            this.header_el = (0, dom_1.div)({ class: tabs.header });
            this.shadow_el.append(this.header_el);
            this._update_headers();
        }
        _update_headers() {
            const { active } = this.model;
            const headers = this.model.tabs.map((tab, i) => {
                const tab_el = (0, dom_1.div)({ class: [tabs.tab, i == active ? tabs.active : null], tabIndex: 0 }, tab.title);
                tab_el.addEventListener("click", (event) => {
                    if (this.model.disabled) {
                        return;
                    }
                    if (event.target == event.currentTarget) {
                        this.change_active(i);
                    }
                });
                const tooltip_view = tab.tooltip != null ? this.tooltip_views.get(tab.tooltip) : null;
                if (tooltip_view != null) {
                    tooltip_view.model.target = tab_el;
                    const toggle_tooltip = (visible) => {
                        tooltip_view.model.visible = visible;
                    };
                    tab_el.addEventListener("mouseenter", () => {
                        toggle_tooltip(true);
                    });
                    tab_el.addEventListener("mouseleave", () => {
                        toggle_tooltip(false);
                    });
                }
                if (tab.closable) {
                    const close_el = (0, dom_1.div)({ class: tabs.close });
                    close_el.addEventListener("click", (event) => {
                        if (event.target == event.currentTarget) {
                            this.model.tabs = (0, array_1.remove_at)(this.model.tabs, i);
                            const ntabs = this.model.tabs.length;
                            if (this.model.active > ntabs - 1) {
                                this.model.active = ntabs - 1;
                            }
                        }
                    });
                    tab_el.appendChild(close_el);
                }
                if (this.model.disabled || tab.disabled) {
                    tab_el.classList.add(tabs.disabled);
                }
                return tab_el;
            });
            this.header_els = headers;
            (0, dom_1.empty)(this.header_el);
            this.header_el.append(...headers);
        }
        change_active(i) {
            if (i != this.model.active) {
                this.model.active = i;
            }
        }
        update_active() {
            const i = this.model.active;
            const { header_els } = this;
            for (const el of header_els) {
                el.classList.remove(tabs.active);
            }
            if (i in header_els) {
                header_els[i].classList.add(tabs.active);
            }
            const { child_views } = this;
            for (const child_view of child_views) {
                (0, dom_1.hide)(child_view.el);
            }
            if (i in child_views) {
                (0, dom_1.show)(child_views[i].el);
            }
        }
    }
    exports.TabsView = TabsView;
    TabsView.__name__ = "TabsView";
    class Tabs extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Tabs = Tabs;
    _a = Tabs;
    Tabs.__name__ = "Tabs";
    (() => {
        _a.prototype.default_view = TabsView;
        _a.define(({ Int, List, Ref }) => ({
            tabs: [List(Ref(tab_panel_1.TabPanel)), []],
            tabs_location: [enums_1.Location, "above"],
            active: [Int, 0],
        }));
    })();
},
/* styles/tabs.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.above = "bk-above";
    exports.below = "bk-below";
    exports.left = "bk-left";
    exports.right = "bk-right";
    exports.header = "bk-header";
    exports.tab = "bk-tab";
    exports.active = "bk-active";
    exports.close = "bk-close";
    exports.disabled = "bk-disabled";
    exports.default = `:host{display:grid;}:host(.bk-above){grid-template:"header" max-content "stack" 1fr / 1fr;}:host(.bk-below){grid-template:"stack" 1fr "header" max-content / 1fr;}:host(.bk-left){grid-template:"header stack" 1fr / max-content 1fr;}:host(.bk-right){grid-template:"stack header" 1fr / 1fr max-content;}.bk-header{grid-area:"header";display:flex;flex-wrap:nowrap;align-items:stretch;user-select:none;-webkit-user-select:none;}:host(.bk-above) .bk-header,:host(.bk-below) .bk-header{flex-direction:row;}:host(.bk-left) .bk-header,:host(.bk-right) .bk-header{flex-direction:column;}:host(.bk-above) .bk-header{border-bottom:1px solid #e6e6e6;}:host(.bk-right) .bk-header{border-left:1px solid #e6e6e6;}:host(.bk-below) .bk-header{border-top:1px solid #e6e6e6;}:host(.bk-left) .bk-header{border-right:1px solid #e6e6e6;}.bk-tab{padding:4px 8px;border:solid transparent;outline:0;outline-offset:-5px;white-space:nowrap;cursor:pointer;text-align:center;}.bk-tab:hover{background-color:#f2f2f2;}.bk-tab:focus,.bk-tab:active{outline:1px dotted #ccc;}.bk-tab.bk-active{color:#4d4d4d;background-color:white;border-color:#e6e6e6;}.bk-tab .bk-close{margin-left:10px;}.bk-tab.bk-disabled{cursor:not-allowed;pointer-events:none;opacity:0.65;}:host(.bk-above) .bk-tab{border-width:3px 1px 0px 1px;border-radius:var(--border-radius) var(--border-radius) 0 0;}:host(.bk-right) .bk-tab{border-width:1px 3px 1px 0px;border-radius:0 var(--border-radius) var(--border-radius) 0;}:host(.bk-below) .bk-tab{border-width:0px 1px 3px 1px;border-radius:0 0 var(--border-radius) var(--border-radius);}:host(.bk-left) .bk-tab{border-width:1px 0px 1px 3px;border-radius:var(--border-radius) 0 0 var(--border-radius);}.bk-close{display:inline-block;vertical-align:middle;width:14px;height:14px;cursor:pointer;background-color:gray;mask-image:var(--bokeh-icon-x);mask-size:contain;mask-repeat:no-repeat;-webkit-mask-image:var(--bokeh-icon-x);-webkit-mask-size:contain;-webkit-mask-repeat:no-repeat;}.bk-close:hover{background-color:red;}`;
},
/* models/layouts/vbox.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const css_grid_box_1 = require(412) /* ./css_grid_box */;
    const kinds_1 = require(185) /* ../common/kinds */;
    const ui_element_1 = require(111) /* ../ui/ui_element */;
    const kinds_2 = require(21) /* ../../core/kinds */;
    const VBoxChild = (0, kinds_2.Struct)({ child: (0, kinds_2.Ref)(ui_element_1.UIElement), row: (0, kinds_2.Opt)(kinds_1.Index), span: (0, kinds_2.Opt)(kinds_1.Span) });
    class VBoxView extends css_grid_box_1.CSSGridBoxView {
        connect_signals() {
            super.connect_signals();
            const { children, rows } = this.model.properties;
            this.on_change(children, () => this.update_children());
            this.on_change(rows, () => this.invalidate_layout());
        }
        get _children() {
            return this.model.children.map(({ child, row, span }, i) => [child, row ?? i, 0, span ?? 1, 1]);
        }
        get _rows() {
            return this.model.rows;
        }
        get _cols() {
            return null;
        }
    }
    exports.VBoxView = VBoxView;
    VBoxView.__name__ = "VBoxView";
    class VBox extends css_grid_box_1.CSSGridBox {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.VBox = VBox;
    _a = VBox;
    VBox.__name__ = "VBox";
    (() => {
        _a.prototype.default_view = VBoxView;
        _a.define(({ List, Nullable }) => ({
            children: [List(VBoxChild), []],
            rows: [Nullable(kinds_1.TracksSizing), null],
        }));
    })();
},
/* models/misc/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var group_by_1 = require(427) /* ./group_by */;
    __esExport("GroupByModels", group_by_1.GroupByModels);
    __esExport("GroupByName", group_by_1.GroupByName);
},
/* models/misc/group_by.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const kinds_1 = require(21) /* ../../core/kinds */;
    class GroupBy extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GroupBy = GroupBy;
    GroupBy.__name__ = "GroupBy";
    class GroupByModels extends GroupBy {
        constructor(attrs) {
            super(attrs);
        }
        *query_groups(models, _pool) {
            for (const model of models) {
                for (const group of this.groups) {
                    if (group.includes(model)) {
                        yield group;
                    }
                }
            }
        }
    }
    exports.GroupByModels = GroupByModels;
    _a = GroupByModels;
    GroupByModels.__name__ = "GroupByModels";
    (() => {
        _a.define({
            groups: [(0, kinds_1.List)((0, kinds_1.List)((0, kinds_1.Ref)(model_1.Model)))],
        });
    })();
    class GroupByName extends GroupBy {
        constructor(attrs) {
            super(attrs);
        }
        *query_groups(models, pool) {
            const groups = new Map();
            for (const model of pool) {
                const { name } = model;
                if (name != null) {
                    let group = groups.get(name);
                    if (group === undefined) {
                        group = new Set();
                        groups.set(name, group);
                    }
                    group.add(model);
                }
            }
            for (const model of models) {
                for (const group of groups.values()) {
                    if (model.name != null && group.has(model)) {
                        yield [...group];
                    }
                }
            }
        }
    }
    exports.GroupByName = GroupByName;
    GroupByName.__name__ = "GroupByName";
},
/* models/text/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var math_text_1 = require(178) /* ./math_text */;
    __esExport("MathText", math_text_1.MathText);
    __esExport("Ascii", math_text_1.Ascii);
    __esExport("MathML", math_text_1.MathML);
    __esExport("TeX", math_text_1.TeX);
    var plain_text_1 = require(184) /* ./plain_text */;
    __esExport("PlainText", plain_text_1.PlainText);
},
/* models/transforms/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var customjs_transform_1 = require(430) /* ./customjs_transform */;
    __esExport("CustomJSTransform", customjs_transform_1.CustomJSTransform);
    var dodge_1 = require(431) /* ./dodge */;
    __esExport("Dodge", dodge_1.Dodge);
    var interpolator_1 = require(433) /* ./interpolator */;
    __esExport("Interpolator", interpolator_1.Interpolator);
    var jitter_1 = require(434) /* ./jitter */;
    __esExport("Jitter", jitter_1.Jitter);
    var linear_interpolator_1 = require(436) /* ./linear_interpolator */;
    __esExport("LinearInterpolator", linear_interpolator_1.LinearInterpolator);
    var step_interpolator_1 = require(437) /* ./step_interpolator */;
    __esExport("StepInterpolator", step_interpolator_1.StepInterpolator);
    var transform_1 = require(97) /* ./transform */;
    __esExport("Transform", transform_1.Transform);
},
/* models/transforms/customjs_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const transform_1 = require(97) /* ./transform */;
    const object_1 = require(9) /* ../../core/util/object */;
    const string_1 = require(40) /* ../../core/util/string */;
    class CustomJSTransform extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        get names() {
            return (0, object_1.keys)(this.args);
        }
        get values() {
            return (0, object_1.values)(this.args);
        }
        _make_transform(name, func) {
            return new Function(...this.names, name, (0, string_1.use_strict)(func));
        }
        get scalar_transform() {
            return this._make_transform("x", this.func);
        }
        get vector_transform() {
            return this._make_transform("xs", this.v_func);
        }
        compute(x) {
            return this.scalar_transform(...this.values, x);
        }
        v_compute(xs) {
            return this.vector_transform(...this.values, xs);
        }
    }
    exports.CustomJSTransform = CustomJSTransform;
    _a = CustomJSTransform;
    CustomJSTransform.__name__ = "CustomJSTransform";
    (() => {
        _a.define(({ Unknown, Str, Dict }) => ({
            args: [Dict(Unknown), {}],
            func: [Str, ""],
            v_func: [Str, ""],
        }));
    })();
},
/* models/transforms/dodge.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const range_transform_1 = require(432) /* ./range_transform */;
    class Dodge extends range_transform_1.RangeTransform {
        constructor(attrs) {
            super(attrs);
        }
        _compute(x) {
            return x + this.value;
        }
    }
    exports.Dodge = Dodge;
    _a = Dodge;
    Dodge.__name__ = "Dodge";
    (() => {
        _a.define(({ Float }) => ({
            value: [Float, 0],
        }));
    })();
},
/* models/transforms/range_transform.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const transform_1 = require(97) /* ./transform */;
    const range_1 = require(98) /* ../ranges/range */;
    const factor_range_1 = require(109) /* ../ranges/factor_range */;
    const types_1 = require(24) /* ../../core/types */;
    const types_2 = require(8) /* ../../core/util/types */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class RangeTransform extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
        }
        v_compute(xs0) {
            let xs;
            if (this.range instanceof factor_range_1.FactorRange) {
                xs = this.range.v_synthetic(xs0);
            }
            else if ((0, types_2.isArrayableOf)(xs0, types_2.isNumber)) {
                xs = xs0;
            }
            else {
                (0, assert_1.unreachable)();
            }
            const result = new ((0, types_1.infer_type)(xs))(xs.length);
            for (let i = 0; i < xs.length; i++) {
                const x = xs[i];
                result[i] = this._compute(x);
            }
            return result;
        }
        compute(x) {
            if (this.range instanceof factor_range_1.FactorRange) {
                return this._compute(this.range.synthetic(x));
            }
            else if ((0, types_2.isNumber)(x)) {
                return this._compute(x);
            }
            else {
                (0, assert_1.unreachable)();
            }
        }
    }
    exports.RangeTransform = RangeTransform;
    _a = RangeTransform;
    RangeTransform.__name__ = "RangeTransform";
    (() => {
        _a.define(({ Ref, Nullable }) => ({
            range: [Nullable(Ref(range_1.Range)), null],
        }));
    })();
},
/* models/transforms/interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const transform_1 = require(97) /* ./transform */;
    const columnar_data_source_1 = require(128) /* ../sources/columnar_data_source */;
    const types_1 = require(24) /* ../../core/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const types_2 = require(8) /* ../../core/util/types */;
    class Interpolator extends transform_1.Transform {
        constructor(attrs) {
            super(attrs);
            this._sorted_dirty = true;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.change, () => this._sorted_dirty = true);
        }
        v_compute(xs) {
            const ArrayType = (0, types_1.infer_type)(xs);
            const result = new ArrayType(xs.length);
            for (let i = 0; i < xs.length; i++) {
                const x = xs[i];
                result[i] = this.compute(x);
            }
            return result;
        }
        sort(descending = false) {
            if (!this._sorted_dirty) {
                return;
            }
            let tsx;
            let tsy;
            if ((0, types_2.isString)(this.x) && (0, types_2.isString)(this.y) && this.data != null) {
                const column_names = this.data.columns();
                if (!(0, array_1.includes)(column_names, this.x)) {
                    throw new Error("The x parameter does not correspond to a valid column name defined in the data parameter");
                }
                if (!(0, array_1.includes)(column_names, this.y)) {
                    throw new Error("The y parameter does not correspond to a valid column name defined in the data parameter");
                }
                tsx = this.data.get_column(this.x);
                tsy = this.data.get_column(this.y);
            }
            else if ((0, types_2.isArray)(this.x) && (0, types_2.isArray)(this.y)) {
                tsx = this.x;
                tsy = this.y;
            }
            else {
                throw new Error("parameters 'x' and 'y' must be both either string fields or arrays");
            }
            if (tsx.length !== tsy.length) {
                throw new Error("The length for x and y do not match");
            }
            if (tsx.length < 2) {
                throw new Error("x and y must have at least two elements to support interpolation");
            }
            const n = tsx.length;
            const index = new Uint32Array(n);
            for (let i = 0; i < n; i++) {
                index[i] = i;
            }
            const sign = descending ? -1 : 1;
            index.sort((i, j) => sign * (tsx[i] - tsx[j]));
            this._x_sorted = new ((0, types_1.infer_type)(tsx))(n);
            this._y_sorted = new ((0, types_1.infer_type)(tsy))(n);
            for (let i = 0; i < n; i++) {
                this._x_sorted[i] = tsx[index[i]];
                this._y_sorted[i] = tsy[index[i]];
            }
            this._sorted_dirty = false;
        }
    }
    exports.Interpolator = Interpolator;
    _a = Interpolator;
    Interpolator.__name__ = "Interpolator";
    (() => {
        _a.define(({ Bool, Float, Str, Ref, List, Or, Nullable }) => ({
            x: [Or(Str, List(Float))],
            y: [Or(Str, List(Float))],
            data: [Nullable(Ref(columnar_data_source_1.ColumnarDataSource)), null],
            clip: [Bool, true],
        }));
    })();
},
/* models/transforms/jitter.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const range_transform_1 = require(432) /* ./range_transform */;
    const factor_range_1 = require(109) /* ../ranges/factor_range */;
    const random_generator_1 = require(435) /* ../random/random_generator */;
    const enums_1 = require(20) /* ../../core/enums */;
    const arrayable_1 = require(13) /* ../../core/util/arrayable */;
    const random_1 = require(115) /* ../../core/util/random */;
    class Jitter extends range_transform_1.RangeTransform {
        constructor(attrs) {
            super(attrs);
            this._previous_offsets = null;
        }
        initialize() {
            super.initialize();
            this._generator = this.random_generator?.generator() ?? new random_1.SystemRandom();
        }
        v_compute(xs0) {
            const xs = (() => {
                if (this.range instanceof factor_range_1.FactorRange) {
                    return this.range.v_synthetic(xs0);
                }
                else {
                    return xs0;
                }
            })();
            const offsets = (() => {
                const xs_length = xs.length;
                if (this._previous_offsets?.length != xs_length) {
                    this._previous_offsets = this._v_compute(xs_length);
                }
                return this._previous_offsets;
            })();
            return (0, arrayable_1.map)(offsets, (offset, i) => offset + xs[i]);
        }
        _compute() {
            const { mean, width } = this;
            switch (this.distribution) {
                case "uniform": return this._generator.uniform(mean, width);
                case "normal": return this._generator.normal(mean, width);
            }
        }
        _v_compute(n) {
            const { mean, width } = this;
            switch (this.distribution) {
                case "uniform": return this._generator.uniforms(mean, width, n);
                case "normal": return this._generator.normals(mean, width, n);
            }
        }
    }
    exports.Jitter = Jitter;
    _a = Jitter;
    Jitter.__name__ = "Jitter";
    (() => {
        _a.define(({ Float }) => ({
            mean: [Float, 0],
            width: [Float, 1],
            distribution: [enums_1.Distribution, "uniform"],
        }));
        _a.internal(({ Nullable, Ref }) => ({
            random_generator: [Nullable(Ref(random_generator_1.RandomGenerator)), null],
        }));
    })();
},
/* models/random/random_generator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const model_1 = require(51) /* ../../model */;
    class RandomGenerator extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.RandomGenerator = RandomGenerator;
    RandomGenerator.__name__ = "RandomGenerator";
},
/* models/transforms/linear_interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const array_1 = require(10) /* ../../core/util/array */;
    const interpolator_1 = require(433) /* ./interpolator */;
    class LinearInterpolator extends interpolator_1.Interpolator {
        constructor(attrs) {
            super(attrs);
        }
        compute(x) {
            this.sort(false);
            if (this.clip) {
                if (x < this._x_sorted[0] || x > this._x_sorted[this._x_sorted.length - 1]) {
                    return NaN;
                }
            }
            else {
                if (x < this._x_sorted[0]) {
                    return this._y_sorted[0];
                }
                if (x > this._x_sorted[this._x_sorted.length - 1]) {
                    return this._y_sorted[this._y_sorted.length - 1];
                }
            }
            if (x == this._x_sorted[0]) {
                return this._y_sorted[0];
            }
            const ind = (0, array_1.find_last_index)(this._x_sorted, num => num < x);
            const x1 = this._x_sorted[ind];
            const x2 = this._x_sorted[ind + 1];
            const y1 = this._y_sorted[ind];
            const y2 = this._y_sorted[ind + 1];
            return y1 + (((x - x1) / (x2 - x1)) * (y2 - y1));
        }
    }
    exports.LinearInterpolator = LinearInterpolator;
    LinearInterpolator.__name__ = "LinearInterpolator";
},
/* models/transforms/step_interpolator.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const interpolator_1 = require(433) /* ./interpolator */;
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    class StepInterpolator extends interpolator_1.Interpolator {
        constructor(attrs) {
            super(attrs);
        }
        compute(x) {
            this.sort(false);
            if (this.clip) {
                if (x < this._x_sorted[0] || x > this._x_sorted[this._x_sorted.length - 1]) {
                    return NaN;
                }
            }
            else {
                if (x < this._x_sorted[0]) {
                    return this._y_sorted[0];
                }
                if (x > this._x_sorted[this._x_sorted.length - 1]) {
                    return this._y_sorted[this._y_sorted.length - 1];
                }
            }
            let ind;
            switch (this.mode) {
                case "after": {
                    ind = (0, array_1.find_last_index)(this._x_sorted, num => x >= num);
                    break;
                }
                case "before": {
                    ind = (0, array_1.find_index)(this._x_sorted, num => x <= num);
                    break;
                }
                case "center": {
                    const diffs = (0, array_1.map)(this._x_sorted, (tx) => Math.abs(tx - x));
                    const mdiff = (0, array_1.min)(diffs);
                    ind = (0, array_1.find_index)(diffs, num => mdiff === num);
                    break;
                }
                default:
                    throw new Error(`unknown mode: ${this.mode}`);
            }
            return ind != -1 ? this._y_sorted[ind] : NaN;
        }
    }
    exports.StepInterpolator = StepInterpolator;
    _a = StepInterpolator;
    StepInterpolator.__name__ = "StepInterpolator";
    (() => {
        _a.define(() => ({
            mode: [enums_1.StepMode, "after"],
        }));
    })();
},
/* models/plots/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var gmap_plot_1 = require(439) /* ./gmap_plot */;
    __esExport("MapOptions", gmap_plot_1.MapOptions);
    var gmap_plot_2 = require(439) /* ./gmap_plot */;
    __esExport("GMapOptions", gmap_plot_2.GMapOptions);
    var gmap_plot_3 = require(439) /* ./gmap_plot */;
    __esExport("GMapPlot", gmap_plot_3.GMapPlot);
    var gmap_1 = require(451) /* ./gmap */;
    __esExport("GMap", gmap_1.GMap);
    var plot_1 = require(440) /* ./plot */;
    __esExport("Plot", plot_1.Plot);
    var grid_plot_1 = require(452) /* ./grid_plot */;
    __esExport("GridPlot", grid_plot_1.GridPlot);
    var figure_1 = require(453) /* ./figure */;
    __esExport("Figure", figure_1.Figure);
},
/* models/plots/gmap_plot.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c;
    __esModule();
    const plot_1 = require(440) /* ./plot */;
    const enums_1 = require(20) /* ../../core/enums */;
    const model_1 = require(51) /* ../../model */;
    const range1d_1 = require(99) /* ../ranges/range1d */;
    const gmap_plot_canvas_1 = require(450) /* ./gmap_plot_canvas */;
    __esExport("GMapPlotView", gmap_plot_canvas_1.GMapPlotView);
    class MapOptions extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.MapOptions = MapOptions;
    _a = MapOptions;
    MapOptions.__name__ = "MapOptions";
    (() => {
        _a.define(({ Int, Float }) => ({
            lat: [Float],
            lng: [Float],
            zoom: [Int, 12],
        }));
    })();
    class GMapOptions extends MapOptions {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GMapOptions = GMapOptions;
    _b = GMapOptions;
    GMapOptions.__name__ = "GMapOptions";
    (() => {
        _b.define(({ Bool, Int, Str, Nullable }) => ({
            map_type: [enums_1.MapType, "roadmap"],
            scale_control: [Bool, false],
            styles: [Nullable(Str), null],
            tilt: [Int, 45],
        }));
    })();
    class GMapPlot extends plot_1.Plot {
        constructor(attrs) {
            super(attrs);
            this.use_map = true;
        }
    }
    exports.GMapPlot = GMapPlot;
    _c = GMapPlot;
    GMapPlot.__name__ = "GMapPlot";
    (() => {
        _c.prototype.default_view = gmap_plot_canvas_1.GMapPlotView;
        _c.define(({ Str, Bytes, Ref }) => ({
            map_options: [Ref(GMapOptions)],
            api_key: [Bytes],
            api_version: [Str, "weekly"],
        }));
        _c.override({
            x_range: () => new range1d_1.Range1d(),
            y_range: () => new range1d_1.Range1d(),
            background_fill_alpha: 0.0,
        });
    })();
},
/* models/plots/plot.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const mixins = tslib_1.__importStar(require(80) /* ../../core/property_mixins */);
    const p = tslib_1.__importStar(require(18) /* ../../core/properties */);
    const signaling_1 = require(15) /* ../../core/signaling */;
    const enums_1 = require(20) /* ../../core/enums */;
    const array_1 = require(10) /* ../../core/util/array */;
    const set_1 = require(44) /* ../../core/util/set */;
    const types_1 = require(8) /* ../../core/util/types */;
    const layout_dom_1 = require(406) /* ../layouts/layout_dom */;
    const axis_1 = require(189) /* ../axes/axis */;
    const grid_1 = require(402) /* ../grids/grid */;
    const annotation_1 = require(81) /* ../annotations/annotation */;
    const title_1 = require(171) /* ../annotations/title */;
    const linear_scale_1 = require(101) /* ../scales/linear_scale */;
    const toolbar_1 = require(292) /* ../tools/toolbar */;
    const html_1 = require(408) /* ../dom/html */;
    const range_1 = require(98) /* ../ranges/range */;
    const scale_1 = require(96) /* ../scales/scale */;
    const column_data_source_1 = require(133) /* ../sources/column_data_source */;
    const renderer_1 = require(83) /* ../renderers/renderer */;
    const data_renderer_1 = require(219) /* ../renderers/data_renderer */;
    const glyph_renderer_1 = require(218) /* ../renderers/glyph_renderer */;
    const tool_1 = require(293) /* ../tools/tool */;
    const data_range1d_1 = require(106) /* ../ranges/data_range1d */;
    const plot_canvas_1 = require(441) /* ./plot_canvas */;
    __esExport("PlotView", plot_canvas_1.PlotView);
    class Plot extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
            this.use_map = false;
            this.reset = new signaling_1.Signal0(this, "reset");
        }
        add_layout(renderer, side = "center") {
            const renderers = this.properties[side].get_value();
            this.setv({ [side]: [...renderers, renderer] });
        }
        remove_layout(renderer) {
            const del = (items) => {
                (0, array_1.remove_by)(items, (item) => item == renderer);
            };
            del(this.left);
            del(this.right);
            del(this.above);
            del(this.below);
            del(this.center);
        }
        get data_renderers() {
            return this.renderers.filter((r) => r instanceof data_renderer_1.DataRenderer);
        }
        add_renderers(...renderers) {
            this.renderers = [...this.renderers, ...renderers];
        }
        add_glyph(glyph, source = new column_data_source_1.ColumnDataSource(), attrs = {}) {
            const renderer = new glyph_renderer_1.GlyphRenderer({ ...attrs, data_source: source, glyph });
            this.add_renderers(renderer);
            return renderer;
        }
        add_tools(...tools) {
            const computed_tools = tools.map((tool) => tool instanceof tool_1.Tool ? tool : tool_1.Tool.from_string(tool));
            this.toolbar.tools = [...this.toolbar.tools, ...computed_tools];
        }
        remove_tools(...tools) {
            this.toolbar.tools = [...(0, set_1.difference)(new Set(this.toolbar.tools), new Set(tools))];
        }
        get panels() {
            return [...this.side_panels, ...this.center];
        }
        get side_panels() {
            const { above, below, left, right } = this;
            return (0, array_1.concat)([above, below, left, right]);
        }
    }
    exports.Plot = Plot;
    _a = Plot;
    Plot.__name__ = "Plot";
    (() => {
        _a.prototype.default_view = plot_canvas_1.PlotView;
        _a.mixins([
            ["outline_", mixins.Line],
            ["background_", mixins.Fill],
            ["border_", mixins.Fill],
        ]);
        _a.define(({ Bool, Float, Str, List, Dict, Or, Ref, Null, Nullable, Struct, Opt }) => ({
            toolbar: [Ref(toolbar_1.Toolbar), () => new toolbar_1.Toolbar()],
            toolbar_location: [Nullable(enums_1.Location), "right"],
            toolbar_sticky: [Bool, true],
            toolbar_inner: [Bool, false],
            frame_width: [Nullable(Float), null],
            frame_height: [Nullable(Float), null],
            frame_align: [Or(Bool, Struct({ left: Opt(Bool), right: Opt(Bool), top: Opt(Bool), bottom: Opt(Bool) })), true],
            // revise this when https://github.com/microsoft/TypeScript/pull/42425 is merged
            title: [Or(Ref(title_1.Title), Str, Null), "", {
                    convert: (title) => (0, types_1.isString)(title) ? new title_1.Title({ text: title }) : title,
                }],
            title_location: [Nullable(enums_1.Location), "above"],
            above: [List(Or(Ref(annotation_1.Annotation), Ref(axis_1.Axis))), []],
            below: [List(Or(Ref(annotation_1.Annotation), Ref(axis_1.Axis))), []],
            left: [List(Or(Ref(annotation_1.Annotation), Ref(axis_1.Axis))), []],
            right: [List(Or(Ref(annotation_1.Annotation), Ref(axis_1.Axis))), []],
            center: [List(Or(Ref(annotation_1.Annotation), Ref(grid_1.Grid))), []],
            renderers: [List(Ref(renderer_1.Renderer)), []],
            x_range: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
            y_range: [Ref(range_1.Range), () => new data_range1d_1.DataRange1d()],
            x_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
            y_scale: [Ref(scale_1.Scale), () => new linear_scale_1.LinearScale()],
            extra_x_ranges: [Dict(Ref(range_1.Range)), {}],
            extra_y_ranges: [Dict(Ref(range_1.Range)), {}],
            extra_x_scales: [Dict(Ref(scale_1.Scale)), {}],
            extra_y_scales: [Dict(Ref(scale_1.Scale)), {}],
            lod_factor: [Float, 10],
            lod_interval: [Float, 300],
            lod_threshold: [Nullable(Float), 2000],
            lod_timeout: [Float, 500],
            hidpi: [Bool, true],
            output_backend: [enums_1.OutputBackend, "canvas"],
            min_border: [Nullable(Float), 5],
            min_border_top: [Nullable(Float), null],
            min_border_left: [Nullable(Float), null],
            min_border_bottom: [Nullable(Float), null],
            min_border_right: [Nullable(Float), null],
            inner_width: [Float, p.unset, { readonly: true }],
            inner_height: [Float, p.unset, { readonly: true }],
            outer_width: [Float, p.unset, { readonly: true }],
            outer_height: [Float, p.unset, { readonly: true }],
            match_aspect: [Bool, false],
            aspect_scale: [Float, 1],
            reset_policy: [enums_1.ResetPolicy, "standard"],
            hold_render: [Bool, false],
            attribution: [List(Or(Str, Ref(html_1.HTML))), []],
        }));
        _a.override({
            width: 600,
            height: 600,
            outline_line_color: "#e5e5e5",
            border_fill_color: "#ffffff",
            background_fill_color: "#ffffff",
        });
    })();
},
/* models/plots/plot_canvas.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const cartesian_frame_1 = require(188) /* ../canvas/cartesian_frame */;
    const canvas_1 = require(325) /* ../canvas/canvas */;
    const renderer_1 = require(83) /* ../renderers/renderer */;
    const composite_renderer_1 = require(82) /* ../renderers/composite_renderer */;
    const tool_proxy_1 = require(294) /* ../tools/tool_proxy */;
    const layout_dom_1 = require(406) /* ../layouts/layout_dom */;
    const annotation_1 = require(81) /* ../annotations/annotation */;
    const title_1 = require(171) /* ../annotations/title */;
    const axis_1 = require(189) /* ../axes/axis */;
    const toolbar_panel_1 = require(291) /* ../annotations/toolbar_panel */;
    const data_range1d_1 = require(106) /* ../ranges/data_range1d */;
    const panel_1 = require(442) /* ../ui/panel */;
    const elements_1 = require(444) /* ../dom/elements */;
    const bokeh_events_1 = require(53) /* ../../core/bokeh_events */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const visuals_1 = require(87) /* ../../core/visuals */;
    const logging_1 = require(19) /* ../../core/logging */;
    const bokeh_events_2 = require(53) /* ../../core/bokeh_events */;
    const signaling_1 = require(15) /* ../../core/signaling */;
    const throttle_1 = require(445) /* ../../core/util/throttle */;
    const types_1 = require(8) /* ../../core/util/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const iterator_1 = require(34) /* ../../core/util/iterator */;
    const canvas_2 = require(112) /* ../../core/util/canvas */;
    const alignments_1 = require(258) /* ../../core/layout/alignments */;
    const border_1 = require(260) /* ../../core/layout/border */;
    const grid_1 = require(259) /* ../../core/layout/grid */;
    const side_panel_1 = require(173) /* ../../core/layout/side_panel */;
    const bbox_1 = require(64) /* ../../core/util/bbox */;
    const text_1 = require(181) /* ../../core/util/text */;
    const range_manager_1 = require(446) /* ./range_manager */;
    const state_manager_1 = require(447) /* ./state_manager */;
    const settings_1 = require(29) /* ../../core/settings */;
    const dom_1 = require(63) /* ../../core/dom */;
    const node_1 = require(59) /* ../coordinates/node */;
    const plots_css_1 = tslib_1.__importDefault(require(448) /* ../../styles/plots.css */);
    const attribution_css_1 = tslib_1.__importDefault(require(449) /* ../../styles/attribution.css */);
    const { max } = Math;
    class PlotView extends layout_dom_1.LayoutDOMView {
        constructor() {
            super(...arguments);
            this._render_count = 0;
            this.repainted = new signaling_1.Signal0(this, "repainted");
            this._computed_style = new dom_1.InlineStyleSheet();
            this._outer_bbox = new bbox_1.BBox();
            this._inner_bbox = new bbox_1.BBox();
            this._needs_paint = true;
            this._invalidated_painters = new Set();
            this._invalidate_all = true;
            this.computed_renderers = [];
            /*protected*/ this.renderer_views = new Map();
            /*protected*/ this.tool_views = new Map();
            this._is_paused = 0;
            this._needs_notify = false;
            this._messages = new Map();
        }
        get frame() {
            return this.frame_view;
        }
        get canvas() {
            return this.canvas_view;
        }
        stylesheets() {
            return [...super.stylesheets(), plots_css_1.default, this._computed_style];
        }
        get toolbar_panel() {
            return this._toolbar != null ? this.views.find_one(this._toolbar) : null;
        }
        get state() {
            return this._state_manager;
        }
        set invalidate_dataranges(value) {
            this._range_manager.invalidate_dataranges = value;
        }
        get computed_renderer_views() {
            return this
                .computed_renderers
                .map((r) => this.renderer_views.get(r))
                .filter((rv) => rv != null); // TODO race condition again
        }
        get all_renderer_views() {
            const collected = [];
            for (const rv of this.computed_renderer_views) {
                collected.push(rv);
                if (rv instanceof composite_renderer_1.CompositeRendererView) {
                    collected.push(...rv.computed_renderer_views);
                }
            }
            return collected;
        }
        get auto_ranged_renderers() {
            return this.computed_renderer_views.filter(data_range1d_1.is_auto_ranged);
        }
        get base_font_size() {
            const font_size = getComputedStyle(this.el).fontSize;
            const result = (0, text_1.parse_css_font_size)(font_size);
            if (result != null) {
                const { value, unit } = result;
                if (unit == "px") {
                    return value;
                }
            }
            return null;
        }
        *children() {
            yield* super.children();
            yield* this.renderer_views.values();
            yield* this.tool_views.values();
        }
        get child_models() {
            return [];
        }
        get is_paused() {
            return this._is_paused != 0;
        }
        pause() {
            this._is_paused += 1;
        }
        unpause(no_render = false) {
            this._is_paused = max(this._is_paused - 1, 0);
            if (!this.is_paused && !no_render) {
                this.request_repaint();
            }
        }
        notify_finished_after_paint() {
            this._needs_notify = true;
        }
        request_repaint() {
            this.request_paint();
        }
        request_paint(...to_invalidate) {
            this.invalidate_painters(...to_invalidate);
            this.schedule_paint();
        }
        invalidate_painters(...to_invalidate) {
            if (to_invalidate.length == 0) {
                this._invalidate_all = true;
                return;
            }
            for (const item of to_invalidate) {
                const view = (() => {
                    if (item instanceof renderer_1.RendererView) {
                        return item;
                    }
                    else {
                        return this.views.get_one(item);
                    }
                })();
                this._invalidated_painters.add(view);
            }
        }
        schedule_paint() {
            if (!this.is_paused) {
                const promise = this.throttled_paint();
                this._ready = this._ready.then(() => promise);
            }
        }
        request_layout() {
            this.request_repaint();
        }
        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() {
            (0, build_views_1.remove_views)(this.renderer_views);
            (0, build_views_1.remove_views)(this.tool_views);
            super.remove();
        }
        get_context_menu(xy) {
            const { x, y } = xy;
            for (const rv of (0, array_1.reversed)([...this.renderer_views.values()])) {
                if (rv.context_menu != null && rv.interactive_hit?.(x, y) == true) {
                    return rv.context_menu;
                }
            }
            return super.get_context_menu(xy);
        }
        initialize() {
            this.pause();
            super.initialize();
            this.lod_started = false;
            this.visuals = new visuals_1.Visuals(this);
            this._initial_state = {
                selection: new Map(), // XXX: initial selection?
            };
            this._frame = new cartesian_frame_1.CartesianFrame({
                x_scale: this.model.x_scale,
                y_scale: this.model.y_scale,
                x_range: this.model.x_range,
                y_range: this.model.y_range,
                extra_x_ranges: this.model.extra_x_ranges,
                extra_y_ranges: this.model.extra_y_ranges,
                extra_x_scales: this.model.extra_x_scales,
                extra_y_scales: this.model.extra_y_scales,
                aspect_scale: this.model.aspect_scale,
                match_aspect: this.model.match_aspect,
            });
            this._range_manager = new range_manager_1.RangeManager(this);
            this._state_manager = new state_manager_1.StateManager(this, this._initial_state);
            this.throttled_paint = (0, throttle_1.throttle)(() => {
                if (!this.is_destroyed) {
                    this.repaint();
                }
            }, 1000 / 60);
            const { title_location, title } = this.model;
            if (title_location != null && title != null) {
                this._title = title instanceof title_1.Title ? title : new title_1.Title({ text: title });
            }
            const { toolbar_location, toolbar_inner, toolbar } = this.model;
            if (toolbar_location != null) {
                this._toolbar = new toolbar_panel_1.ToolbarPanel({ toolbar });
                toolbar.location = toolbar_location;
                toolbar.inner = toolbar_inner;
            }
            const { hidpi, output_backend } = this.model;
            this._canvas = new canvas_1.Canvas({ hidpi, output_backend });
            this._attribution = new panel_1.Panel({
                position: new node_1.Node({ target: "frame", symbol: "bottom_right" }),
                anchor: "bottom_right",
                elements: [],
                css_variables: {
                    "--max-width": new node_1.Node({ target: "frame", symbol: "width" }),
                },
                stylesheets: [attribution_css_1.default],
            });
            this._notifications = new panel_1.Panel({
                position: new node_1.Node({ target: this.model, symbol: "top_center" }),
                anchor: "top_center",
                elements: [],
                stylesheets: [`
        :host {
          display: flex;
          flex-direction: column;
          gap: 1em;
          width: max-content;
          max-width: 80%;
        }

        :host:empty {
          display: none;
        }

        :host > div {
          padding: 0.5em;
          border: 1px solid gray;
          border-radius: 0.5em;
          opacity: 0.8;
        }
      `],
            });
        }
        get elements() {
            return [this._canvas, this._frame, this._attribution, this._notifications, ...super.elements];
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.canvas_view = this._element_views.get(this._canvas);
            this.canvas_view.plot_views = [this];
            this.frame_view = this._element_views.get(this._frame);
            await this.build_tool_views();
            await this.build_renderer_views();
            this._range_manager.update_dataranges();
        }
        box_sizing() {
            const { width_policy, height_policy, ...sizing } = super.box_sizing();
            const { frame_width, frame_height } = this.model;
            return {
                ...sizing,
                width_policy: frame_width != null && width_policy == "auto" ? "fit" : width_policy,
                height_policy: frame_height != null && height_policy == "auto" ? "fit" : height_policy,
            };
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "grid" };
        }
        _update_layout() {
            super._update_layout();
            // TODO: invalidating all should imply "needs paint"
            this._invalidate_all = true;
            this._needs_paint = true;
            const layout = new border_1.BorderLayout();
            const { frame_align } = this.model;
            layout.aligns = (() => {
                if ((0, types_1.isBoolean)(frame_align)) {
                    return { left: frame_align, right: frame_align, top: frame_align, bottom: frame_align };
                }
                else {
                    const { left = true, right = true, top = true, bottom = true } = frame_align;
                    return { left, right, top, bottom };
                }
            })();
            layout.set_sizing({ width_policy: "max", height_policy: "max" });
            if (this.visuals.outline_line.doit) {
                const width = this.visuals.outline_line.line_width.get_value();
                layout.center_border_width = width;
            }
            const outer_above = (0, array_1.copy)(this.model.above);
            const outer_below = (0, array_1.copy)(this.model.below);
            const outer_left = (0, array_1.copy)(this.model.left);
            const outer_right = (0, array_1.copy)(this.model.right);
            const inner_above = [];
            const inner_below = [];
            const inner_left = [];
            const inner_right = [];
            const get_side = (side, inner = false) => {
                switch (side) {
                    case "above": return inner ? inner_above : outer_above;
                    case "below": return inner ? inner_below : outer_below;
                    case "left": return inner ? inner_left : outer_left;
                    case "right": return inner ? inner_right : outer_right;
                }
            };
            const { title_location } = this.model;
            if (title_location != null && this._title != null) {
                get_side(title_location).push(this._title);
            }
            if (this._toolbar != null) {
                const { location } = this._toolbar.toolbar;
                if (!this.model.toolbar_inner) {
                    const panels = get_side(location);
                    let push_toolbar = true;
                    if (this.model.toolbar_sticky) {
                        for (let i = 0; i < panels.length; i++) {
                            const panel = panels[i];
                            if (panel instanceof title_1.Title) {
                                if (location == "above" || location == "below") {
                                    panels[i] = [panel, this._toolbar];
                                }
                                else {
                                    panels[i] = [this._toolbar, panel];
                                }
                                push_toolbar = false;
                                break;
                            }
                        }
                    }
                    if (push_toolbar) {
                        panels.push(this._toolbar);
                    }
                }
                else {
                    const panels = get_side(location, true);
                    panels.push(this._toolbar);
                }
            }
            const set_layout = (side, model) => {
                const view = this.views.get_one(model);
                view.panel = new side_panel_1.SidePanel(side);
                view.update_layout?.();
                return view.layout;
            };
            const set_layouts = (side, panels) => {
                const horizontal = side == "above" || side == "below";
                const layouts = [];
                for (const panel of panels) {
                    if ((0, types_1.isArray)(panel)) {
                        const items = panel.map((subpanel) => {
                            const item = set_layout(side, subpanel);
                            if (item == null) {
                                return undefined;
                            }
                            if (subpanel instanceof toolbar_panel_1.ToolbarPanel) {
                                const dim = horizontal ? "width_policy" : "height_policy";
                                item.set_sizing({ ...item.sizing, [dim]: "min" });
                            }
                            return item;
                        }).filter((item) => item != null);
                        let layout;
                        if (horizontal) {
                            layout = new grid_1.Row(items);
                            layout.set_sizing({ width_policy: "max", height_policy: "min" });
                        }
                        else {
                            layout = new grid_1.Column(items);
                            layout.set_sizing({ width_policy: "min", height_policy: "max" });
                        }
                        layout.absolute = true;
                        layouts.push(layout);
                    }
                    else {
                        const layout = set_layout(side, panel);
                        if (layout != null) {
                            layouts.push(layout);
                        }
                    }
                }
                return layouts;
            };
            const min_border = this.model.min_border ?? 0;
            layout.min_border = {
                left: this.model.min_border_left ?? min_border,
                top: this.model.min_border_top ?? min_border,
                right: this.model.min_border_right ?? min_border,
                bottom: this.model.min_border_bottom ?? min_border,
            };
            const center_panel = new alignments_1.NodeLayout();
            const top_panel = new alignments_1.VStack();
            const bottom_panel = new alignments_1.VStack();
            const left_panel = new alignments_1.HStack();
            const right_panel = new alignments_1.HStack();
            const inner_top_panel = new alignments_1.VStack();
            const inner_bottom_panel = new alignments_1.VStack();
            const inner_left_panel = new alignments_1.HStack();
            const inner_right_panel = new alignments_1.HStack();
            center_panel.absolute = true;
            top_panel.absolute = true;
            bottom_panel.absolute = true;
            left_panel.absolute = true;
            right_panel.absolute = true;
            inner_top_panel.absolute = true;
            inner_bottom_panel.absolute = true;
            inner_left_panel.absolute = true;
            inner_right_panel.absolute = true;
            center_panel.children =
                this.model.center.filter((obj) => {
                    return obj instanceof annotation_1.Annotation;
                }).map((model) => {
                    const view = this.views.get_one(model);
                    view.update_layout?.();
                    return view.layout;
                }).filter((layout) => layout != null);
            const { frame_width, frame_height } = this.model;
            center_panel.set_sizing({
                ...(frame_width != null ? { width_policy: "fixed", width: frame_width } : { width_policy: "fit" }),
                ...(frame_height != null ? { height_policy: "fixed", height: frame_height } : { height_policy: "fit" }),
            });
            center_panel.on_resize((bbox) => this.frame.set_geometry(bbox));
            top_panel.children = (0, array_1.reversed)(set_layouts("above", outer_above));
            bottom_panel.children = set_layouts("below", outer_below);
            left_panel.children = (0, array_1.reversed)(set_layouts("left", outer_left));
            right_panel.children = set_layouts("right", outer_right);
            inner_top_panel.children = set_layouts("above", inner_above);
            inner_bottom_panel.children = set_layouts("below", inner_below);
            inner_left_panel.children = set_layouts("left", inner_left);
            inner_right_panel.children = set_layouts("right", inner_right);
            top_panel.set_sizing({ width_policy: "fit", height_policy: "min" /*, min_height: layout.min_border.top*/ });
            bottom_panel.set_sizing({ width_policy: "fit", height_policy: "min" /*, min_height: layout.min_width.bottom*/ });
            left_panel.set_sizing({ width_policy: "min", height_policy: "fit" /*, min_width: layout.min_width.left*/ });
            right_panel.set_sizing({ width_policy: "min", height_policy: "fit" /*, min_width: layout.min_width.right*/ });
            inner_top_panel.set_sizing({ width_policy: "fit", height_policy: "min" });
            inner_bottom_panel.set_sizing({ width_policy: "fit", height_policy: "min" });
            inner_left_panel.set_sizing({ width_policy: "min", height_policy: "fit" });
            inner_right_panel.set_sizing({ width_policy: "min", height_policy: "fit" });
            layout.center_panel = center_panel;
            layout.top_panel = top_panel;
            layout.bottom_panel = bottom_panel;
            layout.left_panel = left_panel;
            layout.right_panel = right_panel;
            if (inner_top_panel.children.length != 0) {
                layout.inner_top_panel = inner_top_panel;
            }
            if (inner_bottom_panel.children.length != 0) {
                layout.inner_bottom_panel = inner_bottom_panel;
            }
            if (inner_left_panel.children.length != 0) {
                layout.inner_left_panel = inner_left_panel;
            }
            if (inner_right_panel.children.length != 0) {
                layout.inner_right_panel = inner_right_panel;
            }
            this.layout = layout;
        }
        _measure_layout() {
            const { frame_width, frame_height } = this.model;
            const frame = {
                width: frame_width == null ? "1fr" : (0, dom_1.px)(frame_width),
                height: frame_height == null ? "1fr" : (0, dom_1.px)(frame_height),
            };
            const { layout } = this;
            const top = layout.top_panel.measure({ width: Infinity, height: Infinity });
            const bottom = layout.bottom_panel.measure({ width: Infinity, height: Infinity });
            const left = layout.left_panel.measure({ width: Infinity, height: Infinity });
            const right = layout.right_panel.measure({ width: Infinity, height: Infinity });
            const top_height = max(top.height, layout.min_border.top);
            const bottom_height = max(bottom.height, layout.min_border.bottom);
            const left_width = max(left.width, layout.min_border.left);
            const right_width = max(right.width, layout.min_border.right);
            this._computed_style.replace(`
      :host {
        grid-template-rows: ${top_height}px ${frame.height} ${bottom_height}px;
        grid-template-columns: ${left_width}px ${frame.width} ${right_width}px;
      }
    `);
        }
        get axis_views() {
            const views = [];
            for (const [, renderer_view] of this.renderer_views) {
                if (renderer_view instanceof axis_1.AxisView) {
                    views.push(renderer_view);
                }
            }
            return views;
        }
        update_range(range_info, options) {
            this.pause();
            this._range_manager.update(range_info, options);
            this.unpause();
        }
        reset_range() {
            this.pause();
            this._range_manager.reset();
            this.unpause();
            this.trigger_ranges_update_event();
        }
        trigger_ranges_update_event(extra_ranges = []) {
            /**
             * Emits `RangesUpdate` event on all plots linked by all
             * ranges managed by this plot's range manager and linked
             * by additional context dependent ranges (`extra_ranges`).
             */
            const { x_ranges, y_ranges } = this._range_manager.ranges();
            const ranges = [...x_ranges, ...y_ranges, ...extra_ranges];
            const linked_plots = new Set(ranges.flatMap((r) => [...r.linked_plots]));
            for (const plot_view of linked_plots) {
                const { x_range, y_range } = plot_view.model;
                const event = new bokeh_events_2.RangesUpdate(x_range.start, x_range.end, y_range.start, y_range.end);
                plot_view.model.trigger_event(event);
            }
        }
        get_selection() {
            const selection = new Map();
            for (const renderer of this.model.data_renderers) {
                const { selected } = renderer.selection_manager.source;
                selection.set(renderer, selected);
            }
            return selection;
        }
        update_selection(selections) {
            for (const renderer of this.model.data_renderers) {
                const ds = renderer.selection_manager.source;
                if (selections != null) {
                    const selection = selections.get(renderer);
                    if (selection != null) {
                        ds.selected.update(selection, true);
                    }
                }
                else {
                    ds.selection_manager.clear();
                }
            }
        }
        reset_selection() {
            this.update_selection(null);
        }
        _invalidate_layout_if_needed() {
            const needs_layout = (() => {
                for (const panel of this.model.side_panels) {
                    const view = this.renderer_views.get(panel);
                    if (view.layout?.has_size_changed() ?? false) {
                        this.invalidate_painters(view);
                        return true;
                    }
                }
                return false;
            })();
            if (needs_layout) {
                this.compute_layout();
            }
        }
        *_compute_renderers() {
            const { above, below, left, right, center, renderers } = this.model;
            yield* renderers;
            yield* above;
            yield* below;
            yield* left;
            yield* right;
            yield* center;
            if (this._title != null) {
                yield this._title;
            }
            if (this._toolbar != null) {
                yield this._toolbar;
            }
            for (const [, view] of this.tool_views) {
                yield* view.overlays;
            }
        }
        _update_attribution() {
            const attribution = [
                ...this.model.attribution,
                ...this.computed_renderer_views.map((rv) => rv.attribution),
            ].filter((rv) => rv != null);
            const elements = attribution.map((attrib) => (0, types_1.isString)(attrib) ? new elements_1.Div({ children: [attrib] }) : attrib);
            this._attribution.elements = elements;
            // TODO this._attribution.title = contents_el.textContent!.replace(/\s*\n\s*/g, " ")
        }
        async _build_renderers() {
            this.computed_renderers = [...this._compute_renderers()];
            const result = await (0, build_views_1.build_views)(this.renderer_views, this.computed_renderers, { parent: this });
            this._update_attribution();
            return result;
        }
        async _update_renderers() {
            const { created } = await this._build_renderers();
            const created_renderers = new Set(created);
            // First remove and then either reattach existing renderers or render and
            // attach new renderers, so that the order of children is consistent, while
            // avoiding expensive re-rendering of existing views.
            for (const renderer_view of this.renderer_views.values()) {
                renderer_view.el.remove();
            }
            for (const renderer_view of this.renderer_views.values()) {
                const is_new = created_renderers.has(renderer_view);
                const target = renderer_view.rendering_target();
                if (is_new) {
                    renderer_view.render_to(target);
                }
                else {
                    target.append(renderer_view.el);
                }
            }
            this.r_after_render();
        }
        async build_renderer_views() {
            await this._build_renderers();
        }
        async build_tool_views() {
            const tool_models = (0, iterator_1.flat_map)(this.model.toolbar.tools, (item) => item instanceof tool_proxy_1.ToolProxy ? item.tools : [item]);
            const { created } = await (0, build_views_1.build_views)(this.tool_views, [...tool_models], { parent: this });
            created.map((tool_view) => this.canvas_view.ui_event_bus.register_tool(tool_view));
        }
        connect_signals() {
            super.connect_signals();
            const { x_range, y_range, x_scale, y_scale, extra_x_ranges, extra_y_ranges, extra_x_scales, extra_y_scales, aspect_scale, match_aspect, } = this.model.properties;
            this.on_change([
                x_range, y_range,
                x_scale, y_scale,
                extra_x_ranges, extra_y_ranges,
                extra_x_scales, extra_y_scales,
                aspect_scale, match_aspect,
            ], () => {
                const { x_range, y_range, x_scale, y_scale, extra_x_ranges, extra_y_ranges, extra_x_scales, extra_y_scales, aspect_scale, match_aspect, } = this.model;
                this._frame.setv({
                    x_range, y_range,
                    x_scale, y_scale,
                    extra_x_ranges, extra_y_ranges,
                    extra_x_scales, extra_y_scales,
                    aspect_scale, match_aspect,
                });
            });
            const { above, below, left, right, center, renderers } = this.model.properties;
            const panels = [above, below, left, right, center];
            this.on_change(renderers, async () => {
                await this._update_renderers();
            });
            this.on_change(panels, async () => {
                await this._update_renderers();
                this.invalidate_layout();
            });
            this.connect(this.model.toolbar.properties.tools.change, async () => {
                await this.build_tool_views();
                await this._update_renderers();
            });
            const { x_ranges, y_ranges } = this.frame;
            for (const [, range] of x_ranges) {
                this.connect(range.change, () => {
                    this.request_repaint();
                });
            }
            for (const [, range] of y_ranges) {
                this.connect(range.change, () => {
                    this.request_repaint();
                });
            }
            this.connect(this.model.change, () => this.request_repaint());
            this.connect(this.model.reset, () => this.reset());
            const { toolbar_location } = this.model.properties;
            this.on_change(toolbar_location, async () => {
                const { toolbar_location } = this.model;
                if (this._toolbar != null) {
                    if (toolbar_location != null) {
                        this._toolbar.toolbar.location = toolbar_location;
                    }
                    else {
                        this._toolbar = undefined;
                        await this._update_renderers();
                    }
                }
                else {
                    if (toolbar_location != null) {
                        const { toolbar, toolbar_inner } = this.model;
                        this._toolbar = new toolbar_panel_1.ToolbarPanel({ toolbar });
                        toolbar.location = toolbar_location;
                        toolbar.inner = toolbar_inner;
                        await this._update_renderers();
                    }
                }
                this.invalidate_layout();
            });
            const { hold_render } = this.model.properties;
            this.on_change(hold_render, () => {
                if (!this.model.hold_render) {
                    this.request_repaint();
                }
            });
        }
        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() {
            super._after_layout();
            this.unpause(true);
            const left = this.layout.left_panel.bbox;
            const right = this.layout.right_panel.bbox;
            const center = this.layout.center_panel.bbox;
            const top = this.layout.top_panel.bbox;
            const bottom = this.layout.bottom_panel.bbox;
            const { bbox } = this;
            const top_height = top.bottom;
            const bottom_height = bbox.height - bottom.top;
            const left_width = left.right;
            const right_width = bbox.width - right.left;
            // TODO: don't replace here; inject stylesheet?
            this.canvas.style.replace(`
      .bk-layer.bk-events {
        display: grid;
        grid-template-areas:
          ".    above  .    "
          "left center right"
          ".    below  .    ";
        grid-template-rows: ${(0, dom_1.px)(top_height)} ${(0, dom_1.px)(center.height)} ${(0, dom_1.px)(bottom_height)};
        grid-template-columns: ${(0, dom_1.px)(left_width)} ${(0, dom_1.px)(center.width)} ${(0, dom_1.px)(right_width)};
      }
    `);
            for (const [, child_view] of this.renderer_views) {
                if (child_view instanceof annotation_1.AnnotationView) {
                    child_view.after_layout?.();
                }
            }
            this.model.setv({
                inner_width: Math.round(this.frame.bbox.width),
                inner_height: Math.round(this.frame.bbox.height),
                outer_width: Math.round(this.bbox.width),
                outer_height: Math.round(this.bbox.height),
            }, { no_change: true });
            if (this.model.match_aspect) {
                this.pause();
                this._range_manager.update_dataranges();
                this.unpause(true);
            }
            if (!this._outer_bbox.equals(this.bbox)) {
                this.canvas_view.resize(); // XXX temporary hack
                this._outer_bbox = this.bbox;
                this._invalidate_all = true;
                this._needs_paint = true;
            }
            const { inner_bbox } = this.layout;
            if (!this._inner_bbox.equals(inner_bbox)) {
                this._inner_bbox = inner_bbox;
                this._invalidate_all = true;
                this._needs_paint = true;
            }
            if (this._needs_paint) {
                // XXX: can't be this.request_paint(), because it would trigger back-and-forth
                // layout recomputing feedback loop between plots. Plots are also much more
                // responsive this way, especially in interactive mode.
                this.paint();
            }
        }
        render() {
            super.render();
            for (const renderer_view of this.computed_renderer_views) {
                const target = renderer_view.rendering_target();
                renderer_view.render_to(target);
            }
        }
        repaint() {
            this._invalidate_layout_if_needed();
            this.paint();
        }
        paint() {
            if (this.is_paused || this.model.hold_render) {
                return;
            }
            if (this.is_displayed) {
                logging_1.logger.trace(`${this.toString()}.paint()`);
                this._actual_paint();
            }
            else {
                // This is possibly the first render cycle, but plot isn't displayed,
                // so all renderers have to be manually marked as finished, because
                // their `render()` method didn't run.
                for (const renderer_view of this.computed_renderer_views) {
                    renderer_view.force_finished();
                }
            }
            if (this._needs_notify) {
                this._needs_notify = false;
                this.notify_finished();
            }
        }
        _actual_paint() {
            logging_1.logger.trace(`${this.toString()}._actual_paint ${this._render_count} start`);
            const { document } = this.model;
            if (document != null) {
                const interactive_duration = document.interactive_duration();
                if (interactive_duration >= 0 && interactive_duration < this.model.lod_interval) {
                    setTimeout(() => {
                        if (document.interactive_duration() > this.model.lod_timeout) {
                            document.interactive_stop();
                        }
                        this.request_repaint(); // TODO: this.schedule_paint()
                    }, this.model.lod_timeout);
                }
                else {
                    document.interactive_stop();
                }
            }
            if (this._range_manager.invalidate_dataranges) {
                this._range_manager.update_dataranges();
                this._invalidate_layout_if_needed();
            }
            let do_primary = false;
            let do_overlays = false;
            if (this._invalidate_all) {
                do_primary = true;
                do_overlays = true;
            }
            else {
                for (const painter of this._invalidated_painters) {
                    const { level } = painter.model;
                    if (level != "overlay") {
                        do_primary = true;
                    }
                    else {
                        do_overlays = true;
                    }
                    if (do_primary && do_overlays) {
                        break;
                    }
                }
            }
            this._invalidated_painters.clear();
            this._invalidate_all = false;
            const frame_box = [
                this.frame.bbox.left,
                this.frame.bbox.top,
                this.frame.bbox.width,
                this.frame.bbox.height,
            ];
            const { primary, overlays } = this.canvas_view;
            if (do_primary) {
                primary.prepare();
                this.canvas_view.prepare_webgl(frame_box);
                this._paint_empty(primary.ctx, frame_box);
                this._paint_outline(primary.ctx, frame_box);
                this._paint_levels(primary.ctx, "image", frame_box, true);
                this._paint_levels(primary.ctx, "underlay", frame_box, true);
                this._paint_levels(primary.ctx, "glyph", frame_box, true);
                this._paint_levels(primary.ctx, "guide", frame_box, false);
                this._paint_levels(primary.ctx, "annotation", frame_box, false);
                primary.finish();
            }
            if (do_overlays || settings_1.settings.wireframe) {
                overlays.prepare();
                this._paint_levels(overlays.ctx, "overlay", frame_box, false);
                if (settings_1.settings.wireframe) {
                    this.paint_layout(overlays.ctx, this.layout);
                }
                overlays.finish();
            }
            if (this._initial_state.range == null) {
                this._initial_state.range = this._range_manager.compute_initial() ?? undefined;
            }
            for (const element_view of this.element_views) {
                element_view.reposition();
            }
            this._needs_paint = false;
            this.repainted.emit();
            logging_1.logger.trace(`${this.toString()}._actual_paint ${this._render_count} end`);
            this._render_count++;
        }
        _paint_levels(ctx, level, clip_region, global_clip) {
            for (const renderer_view of this.computed_renderer_views) {
                if (renderer_view.model.level != level) {
                    continue;
                }
                ctx.save();
                if (global_clip || renderer_view.needs_clip) {
                    ctx.beginPath();
                    ctx.rect(...clip_region);
                    ctx.clip();
                }
                renderer_view.paint();
                ctx.restore();
                if (renderer_view.has_webgl) {
                    this.canvas_view.blit_webgl(ctx);
                }
            }
        }
        paint_layout(ctx, layout) {
            const { x, y, width, height } = layout.bbox;
            ctx.strokeStyle = "blue";
            ctx.strokeRect(x, y, width, height);
            for (const child of layout) {
                ctx.save();
                if (!layout.absolute) {
                    ctx.translate(x, y);
                }
                this.paint_layout(ctx, child);
                ctx.restore();
            }
        }
        _paint_empty(ctx, frame_box) {
            const [cx, cy, cw, ch] = [0, 0, this.bbox.width, this.bbox.height];
            const [fx, fy, fw, fh] = frame_box;
            if (this.visuals.border_fill.doit) {
                ctx.save();
                ctx.beginPath();
                ctx.rect(cx, cy, cw, ch);
                ctx.rect(fx, fy, fw, fh);
                ctx.clip("evenodd");
                ctx.beginPath();
                ctx.rect(cx, cy, cw, ch);
                this.visuals.border_fill.apply(ctx);
                ctx.restore();
            }
            if (this.visuals.background_fill.doit) {
                this.visuals.background_fill.set_value(ctx);
                ctx.fillRect(fx, fy, fw, fh);
            }
        }
        _paint_outline(ctx, frame_box) {
            if (this.visuals.outline_line.doit) {
                ctx.save();
                this.visuals.outline_line.set_value(ctx);
                let [x0, y0, w, h] = frame_box;
                // XXX: shrink outline region by 1px to make right and bottom lines visible
                // if they are on the edge of the canvas.
                if (x0 + w == this.bbox.width) {
                    w -= 1;
                }
                if (y0 + h == this.bbox.height) {
                    h -= 1;
                }
                ctx.strokeRect(x0, y0, w, h);
                ctx.restore();
            }
        }
        export(type = "auto", hidpi = true) {
            const output_backend = (() => {
                switch (type) {
                    case "auto": return this.canvas_view.model.output_backend;
                    case "png": return "canvas";
                    case "svg": return "svg";
                }
            })();
            const composite = new canvas_2.CanvasLayer(output_backend, hidpi);
            const { width, height } = this.bbox;
            composite.resize(width, height);
            if (width != 0 && height != 0) {
                const { canvas } = this.canvas_view.compose();
                composite.ctx.drawImage(canvas, 0, 0);
            }
            return composite;
        }
        resolve_frame() {
            return this.frame; // TODO CartesianFrameView (PR #13286)
        }
        resolve_canvas() {
            return this.canvas;
        }
        resolve_plot() {
            return this;
        }
        resolve_xy(coord) {
            const { x, y } = coord;
            const sx = this.frame.x_scale.compute(x);
            const sy = this.frame.y_scale.compute(y);
            if (this.frame.bbox.contains(sx, sy)) {
                return { x: sx, y: sy };
            }
            else {
                return { x: NaN, y: NaN };
            }
        }
        resolve_indexed(coord) {
            const { index: i, renderer } = coord;
            const rv = this.views.find_one(renderer);
            if (rv != null && rv.has_finished()) {
                const [sx, sy] = rv.glyph.scenterxy(i, NaN, NaN);
                if (this.frame.bbox.contains(sx, sy)) {
                    return { x: sx, y: sy };
                }
            }
            return { x: NaN, y: NaN };
        }
        notify_about(message) {
            if (this._messages.has(message)) {
                return;
            }
            const el = new elements_1.Div({ children: [message] });
            const timer = setTimeout(() => {
                this._messages.delete(message);
                this._notifications.elements = this._notifications.elements.filter((item) => item != el);
            }, 2000);
            this._messages.set(message, timer);
            this._notifications.elements = [...this._notifications.elements, el];
            logging_1.logger.info(message);
        }
    }
    exports.PlotView = PlotView;
    PlotView.__name__ = "PlotView";
},
/* models/ui/panel.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const pane_1 = require(407) /* ../ui/pane */;
    const coordinate_1 = require(60) /* ../coordinates/coordinate */;
    const node_1 = require(59) /* ../coordinates/node */;
    const kinds_1 = require(185) /* ../common/kinds */;
    const resolve = tslib_1.__importStar(require(186) /* ../common/resolve */);
    const dom_1 = require(63) /* ../../core/dom */;
    const panels_css_1 = tslib_1.__importStar(require(443) /* ../../styles/panels.css */), _panel = panels_css_1;
    class PanelView extends pane_1.PaneView {
        stylesheets() {
            return [...super.stylesheets(), panels_css_1.default];
        }
        connect_signals() {
            super.connect_signals();
            const { position, anchor, width, height, elements } = this.model.properties;
            this.on_change([anchor, width, height, elements], () => this.reposition());
            this.on_transitive_change(position, () => this.reposition());
        }
        reposition(displayed) {
            super.reposition(displayed);
            const { position, visible, anchor, elements } = this.model;
            if (displayed == false || !visible || elements.length == 0) {
                this.el.remove();
                return;
            }
            const { x: left, y: top } = this.resolve_as_xy(position);
            if (!isFinite(left + top)) {
                this.el.remove();
                return;
            }
            const parent_el = this.parent?.el ?? document.body;
            const target_el = parent_el.shadowRoot ?? parent_el;
            if (!this.el.isConnected) {
                target_el.append(this.el);
            }
            this.el.style.left = (0, dom_1.px)(left);
            this.el.style.top = (0, dom_1.px)(top);
            const xy = resolve.anchor(anchor);
            this.el.style.transform = `translate(${-100 * xy.x}%, ${-100 * xy.y}%)`;
        }
    }
    exports.PanelView = PanelView;
    PanelView.__name__ = "PanelView";
    class Panel extends pane_1.Pane {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Panel = Panel;
    _a = Panel;
    Panel.__name__ = "Panel";
    (() => {
        _a.prototype.default_view = PanelView;
        _a.define(({ Ref, Or, Auto, Int }) => ({
            position: [Ref(coordinate_1.Coordinate)],
            anchor: [kinds_1.Anchor, "top_left"],
            width: [Or(Auto, Int, Ref(node_1.Node)), "auto"],
            height: [Or(Auto, Int, Ref(node_1.Node)), "auto"],
        }));
    })();
},
/* styles/panels.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{position:absolute;background-color:white;}`;
},
/* models/dom/elements.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b, _c, _d;
    __esModule();
    const dom_element_1 = require(409) /* ./dom_element */;
    class SpanView extends dom_element_1.DOMElementView {
    }
    exports.SpanView = SpanView;
    SpanView.__name__ = "SpanView";
    SpanView.tag_name = "span";
    class Span extends dom_element_1.DOMElement {
    }
    exports.Span = Span;
    _a = Span;
    Span.__name__ = "Span";
    (() => {
        _a.prototype.default_view = SpanView;
    })();
    class DivView extends dom_element_1.DOMElementView {
    }
    exports.DivView = DivView;
    DivView.__name__ = "DivView";
    DivView.tag_name = "div";
    class Div extends dom_element_1.DOMElement {
    }
    exports.Div = Div;
    _b = Div;
    Div.__name__ = "Div";
    (() => {
        _b.prototype.default_view = DivView;
    })();
    class TableView extends dom_element_1.DOMElementView {
    }
    exports.TableView = TableView;
    TableView.__name__ = "TableView";
    TableView.tag_name = "table";
    class Table extends dom_element_1.DOMElement {
    }
    exports.Table = Table;
    _c = Table;
    Table.__name__ = "Table";
    (() => {
        _c.prototype.default_view = TableView;
    })();
    class TableRowView extends dom_element_1.DOMElementView {
    }
    exports.TableRowView = TableRowView;
    TableRowView.__name__ = "TableRowView";
    TableRowView.tag_name = "tr";
    class TableRow extends dom_element_1.DOMElement {
    }
    exports.TableRow = TableRow;
    _d = TableRow;
    TableRow.__name__ = "TableRow";
    (() => {
        _d.prototype.default_view = TableRowView;
    })();
},
/* core/util/throttle.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.throttle = throttle;
    function throttle(func, wait) {
        let timeout = null;
        let request = null;
        let previous = 0;
        let pending = false;
        let resolver;
        const fn = function () {
            return new Promise((resolve, reject) => {
                resolver = resolve;
                const later = function () {
                    previous = Date.now();
                    timeout = null;
                    request = null;
                    pending = false;
                    try {
                        func();
                        resolve();
                    }
                    catch (error) {
                        reject(error);
                    }
                };
                const now = Date.now();
                const remaining = wait - (now - previous);
                if (remaining <= 0 && !pending) {
                    if (timeout != null) {
                        clearTimeout(timeout);
                    }
                    pending = true;
                    request = requestAnimationFrame(later);
                }
                else if (timeout == null && !pending) {
                    timeout = setTimeout(() => request = requestAnimationFrame(later), remaining);
                }
                else {
                    resolve();
                }
            });
        };
        fn.stop = function () {
            if (timeout != null) {
                clearTimeout(timeout);
            }
            if (request != null) {
                cancelAnimationFrame(request);
            }
            resolver();
        };
        return fn;
    }
},
/* models/plots/range_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const data_range1d_1 = require(106) /* ../ranges/data_range1d */;
    const logging_1 = require(19) /* ../../core/logging */;
    class RangeManager {
        constructor(parent) {
            this.invalidate_dataranges = true;
            this.parent = parent;
        }
        get frame() {
            return this.parent.frame;
        }
        update(range_info, options = {}) {
            const panning = options.panning ?? false;
            const scrolling = options.scrolling ?? false;
            const maintain_focus = options.maintain_focus ?? false;
            const range_state = new Map();
            for (const [range, interval] of range_info.xrs) {
                range_state.set(range, interval);
            }
            for (const [range, interval] of range_info.yrs) {
                range_state.set(range, interval);
            }
            if (scrolling && maintain_focus) {
                this._update_ranges_together(range_state); // apply interval bounds while keeping aspect
            }
            this._update_ranges_individually(range_state, { panning, scrolling, maintain_focus });
        }
        ranges() {
            const x_ranges = new Set();
            const y_ranges = new Set();
            for (const range of this.frame.x_ranges.values()) {
                x_ranges.add(range);
            }
            for (const range of this.frame.y_ranges.values()) {
                y_ranges.add(range);
            }
            for (const renderer of this.parent.model.data_renderers) {
                const { coordinates } = renderer;
                if (coordinates != null) {
                    x_ranges.add(coordinates.x_source);
                    y_ranges.add(coordinates.y_source);
                }
            }
            return {
                x_ranges: [...x_ranges],
                y_ranges: [...y_ranges],
            };
        }
        reset() {
            const { x_ranges, y_ranges } = this.ranges();
            for (const range of x_ranges) {
                range.reset();
            }
            for (const range of y_ranges) {
                range.reset();
            }
            this.update_dataranges();
        }
        _update_dataranges(frame) {
            // Update any DataRange1ds here
            const bounds = new Map();
            const log_bounds = new Map();
            let calculate_log_bounds = false;
            for (const [, xr] of frame.x_ranges) {
                if (xr instanceof data_range1d_1.DataRange1d && xr.scale_hint == "log") {
                    calculate_log_bounds = true;
                }
            }
            for (const [, yr] of frame.y_ranges) {
                if (yr instanceof data_range1d_1.DataRange1d && yr.scale_hint == "log") {
                    calculate_log_bounds = true;
                }
            }
            for (const renderer of this.parent.auto_ranged_renderers) {
                const bds = renderer.bounds();
                bounds.set(renderer.model, bds);
                if (calculate_log_bounds) {
                    const log_bds = renderer.log_bounds();
                    log_bounds.set(renderer.model, log_bds);
                }
            }
            let follow_enabled = false;
            let has_bounds = false;
            //const {width, height} = frame.bbox
            const width = frame.x_target.span;
            const height = frame.y_target.span;
            let r;
            if (this.parent.model.match_aspect !== false && width != 0 && height != 0) {
                r = (1 / this.parent.model.aspect_scale) * (width / height);
            }
            for (const [, xr] of frame.x_ranges) {
                if (xr instanceof data_range1d_1.DataRange1d) {
                    const bounds_to_use = xr.scale_hint == "log" ? log_bounds : bounds;
                    xr.update(bounds_to_use, 0, this.parent, r);
                    if (xr.follow != null) {
                        follow_enabled = true;
                    }
                }
                if (xr.bounds != null) {
                    has_bounds = true;
                }
            }
            for (const [, yr] of frame.y_ranges) {
                if (yr instanceof data_range1d_1.DataRange1d) {
                    const bounds_to_use = yr.scale_hint == "log" ? log_bounds : bounds;
                    yr.update(bounds_to_use, 1, this.parent, r);
                    if (yr.follow != null) {
                        follow_enabled = true;
                    }
                }
                if (yr.bounds != null) {
                    has_bounds = true;
                }
            }
            if (follow_enabled && has_bounds) {
                logging_1.logger.warn("Follow enabled so bounds are unset.");
                for (const [, xr] of frame.x_ranges) {
                    xr.bounds = null;
                }
                for (const [, yr] of frame.y_ranges) {
                    yr.bounds = null;
                }
            }
        }
        update_dataranges() {
            this._update_dataranges(this.frame);
            for (const renderer of this.parent.auto_ranged_renderers) {
                const { coordinates } = renderer.model;
                if (coordinates != null) {
                    this._update_dataranges(coordinates);
                }
            }
            if (this.compute_initial() != null) {
                this.invalidate_dataranges = false;
            }
        }
        compute_initial() {
            // check for good values for ranges before setting initial range
            let good_vals = true;
            const { x_ranges, y_ranges } = this.frame;
            const xrs = new Map();
            const yrs = new Map();
            for (const [, range] of x_ranges) {
                const { start, end } = range;
                if (isNaN(start + end)) {
                    good_vals = false;
                    break;
                }
                xrs.set(range, { start, end });
            }
            if (good_vals) {
                for (const [, range] of y_ranges) {
                    const { start, end } = range;
                    if (isNaN(start + end)) {
                        good_vals = false;
                        break;
                    }
                    yrs.set(range, { start, end });
                }
            }
            if (good_vals) {
                return { xrs, yrs };
            }
            else {
                logging_1.logger.warn("could not set initial ranges");
                return null;
            }
        }
        _update_ranges_together(range_state) {
            // Get weight needed to scale the diff of the range to honor interval limits
            let weight = 1.0;
            for (const [rng, range_info] of range_state) {
                weight = Math.min(weight, this._get_weight_to_constrain_interval(rng, range_info));
            }
            // Apply shared weight to all ranges
            if (weight < 1) {
                for (const [rng, range_info] of range_state) {
                    range_info.start = weight * range_info.start + (1 - weight) * rng.start;
                    range_info.end = weight * range_info.end + (1 - weight) * rng.end;
                }
            }
        }
        _update_ranges_individually(range_state, options) {
            const { panning, scrolling, maintain_focus } = options;
            let hit_bound = false;
            for (const [rng, range_info] of range_state) {
                // Limit range interval first. Note that for scroll events,
                // the interval has already been limited for all ranges simultaneously
                if (!scrolling || maintain_focus) {
                    const weight = this._get_weight_to_constrain_interval(rng, range_info);
                    if (weight < 1) {
                        range_info.start = weight * range_info.start + (1 - weight) * rng.start;
                        range_info.end = weight * range_info.end + (1 - weight) * rng.end;
                    }
                }
                // Prevent range from going outside limits
                // Also ensure that range keeps the same delta when panning/scrolling
                if (rng.bounds != null) {
                    const [min, max] = rng.computed_bounds;
                    const new_interval = Math.abs(range_info.end - range_info.start);
                    if (rng.is_reversed) {
                        if (min > range_info.end) {
                            hit_bound = true;
                            range_info.end = min;
                            if (panning || scrolling) {
                                range_info.start = min + new_interval;
                            }
                        }
                        if (max < range_info.start) {
                            hit_bound = true;
                            range_info.start = max;
                            if (panning || scrolling) {
                                range_info.end = max - new_interval;
                            }
                        }
                    }
                    else {
                        if (min > range_info.start) {
                            hit_bound = true;
                            range_info.start = min;
                            if (panning || scrolling) {
                                range_info.end = min + new_interval;
                            }
                        }
                        if (max < range_info.end) {
                            hit_bound = true;
                            range_info.end = max;
                            if (panning || scrolling) {
                                range_info.start = max - new_interval;
                            }
                        }
                    }
                }
            }
            // Cancel the event when hitting a bound while scrolling. This ensures that
            // the scroll-zoom tool maintains its focus position. Setting `maintain_focus`
            // to false results in a more "gliding" behavior, allowing one to
            // zoom out more smoothly, at the cost of losing the focus position.
            if (scrolling && hit_bound && maintain_focus) {
                return;
            }
            for (const [rng, range_info] of range_state) {
                rng.have_updated_interactively = true;
                if (rng.start != range_info.start || rng.end != range_info.end) {
                    rng.setv(range_info);
                }
            }
        }
        _get_weight_to_constrain_interval(rng, range_info) {
            // Get the weight by which a range-update can be applied
            // to still honor the interval limits (including the implicit
            // max interval imposed by the bounds)
            const { min_interval } = rng;
            let { max_interval } = rng;
            // Express bounds as a max_interval. By doing this, the application of
            // bounds and interval limits can be applied independent from each-other.
            if (rng.bounds != null && rng.bounds != "auto") { // check `auto` for type-checking purpose
                const [min, max] = rng.bounds;
                if (min != null && max != null) {
                    const max_interval2 = Math.abs(max - min);
                    max_interval = max_interval != null ? Math.min(max_interval, max_interval2) : max_interval2;
                }
            }
            let weight = 1.0;
            if (min_interval != null || max_interval != null) {
                const old_interval = Math.abs(rng.end - rng.start);
                const new_interval = Math.abs(range_info.end - range_info.start);
                if (min_interval != null && min_interval > 0 && new_interval < min_interval) {
                    weight = (old_interval - min_interval) / (old_interval - new_interval);
                }
                if (max_interval != null && max_interval > 0 && new_interval > max_interval) {
                    weight = (max_interval - old_interval) / (new_interval - old_interval);
                }
                weight = Math.max(0.0, Math.min(1.0, weight));
            }
            return weight;
        }
    }
    exports.RangeManager = RangeManager;
    RangeManager.__name__ = "RangeManager";
},
/* models/plots/state_manager.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const signaling_1 = require(15) /* ../../core/signaling */;
    class StateManager {
        constructor(parent, initial_state) {
            this.history = [];
            this.index = -1;
            this.parent = parent;
            this.initial_state = initial_state;
            this.changed = new signaling_1.Signal0(this.parent, "state_changed");
        }
        _do_state_change(index) {
            const state = index in this.history ? this.history[index].state : this.initial_state;
            if (state.range != null) {
                this.parent.update_range(state.range);
            }
            if (state.selection != null) {
                this.parent.update_selection(state.selection);
            }
            return state;
        }
        peek() {
            return this.can_undo ? this.history[this.index] : null;
        }
        push(type, new_state) {
            const { history, index } = this;
            const prev_state = index in history ? history[index].state : {};
            const state = { ...this.initial_state, ...prev_state, ...new_state };
            this.history = this.history.slice(0, this.index + 1);
            this.history.push({ type, state });
            this.index = this.history.length - 1;
            this.changed.emit();
        }
        clear() {
            this.history = [];
            this.index = -1;
            this.changed.emit();
        }
        undo() {
            if (this.can_undo) {
                this.index -= 1;
                const state = this._do_state_change(this.index);
                this.changed.emit();
                return state;
            }
            return null;
        }
        redo() {
            if (this.can_redo) {
                this.index += 1;
                const state = this._do_state_change(this.index);
                this.changed.emit();
                return state;
            }
            return null;
        }
        get can_undo() {
            return this.index >= 0;
        }
        get can_redo() {
            return this.index < this.history.length - 1;
        }
    }
    exports.StateManager = StateManager;
    StateManager.__name__ = "StateManager";
},
/* styles/plots.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.Canvas = "bk-Canvas";
    exports.default = `:host{display:grid;grid-template-areas:".    above  .    " "left center right" ".    below  .    ";grid-template-rows:0px 1fr 0px;grid-template-columns:0px 1fr 0px;}.bk-Canvas{grid-row-start:1;grid-row-end:span 3;grid-column-start:1;grid-column-end:span 3;}`;
},
/* styles/attribution.css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.default = `:host{display:flex;flex-direction:column;flex-wrap:nowrap;padding:2px;background-color:rgba(255, 255, 255, 0.5);font-size:9px;line-height:1.05;white-space:nowrap;max-width:var(--max-width);}:host > *{overflow:hidden;text-overflow:ellipsis;text-align:right;}a{color:black;}`;
},
/* 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(63) /* ../../core/dom */;
    const projections_1 = require(134) /* ../../core/util/projections */;
    const plot_canvas_1 = require(441) /* ./plot_canvas */;
    function has_maps_API() {
        return typeof google != "undefined" && typeof google.maps != "undefined";
    }
    const gmaps_ready = new signaling_1.Signal0({}, "gmaps_ready");
    const load_google_api = function (api_key, api_version) {
        window._bokeh_gmaps_callback = () => gmaps_ready.emit();
        const enc = encodeURIComponent;
        const script = document.createElement("script");
        script.type = "text/javascript";
        script.src = `https://maps.googleapis.com/maps/api/js?v=${enc(api_version)}&key=${enc(api_key)}&callback=_bokeh_gmaps_callback&loading=async`;
        document.body.appendChild(script);
    };
    class GMapPlotView extends plot_canvas_1.PlotView {
        initialize() {
            super.initialize();
            this._tiles_loaded = false;
            this.zoom_count = 0;
            const { zoom, lat, lng } = this.model.map_options;
            this.initial_zoom = zoom;
            this.initial_lat = lat;
            this.initial_lng = lng;
            const decoder = new TextDecoder("utf-8");
            this._api_key = decoder.decode(this.model.api_key);
            if (this._api_key == "") {
                const url = "https://developers.google.com/maps/documentation/javascript/get-api-key";
                logging_1.logger.error(`api_key is required. See ${url} for more information on how to obtain your own.`);
            }
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.map_el = (0, dom_1.div)({ style: { position: "absolute" } });
            this.canvas_view.underlays_el.append(this.map_el);
            if (!has_maps_API()) {
                if (typeof window._bokeh_gmaps_callback === "undefined") {
                    const { api_version } = this.model;
                    load_google_api(this._api_key, api_version);
                }
                gmaps_ready.connect(() => {
                    this._build_map();
                    this.request_repaint();
                });
            }
            else {
                this._build_map();
            }
        }
        remove() {
            this.map_el.remove();
            super.remove();
        }
        update_range(range_info, options) {
            // RESET -------------------------
            if (range_info == null) {
                this.map.setCenter({ lat: this.initial_lat, lng: this.initial_lng });
                this.map.setOptions({ zoom: this.initial_zoom });
                super.reset_range();
                // PAN ----------------------------
            }
            else if (range_info.sdx != null || range_info.sdy != null) {
                this.map.panBy(range_info.sdx ?? 0, range_info.sdy ?? 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 bounds = this.map.getBounds();
                if (old_map_zoom != null && bounds != null) {
                    const new_map_zoom = old_map_zoom + zoom_change;
                    // Zooming out too far causes problems
                    if (new_map_zoom >= 2) {
                        this.map.setZoom(new_map_zoom);
                        // Check we haven't gone out of bounds, and if we have undo the zoom
                        const [proj_xstart, proj_xend] = this._get_projected_bounds(bounds);
                        if (proj_xend - proj_xstart < 0) {
                            this.map.setZoom(old_map_zoom);
                        }
                    }
                }
                this.unpause();
            }
            // Finally re-center
            this._set_bokeh_ranges();
        }
        _build_map() {
            const { maps } = google;
            this.map_types = {
                satellite: maps.MapTypeId.SATELLITE,
                terrain: maps.MapTypeId.TERRAIN,
                roadmap: maps.MapTypeId.ROADMAP,
                hybrid: maps.MapTypeId.HYBRID,
            };
            const mo = this.model.map_options;
            const map_options = {
                center: new maps.LatLng(mo.lat, mo.lng),
                zoom: mo.zoom,
                disableDefaultUI: true,
                mapTypeId: this.map_types[mo.map_type],
                scaleControl: mo.scale_control,
                tilt: mo.tilt,
            };
            if (mo.styles != null) {
                map_options.styles = JSON.parse(mo.styles);
            }
            // create the map with above options in div
            this.map = new maps.Map(this.map_el, map_options);
            // update bokeh ranges whenever the map idles, which should be after most UI action
            maps.event.addListener(this.map, "idle", () => this._set_bokeh_ranges());
            // also need an event when bounds change so that map resizes trigger renders too
            maps.event.addListener(this.map, "bounds_changed", () => this._set_bokeh_ranges());
            maps.event.addListenerOnce(this.map, "tilesloaded", () => this._render_finished());
            // wire up listeners so that changes to properties are reflected
            this.connect(this.model.properties.map_options.change, () => this._update_options());
            this.connect(this.model.map_options.properties.styles.change, () => this._update_styling());
            this.connect(this.model.map_options.properties.lat.change, () => this._update_center("lat"));
            this.connect(this.model.map_options.properties.lng.change, () => this._update_center("lng"));
            this.connect(this.model.map_options.properties.zoom.change, () => this._update_zoom());
            this.connect(this.model.map_options.properties.map_type.change, () => this._update_map_type());
            this.connect(this.model.map_options.properties.scale_control.change, () => this._update_scale_control());
            this.connect(this.model.map_options.properties.tilt.change, () => this._update_tilt());
        }
        _render_finished() {
            this._tiles_loaded = true;
            this.notify_finished();
        }
        has_finished() {
            return super.has_finished() && this._tiles_loaded === true;
        }
        _get_latlon_bounds(bounds) {
            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(bounds) {
            const [xstart, xend, ystart, yend] = this._get_latlon_bounds(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 bounds = this.map.getBounds();
            if (bounds != null) {
                const [proj_xstart, proj_xend, proj_ystart, proj_yend] = this._get_projected_bounds(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 center = this.map.getCenter()?.toJSON();
            if (center != null) {
                center[fld] = this.model.map_options[fld];
                this.map.setCenter(center);
                this._set_bokeh_ranges();
            }
        }
        _update_map_type() {
            this.map.setOptions({ mapTypeId: this.map_types[this.model.map_options.map_type] });
        }
        _update_scale_control() {
            this.map.setOptions({ scaleControl: this.model.map_options.scale_control });
        }
        _update_tilt() {
            this.map.setOptions({ tilt: this.model.map_options.tilt });
        }
        _update_options() {
            this._update_styling();
            this._update_center("lat");
            this._update_center("lng");
            this._update_zoom();
            this._update_map_type();
        }
        _update_styling() {
            const { styles } = this.model.map_options;
            this.map.setOptions({ styles: styles != null ? JSON.parse(styles) : null });
        }
        _update_zoom() {
            this.map.setOptions({ zoom: this.model.map_options.zoom });
            this._set_bokeh_ranges();
        }
        _after_layout() {
            super._after_layout();
            const { left, top, width, height } = this.frame.bbox;
            this.map_el.style.top = `${top}px`;
            this.map_el.style.left = `${left}px`;
            this.map_el.style.width = `${width}px`;
            this.map_el.style.height = `${height}px`;
        }
    }
    exports.GMapPlotView = GMapPlotView;
    GMapPlotView.__name__ = "GMapPlotView";
},
/* models/plots/gmap.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const gmap_plot_1 = require(439) /* ./gmap_plot */;
    class GMapView extends gmap_plot_1.GMapPlotView {
    }
    exports.GMapView = GMapView;
    GMapView.__name__ = "GMapView";
    class GMap extends gmap_plot_1.GMapPlot {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GMap = GMap;
    _a = GMap;
    GMap.__name__ = "GMap";
    (() => {
        _a.prototype.default_view = GMapView;
    })();
},
/* models/plots/grid_plot.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const layout_dom_1 = require(406) /* ../layouts/layout_dom */;
    const grid_box_1 = require(411) /* ../layouts/grid_box */;
    const kinds_1 = require(185) /* ../common/kinds */;
    const toolbar_1 = require(292) /* ../tools/toolbar */;
    const action_tool_1 = require(303) /* ../tools/actions/action_tool */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const enums_1 = require(20) /* ../../core/enums */;
    class GridPlotView extends layout_dom_1.LayoutDOMView {
        constructor() {
            super(...arguments);
            this._tool_views = new Map();
        }
        get toolbar_view() {
            return this.child_views.find((v) => v.model == this.model.toolbar);
        }
        get grid_box_view() {
            return this.child_views.find((v) => v.model == this._grid_box);
        }
        _update_location() {
            const location = this.model.toolbar_location;
            if (location == null) {
                this.model.toolbar.visible = false;
            }
            else {
                this.model.toolbar.setv({ visible: true, location });
            }
        }
        initialize() {
            super.initialize();
            this._update_location();
            const { children, rows, cols, spacing } = this.model;
            this._grid_box = new grid_box_1.GridBox({ children, rows, cols, spacing, sizing_mode: "inherit" });
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            await this.build_tool_views();
        }
        connect_signals() {
            super.connect_signals();
            const { toolbar, toolbar_location, children, rows, cols, spacing } = this.model.properties;
            this.on_change(toolbar_location, async () => {
                this._update_location();
                this.invalidate_layout();
            });
            this.on_change(toolbar, async () => {
                await this.update_children();
            });
            this.on_change([children, rows, cols, spacing], async () => {
                const { children, rows, cols, spacing } = this.model;
                this._grid_box.setv({ children, rows, cols, spacing });
                await this.grid_box_view.ready;
            });
            this.on_change(this.model.toolbar.properties.tools, async () => {
                await this.build_tool_views();
            });
            this.mouseenter.connect(() => {
                this.toolbar_view.set_visibility(true);
            });
            this.mouseleave.connect(() => {
                this.toolbar_view.set_visibility(false);
            });
        }
        remove() {
            (0, build_views_1.remove_views)(this._tool_views);
            super.remove();
        }
        async build_tool_views() {
            const tools = this.model.toolbar.tools.filter((tool) => tool instanceof action_tool_1.ActionTool);
            await (0, build_views_1.build_views)(this._tool_views, tools, { parent: this });
        }
        *children() {
            yield* super.children();
            yield* this._tool_views.values();
        }
        get child_models() {
            return [this.model.toolbar, this._grid_box];
        }
        _intrinsic_display() {
            return { inner: this.model.flow_mode, outer: "flex" };
        }
        _update_layout() {
            super._update_layout();
            const { location } = this.model.toolbar;
            const flex_direction = (() => {
                switch (location) {
                    case "above": return "column";
                    case "below": return "column-reverse";
                    case "left": return "row";
                    case "right": return "row-reverse";
                }
            })();
            this.style.append(":host", { flex_direction });
        }
    }
    exports.GridPlotView = GridPlotView;
    GridPlotView.__name__ = "GridPlotView";
    class GridPlot extends layout_dom_1.LayoutDOM {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.GridPlot = GridPlot;
    _a = GridPlot;
    GridPlot.__name__ = "GridPlot";
    (() => {
        _a.prototype.default_view = GridPlotView;
        _a.define(({ List, Ref, Nullable }) => ({
            toolbar: [Ref(toolbar_1.Toolbar), () => new toolbar_1.Toolbar()],
            toolbar_location: [Nullable(enums_1.Location), "above"],
            children: [List((0, kinds_1.GridChild)(layout_dom_1.LayoutDOM)), []],
            rows: [Nullable(kinds_1.TracksSizing), null],
            cols: [Nullable(kinds_1.TracksSizing), null],
            spacing: [kinds_1.GridSpacing, 0],
        }));
    })();
},
/* models/plots/figure.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const plot_1 = require(440) /* ./plot */;
    class FigureView extends plot_1.PlotView {
    }
    exports.FigureView = FigureView;
    FigureView.__name__ = "FigureView";
    class Figure extends plot_1.Plot {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Figure = Figure;
    _a = Figure;
    Figure.__name__ = "Figure";
    (() => {
        _a.prototype.default_view = FigureView;
    })();
},
/* models/policies/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(193) /* ./labeling */, exports);
},
/* models/random/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var park_miller_lcg_1 = require(456) /* ./park_miller_lcg */;
    __esExport("ParkMillerLCG", park_miller_lcg_1.ParkMillerLCG);
},
/* models/random/park_miller_lcg.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const random_generator_1 = require(435) /* ./random_generator */;
    const random_1 = require(115) /* ../../core/util/random */;
    class ParkMillerLCG extends random_generator_1.RandomGenerator {
        constructor(attrs) {
            super(attrs);
        }
        generator() {
            return new random_1.LCGRandom(this.seed ?? Date.now());
        }
    }
    exports.ParkMillerLCG = ParkMillerLCG;
    _a = ParkMillerLCG;
    ParkMillerLCG.__name__ = "ParkMillerLCG";
    (() => {
        _a.define(({ Int, Nullable }) => ({
            seed: [Nullable(Int), null],
        }));
    })();
},
/* models/renderers/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var contour_renderer_1 = require(458) /* ./contour_renderer */;
    __esExport("ContourRenderer", contour_renderer_1.ContourRenderer);
    var glyph_renderer_1 = require(218) /* ./glyph_renderer */;
    __esExport("GlyphRenderer", glyph_renderer_1.GlyphRenderer);
    var graph_renderer_1 = require(459) /* ./graph_renderer */;
    __esExport("GraphRenderer", graph_renderer_1.GraphRenderer);
    var guide_renderer_1 = require(190) /* ./guide_renderer */;
    __esExport("GuideRenderer", guide_renderer_1.GuideRenderer);
    var renderer_1 = require(83) /* ./renderer */;
    __esExport("Renderer", renderer_1.Renderer);
    var renderer_group_1 = require(124) /* ./renderer_group */;
    __esExport("RendererGroup", renderer_group_1.RendererGroup);
},
/* models/renderers/contour_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const data_renderer_1 = require(219) /* ./data_renderer */;
    const glyph_renderer_1 = require(218) /* ./glyph_renderer */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    class ContourRendererView extends data_renderer_1.DataRendererView {
        *children() {
            yield* super.children();
            yield this.fill_view;
            yield this.line_view;
        }
        get glyph_view() {
            if (this.fill_view.glyph.data_size > 0) {
                return this.fill_view.glyph;
            }
            else {
                return this.line_view.glyph;
            }
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            const { parent } = this;
            const { fill_renderer, line_renderer } = this.model;
            this.fill_view = await (0, build_views_1.build_view)(fill_renderer, { parent });
            this.line_view = await (0, build_views_1.build_view)(line_renderer, { parent });
        }
        remove() {
            this.fill_view.remove();
            this.line_view.remove();
            super.remove();
        }
        _paint() {
            this.fill_view.paint();
            this.line_view.paint();
        }
        hit_test(geometry) {
            return this.fill_view.hit_test(geometry);
        }
    }
    exports.ContourRendererView = ContourRendererView;
    ContourRendererView.__name__ = "ContourRendererView";
    class ContourRenderer extends data_renderer_1.DataRenderer {
        constructor(attrs) {
            super(attrs);
        }
        get_selection_manager() {
            return this.fill_renderer.data_source.selection_manager;
        }
    }
    exports.ContourRenderer = ContourRenderer;
    _a = ContourRenderer;
    ContourRenderer.__name__ = "ContourRenderer";
    (() => {
        _a.prototype.default_view = ContourRendererView;
        _a.define(({ List, Float, Ref }) => ({
            fill_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
            line_renderer: [Ref(glyph_renderer_1.GlyphRenderer)],
            levels: [List(Float), []],
        }));
    })();
},
/* models/renderers/graph_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const data_renderer_1 = require(219) /* ./data_renderer */;
    const glyph_renderer_1 = require(218) /* ./glyph_renderer */;
    const layout_provider_1 = require(399) /* ../graphs/layout_provider */;
    const graph_hit_test_policy_1 = require(398) /* ../graphs/graph_hit_test_policy */;
    const build_views_1 = require(56) /* ../../core/build_views */;
    const logging_1 = require(19) /* ../../core/logging */;
    const xy_glyph_1 = require(221) /* ../glyphs/xy_glyph */;
    const multi_line_1 = require(376) /* ../glyphs/multi_line */;
    const patches_1 = require(379) /* ../glyphs/patches */;
    class GraphRendererView extends data_renderer_1.DataRendererView {
        get glyph_view() {
            return this.node_view.glyph;
        }
        *children() {
            yield* super.children();
            yield this.edge_view;
            yield this.node_view;
        }
        async lazy_initialize() {
            await super.lazy_initialize();
            this.apply_coordinates();
            const { parent } = this;
            const { edge_renderer, node_renderer } = this.model;
            this.edge_view = await (0, build_views_1.build_view)(edge_renderer, { parent });
            this.node_view = await (0, build_views_1.build_view)(node_renderer, { parent });
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.layout_provider.change, async () => {
                this.apply_coordinates();
                await this.edge_view.set_data();
                await this.node_view.set_data();
                this.request_paint();
            });
        }
        apply_coordinates() {
            const { edge_renderer, node_renderer } = this.model;
            const edge_coords = this.model.layout_provider.edge_coordinates;
            const node_coords = this.model.layout_provider.node_coordinates;
            const xs = { expr: edge_coords.x };
            const ys = { expr: edge_coords.y };
            const x = { expr: node_coords.x };
            const y = { expr: node_coords.y };
            const edge_glyphs = [
                edge_renderer.glyph,
                edge_renderer.hover_glyph,
                edge_renderer.muted_glyph,
                edge_renderer.selection_glyph,
                edge_renderer.nonselection_glyph,
            ];
            const node_glyphs = [
                node_renderer.glyph,
                node_renderer.hover_glyph,
                node_renderer.muted_glyph,
                node_renderer.selection_glyph,
                node_renderer.nonselection_glyph,
            ];
            for (const glyph of edge_glyphs) {
                if (glyph == null || glyph == "auto") {
                    continue;
                }
                if (!(glyph instanceof multi_line_1.MultiLine || glyph instanceof patches_1.Patches)) {
                    logging_1.logger.warn(`${this}.edge_renderer only supports MultiLine and Patches glyphs`);
                    continue;
                }
                glyph.properties.xs.internal = true;
                glyph.properties.ys.internal = true;
                glyph.xs = xs;
                glyph.ys = ys;
            }
            for (const glyph of node_glyphs) {
                if (glyph == null || glyph == "auto") {
                    continue;
                }
                if (!(glyph instanceof xy_glyph_1.XYGlyph)) {
                    logging_1.logger.warn(`${this}.node_renderer only supports XY glyphs`);
                    continue;
                }
                glyph.properties.x.internal = true;
                glyph.properties.y.internal = true;
                glyph.x = x;
                glyph.y = y;
            }
        }
        remove() {
            this.edge_view.remove();
            this.node_view.remove();
            super.remove();
        }
        _paint() {
            this.edge_view.paint();
            this.node_view.paint();
        }
        get has_webgl() {
            return this.edge_view.has_webgl || this.node_view.has_webgl;
        }
        hit_test(geometry) {
            return this.model.inspection_policy.hit_test(geometry, this);
        }
    }
    exports.GraphRendererView = GraphRendererView;
    GraphRendererView.__name__ = "GraphRendererView";
    class GraphRenderer extends data_renderer_1.DataRenderer {
        constructor(attrs) {
            super(attrs);
        }
        get_selection_manager() {
            return this.node_renderer.data_source.selection_manager;
        }
    }
    exports.GraphRenderer = GraphRenderer;
    _a = GraphRenderer;
    GraphRenderer.__name__ = "GraphRenderer";
    (() => {
        _a.prototype.default_view = GraphRendererView;
        _a.define(({ Ref }) => ({
            layout_provider: [Ref(layout_provider_1.LayoutProvider)],
            node_renderer: [Ref((glyph_renderer_1.GlyphRenderer))],
            edge_renderer: [Ref((glyph_renderer_1.GlyphRenderer))],
            selection_policy: [Ref(graph_hit_test_policy_1.GraphHitTestPolicy), () => new graph_hit_test_policy_1.NodesOnly()],
            inspection_policy: [Ref(graph_hit_test_policy_1.GraphHitTestPolicy), () => new graph_hit_test_policy_1.NodesOnly()],
        }));
    })();
},
/* models/selections/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(131) /* ./interaction_policy */, exports);
    var selection_1 = require(130) /* ./selection */;
    __esExport("Selection", selection_1.Selection);
},
/* models/selectors/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var by_id_1 = require(462) /* ./by_id */;
    __esExport("ByID", by_id_1.ByID);
    var by_class_1 = require(463) /* ./by_class */;
    __esExport("ByClass", by_class_1.ByClass);
    var by_css_1 = require(464) /* ./by_css */;
    __esExport("ByCSS", by_css_1.ByCSS);
    var by_xpath_1 = require(465) /* ./by_xpath */;
    __esExport("ByXPath", by_xpath_1.ByXPath);
},
/* models/selectors/by_id.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selector_1 = require(421) /* ./selector */;
    class ByID extends selector_1.Selector {
        constructor(attrs) {
            super(attrs);
        }
        find_one(target) {
            return target.querySelector(`#${this.query}`);
        }
    }
    exports.ByID = ByID;
    ByID.__name__ = "ByID";
},
/* models/selectors/by_class.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selector_1 = require(421) /* ./selector */;
    class ByClass extends selector_1.Selector {
        constructor(attrs) {
            super(attrs);
        }
        find_one(target) {
            return target.querySelector(`.${this.query}`);
        }
    }
    exports.ByClass = ByClass;
    ByClass.__name__ = "ByClass";
},
/* models/selectors/by_css.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selector_1 = require(421) /* ./selector */;
    class ByCSS extends selector_1.Selector {
        constructor(attrs) {
            super(attrs);
        }
        find_one(target) {
            return target.querySelector(this.query);
        }
    }
    exports.ByCSS = ByCSS;
    ByCSS.__name__ = "ByCSS";
},
/* models/selectors/by_xpath.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const selector_1 = require(421) /* ./selector */;
    class ByXPath extends selector_1.Selector {
        constructor(attrs) {
            super(attrs);
        }
        find_one(target) {
            return document.evaluate(this.query, target).iterateNext();
        }
    }
    exports.ByXPath = ByXPath;
    ByXPath.__name__ = "ByXPath";
},
/* models/sources/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var server_sent_data_source_1 = require(467) /* ./server_sent_data_source */;
    __esExport("ServerSentDataSource", server_sent_data_source_1.ServerSentDataSource);
    var ajax_data_source_1 = require(469) /* ./ajax_data_source */;
    __esExport("AjaxDataSource", ajax_data_source_1.AjaxDataSource);
    var column_data_source_1 = require(133) /* ./column_data_source */;
    __esExport("ColumnDataSource", column_data_source_1.ColumnDataSource);
    var columnar_data_source_1 = require(128) /* ./columnar_data_source */;
    __esExport("ColumnarDataSource", columnar_data_source_1.ColumnarDataSource);
    var cds_view_1 = require(237) /* ./cds_view */;
    __esExport("CDSView", cds_view_1.CDSView);
    var data_source_1 = require(132) /* ./data_source */;
    __esExport("DataSource", data_source_1.DataSource);
    var geojson_data_source_1 = require(470) /* ./geojson_data_source */;
    __esExport("GeoJSONDataSource", geojson_data_source_1.GeoJSONDataSource);
    var web_data_source_1 = require(468) /* ./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(468) /* ./web_data_source */;
    class ServerSentDataSource extends web_data_source_1.WebDataSource {
        constructor(attrs) {
            super(attrs);
            this.initialized = false;
        }
        setup() {
            if (!this.initialized) {
                this.initialized = true;
                const source = new EventSource(this.data_url);
                source.onmessage = async (event) => {
                    await this.load_data(JSON.parse(event.data), this.mode, this.max_size ?? undefined);
                };
            }
        }
    }
    exports.ServerSentDataSource = ServerSentDataSource;
    ServerSentDataSource.__name__ = "ServerSentDataSource";
},
/* models/sources/web_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const column_data_source_1 = require(133) /* ./column_data_source */;
    const enums_1 = require(20) /* ../../core/enums */;
    const callbacks_1 = require(50) /* ../../core/util/callbacks */;
    const object_1 = require(9) /* ../../core/util/object */;
    class WebDataSource extends column_data_source_1.ColumnDataSource {
        constructor(attrs) {
            super(attrs);
        }
        get_column(name) {
            const data = (0, object_1.dict)(this.data);
            return data.get(name) ?? [];
        }
        get_length() {
            return super.get_length() ?? 0;
        }
        initialize() {
            super.initialize();
            this.setup();
        }
        async load_data(raw_data, mode, max_size) {
            const { adapter } = this;
            let data;
            if (adapter != null) {
                data = await (0, callbacks_1.execute)(adapter, this, { response: raw_data });
            }
            else {
                data = raw_data;
            }
            switch (mode) {
                case "replace": {
                    break;
                }
                case "append": {
                    const old_data = (0, object_1.dict)(this.data);
                    const new_data = (0, object_1.dict)(data);
                    for (const column of this.columns()) {
                        // XXX: support typed arrays
                        const old_col = Array.from(old_data.get(column) ?? []);
                        const new_col = Array.from(new_data.get(column) ?? []);
                        const array = old_col.concat(new_col);
                        new_data.set(column, max_size != null ? array.slice(-max_size) : array);
                    }
                    break;
                }
            }
            this.data = data;
        }
    }
    exports.WebDataSource = WebDataSource;
    _a = WebDataSource;
    WebDataSource.__name__ = "WebDataSource";
    (() => {
        _a.define(({ Any, Int, Str, Nullable }) => ({
            max_size: [Nullable(Int), null],
            mode: [enums_1.UpdateMode, "replace"],
            adapter: [Nullable(Any /*TODO*/), null],
            data_url: [Str],
        }));
    })();
},
/* models/sources/ajax_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const web_data_source_1 = require(468) /* ./web_data_source */;
    const enums_1 = require(20) /* ../../core/enums */;
    const logging_1 = require(19) /* ../../core/logging */;
    const object_1 = require(9) /* ../../core/util/object */;
    class AjaxDataSource extends web_data_source_1.WebDataSource {
        constructor(attrs) {
            super(attrs);
        }
        destroy() {
            if (this.interval != null) {
                clearInterval(this.interval);
            }
            super.destroy();
        }
        setup() {
            if (this.initialized !== true) {
                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();
            xhr.addEventListener("load", () => this.do_load(xhr, mode, max_size ?? undefined));
            xhr.addEventListener("error", () => this.do_error(xhr));
            if (if_modified && this.last_fetch_time != null) {
                xhr.setRequestHeader("If-Modified-Since", this.last_fetch_time.toUTCString());
            }
            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);
            for (const [name, value] of (0, object_1.entries)(this.http_headers)) {
                xhr.setRequestHeader(name, value);
            }
            return xhr;
        }
        async do_load(xhr, mode, max_size) {
            if (xhr.status == 200) {
                const raw_data = JSON.parse(xhr.responseText);
                this.last_fetch_time = new Date();
                await this.load_data(raw_data, mode, max_size);
            }
        }
        do_error(xhr) {
            logging_1.logger.error(`Failed to fetch JSON from ${this.data_url} with code ${xhr.status}`);
        }
    }
    exports.AjaxDataSource = AjaxDataSource;
    _a = AjaxDataSource;
    AjaxDataSource.__name__ = "AjaxDataSource";
    (() => {
        _a.define(({ Bool, Int, Str, Dict, Nullable }) => ({
            polling_interval: [Nullable(Int), null],
            content_type: [Str, "application/json"],
            http_headers: [Dict(Str), {}],
            method: [enums_1.HTTPMethod, "POST"],
            if_modified: [Bool, false],
        }));
    })();
},
/* models/sources/geojson_data_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const columnar_data_source_1 = require(128) /* ./columnar_data_source */;
    const logging_1 = require(19) /* ../../core/logging */;
    const types_1 = require(8) /* ../../core/util/types */;
    const array_1 = require(10) /* ../../core/util/array */;
    const object_1 = require(9) /* ../../core/util/object */;
    function orNaN(v) {
        return v != null ? v : NaN;
    }
    class GeoJSONDataSource extends columnar_data_source_1.ColumnarDataSource {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this._update_data();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.properties.geojson.change, () => this._update_data());
        }
        _update_data() {
            this.data = this.geojson_to_column_data();
        }
        _get_new_list_array(length) {
            return (0, array_1.range)(0, length).map((_i) => []);
        }
        _get_new_nan_array(length) {
            return (0, array_1.range)(0, length).map((_i) => NaN);
        }
        _add_properties(item, data, i, item_count) {
            const properties = item.properties ?? {};
            const data_proxy = (0, object_1.dict)(data);
            for (const [property, value] of (0, object_1.dict)(properties)) {
                if (!data_proxy.has(property)) {
                    data[property] = this._get_new_nan_array(item_count);
                }
                // orNaN necessary here to prevent null values from ending up in the column
                data[property][i] = orNaN(value);
            }
        }
        _add_geometry(geometry, data, i) {
            function flatten(acc, item) {
                return acc.concat([[NaN, NaN, NaN]]).concat(item);
            }
            switch (geometry.type) {
                case "Point": {
                    const [x, y, z] = geometry.coordinates;
                    data.x[i] = x;
                    data.y[i] = y;
                    data.z[i] = orNaN(z);
                    break;
                }
                case "LineString": {
                    const { coordinates } = geometry;
                    for (let j = 0; j < coordinates.length; j++) {
                        const [x, y, z] = coordinates[j];
                        data.xs[i][j] = x;
                        data.ys[i][j] = y;
                        data.zs[i][j] = orNaN(z);
                    }
                    break;
                }
                case "Polygon": {
                    if (geometry.coordinates.length > 1) {
                        logging_1.logger.warn("Bokeh does not support Polygons with holes in, only exterior ring used.");
                    }
                    const exterior_ring = geometry.coordinates[0];
                    for (let j = 0; j < exterior_ring.length; j++) {
                        const [x, y, z] = exterior_ring[j];
                        data.xs[i][j] = x;
                        data.ys[i][j] = y;
                        data.zs[i][j] = orNaN(z);
                    }
                    break;
                }
                case "MultiPoint": {
                    logging_1.logger.warn("MultiPoint not supported in Bokeh");
                    break;
                }
                case "MultiLineString": {
                    const coordinates = geometry.coordinates.reduce(flatten);
                    for (let j = 0; j < coordinates.length; j++) {
                        const [x, y, z] = coordinates[j];
                        data.xs[i][j] = x;
                        data.ys[i][j] = y;
                        data.zs[i][j] = orNaN(z);
                    }
                    break;
                }
                case "MultiPolygon": {
                    const exterior_rings = [];
                    for (const polygon of geometry.coordinates) {
                        if (polygon.length > 1) {
                            logging_1.logger.warn("Bokeh does not support Polygons with holes in, only exterior ring used.");
                        }
                        exterior_rings.push(polygon[0]);
                    }
                    const coordinates = exterior_rings.reduce(flatten);
                    for (let j = 0; j < coordinates.length; j++) {
                        const [x, y, z] = coordinates[j];
                        data.xs[i][j] = x;
                        data.ys[i][j] = y;
                        data.zs[i][j] = orNaN(z);
                    }
                    break;
                }
                default:
                    throw new Error(`Invalid GeoJSON geometry type: ${geometry.type}`);
            }
        }
        geojson_to_column_data() {
            const geojson = JSON.parse(this.geojson);
            let items;
            switch (geojson.type) {
                case "GeometryCollection": {
                    if ((0, types_1.is_undefined)(geojson.geometries)) {
                        throw new Error("No geometries found in GeometryCollection");
                    }
                    if (geojson.geometries.length === 0) {
                        throw new Error("geojson.geometries must have one or more items");
                    }
                    items = geojson.geometries;
                    break;
                }
                case "FeatureCollection": {
                    if ((0, types_1.is_undefined)(geojson.features)) {
                        throw new Error("No features found in FeaturesCollection");
                    }
                    if (geojson.features.length == 0) {
                        throw new Error("geojson.features must have one or more items");
                    }
                    items = geojson.features;
                    break;
                }
                default:
                    throw new Error("Bokeh only supports type GeometryCollection and FeatureCollection at top level");
            }
            let item_count = 0;
            for (const item of items) {
                const geometry = item.type === "Feature" ? item.geometry : item;
                if (geometry.type == "GeometryCollection") {
                    item_count += geometry.geometries.length;
                }
                else {
                    item_count += 1;
                }
            }
            const data = {
                x: this._get_new_nan_array(item_count),
                y: this._get_new_nan_array(item_count),
                z: this._get_new_nan_array(item_count),
                xs: this._get_new_list_array(item_count),
                ys: this._get_new_list_array(item_count),
                zs: this._get_new_list_array(item_count),
            };
            let arr_index = 0;
            for (const item of items) {
                const geometry = item.type == "Feature" ? item.geometry : item;
                if (geometry.type == "GeometryCollection") {
                    for (const g of geometry.geometries) {
                        this._add_geometry(g, data, arr_index);
                        if (item.type === "Feature") {
                            this._add_properties(item, data, arr_index, item_count);
                        }
                        arr_index += 1;
                    }
                }
                else {
                    this._add_geometry(geometry, data, arr_index);
                    if (item.type === "Feature") {
                        this._add_properties(item, data, arr_index, item_count);
                    }
                    arr_index += 1;
                }
            }
            return data;
        }
    }
    exports.GeoJSONDataSource = GeoJSONDataSource;
    _a = GeoJSONDataSource;
    GeoJSONDataSource.__name__ = "GeoJSONDataSource";
    (() => {
        _a.define(({ Str }) => ({
            geojson: [Str],
        }));
        _a.internal(({ Unknown, Dict, Arrayable }) => ({
            data: [Dict(Arrayable(Unknown)), {}],
        }));
    })();
},
/* models/tiles/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var bbox_tile_source_1 = require(472) /* ./bbox_tile_source */;
    __esExport("BBoxTileSource", bbox_tile_source_1.BBoxTileSource);
    var mercator_tile_source_1 = require(473) /* ./mercator_tile_source */;
    __esExport("MercatorTileSource", mercator_tile_source_1.MercatorTileSource);
    var quadkey_tile_source_1 = require(476) /* ./quadkey_tile_source */;
    __esExport("QUADKEYTileSource", quadkey_tile_source_1.QUADKEYTileSource);
    var tile_renderer_1 = require(477) /* ./tile_renderer */;
    __esExport("TileRenderer", tile_renderer_1.TileRenderer);
    var tile_source_1 = require(474) /* ./tile_source */;
    __esExport("TileSource", tile_source_1.TileSource);
    var tms_tile_source_1 = require(479) /* ./tms_tile_source */;
    __esExport("TMSTileSource", tms_tile_source_1.TMSTileSource);
    var wmts_tile_source_1 = require(478) /* ./wmts_tile_source */;
    __esExport("WMTSTileSource", wmts_tile_source_1.WMTSTileSource);
},
/* models/tiles/bbox_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const mercator_tile_source_1 = require(473) /* ./mercator_tile_source */;
    class BBoxTileSource extends mercator_tile_source_1.MercatorTileSource {
        constructor(attrs) {
            super(attrs);
        }
        get_image_url(x, y, z) {
            const image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            let xmax, xmin, ymax, ymin;
            if (this.use_latlon) {
                [xmin, ymin, xmax, ymax] = this.get_tile_geographic_bounds(x, y, z);
            }
            else {
                [xmin, ymin, xmax, ymax] = this.get_tile_meter_bounds(x, y, z);
            }
            return image_url
                .replace("{XMIN}", xmin.toString())
                .replace("{YMIN}", ymin.toString())
                .replace("{XMAX}", xmax.toString())
                .replace("{YMAX}", ymax.toString());
        }
    }
    exports.BBoxTileSource = BBoxTileSource;
    _a = BBoxTileSource;
    BBoxTileSource.__name__ = "BBoxTileSource";
    (() => {
        _a.define(({ Bool }) => ({
            use_latlon: [Bool, false],
        }));
    })();
},
/* models/tiles/mercator_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tile_source_1 = require(474) /* ./tile_source */;
    const array_1 = require(10) /* ../../core/util/array */;
    const tile_utils_1 = require(475) /* ./tile_utils */;
    class MercatorTileSource extends tile_source_1.TileSource {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this._resolutions = (0, array_1.range)(this.min_zoom, this.max_zoom + 1).map((z) => this.get_resolution(z));
        }
        _computed_initial_resolution() {
            if (this.initial_resolution != null) {
                return this.initial_resolution;
            }
            else {
                // TODO testing 2015-11-17, if this codepath is used it seems
                // to use 100% cpu and wedge Chrome
                return (2 * Math.PI * 6378137) / this.tile_size;
            }
        }
        is_valid_tile(x, y, z) {
            if (!this.wrap_around) {
                if (x < 0 || x >= 2 ** z) {
                    return false;
                }
            }
            if (y < 0 || y >= 2 ** z) {
                return false;
            }
            return true;
        }
        parent_by_tile_xyz(x, y, z) {
            const quadkey = this.tile_xyz_to_quadkey(x, y, z);
            const parent_quadkey = quadkey.substring(0, quadkey.length - 1);
            return this.quadkey_to_tile_xyz(parent_quadkey);
        }
        get_resolution(level) {
            return this._computed_initial_resolution() / 2 ** level;
        }
        get_resolution_by_extent(extent, height, width) {
            const x_rs = (extent[2] - extent[0]) / width;
            const y_rs = (extent[3] - extent[1]) / height;
            return [x_rs, y_rs];
        }
        get_level_by_extent(extent, height, width) {
            const x_rs = (extent[2] - extent[0]) / width;
            const y_rs = (extent[3] - extent[1]) / height;
            const resolution = Math.max(x_rs, y_rs);
            let i = 0;
            for (const r of this._resolutions) {
                if (resolution > r) {
                    if (i == 0) {
                        return 0;
                    }
                    if (i > 0) {
                        return i - 1;
                    }
                }
                i += 1;
            }
            // otherwise return the highest available resolution
            return (i - 1);
        }
        get_closest_level_by_extent(extent, height, width) {
            const x_rs = (extent[2] - extent[0]) / width;
            const y_rs = (extent[3] - extent[1]) / height;
            const resolution = Math.max(x_rs, y_rs);
            const closest = this._resolutions.reduce(function (previous, current) {
                if (Math.abs(current - resolution) < Math.abs(previous - resolution)) {
                    return current;
                }
                else {
                    return previous;
                }
            });
            return this._resolutions.indexOf(closest);
        }
        snap_to_zoom_level(extent, height, width, level) {
            const [xmin, ymin, xmax, ymax] = extent;
            const desired_res = this._resolutions[level];
            let desired_x_delta = width * desired_res;
            let desired_y_delta = height * desired_res;
            if (!this.snap_to_zoom) {
                const xscale = (xmax - xmin) / desired_x_delta;
                const yscale = (ymax - ymin) / desired_y_delta;
                if (xscale > yscale) {
                    desired_x_delta = (xmax - xmin);
                    desired_y_delta = desired_y_delta * xscale;
                }
                else {
                    desired_x_delta = desired_x_delta * yscale;
                    desired_y_delta = (ymax - ymin);
                }
            }
            const x_adjust = (desired_x_delta - (xmax - xmin)) / 2;
            const y_adjust = (desired_y_delta - (ymax - ymin)) / 2;
            return [xmin - x_adjust, ymin - y_adjust, xmax + x_adjust, ymax + y_adjust];
        }
        tms_to_wmts(x, y, z) {
            // Note this works both ways
            return [x, 2 ** z - 1 - y, z];
        }
        wmts_to_tms(x, y, z) {
            // Note this works both ways
            return [x, 2 ** z - 1 - y, z];
        }
        pixels_to_meters(px, py, level) {
            const res = this.get_resolution(level);
            const mx = (px * res) - this.x_origin_offset;
            const my = (py * res) - this.y_origin_offset;
            return [mx, my];
        }
        meters_to_pixels(mx, my, level) {
            const res = this.get_resolution(level);
            const px = (mx + this.x_origin_offset) / res;
            const py = (my + this.y_origin_offset) / res;
            return [px, py];
        }
        pixels_to_tile(px, py) {
            let tx = Math.ceil(px / this.tile_size);
            tx = tx === 0 ? tx : tx - 1;
            const ty = Math.max(Math.ceil(py / this.tile_size) - 1, 0);
            return [tx, ty];
        }
        pixels_to_raster(px, py, level) {
            const mapSize = this.tile_size << level;
            return [px, mapSize - py];
        }
        meters_to_tile(mx, my, level) {
            const [px, py] = this.meters_to_pixels(mx, my, level);
            return this.pixels_to_tile(px, py);
        }
        get_tile_meter_bounds(tx, ty, level) {
            // expects tms styles coordinates (bottom-left origin)
            const [xmin, ymin] = this.pixels_to_meters(tx * this.tile_size, ty * this.tile_size, level);
            const [xmax, ymax] = this.pixels_to_meters((tx + 1) * this.tile_size, (ty + 1) * this.tile_size, level);
            return [xmin, ymin, xmax, ymax];
        }
        get_tile_geographic_bounds(tx, ty, level) {
            const bounds = this.get_tile_meter_bounds(tx, ty, level);
            const [minLon, minLat, maxLon, maxLat] = (0, tile_utils_1.meters_extent_to_geographic)(bounds);
            return [minLon, minLat, maxLon, maxLat];
        }
        get_tiles_by_extent(extent, level, tile_border = 1) {
            // unpack extent and convert to tile coordinates
            const [xmin, ymin, xmax, ymax] = extent;
            let [txmin, tymin] = this.meters_to_tile(xmin, ymin, level);
            let [txmax, tymax] = this.meters_to_tile(xmax, ymax, level);
            // add tiles which border
            txmin -= tile_border;
            tymin -= tile_border;
            txmax += tile_border;
            tymax += tile_border;
            const tiles = [];
            for (let ty = tymax; ty >= tymin; ty--) {
                for (let tx = txmin; tx <= txmax; tx++) {
                    if (this.is_valid_tile(tx, ty, level)) {
                        tiles.push([tx, ty, level, this.get_tile_meter_bounds(tx, ty, level)]);
                    }
                }
            }
            this.sort_tiles_from_center(tiles, [txmin, tymin, txmax, tymax]);
            return tiles;
        }
        quadkey_to_tile_xyz(quadKey) {
            /**
             * Computes tile x, y and z values based on quadKey.
             */
            let tileX = 0;
            let tileY = 0;
            const tileZ = quadKey.length;
            for (let i = tileZ; i > 0; i--) {
                const value = quadKey.charAt(tileZ - i);
                const mask = 1 << (i - 1);
                switch (value) {
                    case "0":
                        continue;
                    case "1":
                        tileX |= mask;
                        break;
                    case "2":
                        tileY |= mask;
                        break;
                    case "3":
                        tileX |= mask;
                        tileY |= mask;
                        break;
                    default:
                        throw new TypeError(`Invalid Quadkey: ${quadKey}`);
                }
            }
            return [tileX, tileY, tileZ];
        }
        tile_xyz_to_quadkey(x, y, z) {
            /*
             * Computes quadkey value based on tile x, y and z values.
             */
            let quadkey = "";
            for (let i = z; i > 0; i--) {
                const mask = 1 << (i - 1);
                let digit = 0;
                if ((x & mask) !== 0) {
                    digit += 1;
                }
                if ((y & mask) !== 0) {
                    digit += 2;
                }
                quadkey += digit.toString();
            }
            return quadkey;
        }
        children_by_tile_xyz(x, y, z) {
            const quadkey = this.tile_xyz_to_quadkey(x, y, z);
            const child_tile_xyz = [];
            for (let i = 0; i <= 3; i++) {
                const [x, y, z] = this.quadkey_to_tile_xyz(quadkey + i.toString());
                const b = this.get_tile_meter_bounds(x, y, z);
                child_tile_xyz.push([x, y, z, b]);
            }
            return child_tile_xyz;
        }
        get_closest_parent_by_tile_xyz(x, y, z) {
            const world_x = this.calculate_world_x_by_tile_xyz(x, y, z);
            [x, y, z] = this.normalize_xyz(x, y, z);
            let quadkey = this.tile_xyz_to_quadkey(x, y, z);
            while (quadkey.length > 0) {
                quadkey = quadkey.substring(0, quadkey.length - 1);
                [x, y, z] = this.quadkey_to_tile_xyz(quadkey);
                [x, y, z] = this.denormalize_xyz(x, y, z, world_x);
                if (this.tiles.has(this.tile_xyz_to_key(x, y, z))) {
                    return [x, y, z];
                }
            }
            return [0, 0, 0];
        }
        normalize_xyz(x, y, z) {
            if (this.wrap_around) {
                const tile_count = 2 ** z;
                return [((x % tile_count) + tile_count) % tile_count, y, z];
            }
            else {
                return [x, y, z];
            }
        }
        denormalize_xyz(x, y, z, world_x) {
            return [x + (world_x * 2 ** z), y, z];
        }
        denormalize_meters(meters_x, meters_y, _level, world_x) {
            return [meters_x + (world_x * 2 * Math.PI * 6378137), meters_y];
        }
        calculate_world_x_by_tile_xyz(x, _y, z) {
            return Math.floor(x / 2 ** z);
        }
    }
    exports.MercatorTileSource = MercatorTileSource;
    _a = MercatorTileSource;
    MercatorTileSource.__name__ = "MercatorTileSource";
    (() => {
        _a.define(({ Bool }) => ({
            snap_to_zoom: [Bool, false],
            wrap_around: [Bool, true],
        }));
        _a.override({
            x_origin_offset: 20037508.34,
            y_origin_offset: 20037508.34,
            initial_resolution: 156543.03392804097,
        });
    })();
},
/* models/tiles/tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const object_1 = require(9) /* ../../core/util/object */;
    class TileSource extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this.tiles = new Map();
            this._normalize_case();
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.change, () => this._clear_cache());
        }
        string_lookup_replace(str, lookup) {
            let result_str = str;
            for (const [key, value] of (0, object_1.entries)(lookup)) {
                result_str = result_str.replace(`{${key}}`, value);
            }
            return result_str;
        }
        _normalize_case() {
            /*
             * Note: should probably be refactored into subclasses.
             */
            const url = this.url
                .replace("{x}", "{X}")
                .replace("{y}", "{Y}")
                .replace("{z}", "{Z}")
                .replace("{q}", "{Q}")
                .replace("{xmin}", "{XMIN}")
                .replace("{ymin}", "{YMIN}")
                .replace("{xmax}", "{XMAX}")
                .replace("{ymax}", "{YMAX}");
            this.url = url;
        }
        _clear_cache() {
            this.tiles = new Map();
        }
        tile_xyz_to_key(x, y, z) {
            return `${x}:${y}:${z}`;
        }
        key_to_tile_xyz(key) {
            const [x, y, z] = key.split(":").map((c) => parseInt(c));
            return [x, y, z];
        }
        sort_tiles_from_center(tiles, tile_extent) {
            const [txmin, tymin, txmax, tymax] = tile_extent;
            const center_x = ((txmax - txmin) / 2) + txmin;
            const center_y = ((tymax - tymin) / 2) + tymin;
            tiles.sort(function (a, b) {
                const a_distance = Math.sqrt((center_x - a[0]) ** 2 + (center_y - a[1]) ** 2);
                const b_distance = Math.sqrt((center_x - b[0]) ** 2 + (center_y - b[1]) ** 2);
                return a_distance - b_distance;
            });
        }
        get_image_url(x, y, z) {
            const image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            return image_url
                .replace("{X}", x.toString())
                .replace("{Y}", y.toString())
                .replace("{Z}", z.toString());
        }
    }
    exports.TileSource = TileSource;
    _a = TileSource;
    TileSource.__name__ = "TileSource";
    (() => {
        _a.define(({ Float, Str, Dict, Nullable /*, Null, Or, Ref*/ }) => ({
            url: [Str, ""],
            tile_size: [Float, 256],
            max_zoom: [Float, 30],
            min_zoom: [Float, 0],
            extra_url_vars: [Dict(Str), {}],
            attribution: [Str, ""], // Or(Str, Ref(DOMElement), Null), null ],
            x_origin_offset: [Float],
            y_origin_offset: [Float],
            initial_resolution: [Nullable(Float), null],
        }));
    })();
},
/* models/tiles/tile_utils.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    exports.geographic_to_meters = geographic_to_meters;
    exports.meters_to_geographic = meters_to_geographic;
    exports.geographic_extent_to_meters = geographic_extent_to_meters;
    exports.meters_extent_to_geographic = meters_extent_to_geographic;
    const projections_1 = require(134) /* ../../core/util/projections */;
    function geographic_to_meters(x_lon, y_lat) {
        return projections_1.wgs84_mercator.compute(x_lon, y_lat);
    }
    function meters_to_geographic(mx, my) {
        return projections_1.wgs84_mercator.invert(mx, my);
    }
    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];
    }
    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];
    }
},
/* models/tiles/quadkey_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const mercator_tile_source_1 = require(473) /* ./mercator_tile_source */;
    class QUADKEYTileSource extends mercator_tile_source_1.MercatorTileSource {
        constructor(attrs) {
            super(attrs);
        }
        get_image_url(x, y, z) {
            const image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
            const [wx, wy, wz] = this.tms_to_wmts(x, y, z);
            const quadKey = this.tile_xyz_to_quadkey(wx, wy, wz);
            return image_url.replace("{Q}", quadKey);
        }
    }
    exports.QUADKEYTileSource = QUADKEYTileSource;
    QUADKEYTileSource.__name__ = "QUADKEYTileSource";
},
/* models/tiles/tile_renderer.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tile_source_1 = require(474) /* ./tile_source */;
    const wmts_tile_source_1 = require(478) /* ./wmts_tile_source */;
    const renderer_1 = require(83) /* ../renderers/renderer */;
    const range1d_1 = require(99) /* ../ranges/range1d */;
    const html_1 = require(408) /* ../dom/html */;
    const image_1 = require(179) /* ../../core/util/image */;
    const array_1 = require(10) /* ../../core/util/array */;
    const assert_1 = require(12) /* ../../core/util/assert */;
    class TileRendererView extends renderer_1.RendererView {
        constructor() {
            super(...arguments);
            this._tiles = null;
            this.map_initialized = false;
        }
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.request_paint());
            this.connect(this.model.tile_source.change, () => this.request_paint());
        }
        force_finished() {
            super.force_finished();
            if (this._tiles == null) {
                this._tiles = [];
            }
        }
        get_extent() {
            const { x_range, y_range } = this;
            const x_start = x_range.start;
            const y_start = y_range.start;
            const x_end = x_range.end;
            const y_end = y_range.end;
            (0, assert_1.assert)(isFinite(x_start));
            (0, assert_1.assert)(isFinite(y_start));
            (0, assert_1.assert)(isFinite(x_end));
            (0, assert_1.assert)(isFinite(y_end));
            return [x_start, y_start, x_end, y_end];
        }
        get map_plot() {
            return this.plot_model;
        }
        get map_canvas() {
            return this.layer.ctx;
        }
        get map_frame() {
            return this.plot_view.frame;
        }
        get x_range() {
            return this.map_plot.x_range;
        }
        get y_range() {
            return this.map_plot.y_range;
        }
        _set_data() {
            this.extent = this.get_extent();
            this._last_height = undefined;
            this._last_width = undefined;
        }
        get attribution() {
            return new html_1.HTML({ html: [this.model.tile_source.attribution] });
        }
        _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];
            }
        }
        _create_tile(x, y, z, bounds, cache_only = false) {
            const quadkey = this.model.tile_source.tile_xyz_to_quadkey(x, y, z);
            const cache_key = this.model.tile_source.tile_xyz_to_key(x, y, z);
            if (this.model.tile_source.tiles.has(cache_key)) {
                return;
            }
            const [nx, ny, nz] = this.model.tile_source.normalize_xyz(x, y, z);
            const src = this.model.tile_source.get_image_url(nx, ny, nz);
            const tile = {
                img: undefined,
                tile_coords: [x, y, z],
                normalized_coords: [nx, ny, nz],
                quadkey,
                cache_key,
                bounds,
                loaded: false,
                finished: false,
                x_coord: bounds[0],
                y_coord: bounds[3],
            };
            this.model.tile_source.tiles.set(cache_key, tile);
            if (this._tiles == null) {
                this._tiles = [];
            }
            this._tiles.push(tile);
            new image_1.ImageLoader(src, {
                loaded: (img) => {
                    Object.assign(tile, { img, loaded: true });
                    if (cache_only) {
                        tile.finished = true;
                        this.notify_finished();
                    }
                    else {
                        this.request_paint();
                    }
                },
                failed() {
                    tile.finished = true;
                },
            });
        }
        _enforce_aspect_ratio() {
            // brute force way of handling resize or sizing_mode event -------------------------------------------------------------
            if ((this._last_height !== this.map_frame.bbox.height) || (this._last_width !== this.map_frame.bbox.width)) {
                const extent = this.get_extent();
                const zoom_level = this.model.tile_source.get_level_by_extent(extent, this.map_frame.bbox.height, this.map_frame.bbox.width);
                const new_extent = this.model.tile_source.snap_to_zoom_level(extent, this.map_frame.bbox.height, this.map_frame.bbox.width, zoom_level);
                this.x_range.setv({ start: new_extent[0], end: new_extent[2] });
                this.y_range.setv({ start: new_extent[1], end: new_extent[3] });
                this.extent = new_extent;
                this._last_height = this.map_frame.bbox.height;
                this._last_width = this.map_frame.bbox.width;
            }
        }
        has_finished() {
            if (!super.has_finished()) {
                return false;
            }
            if (this._tiles == null) {
                return false;
            }
            for (const tile of this._tiles) {
                if (!tile.finished) {
                    return false;
                }
            }
            return true;
        }
        _paint() {
            if (!this.map_initialized) {
                this._set_data();
                this._map_data();
                this.map_initialized = true;
            }
            this._enforce_aspect_ratio();
            this._update();
            if (this.prefetch_timer != null) {
                clearTimeout(this.prefetch_timer);
            }
            this.prefetch_timer = setTimeout(this._prefetch_tiles.bind(this), 500);
            if (this.has_finished()) {
                this.notify_finished();
            }
        }
        _draw_tile(tile_key) {
            const tile_data = this.model.tile_source.tiles.get(tile_key);
            if (tile_data != null && tile_data.loaded) {
                const [[sxmin], [symin]] = this.coordinates.map_to_screen([tile_data.bounds[0]], [tile_data.bounds[3]]);
                const [[sxmax], [symax]] = this.coordinates.map_to_screen([tile_data.bounds[2]], [tile_data.bounds[1]]);
                const sw = sxmax - sxmin;
                const sh = symax - symin;
                const sx = sxmin;
                const sy = symin;
                const old_smoothing = this.map_canvas.imageSmoothingEnabled;
                this.map_canvas.imageSmoothingEnabled = this.model.smoothing;
                this.map_canvas.drawImage(tile_data.img, sx, sy, sw, sh);
                this.map_canvas.imageSmoothingEnabled = old_smoothing;
                tile_data.finished = true;
            }
        }
        _set_rect() {
            const outline_width = this.plot_model.outline_line_width;
            const l = this.map_frame.bbox.left + (outline_width / 2);
            const t = this.map_frame.bbox.top + (outline_width / 2);
            const w = this.map_frame.bbox.width - outline_width;
            const h = this.map_frame.bbox.height - outline_width;
            this.map_canvas.rect(l, t, w, h);
            this.map_canvas.clip();
        }
        _render_tiles(tile_keys) {
            this.map_canvas.save();
            this._set_rect();
            this.map_canvas.globalAlpha = this.model.alpha;
            for (const tile_key of tile_keys) {
                this._draw_tile(tile_key);
            }
            this.map_canvas.restore();
        }
        _prefetch_tiles() {
            const { tile_source } = this.model;
            const extent = this.get_extent();
            const h = this.map_frame.bbox.height;
            const w = this.map_frame.bbox.width;
            const zoom_level = this.model.tile_source.get_level_by_extent(extent, h, w);
            const tiles = this.model.tile_source.get_tiles_by_extent(extent, zoom_level);
            for (let t = 0, end = Math.min(10, tiles.length); t < end; t++) {
                const [x, y, z] = tiles[t];
                const children = this.model.tile_source.children_by_tile_xyz(x, y, z);
                for (const c of children) {
                    const [cx, cy, cz, cbounds] = c;
                    if (tile_source.tiles.has(tile_source.tile_xyz_to_key(cx, cy, cz))) {
                        continue;
                    }
                    else {
                        this._create_tile(cx, cy, cz, cbounds, true);
                    }
                }
            }
        }
        _fetch_tiles(tiles) {
            for (const tile of tiles) {
                const [x, y, z, bounds] = tile;
                this._create_tile(x, y, z, bounds);
            }
        }
        _update() {
            const { tile_source } = this.model;
            const { min_zoom } = tile_source;
            const { max_zoom } = tile_source;
            let extent = this.get_extent();
            const zooming_out = (this.extent[2] - this.extent[0]) < (extent[2] - extent[0]);
            const h = this.map_frame.bbox.height;
            const w = this.map_frame.bbox.width;
            let zoom_level = tile_source.get_level_by_extent(extent, h, w);
            let snap_back = false;
            if (zoom_level < min_zoom) {
                extent = this.extent;
                zoom_level = min_zoom;
                snap_back = true;
            }
            else if (zoom_level > max_zoom) {
                extent = this.extent;
                zoom_level = max_zoom;
                snap_back = true;
            }
            if (snap_back) {
                this.x_range.setv({ start: extent[0], end: extent[2] });
                this.y_range.setv({ start: extent[1], end: extent[3] });
            }
            this.extent = extent;
            const tiles = tile_source.get_tiles_by_extent(extent, zoom_level);
            const need_load = [];
            const cached = [];
            const parents = [];
            const children = [];
            for (const t of tiles) {
                const [x, y, z] = t;
                const key = tile_source.tile_xyz_to_key(x, y, z);
                const tile = tile_source.tiles.get(key);
                if (tile != null && tile.loaded) {
                    cached.push(key);
                }
                else {
                    if (this.model.render_parents) {
                        const [px, py, pz] = tile_source.get_closest_parent_by_tile_xyz(x, y, z);
                        const parent_key = tile_source.tile_xyz_to_key(px, py, pz);
                        const parent_tile = tile_source.tiles.get(parent_key);
                        if ((parent_tile != null) && parent_tile.loaded && !(0, array_1.includes)(parents, parent_key)) {
                            parents.push(parent_key);
                        }
                        if (zooming_out) {
                            const child_tiles = tile_source.children_by_tile_xyz(x, y, z);
                            for (const [cx, cy, cz] of child_tiles) {
                                const child_key = tile_source.tile_xyz_to_key(cx, cy, cz);
                                if (tile_source.tiles.has(child_key)) {
                                    children.push(child_key);
                                }
                            }
                        }
                    }
                }
                if (tile == null) {
                    need_load.push(t);
                }
            }
            // draw stand-in parents ----------
            this._render_tiles(parents);
            this._render_tiles(children);
            // draw cached ----------
            this._render_tiles(cached);
            // fetch missing -------
            if (this.render_timer != null) {
                clearTimeout(this.render_timer);
            }
            this.render_timer = setTimeout((() => this._fetch_tiles(need_load)), 65);
        }
    }
    exports.TileRendererView = TileRendererView;
    TileRendererView.__name__ = "TileRendererView";
    class TileRenderer extends renderer_1.Renderer {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.TileRenderer = TileRenderer;
    _a = TileRenderer;
    TileRenderer.__name__ = "TileRenderer";
    (() => {
        _a.prototype.default_view = TileRendererView;
        _a.define(({ Bool, Float, Ref }) => ({
            alpha: [Float, 1.0],
            smoothing: [Bool, true],
            tile_source: [Ref(tile_source_1.TileSource), () => new wmts_tile_source_1.WMTSTileSource()],
            render_parents: [Bool, true],
        }));
        _a.override({
            level: "image",
        });
    })();
},
/* models/tiles/wmts_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const mercator_tile_source_1 = require(473) /* ./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";
},
/* models/tiles/tms_tile_source.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const mercator_tile_source_1 = require(473) /* ./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(481) /* ./canvas_texture */;
    __esExport("CanvasTexture", canvas_texture_1.CanvasTexture);
    var image_url_texture_1 = require(483) /* ./image_url_texture */;
    __esExport("ImageURLTexture", image_url_texture_1.ImageURLTexture);
    var texture_1 = require(482) /* ./texture */;
    __esExport("Texture", texture_1.Texture);
},
/* models/textures/canvas_texture.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const texture_1 = require(482) /* ./texture */;
    const string_1 = require(40) /* ../../core/util/string */;
    class CanvasTexture extends texture_1.Texture {
        constructor(attrs) {
            super(attrs);
        }
        get func() {
            const code = (0, string_1.use_strict)(this.code);
            return new Function("ctx", "color", "scale", "weight", code);
        }
        get_pattern(color, scale, weight) {
            const canvas = document.createElement("canvas");
            canvas.width = scale;
            canvas.height = scale;
            const pattern_ctx = canvas.getContext("2d");
            this.func.call(this, pattern_ctx, color, scale, weight);
            return canvas;
        }
    }
    exports.CanvasTexture = CanvasTexture;
    _a = CanvasTexture;
    CanvasTexture.__name__ = "CanvasTexture";
    (() => {
        _a.define(({ Str }) => ({
            code: [Str],
        }));
    })();
},
/* models/textures/texture.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const model_1 = require(51) /* ../../model */;
    const enums_1 = require(20) /* ../../core/enums */;
    class Texture extends model_1.Model {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Texture = Texture;
    _a = Texture;
    Texture.__name__ = "Texture";
    (() => {
        _a.define(() => ({
            repetition: [enums_1.TextureRepetition, "repeat"],
        }));
    })();
},
/* models/textures/image_url_texture.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const texture_1 = require(482) /* ./texture */;
    const image_1 = require(179) /* ../../core/util/image */;
    class ImageURLTexture extends texture_1.Texture {
        constructor(attrs) {
            super(attrs);
        }
        initialize() {
            super.initialize();
            this._loader = new image_1.ImageLoader(this.url);
        }
        get_pattern(_color, _scale, _weight) {
            const { _loader } = this;
            return this._loader.finished ? _loader.image : _loader.promise;
        }
    }
    exports.ImageURLTexture = ImageURLTexture;
    _a = ImageURLTexture;
    ImageURLTexture.__name__ = "ImageURLTexture";
    (() => {
        _a.define(({ Str }) => ({
            url: [Str],
        }));
    })();
},
/* models/ui/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    tslib_1.__exportStar(require(485) /* ./icons */, exports);
    tslib_1.__exportStar(require(490) /* ./menus */, exports);
    var panel_1 = require(442) /* ./panel */;
    __esExport("Panel", panel_1.Panel);
    var dialog_1 = require(320) /* ./dialog */;
    __esExport("Dialog", dialog_1.Dialog);
    var examiner_1 = require(491) /* ./examiner */;
    __esExport("Examiner", examiner_1.Examiner);
    var pane_1 = require(407) /* ./pane */;
    __esExport("Pane", pane_1.Pane);
    var tooltip_1 = require(420) /* ./tooltip */;
    __esExport("Tooltip", tooltip_1.Tooltip);
    var ui_element_1 = require(111) /* ./ui_element */;
    __esExport("UIElement", ui_element_1.UIElement);
},
/* models/ui/icons/index.js */ function _(require, module, exports, __esModule, __esExport) {
    __esModule();
    var builtin_icon_1 = require(486) /* ./builtin_icon */;
    __esExport("BuiltinIcon", builtin_icon_1.BuiltinIcon);
    var svg_icon_1 = require(488) /* ./svg_icon */;
    __esExport("SVGIcon", svg_icon_1.SVGIcon);
    var tabler_icon_1 = require(489) /* ./tabler_icon */;
    __esExport("TablerIcon", tabler_icon_1.TablerIcon);
},
/* models/ui/icons/builtin_icon.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const tslib_1 = require(1) /* tslib */;
    const icon_1 = require(487) /* ./icon */;
    const dom_1 = require(63) /* ../../../core/dom */;
    const color_1 = require(22) /* ../../../core/util/color */;
    const types_1 = require(8) /* ../../../core/util/types */;
    const icons_css_1 = tslib_1.__importDefault(require(123) /* ../../../styles/icons.css */);
    class BuiltinIconView extends icon_1.IconView {
        constructor() {
            super(...arguments);
            this._style = new dom_1.InlineStyleSheet();
        }
        stylesheets() {
            return [...super.stylesheets(), icons_css_1.default, this._style];
        }
        render() {
            super.render();
            const icon = `var(--bokeh-icon-${this.model.icon_name})`;
            const color = (0, color_1.color2css)(this.model.color);
            const size = (() => {
                const { size } = this.model;
                return (0, types_1.isNumber)(size) ? `${size}px` : size;
            })();
            this._style.replace(`
      :host {
        display: inline-block;
        vertical-align: middle;
        width: ${size};
        height: ${size};
        background-color: ${color};
        mask-image: ${icon};
        mask-size: contain;
        mask-repeat: no-repeat;
        -webkit-mask-image: ${icon};
        -webkit-mask-size: contain;
        -webkit-mask-repeat: no-repeat;
      }
    `);
        }
    }
    exports.BuiltinIconView = BuiltinIconView;
    BuiltinIconView.__name__ = "BuiltinIconView";
    class BuiltinIcon extends icon_1.Icon {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.BuiltinIcon = BuiltinIcon;
    _a = BuiltinIcon;
    BuiltinIcon.__name__ = "BuiltinIcon";
    (() => {
        _a.prototype.default_view = BuiltinIconView;
        _a.define(({ Str, Color }) => ({
            icon_name: [Str],
            color: [Color, "gray"],
        }));
    })();
},
/* models/ui/icons/icon.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const ui_element_1 = require(111) /* ../ui_element */;
    class IconView extends ui_element_1.UIElementView {
        connect_signals() {
            super.connect_signals();
            this.connect(this.model.change, () => this.render());
        }
    }
    exports.IconView = IconView;
    IconView.__name__ = "IconView";
    class Icon extends ui_element_1.UIElement {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.Icon = Icon;
    _a = Icon;
    Icon.__name__ = "Icon";
    (() => {
        _a.define(({ Float, Or, CSSLength }) => ({
            size: [Or(Float, CSSLength), "1em"],
        }));
    })();
},
/* models/ui/icons/svg_icon.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a;
    __esModule();
    const icon_1 = require(487) /* ./icon */;
    const dom_1 = require(63) /* ../../../core/dom */;
    const types_1 = require(8) /* ../../../core/util/types */;
    class SVGIconView extends icon_1.IconView {
        constructor() {
            super(...arguments);
            this._style = new dom_1.InlineStyleSheet();
        }
        stylesheets() {
            return [...super.stylesheets(), this._style];
        }
        render() {
            super.render();
            const size = (() => {
                const { size } = this.model;
                return (0, types_1.isNumber)(size) ? `${size}px` : size;
            })();
            this._style.replace(`
      :host {
        display: inline-block;
        vertical-align: middle;
      }
      :host svg {
        width: ${size};
        height: ${size};
      }
    `);
            const parser = new DOMParser();
            const doc = parser.parseFromString(this.model.svg, "image/svg+xml");
            this.shadow_el.append(doc.documentElement);
        }
    }
    exports.SVGIconView = SVGIconView;
    SVGIconView.__name__ = "SVGIconView";
    class SVGIcon extends icon_1.Icon {
        constructor(attrs) {
            super(attrs);
        }
    }
    exports.SVGIcon = SVGIcon;
    _a = SVGIcon;
    SVGIcon.__name__ = "SVGIcon";
    (() => {
        _a.prototype.default_view = SVGIconView;
        _a.define(({ Str }) => ({
            svg: [Str],
        }));
    })();
},
/* models/ui/icons/tabler_icon.js */ function _(require, module, exports, __esModule, __esExport) {
    var _a, _b;
    __esModule();
    const icon_1 = require(487) /* ./icon */;
    const dom_1 = require(63) /* ../../../core/dom */;
    const types_1 = require(8) /* ../../../core/util/types */;
    class TablerIconView extends icon_1.IconView {
        constructor() {
            super(...arguments);
            this._tabler = new dom_1.ImportedStyleSheet(`${_a._url}/tabler-icons.min.css`);
            this._style = new dom_1.InlineStyleSheet();
        }
        stylesheets() {
            return [...super.stylesheets(), _a._fonts, this._tabler, this._style];
        }
        render() {
            super.render();
            const size = (() => {
                const { size } = this.model;
                return (0, types_1.isNumber)(size) ? `${size}px` : size;
            })();
            this._style.replace(`
      :host {
        display: inline-block;
        vertical-align: middle;
        font-size: ${size};
      }
    `);
            const icon = (0, dom_1.span)({ class: ["ti", `ti-${this.model.icon_name}`] });
            this.shadow_el.appendChild(icon);
        }
    }
    exports.TablerIconView = TablerIconView;
    _a = TablerIconView;
    TablerIconView.__name__ = "TablerIconView";
    TablerIconView._url = "https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@latest";
    TablerIconView._fonts = new dom_1.GlobalInlineStyleSheet(`\
    /*!
    * Tabler Icons 1.68.0 by tabler - https://tabler.io
    * License - https://github.com/tabler/tabler-icons/blob/master/LICENSE
    */
  @font-face {
    font-family: "tabler-icons";
    font-style: normal;
    font-weight: 400;
    src: url("${_a._url}/fonts/tabler-icons.eot");
    src: url("${_a._url}/fonts/tabler-icons.eot?#iefix") format("embedded-opentype"),
         url("${_a._url}/fonts/tabler-icons.woff2") format("woff2"),
         url("${_a._url}/fonts/tabler-icons.woff") format("woff"),
         url("${_a._url}/fonts/tabler-icons.ttf") format("truetype"),
         url("${_a._url}/fonts/tabler-icons.svg#tabler-icons") format("svg");
  }

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