diff --git a/public/static/temba-components/temba-components.js b/public/static/temba-components/temba-components.js index 97f40e90d..6acb192ec 100644 --- a/public/static/temba-components/temba-components.js +++ b/public/static/temba-components/temba-components.js @@ -2013,7 +2013,6 @@ font-family: var(--font-family); padding: 0px; margin-left: 8px; - font-weight: 300; font-size: 14px; line-height: 19px; flex-grow: 1; @@ -2223,7 +2222,6 @@ line-height: normal; cursor: var(--input-cursor); resize: none; - font-weight: 300; width: 100%; } @@ -2236,7 +2234,6 @@ .textinput::placeholder { color: var(--color-placeholder); - font-weight: 300; } .grow-wrap { @@ -2258,7 +2255,6 @@ line-height: normal; cursor: text; resize: none; - font-weight: 300; width: 100%; visibility: hidden; word-break: break-word; @@ -2396,6 +2392,7 @@ let i = Z` 0 && @@ -13277,7 +13271,6 @@ align-items: center; font-size: 20px; padding: 12px 20px; - font-weight: 300; color: var(--header-text); background: var(--header-bg); } @@ -13606,7 +13599,6 @@ padding: 10px; margin-bottom: 10px; border-radius: 6px; - font-weight: 300; } .step-ball { @@ -13984,7 +13976,6 @@ .secondary-button { background: transparent; color: var(--color-text); - font-weight: 300; } .destructive-button { @@ -19748,15 +19739,13 @@ } .name { - font-size: 1.5rem; + font-size: var(--contact-name-font-size, 1.5rem); overflow: hidden; max-height: 2rem; line-height: 2rem; -webkit-box-orient: vertical; -webkit-line-clamp: 1; text-overflow: ellipsis; - display: -webkit-box; - margin: auto; } `; } @@ -21323,6 +21312,7 @@ return r` :host { overflow-y: auto !important; + --contact-name-font-size: 1em; } @media only screen and (max-height: 768px) { @@ -21411,7 +21401,7 @@ Z`
0 ? this.messages[this.messages.length - 1] : []; @@ -24232,6 +24253,7 @@ (this.hideTopScroll = 0 === t.target.scrollTop); } handleClickInputPanel(t) { + t.preventDefault(), t.stopPropagation(); this.shadowRoot.querySelector('.input').focus(); } toggleChat() { @@ -24244,6 +24266,15 @@ this.hideBottomScroll ? 'scroll-at-bottom' : '' } ${this.open ? 'open' : ''}" > +
+ + +
${ @@ -25335,7 +25366,7 @@ background: #ccc; ((e = ge.tickets), (i = 'New unassigned ticket')), Z`
${ diff --git a/public/static/temba-components/temba-components.js.map b/public/static/temba-components/temba-components.js.map index b6d34c302..55a78330c 100644 --- a/public/static/temba-components/temba-components.js.map +++ b/public/static/temba-components/temba-components.js.map @@ -1 +1 @@ -{"version":3,"file":"temba-components.js","sources":["../node_modules/tslib/tslib.es6.js","../node_modules/@lit/reactive-element/css-tag.js","../node_modules/@lit/reactive-element/reactive-element.js","../node_modules/lit-html/lit-html.js","../node_modules/lit-element/lit-element.js","../node_modules/color-hash/dist/esm.js","../../src/utils/index.ts","../../src/RapidElement.ts","../node_modules/@lit/reactive-element/decorators/custom-element.js","../node_modules/@lit/reactive-element/decorators/property.js","../../src/FormElement.ts","../../src/vectoricon/index.ts","../../src/checkbox/Checkbox.ts","../node_modules/lit-html/directives/if-defined.js","../node_modules/lit-html/directive.js","../node_modules/lit-html/directives/style-map.js","../../src/textinput/TextInput.ts","../../src/interfaces.ts","../../src/textinput/helpers.ts","../node_modules/tiny-lru/dist/tiny-lru.js","../node_modules/luxon/src/errors.js","../node_modules/luxon/src/impl/formats.js","../node_modules/luxon/src/impl/util.js","../node_modules/luxon/src/impl/english.js","../node_modules/luxon/src/impl/formatter.js","../node_modules/luxon/src/impl/invalid.js","../node_modules/luxon/src/zone.js","../node_modules/luxon/src/zones/systemZone.js","../node_modules/luxon/src/zones/IANAZone.js","../node_modules/luxon/src/zones/fixedOffsetZone.js","../node_modules/luxon/src/zones/invalidZone.js","../node_modules/luxon/src/impl/zoneUtil.js","../node_modules/luxon/src/settings.js","../node_modules/luxon/src/impl/locale.js","../node_modules/luxon/src/impl/regexParser.js","../node_modules/luxon/src/duration.js","../node_modules/luxon/src/interval.js","../node_modules/luxon/src/info.js","../node_modules/luxon/src/impl/diff.js","../node_modules/luxon/src/impl/digits.js","../node_modules/luxon/src/impl/tokenParser.js","../node_modules/luxon/src/impl/conversions.js","../node_modules/luxon/src/datetime.js","../node_modules/@lit/localize/internal/str-tag.js","../node_modules/@lit/localize/internal/default-msg.js","../node_modules/@lit/localize/internal/deferred.js","../node_modules/@lit/localize/internal/fnv1a64.js","../node_modules/@lit/localize/internal/id-generation.js","../node_modules/@lit/localize/internal/runtime-msg.js","../node_modules/@lit/localize/init/runtime.js","../node_modules/@lit/localize/internal/locale-status-event.js","../node_modules/@lit/localize/lit-localize.js","../../src/locales/locale-codes.ts","../../src/store/Store.ts","../../src/options/Options.ts","../node_modules/lit-html/directives/unsafe-html.js","../../src/completion/ExcellentParser.ts","../node_modules/remarkable/dist/esm/index.js","../../src/completion/helpers.ts","../../src/select/Select.ts","../../src/completion/Completion.ts","../../src/ResizeElement.ts","../../src/dialog/Dialog.ts","../../src/dialog/Modax.ts","../../src/button/Button.ts","../../src/formfield/FormField.ts","../../src/loading/Loading.ts","../../src/sms/gsmvalidator.ts","../../src/sms/gsmsplitter.ts","../../src/sms/unicodesplitter.ts","../../src/sms/index.ts","../../src/charcount/helpers.ts","../../src/charcount/CharCount.ts","../../src/store/StoreMonitorElement.ts","../../src/store/StoreElement.ts","../../src/contacts/ContactStoreElement.ts","../../src/contacts/ContactChat.ts","../../src/contacts/helpers.ts","../../src/contacts/events.ts","../../src/contacts/ContactHistory.ts","../../src/list/TembaList.ts","../../src/list/TicketList.ts","../../src/contacts/ContactDetails.ts","../../src/alert/Alert.ts","../../src/contactsearch/ContactSearch.ts","../../src/vectoricon/VectorIcon.ts","../../src/omnibox/Omnibox.ts","../../src/tip/helpers.ts","../../src/tip/Tip.ts","../../src/list/TembaMenu.ts","../../src/anchor/Anchor.ts","../../src/dropdown/Dropdown.ts","../../src/tabpane/TabPane.ts","../../src/tabpane/Tab.ts","../../src/label/Label.ts","../../src/contacts/ContactName.ts","../../src/contacts/ContactUrn.ts","../../src/contacts/ContactFields.ts","../../src/contacts/ContactFieldEditor.ts","../../src/contacts/ContactBadges.ts","../../src/contacts/ContactPending.ts","../../src/contacts/ContactTickets.ts","../../src/slider/TembaSlider.ts","../../src/list/RunList.ts","../../src/flow/FlowStoreElement.ts","../../src/contacts/ContactNameFetch.ts","../../src/datepicker/DatePicker.ts","../../src/fields/FieldManager.ts","../../src/list/SortableList.ts","../../src/list/ContentMenu.ts","../../src/date/TembaDate.ts","../../src/remote/Remote.ts","../../src/webchat/WebChat.ts","../../src/compose/Compose.ts","../../src/lightbox/Lightbox.ts","../../src/colorpicker/ColorPicker.ts","../../src/resizer/Resizer.ts","../../src/thumbnail/Thumbnail.ts","../../src/imagepicker/CroppieCSS.ts","../../src/imagepicker/ImagePicker.ts","../../src/mask/Mask.ts","../../src/user/TembaUser.ts","../../src/templates/TemplateEditor.ts","../../temba-modules.ts","../../src/list/NotificationList.ts","../../src/aliaseditor/AliasEditor.ts","../node_modules/leaflet/dist/leaflet-src.js","../../src/leafletmap/helpers.ts","../../src/leafletmap/LeafletMap.ts","../../temba-components.ts"],"sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n 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;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n 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;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n 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; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n 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);\r\n 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); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n 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\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n 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\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=globalThis,e=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&\"adoptedStyleSheets\"in Document.prototype&&\"replace\"in CSSStyleSheet.prototype,s=Symbol(),o=new WeakMap;class n{constructor(t,e,o){if(this._$cssResult$=!0,o!==s)throw Error(\"CSSResult is not constructable. Use `unsafeCSS` or `css` instead.\");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const s=this.t;if(e&&void 0===t){const e=void 0!==s&&1===s.length;e&&(t=o.get(s)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),e&&o.set(s,t))}return t}toString(){return this.cssText}}const r=t=>new n(\"string\"==typeof t?t:t+\"\",void 0,s),i=(t,...e)=>{const o=1===t.length?t[0]:e.reduce(((e,s,o)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if(\"number\"==typeof t)return t;throw Error(\"Value passed to 'css' function must be a 'css' function result: \"+t+\". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.\")})(s)+t[o+1]),t[0]);return new n(o,t,s)},S=(s,o)=>{if(e)s.adoptedStyleSheets=o.map((t=>t instanceof CSSStyleSheet?t:t.styleSheet));else for(const e of o){const o=document.createElement(\"style\"),n=t.litNonce;void 0!==n&&o.setAttribute(\"nonce\",n),o.textContent=e.cssText,s.appendChild(o)}},c=e?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e=\"\";for(const s of t.cssRules)e+=s.cssText;return r(e)})(t):t;export{n as CSSResult,S as adoptStyles,i as css,c as getCompatibleStyle,e as supportsAdoptingStyleSheets,r as unsafeCSS};\n//# sourceMappingURL=css-tag.js.map\n","import{getCompatibleStyle as t,adoptStyles as s}from\"./css-tag.js\";export{CSSResult,adoptStyles,css,getCompatibleStyle,supportsAdoptingStyleSheets,unsafeCSS}from\"./css-tag.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const{is:i,defineProperty:e,getOwnPropertyDescriptor:r,getOwnPropertyNames:h,getOwnPropertySymbols:o,getPrototypeOf:n}=Object,a=globalThis,c=a.trustedTypes,l=c?c.emptyScript:\"\",p=a.reactiveElementPolyfillSupport,d=(t,s)=>t,u={toAttribute(t,s){switch(s){case Boolean:t=t?l:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,s){let i=t;switch(s){case Boolean:i=null!==t;break;case Number:i=null===t?null:Number(t);break;case Object:case Array:try{i=JSON.parse(t)}catch(t){i=null}}return i}},f=(t,s)=>!i(t,s),y={attribute:!0,type:String,converter:u,reflect:!1,hasChanged:f};Symbol.metadata??=Symbol(\"metadata\"),a.litPropertyMetadata??=new WeakMap;class b extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,s=y){if(s.state&&(s.attribute=!1),this._$Ei(),this.elementProperties.set(t,s),!s.noAccessor){const i=Symbol(),r=this.getPropertyDescriptor(t,i,s);void 0!==r&&e(this.prototype,t,r)}}static getPropertyDescriptor(t,s,i){const{get:e,set:h}=r(this.prototype,t)??{get(){return this[s]},set(t){this[s]=t}};return{get(){return e?.call(this)},set(s){const r=e?.call(this);h.call(this,s),this.requestUpdate(t,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??y}static _$Ei(){if(this.hasOwnProperty(d(\"elementProperties\")))return;const t=n(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(d(\"finalized\")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(d(\"properties\"))){const t=this.properties,s=[...h(t),...o(t)];for(const i of s)this.createProperty(i,t[i])}const t=this[Symbol.metadata];if(null!==t){const s=litPropertyMetadata.get(t);if(void 0!==s)for(const[t,i]of s)this.elementProperties.set(t,i)}this._$Eh=new Map;for(const[t,s]of this.elementProperties){const i=this._$Eu(t,s);void 0!==i&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(s){const i=[];if(Array.isArray(s)){const e=new Set(s.flat(1/0).reverse());for(const s of e)i.unshift(t(s))}else void 0!==s&&i.push(t(s));return i}static _$Eu(t,s){const i=s.attribute;return!1===i?void 0:\"string\"==typeof i?i:\"string\"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,s=this.constructor.elementProperties;for(const i of s.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return s(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,s,i){this._$AK(t,i)}_$EC(t,s){const i=this.constructor.elementProperties.get(t),e=this.constructor._$Eu(t,i);if(void 0!==e&&!0===i.reflect){const r=(void 0!==i.converter?.toAttribute?i.converter:u).toAttribute(s,i.type);this._$Em=t,null==r?this.removeAttribute(e):this.setAttribute(e,r),this._$Em=null}}_$AK(t,s){const i=this.constructor,e=i._$Eh.get(t);if(void 0!==e&&this._$Em!==e){const t=i.getPropertyOptions(e),r=\"function\"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:u;this._$Em=e,this[e]=r.fromAttribute(s,t.type),this._$Em=null}}requestUpdate(t,s,i){if(void 0!==t){if(i??=this.constructor.getPropertyOptions(t),!(i.hasChanged??f)(this[t],s))return;this.P(t,s,i)}!1===this.isUpdatePending&&(this._$ES=this._$ET())}P(t,s,i){this._$AL.has(t)||this._$AL.set(t,s),!0===i.reflect&&this._$Em!==t&&(this._$Ej??=new Set).add(t)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,s]of this._$Ep)this[t]=s;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[s,i]of t)!0!==i.wrapped||this._$AL.has(s)||void 0===this[s]||this.P(s,this[s],i)}let t=!1;const s=this._$AL;try{t=this.shouldUpdate(s),t?(this.willUpdate(s),this._$EO?.forEach((t=>t.hostUpdate?.())),this.update(s)):this._$EU()}catch(s){throw t=!1,this._$EU(),s}t&&this._$AE(s)}willUpdate(t){}_$AE(t){this._$EO?.forEach((t=>t.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Ej&&=this._$Ej.forEach((t=>this._$EC(t,this[t]))),this._$EU()}updated(t){}firstUpdated(t){}}b.elementStyles=[],b.shadowRootOptions={mode:\"open\"},b[d(\"elementProperties\")]=new Map,b[d(\"finalized\")]=new Map,p?.({ReactiveElement:b}),(a.reactiveElementVersions??=[]).push(\"2.0.4\");export{b as ReactiveElement,u as defaultConverter,f as notEqual};\n//# sourceMappingURL=reactive-element.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=globalThis,i=t.trustedTypes,s=i?i.createPolicy(\"lit-html\",{createHTML:t=>t}):void 0,e=\"$lit$\",h=`lit$${(Math.random()+\"\").slice(9)}$`,o=\"?\"+h,n=`<${o}>`,r=document,l=()=>r.createComment(\"\"),c=t=>null===t||\"object\"!=typeof t&&\"function\"!=typeof t,a=Array.isArray,u=t=>a(t)||\"function\"==typeof t?.[Symbol.iterator],d=\"[ \\t\\n\\f\\r]\",f=/<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g,v=/-->/g,_=/>/g,m=RegExp(`>|${d}(?:([^\\\\s\"'>=/]+)(${d}*=${d}*(?:[^ \\t\\n\\f\\r\"'\\`<>=]|(\"|')|))|$)`,\"g\"),p=/'/g,g=/\"/g,$=/^(?:script|style|textarea|title)$/i,y=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),x=y(1),b=y(2),w=Symbol.for(\"lit-noChange\"),T=Symbol.for(\"lit-nothing\"),A=new WeakMap,E=r.createTreeWalker(r,129);function C(t,i){if(!Array.isArray(t)||!t.hasOwnProperty(\"raw\"))throw Error(\"invalid template strings array\");return void 0!==s?s.createHTML(i):i}const P=(t,i)=>{const s=t.length-1,o=[];let r,l=2===i?\"\":\"\",c=f;for(let i=0;i\"===u[0]?(c=r??f,d=-1):void 0===u[1]?d=-2:(d=c.lastIndex-u[2].length,a=u[1],c=void 0===u[3]?m:'\"'===u[3]?g:p):c===g||c===p?c=m:c===v||c===_?c=f:(c=m,r=void 0);const x=c===m&&t[i+1].startsWith(\"/>\")?\" \":\"\";l+=c===f?s+n:d>=0?(o.push(a),s.slice(0,d)+e+s.slice(d)+h+x):s+h+(-2===d?i:x)}return[C(t,l+(t[s]||\"\")+(2===i?\"\":\"\")),o]};class V{constructor({strings:t,_$litType$:s},n){let r;this.parts=[];let c=0,a=0;const u=t.length-1,d=this.parts,[f,v]=P(t,s);if(this.el=V.createElement(f,n),E.currentNode=this.el.content,2===s){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(r=E.nextNode())&&d.length0){r.textContent=i?i.emptyScript:\"\";for(let i=0;i2||\"\"!==s[0]||\"\"!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=T}_$AI(t,i=this,s,e){const h=this.strings;let o=!1;if(void 0===h)t=N(this,t,i,0),o=!c(t)||t!==this._$AH&&t!==w,o&&(this._$AH=t);else{const e=t;let n,r;for(t=h[0],n=0;n{const e=s?.renderBefore??i;let h=e._$litPart$;if(void 0===h){const t=s?.renderBefore??null;e._$litPart$=h=new M(i.insertBefore(l(),t),t,void 0,s??{})}return h._$AI(t),h};export{z as _$LH,x as html,w as noChange,T as nothing,j as render,b as svg};\n//# sourceMappingURL=lit-html.js.map\n","import{ReactiveElement as t}from\"@lit/reactive-element\";export*from\"@lit/reactive-element\";import{render as e,noChange as i}from\"lit-html\";export*from\"lit-html\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */class s extends t{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=e(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return i}}s._$litElement$=!0,s[(\"finalized\",\"finalized\")]=!0,globalThis.litElementHydrateSupport?.({LitElement:s});const r=globalThis.litElementPolyfillSupport;r?.({LitElement:s});const o={_$AK:(t,e,i)=>{t._$AK(e,i)},_$AL:t=>t._$AL};(globalThis.litElementVersions??=[]).push(\"4.0.4\");export{s as LitElement,o as _$LE};\n//# sourceMappingURL=lit-element.js.map\n","// deno-fmt-ignore-file\n// deno-lint-ignore-file\n// This code was bundled using `deno bundle` and it's not recommended to edit it manually\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to set private field on non-instance\");\n }\n privateMap.set(receiver, value);\n return value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError(\"attempted to get private field on non-instance\");\n }\n return privateMap.get(receiver);\n};\nvar _block, _blocks, _bytes, _finalized, _first, _h0, _h1, _h2, _h3, _h4, _h5, _h6, _h7, _hashed, _hBytes, _is224, _lastByteIndex, _start;\nconst BKDRHash = function (str) {\n var seed = 131;\n var seed2 = 137;\n var hash = 0;\n str += 'x';\n var MAX_SAFE_INTEGER = Math.floor(9007199254740991 / seed2);\n for (let i = 0; i < str.length; i++) {\n if (hash > MAX_SAFE_INTEGER) {\n hash = Math.floor(hash / seed2);\n }\n hash = hash * seed + str.charCodeAt(i);\n }\n return hash;\n};\nconst HEX_CHARS = \"0123456789abcdef\".split(\"\");\nconst EXTRA = [\n -2147483648,\n 8388608,\n 32768,\n 128\n];\nconst SHIFT = [\n 24,\n 16,\n 8,\n 0\n];\nconst K = [\n 0x428a2f98,\n 0x71374491,\n 0xb5c0fbcf,\n 0xe9b5dba5,\n 0x3956c25b,\n 0x59f111f1,\n 0x923f82a4,\n 0xab1c5ed5,\n 0xd807aa98,\n 0x12835b01,\n 0x243185be,\n 0x550c7dc3,\n 0x72be5d74,\n 0x80deb1fe,\n 0x9bdc06a7,\n 0xc19bf174,\n 0xe49b69c1,\n 0xefbe4786,\n 0x0fc19dc6,\n 0x240ca1cc,\n 0x2de92c6f,\n 0x4a7484aa,\n 0x5cb0a9dc,\n 0x76f988da,\n 0x983e5152,\n 0xa831c66d,\n 0xb00327c8,\n 0xbf597fc7,\n 0xc6e00bf3,\n 0xd5a79147,\n 0x06ca6351,\n 0x14292967,\n 0x27b70a85,\n 0x2e1b2138,\n 0x4d2c6dfc,\n 0x53380d13,\n 0x650a7354,\n 0x766a0abb,\n 0x81c2c92e,\n 0x92722c85,\n 0xa2bfe8a1,\n 0xa81a664b,\n 0xc24b8b70,\n 0xc76c51a3,\n 0xd192e819,\n 0xd6990624,\n 0xf40e3585,\n 0x106aa070,\n 0x19a4c116,\n 0x1e376c08,\n 0x2748774c,\n 0x34b0bcb5,\n 0x391c0cb3,\n 0x4ed8aa4a,\n 0x5b9cca4f,\n 0x682e6ff3,\n 0x748f82ee,\n 0x78a5636f,\n 0x84c87814,\n 0x8cc70208,\n 0x90befffa,\n 0xa4506ceb,\n 0xbef9a3f7,\n 0xc67178f2\n];\nconst blocks = [];\nclass Sha256 {\n constructor(is224 = false, sharedMemory = false) {\n _block.set(this, void 0);\n _blocks.set(this, void 0);\n _bytes.set(this, void 0);\n _finalized.set(this, void 0);\n _first.set(this, void 0);\n _h0.set(this, void 0);\n _h1.set(this, void 0);\n _h2.set(this, void 0);\n _h3.set(this, void 0);\n _h4.set(this, void 0);\n _h5.set(this, void 0);\n _h6.set(this, void 0);\n _h7.set(this, void 0);\n _hashed.set(this, void 0);\n _hBytes.set(this, void 0);\n _is224.set(this, void 0);\n _lastByteIndex.set(this, 0);\n _start.set(this, void 0);\n this.init(is224, sharedMemory);\n }\n init(is224, sharedMemory) {\n if (sharedMemory) {\n blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;\n __classPrivateFieldSet(this, _blocks, blocks);\n }\n else {\n __classPrivateFieldSet(this, _blocks, [\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0\n ]);\n }\n if (is224) {\n __classPrivateFieldSet(this, _h0, 0xc1059ed8);\n __classPrivateFieldSet(this, _h1, 0x367cd507);\n __classPrivateFieldSet(this, _h2, 0x3070dd17);\n __classPrivateFieldSet(this, _h3, 0xf70e5939);\n __classPrivateFieldSet(this, _h4, 0xffc00b31);\n __classPrivateFieldSet(this, _h5, 0x68581511);\n __classPrivateFieldSet(this, _h6, 0x64f98fa7);\n __classPrivateFieldSet(this, _h7, 0xbefa4fa4);\n }\n else {\n __classPrivateFieldSet(this, _h0, 0x6a09e667);\n __classPrivateFieldSet(this, _h1, 0xbb67ae85);\n __classPrivateFieldSet(this, _h2, 0x3c6ef372);\n __classPrivateFieldSet(this, _h3, 0xa54ff53a);\n __classPrivateFieldSet(this, _h4, 0x510e527f);\n __classPrivateFieldSet(this, _h5, 0x9b05688c);\n __classPrivateFieldSet(this, _h6, 0x1f83d9ab);\n __classPrivateFieldSet(this, _h7, 0x5be0cd19);\n }\n __classPrivateFieldSet(this, _block, __classPrivateFieldSet(this, _start, __classPrivateFieldSet(this, _bytes, __classPrivateFieldSet(this, _hBytes, 0))));\n __classPrivateFieldSet(this, _finalized, __classPrivateFieldSet(this, _hashed, false));\n __classPrivateFieldSet(this, _first, true);\n __classPrivateFieldSet(this, _is224, is224);\n }\n update(message) {\n if (__classPrivateFieldGet(this, _finalized)) {\n return this;\n }\n let msg;\n if (message instanceof ArrayBuffer) {\n msg = new Uint8Array(message);\n }\n else {\n msg = message;\n }\n let index = 0;\n const length = msg.length;\n const blocks = __classPrivateFieldGet(this, _blocks);\n while (index < length) {\n let i;\n if (__classPrivateFieldGet(this, _hashed)) {\n __classPrivateFieldSet(this, _hashed, false);\n blocks[0] = __classPrivateFieldGet(this, _block);\n blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;\n }\n if (typeof msg !== \"string\") {\n for (i = __classPrivateFieldGet(this, _start); index < length && i < 64; ++index) {\n blocks[i >> 2] |= msg[index] << SHIFT[i++ & 3];\n }\n }\n else {\n for (i = __classPrivateFieldGet(this, _start); index < length && i < 64; ++index) {\n let code = msg.charCodeAt(index);\n if (code < 0x80) {\n blocks[i >> 2] |= code << SHIFT[i++ & 3];\n }\n else if (code < 0x800) {\n blocks[i >> 2] |= (0xc0 | code >> 6) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];\n }\n else if (code < 0xd800 || code >= 0xe000) {\n blocks[i >> 2] |= (0xe0 | code >> 12) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];\n }\n else {\n code = 0x10000 + ((code & 0x3ff) << 10 | msg.charCodeAt(++index) & 0x3ff);\n blocks[i >> 2] |= (0xf0 | code >> 18) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | code >> 12 & 0x3f) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];\n }\n }\n }\n __classPrivateFieldSet(this, _lastByteIndex, i);\n __classPrivateFieldSet(this, _bytes, __classPrivateFieldGet(this, _bytes) + (i - __classPrivateFieldGet(this, _start)));\n if (i >= 64) {\n __classPrivateFieldSet(this, _block, blocks[16]);\n __classPrivateFieldSet(this, _start, i - 64);\n this.hash();\n __classPrivateFieldSet(this, _hashed, true);\n }\n else {\n __classPrivateFieldSet(this, _start, i);\n }\n }\n if (__classPrivateFieldGet(this, _bytes) > 4294967295) {\n __classPrivateFieldSet(this, _hBytes, __classPrivateFieldGet(this, _hBytes) + (__classPrivateFieldGet(this, _bytes) / 4294967296 << 0));\n __classPrivateFieldSet(this, _bytes, __classPrivateFieldGet(this, _bytes) % 4294967296);\n }\n return this;\n }\n finalize() {\n if (__classPrivateFieldGet(this, _finalized)) {\n return;\n }\n __classPrivateFieldSet(this, _finalized, true);\n const blocks = __classPrivateFieldGet(this, _blocks);\n const i = __classPrivateFieldGet(this, _lastByteIndex);\n blocks[16] = __classPrivateFieldGet(this, _block);\n blocks[i >> 2] |= EXTRA[i & 3];\n __classPrivateFieldSet(this, _block, blocks[16]);\n if (i >= 56) {\n if (!__classPrivateFieldGet(this, _hashed)) {\n this.hash();\n }\n blocks[0] = __classPrivateFieldGet(this, _block);\n blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;\n }\n blocks[14] = __classPrivateFieldGet(this, _hBytes) << 3 | __classPrivateFieldGet(this, _bytes) >>> 29;\n blocks[15] = __classPrivateFieldGet(this, _bytes) << 3;\n this.hash();\n }\n hash() {\n let a = __classPrivateFieldGet(this, _h0);\n let b = __classPrivateFieldGet(this, _h1);\n let c = __classPrivateFieldGet(this, _h2);\n let d = __classPrivateFieldGet(this, _h3);\n let e = __classPrivateFieldGet(this, _h4);\n let f = __classPrivateFieldGet(this, _h5);\n let g = __classPrivateFieldGet(this, _h6);\n let h = __classPrivateFieldGet(this, _h7);\n const blocks = __classPrivateFieldGet(this, _blocks);\n let s0;\n let s1;\n let maj;\n let t1;\n let t2;\n let ch;\n let ab;\n let da;\n let cd;\n let bc;\n for (let j = 16; j < 64; ++j) {\n t1 = blocks[j - 15];\n s0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3;\n t1 = blocks[j - 2];\n s1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10;\n blocks[j] = blocks[j - 16] + s0 + blocks[j - 7] + s1 << 0;\n }\n bc = b & c;\n for (let j1 = 0; j1 < 64; j1 += 4) {\n if (__classPrivateFieldGet(this, _first)) {\n if (__classPrivateFieldGet(this, _is224)) {\n ab = 300032;\n t1 = blocks[0] - 1413257819;\n h = t1 - 150054599 << 0;\n d = t1 + 24177077 << 0;\n }\n else {\n ab = 704751109;\n t1 = blocks[0] - 210244248;\n h = t1 - 1521486534 << 0;\n d = t1 + 143694565 << 0;\n }\n __classPrivateFieldSet(this, _first, false);\n }\n else {\n s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);\n s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);\n ab = a & b;\n maj = ab ^ a & c ^ bc;\n ch = e & f ^ ~e & g;\n t1 = h + s1 + ch + K[j1] + blocks[j1];\n t2 = s0 + maj;\n h = d + t1 << 0;\n d = t1 + t2 << 0;\n }\n s0 = (d >>> 2 | d << 30) ^ (d >>> 13 | d << 19) ^ (d >>> 22 | d << 10);\n s1 = (h >>> 6 | h << 26) ^ (h >>> 11 | h << 21) ^ (h >>> 25 | h << 7);\n da = d & a;\n maj = da ^ d & b ^ ab;\n ch = h & e ^ ~h & f;\n t1 = g + s1 + ch + K[j1 + 1] + blocks[j1 + 1];\n t2 = s0 + maj;\n g = c + t1 << 0;\n c = t1 + t2 << 0;\n s0 = (c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10);\n s1 = (g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7);\n cd = c & d;\n maj = cd ^ c & a ^ da;\n ch = g & h ^ ~g & e;\n t1 = f + s1 + ch + K[j1 + 2] + blocks[j1 + 2];\n t2 = s0 + maj;\n f = b + t1 << 0;\n b = t1 + t2 << 0;\n s0 = (b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10);\n s1 = (f >>> 6 | f << 26) ^ (f >>> 11 | f << 21) ^ (f >>> 25 | f << 7);\n bc = b & c;\n maj = bc ^ b & d ^ cd;\n ch = f & g ^ ~f & h;\n t1 = e + s1 + ch + K[j1 + 3] + blocks[j1 + 3];\n t2 = s0 + maj;\n e = a + t1 << 0;\n a = t1 + t2 << 0;\n }\n __classPrivateFieldSet(this, _h0, __classPrivateFieldGet(this, _h0) + a << 0);\n __classPrivateFieldSet(this, _h1, __classPrivateFieldGet(this, _h1) + b << 0);\n __classPrivateFieldSet(this, _h2, __classPrivateFieldGet(this, _h2) + c << 0);\n __classPrivateFieldSet(this, _h3, __classPrivateFieldGet(this, _h3) + d << 0);\n __classPrivateFieldSet(this, _h4, __classPrivateFieldGet(this, _h4) + e << 0);\n __classPrivateFieldSet(this, _h5, __classPrivateFieldGet(this, _h5) + f << 0);\n __classPrivateFieldSet(this, _h6, __classPrivateFieldGet(this, _h6) + g << 0);\n __classPrivateFieldSet(this, _h7, __classPrivateFieldGet(this, _h7) + h << 0);\n }\n hex() {\n this.finalize();\n const h0 = __classPrivateFieldGet(this, _h0);\n const h1 = __classPrivateFieldGet(this, _h1);\n const h2 = __classPrivateFieldGet(this, _h2);\n const h3 = __classPrivateFieldGet(this, _h3);\n const h4 = __classPrivateFieldGet(this, _h4);\n const h5 = __classPrivateFieldGet(this, _h5);\n const h6 = __classPrivateFieldGet(this, _h6);\n const h7 = __classPrivateFieldGet(this, _h7);\n let hex = HEX_CHARS[h0 >> 28 & 0x0f] + HEX_CHARS[h0 >> 24 & 0x0f] + HEX_CHARS[h0 >> 20 & 0x0f] + HEX_CHARS[h0 >> 16 & 0x0f] + HEX_CHARS[h0 >> 12 & 0x0f] + HEX_CHARS[h0 >> 8 & 0x0f] + HEX_CHARS[h0 >> 4 & 0x0f] + HEX_CHARS[h0 & 0x0f] + HEX_CHARS[h1 >> 28 & 0x0f] + HEX_CHARS[h1 >> 24 & 0x0f] + HEX_CHARS[h1 >> 20 & 0x0f] + HEX_CHARS[h1 >> 16 & 0x0f] + HEX_CHARS[h1 >> 12 & 0x0f] + HEX_CHARS[h1 >> 8 & 0x0f] + HEX_CHARS[h1 >> 4 & 0x0f] + HEX_CHARS[h1 & 0x0f] + HEX_CHARS[h2 >> 28 & 0x0f] + HEX_CHARS[h2 >> 24 & 0x0f] + HEX_CHARS[h2 >> 20 & 0x0f] + HEX_CHARS[h2 >> 16 & 0x0f] + HEX_CHARS[h2 >> 12 & 0x0f] + HEX_CHARS[h2 >> 8 & 0x0f] + HEX_CHARS[h2 >> 4 & 0x0f] + HEX_CHARS[h2 & 0x0f] + HEX_CHARS[h3 >> 28 & 0x0f] + HEX_CHARS[h3 >> 24 & 0x0f] + HEX_CHARS[h3 >> 20 & 0x0f] + HEX_CHARS[h3 >> 16 & 0x0f] + HEX_CHARS[h3 >> 12 & 0x0f] + HEX_CHARS[h3 >> 8 & 0x0f] + HEX_CHARS[h3 >> 4 & 0x0f] + HEX_CHARS[h3 & 0x0f] + HEX_CHARS[h4 >> 28 & 0x0f] + HEX_CHARS[h4 >> 24 & 0x0f] + HEX_CHARS[h4 >> 20 & 0x0f] + HEX_CHARS[h4 >> 16 & 0x0f] + HEX_CHARS[h4 >> 12 & 0x0f] + HEX_CHARS[h4 >> 8 & 0x0f] + HEX_CHARS[h4 >> 4 & 0x0f] + HEX_CHARS[h4 & 0x0f] + HEX_CHARS[h5 >> 28 & 0x0f] + HEX_CHARS[h5 >> 24 & 0x0f] + HEX_CHARS[h5 >> 20 & 0x0f] + HEX_CHARS[h5 >> 16 & 0x0f] + HEX_CHARS[h5 >> 12 & 0x0f] + HEX_CHARS[h5 >> 8 & 0x0f] + HEX_CHARS[h5 >> 4 & 0x0f] + HEX_CHARS[h5 & 0x0f] + HEX_CHARS[h6 >> 28 & 0x0f] + HEX_CHARS[h6 >> 24 & 0x0f] + HEX_CHARS[h6 >> 20 & 0x0f] + HEX_CHARS[h6 >> 16 & 0x0f] + HEX_CHARS[h6 >> 12 & 0x0f] + HEX_CHARS[h6 >> 8 & 0x0f] + HEX_CHARS[h6 >> 4 & 0x0f] + HEX_CHARS[h6 & 0x0f];\n if (!__classPrivateFieldGet(this, _is224)) {\n hex += HEX_CHARS[h7 >> 28 & 0x0f] + HEX_CHARS[h7 >> 24 & 0x0f] + HEX_CHARS[h7 >> 20 & 0x0f] + HEX_CHARS[h7 >> 16 & 0x0f] + HEX_CHARS[h7 >> 12 & 0x0f] + HEX_CHARS[h7 >> 8 & 0x0f] + HEX_CHARS[h7 >> 4 & 0x0f] + HEX_CHARS[h7 & 0x0f];\n }\n return hex;\n }\n toString() {\n return this.hex();\n }\n digest() {\n this.finalize();\n const h0 = __classPrivateFieldGet(this, _h0);\n const h1 = __classPrivateFieldGet(this, _h1);\n const h2 = __classPrivateFieldGet(this, _h2);\n const h3 = __classPrivateFieldGet(this, _h3);\n const h4 = __classPrivateFieldGet(this, _h4);\n const h5 = __classPrivateFieldGet(this, _h5);\n const h6 = __classPrivateFieldGet(this, _h6);\n const h7 = __classPrivateFieldGet(this, _h7);\n const arr = [\n h0 >> 24 & 0xff,\n h0 >> 16 & 0xff,\n h0 >> 8 & 0xff,\n h0 & 0xff,\n h1 >> 24 & 0xff,\n h1 >> 16 & 0xff,\n h1 >> 8 & 0xff,\n h1 & 0xff,\n h2 >> 24 & 0xff,\n h2 >> 16 & 0xff,\n h2 >> 8 & 0xff,\n h2 & 0xff,\n h3 >> 24 & 0xff,\n h3 >> 16 & 0xff,\n h3 >> 8 & 0xff,\n h3 & 0xff,\n h4 >> 24 & 0xff,\n h4 >> 16 & 0xff,\n h4 >> 8 & 0xff,\n h4 & 0xff,\n h5 >> 24 & 0xff,\n h5 >> 16 & 0xff,\n h5 >> 8 & 0xff,\n h5 & 0xff,\n h6 >> 24 & 0xff,\n h6 >> 16 & 0xff,\n h6 >> 8 & 0xff,\n h6 & 0xff\n ];\n if (!__classPrivateFieldGet(this, _is224)) {\n arr.push(h7 >> 24 & 0xff, h7 >> 16 & 0xff, h7 >> 8 & 0xff, h7 & 0xff);\n }\n return arr;\n }\n array() {\n return this.digest();\n }\n arrayBuffer() {\n this.finalize();\n const buffer = new ArrayBuffer(__classPrivateFieldGet(this, _is224) ? 28 : 32);\n const dataView = new DataView(buffer);\n dataView.setUint32(0, __classPrivateFieldGet(this, _h0));\n dataView.setUint32(4, __classPrivateFieldGet(this, _h1));\n dataView.setUint32(8, __classPrivateFieldGet(this, _h2));\n dataView.setUint32(12, __classPrivateFieldGet(this, _h3));\n dataView.setUint32(16, __classPrivateFieldGet(this, _h4));\n dataView.setUint32(20, __classPrivateFieldGet(this, _h5));\n dataView.setUint32(24, __classPrivateFieldGet(this, _h6));\n if (!__classPrivateFieldGet(this, _is224)) {\n dataView.setUint32(28, __classPrivateFieldGet(this, _h7));\n }\n return buffer;\n }\n}\n_block = new WeakMap(), _blocks = new WeakMap(), _bytes = new WeakMap(), _finalized = new WeakMap(), _first = new WeakMap(), _h0 = new WeakMap(), _h1 = new WeakMap(), _h2 = new WeakMap(), _h3 = new WeakMap(), _h4 = new WeakMap(), _h5 = new WeakMap(), _h6 = new WeakMap(), _h7 = new WeakMap(), _hashed = new WeakMap(), _hBytes = new WeakMap(), _is224 = new WeakMap(), _lastByteIndex = new WeakMap(), _start = new WeakMap();\nfunction Sha256ToInt(s) {\n const sha256 = new Sha256();\n sha256.update(s);\n return parseInt(sha256.hex().substring(0, 8), 16);\n}\nconst RGB2HEX = function (RGBArray) {\n var hex = '#';\n RGBArray.forEach(function (value) {\n if (value < 16) {\n hex += 0;\n }\n hex += value.toString(16);\n });\n return hex;\n};\nconst HSL2RGB = function (H, S, L) {\n H /= 360;\n var q = L < 0.5 ? L * (1 + S) : L + S - L * S;\n var p = 2 * L - q;\n return [\n H + 1 / 3,\n H,\n H - 1 / 3\n ].map(function (color) {\n if (color < 0) {\n color++;\n }\n if (color > 1) {\n color--;\n }\n if (color < 1 / 6) {\n color = p + (q - p) * 6 * color;\n }\n else if (color < 0.5) {\n color = q;\n }\n else if (color < 2 / 3) {\n color = p + (q - p) * 6 * (2 / 3 - color);\n }\n else {\n color = p;\n }\n return Math.round(color * 255);\n });\n};\nclass ColorHash {\n constructor(options = {}) {\n const [L, S] = [\n options.lightness,\n options.saturation\n ].map(function (param) {\n param = param !== undefined ? param : [\n 0.35,\n 0.5,\n 0.65\n ];\n return Array.isArray(param) ? param.concat() : [\n param\n ];\n });\n this.L = L;\n this.S = S;\n if (typeof options.hue === 'number') {\n options.hue = {\n min: options.hue,\n max: options.hue\n };\n }\n if (typeof options.hue === 'object' && !Array.isArray(options.hue)) {\n options.hue = [\n options.hue\n ];\n }\n if (typeof options.hue === 'undefined') {\n options.hue = [];\n }\n this.hueRanges = options.hue.map(function (range) {\n return {\n min: typeof range.min === 'undefined' ? 0 : range.min,\n max: typeof range.max === 'undefined' ? 360 : range.max\n };\n });\n this.hash = Sha256ToInt;\n if (typeof options.hash === 'function') {\n this.hash = options.hash;\n }\n if (options.hash === 'bkdr') {\n this.hash = BKDRHash;\n }\n }\n hsl(str) {\n var H, S, L;\n var hash = this.hash(str);\n var hueResolution = 727;\n if (this.hueRanges.length) {\n const range = this.hueRanges[hash % this.hueRanges.length];\n H = hash / this.hueRanges.length % hueResolution * (range.max - range.min) / hueResolution + range.min;\n }\n else {\n H = hash % 359;\n }\n hash = Math.ceil(hash / 360);\n S = this.S[hash % this.S.length];\n hash = Math.ceil(hash / this.S.length);\n L = this.L[hash % this.L.length];\n return [\n H,\n S,\n L\n ];\n }\n rgb(str) {\n var hsl = this.hsl(str);\n return HSL2RGB.apply(this, hsl);\n }\n hex(str) {\n var rgb = this.rgb(str);\n return RGB2HEX(rgb);\n }\n}\nexport { ColorHash as default };\n","/* eslint-disable @typescript-eslint/no-this-alias */\nimport { html, TemplateResult } from 'lit-html';\nimport { Button } from '../button/Button';\nimport { Dialog } from '../dialog/Dialog';\nimport { Attachment, ContactField, Ticket, User } from '../interfaces';\nimport ColorHash from 'color-hash';\n\nexport const DEFAULT_MEDIA_ENDPOINT = '/api/v2/media.json';\n\nexport const colorHash = new ColorHash();\n\nexport type Asset = KeyedAsset & Ticket & ContactField;\n\nexport const DATE_FORMAT =\n /(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z))|(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d([+-][0-2]\\d:[0-5]\\d|Z))|(\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d([+-][0-2]\\d:[0-5]\\d|Z))/;\n\ninterface KeyedAsset {\n key?: string;\n}\n\ninterface AssetPage {\n assets: Asset[];\n next: string;\n}\n\nexport interface ResultsPage {\n results: any[];\n next: string;\n}\n\nexport enum Color {\n BLUE = 'color:#5078b5;',\n GREEN = 'color:#62bd6a;',\n RED = 'color:#e36049;',\n PURPLE = 'color:#a626a4;',\n}\n\nexport const log = (message: string | object, styling = '', details = []) => {\n if (styling === '') {\n console.log(message);\n return;\n }\n\n if (typeof message === 'object') {\n console.log('%c' + JSON.stringify(message, null, 2), styling);\n return;\n }\n console.log('%c' + message, styling, ...details);\n};\n\n/** Get the value for a named cookie */\nexport const getHTTPCookie = (name: string): string => {\n for (const cookie of document.cookie.split(';')) {\n const idx = cookie.indexOf('=');\n let key = cookie.substr(0, idx);\n let value = cookie.substr(idx + 1);\n\n // no spaces allowed\n key = key.trim();\n value = value.trim();\n\n if (key === name) {\n return value;\n }\n }\n return null;\n};\n\nexport const getHeaders = (headers: any = {}) => {\n const csrf = getHTTPCookie('csrftoken');\n const fetchHeaders: any = csrf ? { 'X-CSRFToken': csrf } : {};\n\n // mark us as ajax\n fetchHeaders['X-Requested-With'] = 'XMLHttpRequest';\n\n Object.keys(headers).forEach(key => {\n fetchHeaders[key] = headers[key];\n });\n\n return fetchHeaders;\n};\n\nexport const getUrl = (\n url: string,\n controller: AbortController = null,\n headers: { [key: string]: string } = {}\n): Promise => {\n return new Promise((resolve, reject) => {\n const options = {\n method: 'GET',\n headers: getHeaders(headers),\n };\n\n if (controller) {\n options['signal'] = controller.signal;\n }\n\n fetch(url, options)\n .then(response => {\n response.text().then((body: string) => {\n let json = {};\n try {\n json = JSON.parse(body);\n // eslint-disable-next-line no-empty\n } catch (err) {}\n resolve({\n controller,\n body,\n json,\n url: response.url,\n headers: response.headers,\n status: response.status,\n });\n });\n })\n .catch(error => {\n reject(error);\n });\n });\n};\n\nexport type ClassMap = {\n [className: string]: boolean;\n};\n\nexport const getClasses = (map: ClassMap): string => {\n const classNames: string[] = [];\n Object.keys(map).forEach((className: string) => {\n if (map[className]) {\n classNames.push(className);\n }\n });\n\n let result = classNames.join(' ');\n if (result.trim().length > 0) {\n result = ' ' + result;\n }\n return result.trim();\n};\n\nexport const fetchResultsPage = (\n url: string,\n controller: AbortController = null\n): Promise => {\n return new Promise((resolve, reject) => {\n getUrl(url, controller)\n .then((response: WebResponse) => {\n resolve({\n results: response.json.results,\n next: response.json.next,\n });\n })\n .catch(error => reject(error));\n });\n};\n\nexport const fetchResults = async (url: string): Promise => {\n if (!url) {\n return new Promise(resolve => resolve([]));\n }\n\n let results: any[] = [];\n let pageUrl = url;\n while (pageUrl) {\n const resultsPage = await fetchResultsPage(pageUrl);\n if (resultsPage.results) {\n results = results.concat(resultsPage.results);\n }\n pageUrl = resultsPage.next;\n }\n return results;\n};\n\nexport const getAssetPage = (url: string): Promise => {\n return new Promise((resolve, reject) => {\n getUrl(url)\n .then((response: WebResponse) => {\n if (response.status >= 200 && response.status < 300) {\n resolve({\n assets: response.json.results,\n next: response.json.next,\n });\n } else {\n reject(response);\n }\n })\n .catch(error => reject(error));\n });\n};\n\nexport const getAssets = async (url: string): Promise => {\n if (!url) {\n return new Promise(resolve => resolve([]));\n }\n\n let assets: Asset[] = [];\n let pageUrl = url;\n while (pageUrl) {\n const assetPage = await getAssetPage(pageUrl);\n if (assetPage.assets) {\n assets = assets.concat(assetPage.assets);\n pageUrl = assetPage.next;\n } else {\n pageUrl = null;\n }\n }\n return assets;\n};\n\nexport interface WebResponse {\n json: any;\n body?: string;\n status: number;\n url?: string;\n headers: Headers;\n controller?: AbortController;\n redirected?: boolean;\n}\n\nexport const postUrl = (\n url: string,\n payload: any,\n headers: any = {},\n contentType = null\n): Promise => {\n const fetchHeaders = getHeaders(headers);\n\n if (contentType) {\n fetchHeaders['Content-Type'] = contentType;\n }\n\n const options = {\n method: 'POST',\n headers: fetchHeaders,\n body: payload,\n };\n\n return new Promise((resolve, reject) => {\n fetch(url, options)\n .then(async response => {\n if (response.status >= 500) {\n reject(response);\n return;\n }\n\n response.text().then((body: string) => {\n let json = {};\n try {\n json = JSON.parse(body);\n // eslint-disable-next-line no-empty\n } catch (err) {}\n resolve({\n body,\n json,\n headers: response.headers,\n status: response.status,\n redirected: response.redirected,\n url: response.url,\n });\n });\n })\n .catch(error => {\n reject(error);\n });\n });\n};\n\nexport const postJSON = (url: string, payload: any): Promise => {\n return postUrl(url, JSON.stringify(payload), false, 'application/json');\n};\n\nexport const postFormData = (\n url: string,\n formData: FormData\n): Promise => {\n return new Promise((resolve, reject) => {\n postUrl(url, formData, true)\n .then(response => {\n if (response.status >= 200 && response.status < 400) {\n resolve(response);\n } else {\n if (url === DEFAULT_MEDIA_ENDPOINT) {\n reject(response);\n } else {\n reject('Server failure');\n }\n }\n })\n .catch(err => {\n console.error(err);\n reject(err);\n });\n });\n};\n\nexport const postForm = (\n url: string,\n payload: any | FormData\n): Promise => {\n const formData = new FormData();\n Object.keys(payload).forEach((key: string) => {\n formData.append(key, payload[key]);\n });\n return postFormData(url, formData);\n};\n\n/**\n */\nexport const renderIf =\n (predicate: boolean | any) =>\n (then: () => TemplateResult, otherwise?: () => TemplateResult) => {\n return predicate ? then() : otherwise ? otherwise() : html``;\n };\n\nexport const hexToRgb = (hex: string): { r: number; g: number; b: number } => {\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n return result\n ? {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n }\n : null;\n};\n\nexport const getElementOffset = (\n ele: HTMLElement\n): {\n top: number;\n left: number;\n bottom: number;\n right: number;\n width: number;\n height: number;\n} => {\n const rect = ele.getBoundingClientRect();\n const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;\n const scrollTop = window.pageYOffset || document.documentElement.scrollTop;\n return {\n top: rect.top + scrollTop,\n left: rect.left + scrollLeft,\n bottom: rect.top + rect.height,\n right: rect.left + rect.width,\n width: rect.width,\n height: rect.height,\n };\n};\n\nexport const plural = (count: number, singular: string, plural: string) => {\n return count === 1 ? singular : plural;\n};\n\nexport const range = (start: number, end: number) =>\n Array.from({ length: end - start }, (v: number, k: number) => k + start);\n\nexport const fillTemplate = (\n template: string,\n replacements: { [key: string]: string | number }\n): TemplateResult => {\n for (const key in replacements) {\n const className = key + '-replaced';\n replacements[\n key\n ] = `${replacements[key]}`;\n }\n\n const templateDiv = document.createElement('div');\n // templateDiv.innerHTML = dynamicTemplate(template, replacements);\n return html` ${templateDiv} `;\n};\n\n/*!\n * Serialize all form data into a query string\n * (c) 2018 Chris Ferdinandi, MIT License, https://gomakethings.com\n * @param {Node} form The form to serialize\n * @return {String} The serialized form data\n */\nexport const serialize = function (form: any) {\n // Setup our serialized data\n const serialized = [];\n\n // Loop through each field in the form\n for (let i = 0; i < form.elements.length; i++) {\n const field = form.elements[i];\n\n // Don't serialize fields without a name, submits, buttons, file and reset inputs, and disabled fields\n if (\n !field.name ||\n field.disabled ||\n field.type === 'file' ||\n field.type === 'reset' ||\n field.type === 'submit' ||\n field.type === 'button'\n )\n continue;\n\n // If a multi-select, get all selections\n if (field.type === 'select-multiple') {\n for (let n = 0; n < field.options.length; n++) {\n if (!field.options[n].selected) continue;\n if (field.options[n].value) {\n serialized.push(\n encodeURIComponent(field.name) +\n '=' +\n encodeURIComponent(field.options[n].value)\n );\n }\n }\n }\n\n // Convert field data to a query string\n else if (\n (field.type !== 'checkbox' && field.type !== 'radio') ||\n field.checked\n ) {\n let value = field.value;\n if (!value && field.checked) {\n value = '1';\n }\n\n if (value) {\n serialized.push(\n encodeURIComponent(field.name) + '=' + encodeURIComponent(value)\n );\n }\n }\n }\n return serialized.join('&');\n};\n\nexport const getScrollParent = (node: any): any => {\n const parent = node.parentNode || node.host;\n if (parent) {\n const isElement = parent instanceof HTMLElement;\n const overflowY = isElement && window.getComputedStyle(parent).overflowY;\n const isScrollable =\n overflowY &&\n !(overflowY.includes('hidden') || overflowY.includes('visible'));\n\n if (!parent) {\n return null;\n } else if (isScrollable && parent.scrollHeight >= parent.clientHeight) {\n return parent;\n }\n\n return getScrollParent(parent);\n }\n return null;\n};\n\nexport const isElementVisible = (el: any, holder: any) => {\n holder = holder || document.body;\n const { top, bottom } = el.getBoundingClientRect();\n const holderRect = holder.getBoundingClientRect();\n\n return top <= holderRect.top\n ? bottom > holderRect.top\n : bottom < holderRect.bottom;\n};\n\nconst HOUR = 3600;\nconst DAY = HOUR * 24;\nconst MONTH = DAY * 30;\n\nexport class Stubbable {\n public getCurrentDate() {\n return new Date();\n }\n}\n\nexport const stubbable = new Stubbable();\n\nexport const timeSince = (\n date: Date,\n options: { compareDate?: Date; hideRecentText?: boolean; suffix?: string } = {\n suffix: '',\n }\n) => {\n const { compareDate, hideRecentText, suffix } = options;\n const now = compareDate || stubbable.getCurrentDate();\n const secondsPast = Math.floor((now.getTime() - date.getTime()) / 1000);\n\n if (secondsPast < 60) {\n if (compareDate) {\n return secondsPast + 's' + suffix;\n }\n\n if (!hideRecentText && suffix) {\n return suffix;\n }\n return 'just now';\n }\n\n if (secondsPast < HOUR) {\n return Math.round(secondsPast / 60) + 'm' + suffix;\n }\n\n if (secondsPast <= DAY) {\n return Math.round(secondsPast / HOUR) + 'h' + suffix;\n }\n\n if (secondsPast <= MONTH) {\n return Math.round(secondsPast / DAY) + 'd' + suffix;\n }\n\n if (secondsPast < MONTH * 6) {\n return Math.round(secondsPast / MONTH) + 'mth' + suffix;\n } else {\n const day = date.getDate();\n const month = date\n .toDateString()\n .match(/ [a-zA-Z]*/)[0]\n .replace(' ', '');\n const year =\n date.getFullYear() == now.getFullYear() ? '' : ' ' + date.getFullYear();\n return day + ' ' + month + year;\n }\n};\n\nexport const isDate = (value: string): boolean => {\n if (toString.call(value) === '[object Date]') {\n return true;\n }\n if (typeof value.replace === 'function') {\n value.replace(/^\\s+|\\s+$/gm, '');\n }\n\n // value = value.split(\"+\")[0];\n return DATE_FORMAT.test(value);\n};\n\nexport const debounce = (fn: any, millis: number, immediate = false) => {\n let timeout: any;\n return function (...args: any) {\n const context = this;\n const later = function () {\n timeout = null;\n if (!immediate) {\n fn.apply(context, args);\n }\n };\n const callNow = immediate && !timeout;\n clearTimeout(timeout);\n timeout = setTimeout(later, millis);\n if (callNow) {\n fn.apply(context, args);\n }\n };\n};\n\nexport const throttle = (fn: any, millis: number) => {\n let ready = true;\n return function (...args: any) {\n const context = this;\n if (!ready) {\n return;\n }\n\n ready = false;\n fn.apply(context, args);\n setTimeout(() => {\n ready = true;\n }, millis);\n };\n};\n\nexport interface NamedObject {\n name: string;\n}\n\nexport const truncate = (input: string, max: number): string => {\n if (input.length > max) {\n return input.substring(0, max) + '...';\n }\n\n return input;\n};\n\nexport const oxford = (items: any[], joiner = 'and'): any => {\n if (items.length === 1) {\n return items[0];\n }\n\n if (items.length === 2) {\n // TemplateResults get a different treatment\n if (typeof items[0] === 'object') {\n return html`${items[0]} ${joiner} ${items[1]}`;\n }\n return items.join(' ' + joiner + ' ');\n }\n\n // TemplateResults get a different treatment\n if (typeof items[0] === 'object') {\n return items.map((tr: TemplateResult, idx: number) => {\n if (idx < items.length - 1) {\n return html`${tr}, `;\n }\n return html`${joiner} ${tr}`;\n });\n }\n\n return items.join(', ') + joiner + items[items.length - 1];\n};\n\nexport const oxfordFn = (\n items: any[],\n fn: (item: any) => any,\n joiner = 'and'\n): any => {\n return oxford(items.map(fn), joiner);\n};\n\nexport const oxfordNamed = (items: NamedObject[], joiner = 'and'): any => {\n return oxfordFn(items, (value: any) => value.name, joiner);\n};\n\nexport const getDialog = (button: Button): Dialog => {\n return (button.getRootNode() as ShadowRoot).host as Dialog;\n};\n\nexport const setCookie = (name: string, value: any, path = undefined) => {\n if (!path) {\n // default path is the first word in the url\n const url = document.location.pathname;\n path = url.substring(0, url.indexOf('/', 1));\n }\n const now = new Date();\n now.setTime(now.getTime() + 60 * 1000 * 60 * 24 * 30);\n document.cookie = `${name}=${value};expires=${now.toUTCString()};path=${path}`;\n};\n\nexport const getCookie = (name: string) => {\n let cookieValue = null;\n if (document.cookie && document.cookie != '') {\n const cookies = document.cookie.split(';');\n for (let i = 0; i < cookies.length; i++) {\n const cookie = cookies[i].trim();\n // Does this cookie string begin with the name we want?\n if (cookie.substring(0, name.length + 1) == name + '=') {\n cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n break;\n }\n }\n }\n return cookieValue;\n};\n\nexport const getCookieBoolean = (name: string) => {\n return (getCookie(name) || '') === 'true';\n};\n\nexport enum COOKIE_KEYS {\n SETTINGS = 'settings',\n MENU_COLLAPSED = 'menu-collapsed',\n TICKET_SHOW_DETAILS = 'tickets.show-details',\n}\n\nexport const capitalize = ([first, ...rest], locale = navigator.language) =>\n first === undefined ? '' : first.toLocaleUpperCase(locale) + rest.join('');\n\nexport const formatFileType = (type: string): string => {\n return type.split('/')[1];\n};\nexport const formatFileSize = (bytes: number, decimalPoint: number): string => {\n if (bytes == 0) return '0 KB';\n const k = 1024,\n dm = decimalPoint || 2,\n sizes = ['B', 'KB', 'MB', 'GB'], //, 'TB', 'PB', 'EB', 'ZB', 'YB'],\n i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];\n};\n\nexport const isImageAttachment = (attachment: Attachment) => {\n if (attachment) {\n return attachment.content_type.split('/')[0] === 'image';\n }\n return false;\n};\n\nexport const stopEvent = (event: Event) => {\n if (event) {\n event.stopPropagation();\n event.preventDefault();\n }\n};\n\nexport const getFullName = (user: User) => {\n if (user.first_name && user.last_name) {\n return `${user.first_name} ${user.last_name}`;\n }\n\n return user.email;\n};\n\n/**\n * Extracts 2-letter initials from text like a workspace or user name\n * @param text the input text\n * @returns the initials\n */\nexport const extractInitials = (text: string) => {\n text = text.trim();\n\n // split into words, first allowing hypens inside words,\n // then splitting by hypen to try to get more than one word\n let words =\n text.match(/(([\\p{L}\\p{N}]+-[\\p{L}\\p{N}]+)|([\\p{L}\\p{N}]+))/gu) || [];\n if (words.length == 1) {\n words = text.match(/[\\p{L}\\p{N}]+/gu);\n }\n\n // for the case of no words use ? and for only one word take first 2 characters\n if (words.length == 0) {\n return '?';\n } else if (words.length == 1) {\n return words[0].substring(0, 2).toUpperCase();\n }\n\n // use initial letters of words with preference to first word and capital letters\n const firstLetters = words.map(w => w.substring(0, 1));\n const firstCapitals = firstLetters.filter(\n (l, index) => l == l.toUpperCase() || index == 0\n );\n if (firstCapitals.length >= 2) {\n return (firstCapitals[0] + firstCapitals[1]).toUpperCase();\n } else {\n return (firstLetters[0] + firstLetters[1]).toUpperCase();\n }\n};\n\nexport const hslToHex = (h, s, l) => {\n l /= 100;\n const a = (s * Math.min(l, 1 - l)) / 100;\n const f = n => {\n const k = (n + h / 30) % 12;\n const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n return Math.round(255 * color)\n .toString(16)\n .padStart(2, '0'); // convert to Hex and prefix \"0\" if needed\n };\n return `#${f(0)}${f(8)}${f(4)}`;\n};\n\nexport const renderAvatar = (input: {\n name?: string;\n user?: User;\n icon?: string;\n position?: string;\n tip?: boolean;\n scale?: number;\n}) => {\n if (!input.position) {\n input.position = 'right';\n }\n\n let text = input.name;\n if (input.user && input.user.first_name && input.user.last_name) {\n text = `${input.user.first_name} ${input.user.last_name}`;\n }\n\n if (!text) {\n return null;\n }\n\n let initials = '';\n let color = colorHash.hex(text);\n // just a url\n if (input.user && input.user.avatar) {\n color = `url('${input.user.avatar}') center / contain no-repeat`;\n } else if (text) {\n initials = extractInitials(text);\n }\n\n const avatar = html`\n \n \n ${initials\n ? html` \n
${initials}
\n
`\n : null}\n
\n
\n `;\n return input.tip\n ? html`\n \n ${avatar}\n \n `\n : avatar;\n};\n","import { LitElement, PropertyValueMap } from 'lit';\nimport { CustomEventType } from './interfaces';\nimport { Color, log } from './utils';\n\nconst showUpdates = (\n ele: HTMLElement,\n changes: Map,\n firstUpdated = false\n) => {\n if (ele['DEBUG_UPDATES'] || ele['DEBUG']) {\n if (changes.size > 0) {\n const fromto = {};\n for (const key of changes.keys()) {\n fromto[key] = [changes[key], ele[key]];\n }\n\n log(ele.tagName, Color.PURPLE, [\n firstUpdated ? '' : '',\n fromto,\n ]);\n }\n }\n};\n\nconst showEvent = (ele: HTMLElement, type: string, details = undefined) => {\n if (ele['DEBUG_EVENTS'] || ele['DEBUG']) {\n if (details !== undefined) {\n log(ele.tagName, Color.GREEN, [type, details]);\n } else {\n log(ele.tagName, Color.GREEN, [type]);\n }\n }\n};\n\nexport interface EventHandler {\n event: string;\n method: EventListener;\n isDocument?: boolean;\n isWindow?: boolean;\n}\n\nexport class RapidElement extends LitElement {\n DEBUG = false;\n DEBUG_UPDATES = false;\n DEBUG_EVENTS = false;\n\n private eles: { [selector: string]: HTMLDivElement } = {};\n public getEventHandlers(): EventHandler[] {\n return [];\n }\n\n connectedCallback() {\n super.connectedCallback();\n\n for (const handler of this.getEventHandlers()) {\n if (handler.isDocument) {\n document.addEventListener(handler.event, handler.method.bind(this));\n } else if (handler.isWindow) {\n window.addEventListener(handler.event, handler.method.bind(this));\n } else {\n this.addEventListener(handler.event, handler.method.bind(this));\n }\n }\n }\n\n disconnectedCallback() {\n for (const handler of this.getEventHandlers()) {\n if (handler.isDocument) {\n document.removeEventListener(handler.event, handler.method);\n } else if (handler.isWindow) {\n window.removeEventListener(handler.event, handler.method);\n } else {\n this.removeEventListener(handler.event, handler.method);\n }\n }\n super.disconnectedCallback();\n }\n\n protected firstUpdated(\n changes: PropertyValueMap | Map\n ): void {\n super.firstUpdated(changes);\n showUpdates(this, changes, true);\n }\n\n protected updated(\n changes: PropertyValueMap | Map\n ): void {\n super.updated(changes);\n showUpdates(this, changes, false);\n }\n\n public fireEvent(type: string): any {\n showEvent(this, type);\n\n return this.dispatchEvent(\n new Event(type, {\n bubbles: true,\n composed: true,\n })\n );\n }\n\n swallowEvent(event: Event) {\n event.stopPropagation();\n event.preventDefault();\n }\n\n public fireCustomEvent(type: CustomEventType, detail: any = {}): any {\n if (this['DEBUG_EVENTS']) {\n showEvent(this, type, detail);\n }\n\n const event = new CustomEvent(type, {\n detail,\n bubbles: true,\n composed: true,\n });\n\n return this.dispatchEvent(event);\n }\n\n public dispatchEvent(event: any): any {\n super.dispatchEvent(event);\n const ele = event.target;\n if (ele) {\n // lookup events with - prefix and try to invoke them\n const eventFire = (ele as any)['-' + event.type];\n if (eventFire) {\n return eventFire(event);\n } else {\n const func = new Function(\n 'event',\n `\n with(document) {\n with(this) {\n let handler = ${ele.getAttribute('-' + event.type)};\n if(typeof handler === 'function') { \n handler(event);\n }\n }\n }\n `\n );\n return func.call(ele, event);\n }\n }\n }\n\n public closestElement(selector: string, base: Element = this) {\n function __closestFrom(el: Element | Window | Document): Element {\n if (!el || el === document || el === window) return null;\n if ((el as any).assignedSlot) el = (el as any).assignedSlot;\n const found = (el as Element).closest(selector);\n return found\n ? found\n : __closestFrom(((el as Element).getRootNode() as ShadowRoot).host);\n }\n return __closestFrom(base);\n }\n\n public getDiv(selector: string) {\n let ele = this.eles[selector];\n if (ele) {\n return ele;\n }\n\n ele = this.shadowRoot.querySelector(selector);\n if (ele) {\n this.eles[selector] = ele;\n }\n return ele;\n }\n\n public stopEvent(event: Event) {\n if (event) {\n event.stopPropagation();\n event.preventDefault();\n }\n }\n\n public isMobile() {\n const win = window as any;\n if (win.isMobile) {\n return win.isMobile();\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=t=>(e,o)=>{void 0!==o?o.addInitializer((()=>{customElements.define(t,e)})):customElements.define(t,e)};export{t as customElement};\n//# sourceMappingURL=custom-element.js.map\n","import{defaultConverter as t,notEqual as e}from\"../reactive-element.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const o={attribute:!0,type:String,converter:t,reflect:!1,hasChanged:e},r=(t=o,e,r)=>{const{kind:n,metadata:i}=r;let s=globalThis.litPropertyMetadata.get(i);if(void 0===s&&globalThis.litPropertyMetadata.set(i,s=new Map),s.set(r.name,t),\"accessor\"===n){const{name:o}=r;return{set(r){const n=e.get.call(this);e.set.call(this,r),this.requestUpdate(o,n,t)},init(e){return void 0!==e&&this.P(o,void 0,t),e}}}if(\"setter\"===n){const{name:o}=r;return function(r){const n=this[o];e.call(this,r),this.requestUpdate(o,n,t)}}throw Error(\"Unsupported decorator location: \"+n)};function n(t){return(e,o)=>\"object\"==typeof o?r(t,e,o):((t,e,o)=>{const r=e.hasOwnProperty(o);return e.constructor.createProperty(o,r?{...t,wrapped:!0}:t),r?Object.getOwnPropertyDescriptor(e,o):void 0})(t,e,o)}export{n as property,r as standardProperty};\n//# sourceMappingURL=property.js.map\n","import { RapidElement } from './RapidElement';\nimport { property } from 'lit/decorators.js';\n\n/**\n * FormElement is a component that appends a hidden input (outside of\n * its own shadow) with its value to be included in forms.\n */\nexport class FormElement extends RapidElement {\n @property({ type: String })\n name = '';\n\n @property({ type: String, attribute: 'help_text' })\n helpText: string;\n\n @property({ type: Boolean, attribute: 'help_always' })\n helpAlways: boolean;\n\n @property({ type: Boolean, attribute: 'widget_only' })\n widgetOnly: boolean;\n\n @property({ type: Boolean, attribute: 'hide_label' })\n hideLabel: boolean;\n\n @property({ type: String })\n label: string;\n\n @property({ type: Array })\n errors: string[];\n\n @property({ type: String })\n value = null;\n\n @property({ attribute: false })\n inputRoot: HTMLElement = this;\n\n @property({ type: Boolean })\n disabled = false;\n static formAssociated = true;\n\n protected internals: ElementInternals;\n\n constructor() {\n super();\n this.internals = this.attachInternals();\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n if (changedProperties.has('value')) {\n this.internals.setFormValue(this.value);\n }\n }\n\n get form() {\n return this.internals.form;\n }\n\n public setValue(value: any) {\n this.value = this.serializeValue(value);\n }\n\n public getDeserializedValue(): any {\n return JSON.parse(this.value);\n }\n\n public serializeValue(value: any): string {\n return JSON.stringify(value);\n }\n}\n","// for cache busting we dynamically generate a fingerprint, use yarn svg to update\nexport const SVG_FINGERPRINT = 'e5bcaf1a10896e9b870da4b40474d67b';\n\n// only icons below are included in the sprite sheet\nexport enum Icon {\n alert_warning = 'alert-square',\n account = 'user-01',\n active = 'play',\n add = 'plus',\n add_note = 'file-02',\n airtime = 'bank-note-01',\n analytics = 'bar-chart-01',\n archive = 'archive',\n arrow_up = 'chevron-up',\n arrow_down = 'chevron-down',\n arrow_left = 'chevron-left',\n arrow_right = 'chevron-right',\n attachment = 'paperclip',\n attachment_audio = 'volume-min',\n attachment_document = 'file-06',\n attachment_image = 'image-01',\n attachment_location = 'marker-pin-01',\n attachment_video = 'video-recorder',\n branding = 'brush-02',\n branding_hostname = 'server-05',\n branding_notifications = 'mail-01',\n branding_styling = 'palette',\n branding_raw = 'pencil-01',\n broadcast = 'announcement-01',\n call = 'phone-call-01',\n call_missed = 'phone-call-02',\n campaign = 'clock-refresh',\n campaign_active = 'play',\n campaign_archived = 'archive',\n campaigns = 'clock-refresh',\n channel = 'zap',\n children = 'git-branch-01',\n check = 'check',\n checkbox = 'square',\n checkbox_checked = 'check-square',\n checkbox_partial = 'stop-square',\n classifier_wit = 'classifier-wit',\n classifier_luis = 'classifier-luis',\n classifier_bothub = 'classifier-bothub',\n close = 'x',\n compose = 'send-01',\n contact = 'user-01',\n contact_archived = 'archive',\n contact_blocked = 'message-x-square',\n contact_export = 'download-cloud-01',\n contact_import = 'upload-cloud-01',\n contact_stopped = 'slash-octagon',\n contact_updated = 'user-edit',\n contacts = 'user-01',\n copy = 'copy-04',\n dashboard = 'pie-chart-01',\n delete = 'trash-03',\n delete_small = 'x',\n down = 'chevron-down',\n download = 'download-01',\n edit = 'edit-03',\n email = 'mail-01',\n error = 'alert-circle',\n event = 'zap',\n expressions = 'at-sign',\n fields = 'user-edit',\n filter = 'filter-funnel-01',\n flow = 'flow',\n flow_background = 'layers-two-01',\n flow_interrupted = 'x-close',\n flow_ivr = 'phone',\n flow_message = 'message-square-02',\n flow_surveyor = 'tablet-01',\n flow_user = 'hard-drive',\n flows = 'flow',\n global = 'at-sign',\n grid = 'dots-grid',\n group = 'users-01',\n group_exclude = 'users-x',\n group_include = 'users-check',\n group_smart = 'atom-01',\n help = 'help-circle',\n hide = 'eye-off',\n home = 'settings-02',\n image = 'image-01',\n inbox = 'inbox-01',\n incidents = 'alert-square',\n incoming_call = 'phone-incoming-01',\n integrations = 'layers-three-01',\n info = 'user-square',\n issue = 'alert-square',\n label = 'tag-01',\n language = 'translate-01',\n link = 'link-external-01',\n location = 'marker-pin-01',\n log = 'file-02',\n logout = 'log-out-04',\n menu = 'menu-01',\n menu_collapse = 'chevron-left-double',\n message = 'message-square-02',\n message_export = 'download-cloud-01',\n messages = 'message-square-02',\n missing = 'maximize-02',\n missed_call = 'phone-x',\n new = 'plus',\n next_schedule = 'alarm-clock',\n notification = 'bell-01',\n number = 'hash-01',\n optin_requested = 'message-notification-circle',\n optin = 'message-check-circle',\n optout = 'message-x-circle',\n org_active = 'credit-card-02',\n org_anonymous = 'glasses-01',\n org_bulk = 'credit-card-plus',\n org_flagged = 'flag-01',\n org_new = 'stars-02',\n org_suspended = 'slash-circle-01',\n org_verified = 'check-verified-02',\n overview = 'pie-chart-01',\n prometheus = 'prometheus',\n progress_spinner = 'refresh-cw-04',\n featured = 'star-01',\n quick_replies = 'dotpoints-01',\n recording = 'microphone-01',\n resend = 'refresh-cw-05',\n reset = 'flip-backward',\n resthooks = 'share-07',\n restore = 'play',\n results_export = 'download-cloud-01',\n retry = 'refresh-cw-05',\n revisions = 'clock-rewind',\n rocketchat = 'rocketchat',\n runs = 'rows-03',\n schedule = 'calendar',\n search = 'search-refraction',\n select_open = 'chevron-down',\n select_clear = 'x',\n send = 'send-03',\n service = 'magic-wand-01',\n service_end = 'log-out-04',\n settings = 'settings-02',\n show = 'eye',\n simulator = 'phone-02',\n sort = 'chevron-selector-vertical',\n sort_down = 'sort-arrow-down',\n sort_up = 'sort-arrow-up',\n staff = 'hard-drive',\n submit = 'check',\n success = 'check',\n template_approved = 'check-circle',\n template_pending = 'hourglass-01',\n template_rejected = 'alert-circle',\n template_unsupported = 'alert-circle',\n tickets = 'agent',\n tickets_all = 'archive',\n tickets_closed = 'check',\n tickets_mine = 'coffee',\n tickets_open = 'inbox-01',\n tickets_export = 'download-cloud-01',\n tickets_unassigned = 'inbox-01',\n topic = 'message-text-circle-02',\n two_factor_enabled = 'shield-02',\n two_factor_disabled = 'shield-01',\n trigger = 'signal-01',\n trigger_active = 'play',\n trigger_archived = 'archive',\n trigger_new = 'plus',\n trigger_keyword = 'message-check-square',\n trigger_catch_all = 'message-question-square',\n trigger_inbound_call = 'phone-incoming-01',\n trigger_missed_call = 'phone-hang-up',\n trigger_schedule = 'calendar',\n trigger_new_conversation = 'message-chat-square',\n trigger_referral = 'user-right-01',\n trigger_closed_ticket = 'agent',\n trigger_opt_in = 'message-check-circle',\n trigger_opt_out = 'message-x-circle',\n triggers = 'signal-01',\n updated = 'edit-02',\n up = 'chevron-up',\n upload = 'upload-cloud-01',\n upload_image = 'camera-01',\n usages = 'link-04',\n user = 'users-01',\n users = 'users-01',\n user_beta = 'shield-zap',\n webhook = 'link-external-01',\n wit = 'wit',\n workspace = 'folder',\n zapier = 'zapier',\n zendesk = 'zendesk',\n\n // channel types\n channel_a = 'channel-android',\n channel_ac = 'zap', // TODO https://www.arabiacell.com/\n channel_at = 'zap', // TODO https://africastalking.com/\n channel_bs = 'zap', // TODO https://burstsms.com/\n channel_bw = 'zap', // TODO https://www.bandwidth.com/\n channel_cs = 'zap', // TODO https://www.clicksend.com/\n channel_ct = 'channel-clickatell',\n channel_d3 = 'channel-whatsapp',\n channel_d3c = 'channel-whatsapp',\n channel_da = 'zap', // TODO https://dartmedia.co.id/\n channel_ds = 'channel-discord',\n channel_ex = 'zap',\n channel_fb = 'channel-facebook',\n channel_fba = 'channel-facebook',\n channel_fc = 'channel-freshchat',\n channel_fcm = 'channel-firebase',\n channel_hm = 'zap', // TODO https://hormuud.com/\n channel_ib = 'zap', // TODO https://www.infobip.com/\n channel_ig = 'channel-instagram',\n channel_jc = 'channel-jiochat',\n channel_kn = 'channel-kannel',\n channel_kwa = 'channel-whatsapp',\n channel_ln = 'channel-line',\n channel_mt = 'channel-mtarget',\n channel_mtn = 'zap', // TODO https://mtn.com/\n channel_nx = 'channel-vonage',\n channel_pl = 'channel-plivo',\n channel_rc = 'channel-rocketchat',\n channel_sl = 'channel-slack',\n channel_sq = 'zap', // TODO https://shaqodoon.org/\n channel_st = 'zap', // TODO https://bulk.startmobile.ua\n channel_sw = 'channel-signalwire',\n channel_t = 'channel-twilio',\n channel_tg = 'channel-telegram',\n channel_tms = 'channel-twilio',\n channel_tq = 'channel-thinq',\n channel_tw = 'zap', // TODO https://www.somleng.org/\n channel_twa = 'channel-whatsapp',\n channel_twc = 'zap', // TODO\n channel_twt = 'channel-twitter',\n channel_vk = 'channel-vk',\n channel_vp = 'channel-viber',\n channel_wa = 'channel-whatsapp',\n channel_wac = 'channel-whatsapp',\n channel_wc = 'channel-wechat',\n channel_yo = 'zap', // TODO https://www.yo.co.ug/\n channel_zvw = 'channel-whatsapp',\n\n bothub = 'bothub',\n chatbase = 'chatbase',\n dtone = 'dtone',\n\n // demo\n default = 'list',\n datepicker = 'calendar',\n slider = 'sliders-02',\n select = 'browser',\n input = 'edit-05',\n}\n","import { TemplateResult, html, css } from 'lit';\nimport { FormElement } from '../FormElement';\nimport { property } from 'lit/decorators.js';\nimport { Icon } from '../vectoricon';\n\nexport class Checkbox extends FormElement {\n static get styles() {\n return css`\n :host {\n color: var(--color-text);\n display: inline-block;\n }\n\n :host([label]) {\n width: 100%;\n }\n\n .wrapper.label {\n padding: var(--checkbox-padding, 10px);\n border-radius: var(--curvature);\n }\n\n .wrapper.label:hover {\n background: #f9f9f9;\n }\n\n temba-field {\n --help-text-margin-left: 24px;\n cursor: pointer;\n }\n\n .checkbox-container {\n cursor: pointer;\n display: flex;\n user-select: none;\n -webkit-user-select: none;\n }\n\n .checkbox-label {\n font-family: var(--font-family);\n padding: 0px;\n margin-left: 8px;\n font-weight: 300;\n font-size: 14px;\n line-height: 19px;\n flex-grow: 1;\n }\n\n .far {\n height: 16px;\n margin-top: 1px;\n }\n\n .disabled {\n cursor: not-allowed;\n --icon-color: #ccc;\n }\n `;\n }\n\n @property({ type: String })\n name = '';\n\n @property({ type: Boolean })\n checked: boolean;\n\n @property({ type: Boolean })\n partial: boolean;\n\n @property({ type: Boolean })\n disabled = false;\n\n @property({ type: Number })\n size = 1.2;\n\n @property({ type: String })\n animateChange = 'pulse';\n\n public updated(changes: Map) {\n super.updated(changes);\n if (changes.has('checked') || changes.has('value')) {\n if (this.checked || this.partial) {\n this.internals.setFormValue(this.value || '1');\n } else {\n this.internals.setFormValue(undefined);\n }\n this.fireEvent('change');\n }\n }\n\n public serializeValue(value: any): string {\n return value;\n }\n\n private handleClick(): void {\n if (!this.disabled) {\n this.checked = !this.checked;\n }\n }\n\n public click(): void {\n this.handleClick();\n super.click();\n }\n\n public render(): TemplateResult {\n const icon = html``;\n\n this.label = this.label ? this.label.trim() : null;\n\n return html`\n
\n \n
\n ${icon}\n ${this.label\n ? html`
${this.label}
`\n : null}\n
\n \n
\n `;\n }\n}\n","import{nothing as t}from\"../lit-html.js\";\n/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const o=o=>o??t;export{o as ifDefined};\n//# sourceMappingURL=if-defined.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},e=t=>(...e)=>({_$litDirective$:t,values:e});class i{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}}export{i as Directive,t as PartType,e as directive};\n//# sourceMappingURL=directive.js.map\n","import{noChange as t}from\"../lit-html.js\";import{directive as e,Directive as r,PartType as s}from\"../directive.js\";\n/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const n=\"important\",i=\" !\"+n,o=e(class extends r{constructor(t){if(super(t),t.type!==s.ATTRIBUTE||\"style\"!==t.name||t.strings?.length>2)throw Error(\"The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.\")}render(t){return Object.keys(t).reduce(((e,r)=>{const s=t[r];return null==s?e:e+`${r=r.includes(\"-\")?r:r.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,\"-$&\").toLowerCase()}:${s};`}),\"\")}update(e,[r]){const{style:s}=e.element;if(void 0===this.ft)return this.ft=new Set(Object.keys(r)),this.render(r);for(const t of this.ft)null==r[t]&&(this.ft.delete(t),t.includes(\"-\")?s.removeProperty(t):s[t]=null);for(const t in r){const e=r[t];if(null!=e){this.ft.add(t);const r=\"string\"==typeof e&&e.endsWith(i);t.includes(\"-\")||r?s.setProperty(t,r?e.slice(0,-11):e,r?n:\"\"):s[t]=e}}return t}});export{o as styleMap};\n//# sourceMappingURL=style-map.js.map\n","import { TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { ifDefined } from 'lit-html/directives/if-defined.js';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { FormElement } from '../FormElement';\nimport { Modax } from '../dialog/Modax';\nimport { sanitize } from './helpers';\nimport { CharCount } from '../charcount/CharCount';\n\nexport enum InputType {\n Text = 'text',\n Password = 'password',\n Number = 'number',\n}\n\nexport class TextInput extends FormElement {\n static get styles() {\n return css`\n .input-container {\n border-radius: var(--curvature-widget);\n cursor: var(--input-cursor);\n background: var(--color-widget-bg);\n border: 1px solid var(--color-widget-border);\n transition: all ease-in-out var(--transition-speed);\n display: flex;\n flex-direction: row;\n align-items: stretch;\n box-shadow: var(--widget-box-shadow);\n caret-color: var(--input-caret);\n }\n\n .clear-icon {\n --icon-color: var(--color-text-dark-secondary);\n cursor: pointer;\n margin: auto;\n padding-right: 10px;\n line-height: 1;\n }\n\n .clear-icon:hover {\n --icon-color: var(--color-text-dark);\n }\n\n .hidden {\n visibility: hidden;\n position: absolute;\n }\n\n .input-container:focus-within {\n border-color: var(--color-focus);\n background: var(--color-widget-bg-focused);\n box-shadow: var(--widget-box-shadow-focused);\n position: relative;\n }\n\n .input-container:hover {\n }\n\n textarea {\n height: var(--textarea-height);\n min-height: var(--textarea-min-height, var(--textarea-height));\n transition: height var(--transition-speed) ease-in-out;\n }\n\n .textinput {\n padding: var(--temba-textinput-padding);\n border: none;\n flex: 1;\n margin: 0;\n background: none;\n background-color: transparent;\n color: var(--color-widget-text);\n font-family: var(--font-family);\n font-size: var(--temba-textinput-font-size);\n line-height: normal;\n cursor: var(--input-cursor);\n resize: none;\n font-weight: 300;\n width: 100%;\n }\n\n .textinput:focus {\n outline: none;\n box-shadow: none;\n cursor: text;\n color: var(--color-widget-text-focused, var(--color-widget-text));\n }\n\n .textinput::placeholder {\n color: var(--color-placeholder);\n font-weight: 300;\n }\n\n .grow-wrap {\n display: flex;\n align-items: stretch;\n width: 100%;\n }\n\n .grow-wrap > div {\n border: 0px solid green;\n width: 100%;\n padding: var(--temba-textinput-padding);\n flex: 1;\n margin: 0;\n background: none;\n color: var(--color-widget-text);\n font-family: var(--font-family);\n font-size: var(--temba-textinput-font-size);\n line-height: normal;\n cursor: text;\n resize: none;\n font-weight: 300;\n width: 100%;\n visibility: hidden;\n word-break: break-word;\n }\n\n .grow-wrap textarea {\n margin-left: -100%;\n }\n\n input[type='number'] {\n appearance: none;\n }\n\n input[type='number']::-webkit-inner-spin-button {\n display: none;\n }\n\n .type-icon {\n color: #e3e3e3;\n }\n `;\n }\n\n @property({ type: Boolean })\n textarea: boolean;\n\n @property({ type: String })\n placeholder = '';\n\n @property({ type: Boolean })\n password: boolean;\n\n @property({ type: Number })\n maxlength: number;\n\n @property({ type: Object })\n inputElement: HTMLInputElement;\n\n @property({ type: Boolean })\n clearable: boolean;\n\n @property({ type: Boolean })\n gsm: boolean;\n\n @property({ type: String })\n counter: string;\n\n // if we are still loading\n @property({ type: Boolean })\n loading = true;\n\n @property({ type: Boolean })\n submitOnEnter = true;\n\n @property()\n onBlur: any;\n\n @property({ type: Boolean })\n autogrow = false;\n\n @property({ type: String })\n type = InputType.Text;\n\n counterElement: CharCount = null;\n cursorStart = -1;\n cursorEnd = -1;\n\n public constructor() {\n super();\n }\n\n public firstUpdated(changes: Map) {\n super.firstUpdated(changes);\n\n this.inputElement = this.shadowRoot.querySelector('.textinput');\n\n if (changes.has('counter')) {\n let root = this.getParentModax() as any;\n if (root) {\n root = root.shadowRoot;\n }\n if (!root) {\n root = document;\n }\n this.counterElement = root.querySelector(this.counter);\n this.counterElement.text = this.value;\n }\n }\n\n public updated(changes: Map) {\n super.updated(changes);\n\n if (changes.has('value')) {\n if (changes.get('value') !== undefined) {\n this.fireEvent('change');\n }\n\n if (this.textarea && this.autogrow) {\n const autogrow = this.shadowRoot.querySelector(\n '.grow-wrap > div'\n ) as HTMLDivElement;\n autogrow.innerText = this.value + String.fromCharCode(10);\n }\n\n if (this.cursorStart > -1 && this.cursorEnd > -1) {\n this.inputElement.setSelectionRange(this.cursorStart, this.cursorEnd);\n this.cursorStart = -1;\n this.cursorEnd = -1;\n }\n }\n }\n\n public getDisplayValue() {\n return this.inputElement.value;\n }\n\n private handleClear(event: any): void {\n event.stopPropagation();\n event.preventDefault();\n this.value = null;\n }\n\n private updateValue(value: string): void {\n const cursorStart = this.inputElement.selectionStart;\n const cursorEnd = this.inputElement.selectionEnd;\n\n const sanitized = this.sanitizeGSM(value);\n\n if (sanitized !== value) {\n this.cursorStart = cursorStart;\n this.cursorEnd = cursorEnd;\n }\n\n this.value = sanitized;\n\n if (this.textarea) {\n this.inputElement.value = this.value;\n }\n\n if (this.counterElement) {\n this.counterElement.text = value;\n }\n }\n\n private sanitizeGSM(text: string): string {\n return this.gsm ? sanitize(text) : text;\n }\n\n private handleChange(update: any): void {\n if (this.disabled) {\n return;\n }\n this.updateValue(update.target.value);\n this.fireEvent('change');\n }\n\n private handleContainerClick(): void {\n if (this.disabled) {\n return;\n }\n if (this.inputElement) {\n this.inputElement.click();\n }\n }\n\n private handleContainerFocus(): void {\n if (this.disabled) {\n return;\n }\n if (this.inputElement) {\n this.inputElement.focus();\n }\n }\n\n private handleInput(update: any): void {\n if (this.disabled) {\n return;\n }\n\n this.updateValue(update.target.value);\n this.fireEvent('input');\n }\n\n /** we just return the value since it should be a string */\n public serializeValue(value: any): string {\n return value;\n }\n\n public getParentModax(): Modax {\n let parent = this as HTMLElement;\n\n while (parent) {\n if (parent.parentElement) {\n parent = parent.parentElement;\n } else {\n parent = (parent as any).getRootNode().host;\n }\n\n if (!parent) {\n return null;\n }\n\n if (parent.tagName == 'TEMBA-MODAX') {\n return parent as Modax;\n }\n }\n }\n\n public getParentForm(): HTMLFormElement {\n let parent = this as HTMLElement;\n\n while (parent) {\n if (parent.parentElement) {\n parent = parent.parentElement;\n } else {\n parent = (parent as any).getRootNode().host;\n }\n\n if (!parent) {\n return null;\n }\n\n if (parent.tagName === 'FORM') {\n return parent as HTMLFormElement;\n }\n }\n }\n\n public click(): void {\n super.click();\n this.handleContainerClick();\n }\n\n public focus(): void {\n super.focus();\n this.handleContainerFocus();\n }\n\n // TODO make this a formelement and have contactsearch set the root\n public render(): TemplateResult {\n const containerStyle = {\n height: `${this.textarea ? '100%' : 'auto'}`,\n };\n\n const clear =\n this.clearable && this.inputElement && this.inputElement.value\n ? html``\n : null;\n\n let input = html`\n {\n if (e.key === 'Enter') {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const input = this;\n\n if (this.submitOnEnter) {\n const parentModax = input.getParentModax();\n const parentForm = !parentModax ? input.getParentForm() : null;\n\n // if we don't have something to submit then bail\n if (!parentModax && !parentForm) {\n return false;\n }\n\n // don't submit disabled forms on enter\n if (parentModax && parentModax.disabled) {\n return false;\n }\n\n input.blur();\n\n // look for a form to submit\n window.setTimeout(function () {\n // first, look for a modax that contains us\n const modax = input.getParentModax();\n if (modax) {\n input.blur();\n\n modax.submit();\n } else {\n // otherwise, just look for a vanilla submit button\n const form = input.getParentForm();\n\n if (form) {\n const submitButton = form.querySelector(\n \"input[type='submit']\"\n ) as HTMLInputElement;\n if (submitButton) {\n submitButton.click();\n } else {\n form.submit();\n }\n }\n }\n }, 10);\n // this is needed for firefox, would be nice to\n // find a way to do this with a callback instead\n }\n }\n }}\n placeholder=${this.placeholder}\n .value=${this.value}\n .disabled=${this.disabled}\n />\n `;\n\n if (this.textarea) {\n input = html`\n \n `;\n\n if (this.autogrow) {\n input = html`
\n
\n ${input}\n
`;\n }\n }\n\n return html`\n \n \n \n\n ${input} ${clear}\n ${this.type === InputType.Number\n ? html``\n : null}\n \n
\n \n `;\n }\n}\n","export interface Workspace {\n uuid: string;\n name: string;\n country: string;\n languages: string[];\n timezone: string;\n date_style: DateStyle;\n anon: boolean;\n}\n\nexport interface Language {\n iso: string;\n name: string;\n}\n\nexport interface Attachment {\n uuid: string;\n content_type: string;\n url: string;\n filename: string;\n size: number;\n error: string;\n}\n\nexport enum DateStyle {\n DayFirst = 'day_first',\n MonthFirst = 'month_first',\n YearFirst = 'year_first',\n}\n\nexport enum ScheduledEventType {\n CampaignEvent = 'campaign_event',\n ScheduledBroadcast = 'scheduled_broadcast',\n ScheduledTrigger = 'scheduled_trigger',\n}\n\nexport enum TicketStatus {\n Open = 'open',\n Closed = 'closed',\n}\n\nexport interface ScheduledEvent {\n type: ScheduledEventType;\n scheduled: string;\n repeat_period: string;\n campaign?: ObjectReference;\n flow?: ObjectReference;\n message?: string;\n}\n\nexport interface User {\n id?: number;\n first_name?: string;\n last_name?: string;\n email?: string;\n role?: string;\n created_on?: string;\n avatar?: string;\n}\n\nexport interface Ticket {\n uuid: string;\n subject: string;\n body?: string;\n closed_on: string;\n opened_on: string;\n status: string;\n contact: ObjectReference;\n topic: ObjectReference;\n assignee?: { email: string; name: string; avatar?: string };\n}\n\nexport interface FlowResult {\n key: string;\n name: string;\n categories: string[];\n node_uuids: string[];\n}\n\nexport interface FlowDetails {\n name: string;\n results: FlowResult[];\n modified_on: string;\n runs: {\n active: number;\n completed: number;\n expired: number;\n interrupted: number;\n };\n}\n\nexport interface Msg {\n text: string;\n status: string;\n channel: ObjectReference;\n quick_replies: string[];\n urn: string;\n id: number;\n direction: string;\n type: string;\n attachments: string[];\n}\n\nexport interface ObjectReference {\n uuid: string;\n name: string;\n}\n\nexport interface ContactField {\n key: string;\n label: string;\n value_type: string;\n featured: boolean;\n priority: number;\n agent_access: string;\n type: string;\n usages: { campaign_events: number; flows: number; groups: number };\n}\n\nexport interface ContactGroup {\n uuid: string;\n count: number;\n name: string;\n query?: string;\n status: string;\n}\n\nexport interface URN {\n scheme: string;\n path: string;\n}\n\nexport interface Group {\n name: string;\n uuid: string;\n is_dynamic?: boolean;\n}\n\nexport interface ContactTicket {\n name: string;\n uuid: string;\n status: string;\n\n contact: {\n uuid: string;\n name: string;\n created_on: Date;\n last_seen_on: Date;\n };\n}\n\nexport interface Contact {\n name: string;\n uuid: string;\n stopped: boolean;\n blocked: boolean;\n urns: string[];\n language?: string;\n fields: { [key: string]: string };\n groups: Group[];\n modified_on: string;\n created_on: string;\n last_seen_on: string;\n status: string;\n\n anon_display?: string;\n flow?: ObjectReference;\n last_msg?: Msg;\n direction?: string;\n ticket: {\n uuid: string;\n subject: string;\n closed_on?: string;\n last_activity_on: string;\n assignee?: User;\n topic?: ObjectReference;\n };\n}\n\nexport interface FeatureProperties {\n name: string;\n osm_id: string;\n level: number;\n children?: FeatureProperties[];\n has_children?: boolean;\n aliases?: string;\n parent_osm_id?: string;\n id?: number;\n path?: string;\n}\n\nexport interface Position {\n top: number;\n left: number;\n}\n\nexport interface FunctionExample {\n template: string;\n output: string;\n}\n\nexport interface CompletionOption {\n name?: string;\n summary: string;\n\n // functions\n signature?: string;\n detail?: string;\n examples?: FunctionExample[];\n}\n\nexport interface CompletionResult {\n anchorPosition: Position;\n query: string;\n options: CompletionOption[];\n currentFunction: CompletionOption;\n}\n\nexport interface CompletionProperty {\n key: string;\n help: string;\n type: string;\n}\n\nexport interface CompletionType {\n name: string;\n\n key_source?: string;\n property_template?: CompletionProperty;\n properties?: CompletionProperty[];\n}\n\nexport interface CompletionSchema {\n types: CompletionType[];\n root: CompletionProperty[];\n root_no_session: CompletionProperty[];\n}\n\nexport type KeyedAssets = { [assetType: string]: string[] };\n\nexport enum CustomEventType {\n Loaded = 'temba-loaded',\n Canceled = 'temba-canceled',\n CursorChanged = 'temba-cursor-changed',\n Refreshed = 'temba-refreshed',\n Selection = 'temba-selection',\n ButtonClicked = 'temba-button-clicked',\n DialogHidden = 'temba-dialog-hidden',\n ScrollThreshold = 'temba-scroll-threshold',\n ContentChanged = 'temba-content-changed',\n ContextChanged = 'temba-context-changed',\n FetchComplete = 'temba-fetch-complete',\n MessageSent = 'temba-message-sent',\n Submitted = 'temba-submitted',\n Redirected = 'temba-redirected',\n NoPath = 'temba-no-path',\n StoreUpdated = 'temba-store-updated',\n Ready = 'temba-ready',\n OrderChanged = 'temba-order-changed',\n DragStart = 'temba-drag-start',\n DragStop = 'temba-drag-stop',\n Resized = 'temba-resized',\n}\n","export const sanitize = (text: string): string => {\n if (text) {\n return text\n .replace(/[\\u2018\\u2019]/g, \"'\") // Smart single quotes\n .replace(/[\\u201C\\u201D]/g, '\"') // Smart double quotes\n .replace(/[\\u2013\\u2014]/g, '-') // En/em dash\n .replace(/\\u2026/g, '...') // Horizontal ellipsis\n .replace(/\\u2002/g, ' '); // En space\n }\n return text;\n};\n","/**\n * tiny-lru\n *\n * @copyright 2023 Jason Mulligan \n * @license BSD-3-Clause\n * @version 11.2.5\n */\nclass LRU {\r\n\tconstructor (max = 0, ttl = 0, resetTtl = false) {\r\n\t\tthis.first = null;\r\n\t\tthis.items = Object.create(null);\r\n\t\tthis.last = null;\r\n\t\tthis.max = max;\r\n\t\tthis.resetTtl = resetTtl;\r\n\t\tthis.size = 0;\r\n\t\tthis.ttl = ttl;\r\n\t}\r\n\r\n\tclear () {\r\n\t\tthis.first = null;\r\n\t\tthis.items = Object.create(null);\r\n\t\tthis.last = null;\r\n\t\tthis.size = 0;\r\n\r\n\t\treturn this;\r\n\t}\r\n\r\n\tdelete (key) {\r\n\t\tif (this.has(key)) {\r\n\t\t\tconst item = this.items[key];\r\n\r\n\t\t\tdelete this.items[key];\r\n\t\t\tthis.size--;\r\n\r\n\t\t\tif (item.prev !== null) {\r\n\t\t\t\titem.prev.next = item.next;\r\n\t\t\t}\r\n\r\n\t\t\tif (item.next !== null) {\r\n\t\t\t\titem.next.prev = item.prev;\r\n\t\t\t}\r\n\r\n\t\t\tif (this.first === item) {\r\n\t\t\t\tthis.first = item.next;\r\n\t\t\t}\r\n\r\n\t\t\tif (this.last === item) {\r\n\t\t\t\tthis.last = item.prev;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t}\r\n\r\n\tentries (keys = this.keys()) {\r\n\t\treturn keys.map(key => [key, this.get(key)]);\r\n\t}\r\n\r\n\tevict (bypass = false) {\r\n\t\tif (bypass || this.size > 0) {\r\n\t\t\tconst item = this.first;\r\n\r\n\t\t\tdelete this.items[item.key];\r\n\r\n\t\t\tif (--this.size === 0) {\r\n\t\t\t\tthis.first = null;\r\n\t\t\t\tthis.last = null;\r\n\t\t\t} else {\r\n\t\t\t\tthis.first = item.next;\r\n\t\t\t\tthis.first.prev = null;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t}\r\n\r\n\texpiresAt (key) {\r\n\t\tlet result;\r\n\r\n\t\tif (this.has(key)) {\r\n\t\t\tresult = this.items[key].expiry;\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tget (key) {\r\n\t\tlet result;\r\n\r\n\t\tif (this.has(key)) {\r\n\t\t\tconst item = this.items[key];\r\n\r\n\t\t\tif (this.ttl > 0 && item.expiry <= Date.now()) {\r\n\t\t\t\tthis.delete(key);\r\n\t\t\t} else {\r\n\t\t\t\tresult = item.value;\r\n\t\t\t\tthis.set(key, result, true);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\thas (key) {\r\n\t\treturn key in this.items;\r\n\t}\r\n\r\n\tkeys () {\r\n\t\tconst result = [];\r\n\t\tlet x = this.first;\r\n\r\n\t\twhile (x !== null) {\r\n\t\t\tresult.push(x.key);\r\n\t\t\tx = x.next;\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tset (key, value, bypass = false, resetTtl = this.resetTtl) {\r\n\t\tlet item;\r\n\r\n\t\tif (bypass || this.has(key)) {\r\n\t\t\titem = this.items[key];\r\n\t\t\titem.value = value;\r\n\r\n\t\t\tif (bypass === false && resetTtl) {\r\n\t\t\t\titem.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl;\r\n\t\t\t}\r\n\r\n\t\t\tif (this.last !== item) {\r\n\t\t\t\tconst last = this.last,\r\n\t\t\t\t\tnext = item.next,\r\n\t\t\t\t\tprev = item.prev;\r\n\r\n\t\t\t\tif (this.first === item) {\r\n\t\t\t\t\tthis.first = item.next;\r\n\t\t\t\t}\r\n\r\n\t\t\t\titem.next = null;\r\n\t\t\t\titem.prev = this.last;\r\n\t\t\t\tlast.next = item;\r\n\r\n\t\t\t\tif (prev !== null) {\r\n\t\t\t\t\tprev.next = next;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (next !== null) {\r\n\t\t\t\t\tnext.prev = prev;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif (this.max > 0 && this.size === this.max) {\r\n\t\t\t\tthis.evict(true);\r\n\t\t\t}\r\n\r\n\t\t\titem = this.items[key] = {\r\n\t\t\t\texpiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,\r\n\t\t\t\tkey: key,\r\n\t\t\t\tprev: this.last,\r\n\t\t\t\tnext: null,\r\n\t\t\t\tvalue\r\n\t\t\t};\r\n\r\n\t\t\tif (++this.size === 1) {\r\n\t\t\t\tthis.first = item;\r\n\t\t\t} else {\r\n\t\t\t\tthis.last.next = item;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis.last = item;\r\n\r\n\t\treturn this;\r\n\t}\r\n\r\n\tvalues (keys = this.keys()) {\r\n\t\treturn keys.map(key => this.get(key));\r\n\t}\r\n}\r\n\r\nfunction lru (max = 1000, ttl = 0, resetTtl = false) {\r\n\tif (isNaN(max) || max < 0) {\r\n\t\tthrow new TypeError(\"Invalid max value\");\r\n\t}\r\n\r\n\tif (isNaN(ttl) || ttl < 0) {\r\n\t\tthrow new TypeError(\"Invalid ttl value\");\r\n\t}\r\n\r\n\tif (typeof resetTtl !== \"boolean\") {\r\n\t\tthrow new TypeError(\"Invalid resetTtl value\");\r\n\t}\r\n\r\n\treturn new LRU(max, ttl, resetTtl);\r\n}export{LRU,lru};","// these aren't really private, but nor are they really useful to document\n\n/**\n * @private\n */\nclass LuxonError extends Error {}\n\n/**\n * @private\n */\nexport class InvalidDateTimeError extends LuxonError {\n constructor(reason) {\n super(`Invalid DateTime: ${reason.toMessage()}`);\n }\n}\n\n/**\n * @private\n */\nexport class InvalidIntervalError extends LuxonError {\n constructor(reason) {\n super(`Invalid Interval: ${reason.toMessage()}`);\n }\n}\n\n/**\n * @private\n */\nexport class InvalidDurationError extends LuxonError {\n constructor(reason) {\n super(`Invalid Duration: ${reason.toMessage()}`);\n }\n}\n\n/**\n * @private\n */\nexport class ConflictingSpecificationError extends LuxonError {}\n\n/**\n * @private\n */\nexport class InvalidUnitError extends LuxonError {\n constructor(unit) {\n super(`Invalid unit ${unit}`);\n }\n}\n\n/**\n * @private\n */\nexport class InvalidArgumentError extends LuxonError {}\n\n/**\n * @private\n */\nexport class ZoneIsAbstractError extends LuxonError {\n constructor() {\n super(\"Zone is an abstract class\");\n }\n}\n","/**\n * @private\n */\n\nconst n = \"numeric\",\n s = \"short\",\n l = \"long\";\n\nexport const DATE_SHORT = {\n year: n,\n month: n,\n day: n,\n};\n\nexport const DATE_MED = {\n year: n,\n month: s,\n day: n,\n};\n\nexport const DATE_MED_WITH_WEEKDAY = {\n year: n,\n month: s,\n day: n,\n weekday: s,\n};\n\nexport const DATE_FULL = {\n year: n,\n month: l,\n day: n,\n};\n\nexport const DATE_HUGE = {\n year: n,\n month: l,\n day: n,\n weekday: l,\n};\n\nexport const TIME_SIMPLE = {\n hour: n,\n minute: n,\n};\n\nexport const TIME_WITH_SECONDS = {\n hour: n,\n minute: n,\n second: n,\n};\n\nexport const TIME_WITH_SHORT_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n timeZoneName: s,\n};\n\nexport const TIME_WITH_LONG_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n timeZoneName: l,\n};\n\nexport const TIME_24_SIMPLE = {\n hour: n,\n minute: n,\n hourCycle: \"h23\",\n};\n\nexport const TIME_24_WITH_SECONDS = {\n hour: n,\n minute: n,\n second: n,\n hourCycle: \"h23\",\n};\n\nexport const TIME_24_WITH_SHORT_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n hourCycle: \"h23\",\n timeZoneName: s,\n};\n\nexport const TIME_24_WITH_LONG_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n hourCycle: \"h23\",\n timeZoneName: l,\n};\n\nexport const DATETIME_SHORT = {\n year: n,\n month: n,\n day: n,\n hour: n,\n minute: n,\n};\n\nexport const DATETIME_SHORT_WITH_SECONDS = {\n year: n,\n month: n,\n day: n,\n hour: n,\n minute: n,\n second: n,\n};\n\nexport const DATETIME_MED = {\n year: n,\n month: s,\n day: n,\n hour: n,\n minute: n,\n};\n\nexport const DATETIME_MED_WITH_SECONDS = {\n year: n,\n month: s,\n day: n,\n hour: n,\n minute: n,\n second: n,\n};\n\nexport const DATETIME_MED_WITH_WEEKDAY = {\n year: n,\n month: s,\n day: n,\n weekday: s,\n hour: n,\n minute: n,\n};\n\nexport const DATETIME_FULL = {\n year: n,\n month: l,\n day: n,\n hour: n,\n minute: n,\n timeZoneName: s,\n};\n\nexport const DATETIME_FULL_WITH_SECONDS = {\n year: n,\n month: l,\n day: n,\n hour: n,\n minute: n,\n second: n,\n timeZoneName: s,\n};\n\nexport const DATETIME_HUGE = {\n year: n,\n month: l,\n day: n,\n weekday: l,\n hour: n,\n minute: n,\n timeZoneName: l,\n};\n\nexport const DATETIME_HUGE_WITH_SECONDS = {\n year: n,\n month: l,\n day: n,\n weekday: l,\n hour: n,\n minute: n,\n second: n,\n timeZoneName: l,\n};\n","/*\n This is just a junk drawer, containing anything used across multiple classes.\n Because Luxon is small(ish), this should stay small and we won't worry about splitting\n it up into, say, parsingUtil.js and basicUtil.js and so on. But they are divided up by feature area.\n*/\n\nimport { InvalidArgumentError } from \"../errors.js\";\n\n/**\n * @private\n */\n\n// TYPES\n\nexport function isUndefined(o) {\n return typeof o === \"undefined\";\n}\n\nexport function isNumber(o) {\n return typeof o === \"number\";\n}\n\nexport function isInteger(o) {\n return typeof o === \"number\" && o % 1 === 0;\n}\n\nexport function isString(o) {\n return typeof o === \"string\";\n}\n\nexport function isDate(o) {\n return Object.prototype.toString.call(o) === \"[object Date]\";\n}\n\n// CAPABILITIES\n\nexport function hasRelative() {\n try {\n return typeof Intl !== \"undefined\" && !!Intl.RelativeTimeFormat;\n } catch (e) {\n return false;\n }\n}\n\n// OBJECTS AND ARRAYS\n\nexport function maybeArray(thing) {\n return Array.isArray(thing) ? thing : [thing];\n}\n\nexport function bestBy(arr, by, compare) {\n if (arr.length === 0) {\n return undefined;\n }\n return arr.reduce((best, next) => {\n const pair = [by(next), next];\n if (!best) {\n return pair;\n } else if (compare(best[0], pair[0]) === best[0]) {\n return best;\n } else {\n return pair;\n }\n }, null)[1];\n}\n\nexport function pick(obj, keys) {\n return keys.reduce((a, k) => {\n a[k] = obj[k];\n return a;\n }, {});\n}\n\nexport function hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\n// NUMBERS AND STRINGS\n\nexport function integerBetween(thing, bottom, top) {\n return isInteger(thing) && thing >= bottom && thing <= top;\n}\n\n// x % n but takes the sign of n instead of x\nexport function floorMod(x, n) {\n return x - n * Math.floor(x / n);\n}\n\nexport function padStart(input, n = 2) {\n const isNeg = input < 0;\n let padded;\n if (isNeg) {\n padded = \"-\" + (\"\" + -input).padStart(n, \"0\");\n } else {\n padded = (\"\" + input).padStart(n, \"0\");\n }\n return padded;\n}\n\nexport function parseInteger(string) {\n if (isUndefined(string) || string === null || string === \"\") {\n return undefined;\n } else {\n return parseInt(string, 10);\n }\n}\n\nexport function parseFloating(string) {\n if (isUndefined(string) || string === null || string === \"\") {\n return undefined;\n } else {\n return parseFloat(string);\n }\n}\n\nexport function parseMillis(fraction) {\n // Return undefined (instead of 0) in these cases, where fraction is not set\n if (isUndefined(fraction) || fraction === null || fraction === \"\") {\n return undefined;\n } else {\n const f = parseFloat(\"0.\" + fraction) * 1000;\n return Math.floor(f);\n }\n}\n\nexport function roundTo(number, digits, towardZero = false) {\n const factor = 10 ** digits,\n rounder = towardZero ? Math.trunc : Math.round;\n return rounder(number * factor) / factor;\n}\n\n// DATE BASICS\n\nexport function isLeapYear(year) {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n\nexport function daysInYear(year) {\n return isLeapYear(year) ? 366 : 365;\n}\n\nexport function daysInMonth(year, month) {\n const modMonth = floorMod(month - 1, 12) + 1,\n modYear = year + (month - modMonth) / 12;\n\n if (modMonth === 2) {\n return isLeapYear(modYear) ? 29 : 28;\n } else {\n return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];\n }\n}\n\n// covert a calendar object to a local timestamp (epoch, but with the offset baked in)\nexport function objToLocalTS(obj) {\n let d = Date.UTC(\n obj.year,\n obj.month - 1,\n obj.day,\n obj.hour,\n obj.minute,\n obj.second,\n obj.millisecond\n );\n\n // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that\n if (obj.year < 100 && obj.year >= 0) {\n d = new Date(d);\n d.setUTCFullYear(d.getUTCFullYear() - 1900);\n }\n return +d;\n}\n\nexport function weeksInWeekYear(weekYear) {\n const p1 =\n (weekYear +\n Math.floor(weekYear / 4) -\n Math.floor(weekYear / 100) +\n Math.floor(weekYear / 400)) %\n 7,\n last = weekYear - 1,\n p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7;\n return p1 === 4 || p2 === 3 ? 53 : 52;\n}\n\nexport function untruncateYear(year) {\n if (year > 99) {\n return year;\n } else return year > 60 ? 1900 + year : 2000 + year;\n}\n\n// PARSING\n\nexport function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) {\n const date = new Date(ts),\n intlOpts = {\n hourCycle: \"h23\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n };\n\n if (timeZone) {\n intlOpts.timeZone = timeZone;\n }\n\n const modified = { timeZoneName: offsetFormat, ...intlOpts };\n\n const parsed = new Intl.DateTimeFormat(locale, modified)\n .formatToParts(date)\n .find((m) => m.type.toLowerCase() === \"timezonename\");\n return parsed ? parsed.value : null;\n}\n\n// signedOffset('-5', '30') -> -330\nexport function signedOffset(offHourStr, offMinuteStr) {\n let offHour = parseInt(offHourStr, 10);\n\n // don't || this because we want to preserve -0\n if (Number.isNaN(offHour)) {\n offHour = 0;\n }\n\n const offMin = parseInt(offMinuteStr, 10) || 0,\n offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;\n return offHour * 60 + offMinSigned;\n}\n\n// COERCION\n\nexport function asNumber(value) {\n const numericValue = Number(value);\n if (typeof value === \"boolean\" || value === \"\" || Number.isNaN(numericValue))\n throw new InvalidArgumentError(`Invalid unit value ${value}`);\n return numericValue;\n}\n\nexport function normalizeObject(obj, normalizer) {\n const normalized = {};\n for (const u in obj) {\n if (hasOwnProperty(obj, u)) {\n const v = obj[u];\n if (v === undefined || v === null) continue;\n normalized[normalizer(u)] = asNumber(v);\n }\n }\n return normalized;\n}\n\nexport function formatOffset(offset, format) {\n const hours = Math.trunc(Math.abs(offset / 60)),\n minutes = Math.trunc(Math.abs(offset % 60)),\n sign = offset >= 0 ? \"+\" : \"-\";\n\n switch (format) {\n case \"short\":\n return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`;\n case \"narrow\":\n return `${sign}${hours}${minutes > 0 ? `:${minutes}` : \"\"}`;\n case \"techie\":\n return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`;\n default:\n throw new RangeError(`Value format ${format} is out of range for property format`);\n }\n}\n\nexport function timeObject(obj) {\n return pick(obj, [\"hour\", \"minute\", \"second\", \"millisecond\"]);\n}\n\nexport const ianaRegex =\n /[A-Za-z_+-]{1,256}(?::?\\/[A-Za-z0-9_+-]{1,256}(?:\\/[A-Za-z0-9_+-]{1,256})?)?/;\n","import * as Formats from \"./formats.js\";\nimport { pick } from \"./util.js\";\n\nfunction stringify(obj) {\n return JSON.stringify(obj, Object.keys(obj).sort());\n}\n\n/**\n * @private\n */\n\nexport const monthsLong = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\nexport const monthsShort = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n];\n\nexport const monthsNarrow = [\"J\", \"F\", \"M\", \"A\", \"M\", \"J\", \"J\", \"A\", \"S\", \"O\", \"N\", \"D\"];\n\nexport function months(length) {\n switch (length) {\n case \"narrow\":\n return [...monthsNarrow];\n case \"short\":\n return [...monthsShort];\n case \"long\":\n return [...monthsLong];\n case \"numeric\":\n return [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\"];\n case \"2-digit\":\n return [\"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\", \"11\", \"12\"];\n default:\n return null;\n }\n}\n\nexport const weekdaysLong = [\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n \"Sunday\",\n];\n\nexport const weekdaysShort = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"];\n\nexport const weekdaysNarrow = [\"M\", \"T\", \"W\", \"T\", \"F\", \"S\", \"S\"];\n\nexport function weekdays(length) {\n switch (length) {\n case \"narrow\":\n return [...weekdaysNarrow];\n case \"short\":\n return [...weekdaysShort];\n case \"long\":\n return [...weekdaysLong];\n case \"numeric\":\n return [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\"];\n default:\n return null;\n }\n}\n\nexport const meridiems = [\"AM\", \"PM\"];\n\nexport const erasLong = [\"Before Christ\", \"Anno Domini\"];\n\nexport const erasShort = [\"BC\", \"AD\"];\n\nexport const erasNarrow = [\"B\", \"A\"];\n\nexport function eras(length) {\n switch (length) {\n case \"narrow\":\n return [...erasNarrow];\n case \"short\":\n return [...erasShort];\n case \"long\":\n return [...erasLong];\n default:\n return null;\n }\n}\n\nexport function meridiemForDateTime(dt) {\n return meridiems[dt.hour < 12 ? 0 : 1];\n}\n\nexport function weekdayForDateTime(dt, length) {\n return weekdays(length)[dt.weekday - 1];\n}\n\nexport function monthForDateTime(dt, length) {\n return months(length)[dt.month - 1];\n}\n\nexport function eraForDateTime(dt, length) {\n return eras(length)[dt.year < 0 ? 0 : 1];\n}\n\nexport function formatRelativeTime(unit, count, numeric = \"always\", narrow = false) {\n const units = {\n years: [\"year\", \"yr.\"],\n quarters: [\"quarter\", \"qtr.\"],\n months: [\"month\", \"mo.\"],\n weeks: [\"week\", \"wk.\"],\n days: [\"day\", \"day\", \"days\"],\n hours: [\"hour\", \"hr.\"],\n minutes: [\"minute\", \"min.\"],\n seconds: [\"second\", \"sec.\"],\n };\n\n const lastable = [\"hours\", \"minutes\", \"seconds\"].indexOf(unit) === -1;\n\n if (numeric === \"auto\" && lastable) {\n const isDay = unit === \"days\";\n switch (count) {\n case 1:\n return isDay ? \"tomorrow\" : `next ${units[unit][0]}`;\n case -1:\n return isDay ? \"yesterday\" : `last ${units[unit][0]}`;\n case 0:\n return isDay ? \"today\" : `this ${units[unit][0]}`;\n default: // fall through\n }\n }\n\n const isInPast = Object.is(count, -0) || count < 0,\n fmtValue = Math.abs(count),\n singular = fmtValue === 1,\n lilUnits = units[unit],\n fmtUnit = narrow\n ? singular\n ? lilUnits[1]\n : lilUnits[2] || lilUnits[1]\n : singular\n ? units[unit][0]\n : unit;\n return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;\n}\n\nexport function formatString(knownFormat) {\n // these all have the offsets removed because we don't have access to them\n // without all the intl stuff this is backfilling\n const filtered = pick(knownFormat, [\n \"weekday\",\n \"era\",\n \"year\",\n \"month\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n \"timeZoneName\",\n \"hourCycle\",\n ]),\n key = stringify(filtered),\n dateTimeHuge = \"EEEE, LLLL d, yyyy, h:mm a\";\n switch (key) {\n case stringify(Formats.DATE_SHORT):\n return \"M/d/yyyy\";\n case stringify(Formats.DATE_MED):\n return \"LLL d, yyyy\";\n case stringify(Formats.DATE_MED_WITH_WEEKDAY):\n return \"EEE, LLL d, yyyy\";\n case stringify(Formats.DATE_FULL):\n return \"LLLL d, yyyy\";\n case stringify(Formats.DATE_HUGE):\n return \"EEEE, LLLL d, yyyy\";\n case stringify(Formats.TIME_SIMPLE):\n return \"h:mm a\";\n case stringify(Formats.TIME_WITH_SECONDS):\n return \"h:mm:ss a\";\n case stringify(Formats.TIME_WITH_SHORT_OFFSET):\n return \"h:mm a\";\n case stringify(Formats.TIME_WITH_LONG_OFFSET):\n return \"h:mm a\";\n case stringify(Formats.TIME_24_SIMPLE):\n return \"HH:mm\";\n case stringify(Formats.TIME_24_WITH_SECONDS):\n return \"HH:mm:ss\";\n case stringify(Formats.TIME_24_WITH_SHORT_OFFSET):\n return \"HH:mm\";\n case stringify(Formats.TIME_24_WITH_LONG_OFFSET):\n return \"HH:mm\";\n case stringify(Formats.DATETIME_SHORT):\n return \"M/d/yyyy, h:mm a\";\n case stringify(Formats.DATETIME_MED):\n return \"LLL d, yyyy, h:mm a\";\n case stringify(Formats.DATETIME_FULL):\n return \"LLLL d, yyyy, h:mm a\";\n case stringify(Formats.DATETIME_HUGE):\n return dateTimeHuge;\n case stringify(Formats.DATETIME_SHORT_WITH_SECONDS):\n return \"M/d/yyyy, h:mm:ss a\";\n case stringify(Formats.DATETIME_MED_WITH_SECONDS):\n return \"LLL d, yyyy, h:mm:ss a\";\n case stringify(Formats.DATETIME_MED_WITH_WEEKDAY):\n return \"EEE, d LLL yyyy, h:mm a\";\n case stringify(Formats.DATETIME_FULL_WITH_SECONDS):\n return \"LLLL d, yyyy, h:mm:ss a\";\n case stringify(Formats.DATETIME_HUGE_WITH_SECONDS):\n return \"EEEE, LLLL d, yyyy, h:mm:ss a\";\n default:\n return dateTimeHuge;\n }\n}\n","import * as English from \"./english.js\";\nimport * as Formats from \"./formats.js\";\nimport { padStart } from \"./util.js\";\n\nfunction stringifyTokens(splits, tokenToString) {\n let s = \"\";\n for (const token of splits) {\n if (token.literal) {\n s += token.val;\n } else {\n s += tokenToString(token.val);\n }\n }\n return s;\n}\n\nconst macroTokenToFormatOpts = {\n D: Formats.DATE_SHORT,\n DD: Formats.DATE_MED,\n DDD: Formats.DATE_FULL,\n DDDD: Formats.DATE_HUGE,\n t: Formats.TIME_SIMPLE,\n tt: Formats.TIME_WITH_SECONDS,\n ttt: Formats.TIME_WITH_SHORT_OFFSET,\n tttt: Formats.TIME_WITH_LONG_OFFSET,\n T: Formats.TIME_24_SIMPLE,\n TT: Formats.TIME_24_WITH_SECONDS,\n TTT: Formats.TIME_24_WITH_SHORT_OFFSET,\n TTTT: Formats.TIME_24_WITH_LONG_OFFSET,\n f: Formats.DATETIME_SHORT,\n ff: Formats.DATETIME_MED,\n fff: Formats.DATETIME_FULL,\n ffff: Formats.DATETIME_HUGE,\n F: Formats.DATETIME_SHORT_WITH_SECONDS,\n FF: Formats.DATETIME_MED_WITH_SECONDS,\n FFF: Formats.DATETIME_FULL_WITH_SECONDS,\n FFFF: Formats.DATETIME_HUGE_WITH_SECONDS,\n};\n\n/**\n * @private\n */\n\nexport default class Formatter {\n static create(locale, opts = {}) {\n return new Formatter(locale, opts);\n }\n\n static parseFormat(fmt) {\n let current = null,\n currentFull = \"\",\n bracketed = false;\n const splits = [];\n for (let i = 0; i < fmt.length; i++) {\n const c = fmt.charAt(i);\n if (c === \"'\") {\n if (currentFull.length > 0) {\n splits.push({ literal: bracketed, val: currentFull });\n }\n current = null;\n currentFull = \"\";\n bracketed = !bracketed;\n } else if (bracketed) {\n currentFull += c;\n } else if (c === current) {\n currentFull += c;\n } else {\n if (currentFull.length > 0) {\n splits.push({ literal: false, val: currentFull });\n }\n currentFull = c;\n current = c;\n }\n }\n\n if (currentFull.length > 0) {\n splits.push({ literal: bracketed, val: currentFull });\n }\n\n return splits;\n }\n\n static macroTokenToFormatOpts(token) {\n return macroTokenToFormatOpts[token];\n }\n\n constructor(locale, formatOpts) {\n this.opts = formatOpts;\n this.loc = locale;\n this.systemLoc = null;\n }\n\n formatWithSystemDefault(dt, opts) {\n if (this.systemLoc === null) {\n this.systemLoc = this.loc.redefaultToSystem();\n }\n const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts });\n return df.format();\n }\n\n formatDateTime(dt, opts = {}) {\n const df = this.loc.dtFormatter(dt, { ...this.opts, ...opts });\n return df.format();\n }\n\n formatDateTimeParts(dt, opts = {}) {\n const df = this.loc.dtFormatter(dt, { ...this.opts, ...opts });\n return df.formatToParts();\n }\n\n resolvedOptions(dt, opts = {}) {\n const df = this.loc.dtFormatter(dt, { ...this.opts, ...opts });\n return df.resolvedOptions();\n }\n\n num(n, p = 0) {\n // we get some perf out of doing this here, annoyingly\n if (this.opts.forceSimple) {\n return padStart(n, p);\n }\n\n const opts = { ...this.opts };\n\n if (p > 0) {\n opts.padTo = p;\n }\n\n return this.loc.numberFormatter(opts).format(n);\n }\n\n formatDateTimeFromString(dt, fmt) {\n const knownEnglish = this.loc.listingMode() === \"en\",\n useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== \"gregory\",\n string = (opts, extract) => this.loc.extract(dt, opts, extract),\n formatOffset = (opts) => {\n if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {\n return \"Z\";\n }\n\n return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : \"\";\n },\n meridiem = () =>\n knownEnglish\n ? English.meridiemForDateTime(dt)\n : string({ hour: \"numeric\", hourCycle: \"h12\" }, \"dayperiod\"),\n month = (length, standalone) =>\n knownEnglish\n ? English.monthForDateTime(dt, length)\n : string(standalone ? { month: length } : { month: length, day: \"numeric\" }, \"month\"),\n weekday = (length, standalone) =>\n knownEnglish\n ? English.weekdayForDateTime(dt, length)\n : string(\n standalone ? { weekday: length } : { weekday: length, month: \"long\", day: \"numeric\" },\n \"weekday\"\n ),\n maybeMacro = (token) => {\n const formatOpts = Formatter.macroTokenToFormatOpts(token);\n if (formatOpts) {\n return this.formatWithSystemDefault(dt, formatOpts);\n } else {\n return token;\n }\n },\n era = (length) =>\n knownEnglish ? English.eraForDateTime(dt, length) : string({ era: length }, \"era\"),\n tokenToString = (token) => {\n // Where possible: http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles\n switch (token) {\n // ms\n case \"S\":\n return this.num(dt.millisecond);\n case \"u\":\n // falls through\n case \"SSS\":\n return this.num(dt.millisecond, 3);\n // seconds\n case \"s\":\n return this.num(dt.second);\n case \"ss\":\n return this.num(dt.second, 2);\n // fractional seconds\n case \"uu\":\n return this.num(Math.floor(dt.millisecond / 10), 2);\n case \"uuu\":\n return this.num(Math.floor(dt.millisecond / 100));\n // minutes\n case \"m\":\n return this.num(dt.minute);\n case \"mm\":\n return this.num(dt.minute, 2);\n // hours\n case \"h\":\n return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);\n case \"hh\":\n return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);\n case \"H\":\n return this.num(dt.hour);\n case \"HH\":\n return this.num(dt.hour, 2);\n // offset\n case \"Z\":\n // like +6\n return formatOffset({ format: \"narrow\", allowZ: this.opts.allowZ });\n case \"ZZ\":\n // like +06:00\n return formatOffset({ format: \"short\", allowZ: this.opts.allowZ });\n case \"ZZZ\":\n // like +0600\n return formatOffset({ format: \"techie\", allowZ: this.opts.allowZ });\n case \"ZZZZ\":\n // like EST\n return dt.zone.offsetName(dt.ts, { format: \"short\", locale: this.loc.locale });\n case \"ZZZZZ\":\n // like Eastern Standard Time\n return dt.zone.offsetName(dt.ts, { format: \"long\", locale: this.loc.locale });\n // zone\n case \"z\":\n // like America/New_York\n return dt.zoneName;\n // meridiems\n case \"a\":\n return meridiem();\n // dates\n case \"d\":\n return useDateTimeFormatter ? string({ day: \"numeric\" }, \"day\") : this.num(dt.day);\n case \"dd\":\n return useDateTimeFormatter ? string({ day: \"2-digit\" }, \"day\") : this.num(dt.day, 2);\n // weekdays - standalone\n case \"c\":\n // like 1\n return this.num(dt.weekday);\n case \"ccc\":\n // like 'Tues'\n return weekday(\"short\", true);\n case \"cccc\":\n // like 'Tuesday'\n return weekday(\"long\", true);\n case \"ccccc\":\n // like 'T'\n return weekday(\"narrow\", true);\n // weekdays - format\n case \"E\":\n // like 1\n return this.num(dt.weekday);\n case \"EEE\":\n // like 'Tues'\n return weekday(\"short\", false);\n case \"EEEE\":\n // like 'Tuesday'\n return weekday(\"long\", false);\n case \"EEEEE\":\n // like 'T'\n return weekday(\"narrow\", false);\n // months - standalone\n case \"L\":\n // like 1\n return useDateTimeFormatter\n ? string({ month: \"numeric\", day: \"numeric\" }, \"month\")\n : this.num(dt.month);\n case \"LL\":\n // like 01, doesn't seem to work\n return useDateTimeFormatter\n ? string({ month: \"2-digit\", day: \"numeric\" }, \"month\")\n : this.num(dt.month, 2);\n case \"LLL\":\n // like Jan\n return month(\"short\", true);\n case \"LLLL\":\n // like January\n return month(\"long\", true);\n case \"LLLLL\":\n // like J\n return month(\"narrow\", true);\n // months - format\n case \"M\":\n // like 1\n return useDateTimeFormatter\n ? string({ month: \"numeric\" }, \"month\")\n : this.num(dt.month);\n case \"MM\":\n // like 01\n return useDateTimeFormatter\n ? string({ month: \"2-digit\" }, \"month\")\n : this.num(dt.month, 2);\n case \"MMM\":\n // like Jan\n return month(\"short\", false);\n case \"MMMM\":\n // like January\n return month(\"long\", false);\n case \"MMMMM\":\n // like J\n return month(\"narrow\", false);\n // years\n case \"y\":\n // like 2014\n return useDateTimeFormatter ? string({ year: \"numeric\" }, \"year\") : this.num(dt.year);\n case \"yy\":\n // like 14\n return useDateTimeFormatter\n ? string({ year: \"2-digit\" }, \"year\")\n : this.num(dt.year.toString().slice(-2), 2);\n case \"yyyy\":\n // like 0012\n return useDateTimeFormatter\n ? string({ year: \"numeric\" }, \"year\")\n : this.num(dt.year, 4);\n case \"yyyyyy\":\n // like 000012\n return useDateTimeFormatter\n ? string({ year: \"numeric\" }, \"year\")\n : this.num(dt.year, 6);\n // eras\n case \"G\":\n // like AD\n return era(\"short\");\n case \"GG\":\n // like Anno Domini\n return era(\"long\");\n case \"GGGGG\":\n return era(\"narrow\");\n case \"kk\":\n return this.num(dt.weekYear.toString().slice(-2), 2);\n case \"kkkk\":\n return this.num(dt.weekYear, 4);\n case \"W\":\n return this.num(dt.weekNumber);\n case \"WW\":\n return this.num(dt.weekNumber, 2);\n case \"o\":\n return this.num(dt.ordinal);\n case \"ooo\":\n return this.num(dt.ordinal, 3);\n case \"q\":\n // like 1\n return this.num(dt.quarter);\n case \"qq\":\n // like 01\n return this.num(dt.quarter, 2);\n case \"X\":\n return this.num(Math.floor(dt.ts / 1000));\n case \"x\":\n return this.num(dt.ts);\n default:\n return maybeMacro(token);\n }\n };\n\n return stringifyTokens(Formatter.parseFormat(fmt), tokenToString);\n }\n\n formatDurationFromString(dur, fmt) {\n const tokenToField = (token) => {\n switch (token[0]) {\n case \"S\":\n return \"millisecond\";\n case \"s\":\n return \"second\";\n case \"m\":\n return \"minute\";\n case \"h\":\n return \"hour\";\n case \"d\":\n return \"day\";\n case \"w\":\n return \"week\";\n case \"M\":\n return \"month\";\n case \"y\":\n return \"year\";\n default:\n return null;\n }\n },\n tokenToString = (lildur) => (token) => {\n const mapped = tokenToField(token);\n if (mapped) {\n return this.num(lildur.get(mapped), token.length);\n } else {\n return token;\n }\n },\n tokens = Formatter.parseFormat(fmt),\n realTokens = tokens.reduce(\n (found, { literal, val }) => (literal ? found : found.concat(val)),\n []\n ),\n collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t));\n return stringifyTokens(tokens, tokenToString(collapsed));\n }\n}\n","export default class Invalid {\n constructor(reason, explanation) {\n this.reason = reason;\n this.explanation = explanation;\n }\n\n toMessage() {\n if (this.explanation) {\n return `${this.reason}: ${this.explanation}`;\n } else {\n return this.reason;\n }\n }\n}\n","import { ZoneIsAbstractError } from \"./errors.js\";\n\n/**\n * @interface\n */\nexport default class Zone {\n /**\n * The type of zone\n * @abstract\n * @type {string}\n */\n get type() {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * The name of this zone.\n * @abstract\n * @type {string}\n */\n get name() {\n throw new ZoneIsAbstractError();\n }\n\n get ianaName() {\n return this.name;\n }\n\n /**\n * Returns whether the offset is known to be fixed for the whole year.\n * @abstract\n * @type {boolean}\n */\n get isUniversal() {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Returns the offset's common name (such as EST) at the specified timestamp\n * @abstract\n * @param {number} ts - Epoch milliseconds for which to get the name\n * @param {Object} opts - Options to affect the format\n * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.\n * @param {string} opts.locale - What locale to return the offset name in.\n * @return {string}\n */\n offsetName(ts, opts) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Returns the offset's value as a string\n * @abstract\n * @param {number} ts - Epoch milliseconds for which to get the offset\n * @param {string} format - What style of offset to return.\n * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively\n * @return {string}\n */\n formatOffset(ts, format) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Return the offset in minutes for this zone at the specified timestamp.\n * @abstract\n * @param {number} ts - Epoch milliseconds for which to compute the offset\n * @return {number}\n */\n offset(ts) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Return whether this Zone is equal to another zone\n * @abstract\n * @param {Zone} otherZone - the zone to compare\n * @return {boolean}\n */\n equals(otherZone) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Return whether this Zone is valid.\n * @abstract\n * @type {boolean}\n */\n get isValid() {\n throw new ZoneIsAbstractError();\n }\n}\n","import { formatOffset, parseZoneInfo } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet singleton = null;\n\n/**\n * Represents the local zone for this JavaScript environment.\n * @implements {Zone}\n */\nexport default class SystemZone extends Zone {\n /**\n * Get a singleton instance of the local zone\n * @return {SystemZone}\n */\n static get instance() {\n if (singleton === null) {\n singleton = new SystemZone();\n }\n return singleton;\n }\n\n /** @override **/\n get type() {\n return \"system\";\n }\n\n /** @override **/\n get name() {\n return new Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n /** @override **/\n get isUniversal() {\n return false;\n }\n\n /** @override **/\n offsetName(ts, { format, locale }) {\n return parseZoneInfo(ts, format, locale);\n }\n\n /** @override **/\n formatOffset(ts, format) {\n return formatOffset(this.offset(ts), format);\n }\n\n /** @override **/\n offset(ts) {\n return -new Date(ts).getTimezoneOffset();\n }\n\n /** @override **/\n equals(otherZone) {\n return otherZone.type === \"system\";\n }\n\n /** @override **/\n get isValid() {\n return true;\n }\n}\n","import { formatOffset, parseZoneInfo, isUndefined, objToLocalTS } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet dtfCache = {};\nfunction makeDTF(zone) {\n if (!dtfCache[zone]) {\n dtfCache[zone] = new Intl.DateTimeFormat(\"en-US\", {\n hour12: false,\n timeZone: zone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n era: \"short\",\n });\n }\n return dtfCache[zone];\n}\n\nconst typeToPos = {\n year: 0,\n month: 1,\n day: 2,\n era: 3,\n hour: 4,\n minute: 5,\n second: 6,\n};\n\nfunction hackyOffset(dtf, date) {\n const formatted = dtf.format(date).replace(/\\u200E/g, \"\"),\n parsed = /(\\d+)\\/(\\d+)\\/(\\d+) (AD|BC),? (\\d+):(\\d+):(\\d+)/.exec(formatted),\n [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed;\n return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];\n}\n\nfunction partsOffset(dtf, date) {\n const formatted = dtf.formatToParts(date);\n const filled = [];\n for (let i = 0; i < formatted.length; i++) {\n const { type, value } = formatted[i];\n const pos = typeToPos[type];\n\n if (type === \"era\") {\n filled[pos] = value;\n } else if (!isUndefined(pos)) {\n filled[pos] = parseInt(value, 10);\n }\n }\n return filled;\n}\n\nlet ianaZoneCache = {};\n/**\n * A zone identified by an IANA identifier, like America/New_York\n * @implements {Zone}\n */\nexport default class IANAZone extends Zone {\n /**\n * @param {string} name - Zone name\n * @return {IANAZone}\n */\n static create(name) {\n if (!ianaZoneCache[name]) {\n ianaZoneCache[name] = new IANAZone(name);\n }\n return ianaZoneCache[name];\n }\n\n /**\n * Reset local caches. Should only be necessary in testing scenarios.\n * @return {void}\n */\n static resetCache() {\n ianaZoneCache = {};\n dtfCache = {};\n }\n\n /**\n * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.\n * @param {string} s - The string to check validity on\n * @example IANAZone.isValidSpecifier(\"America/New_York\") //=> true\n * @example IANAZone.isValidSpecifier(\"Sport~~blorp\") //=> false\n * @deprecated This method returns false for some valid IANA names. Use isValidZone instead.\n * @return {boolean}\n */\n static isValidSpecifier(s) {\n return this.isValidZone(s);\n }\n\n /**\n * Returns whether the provided string identifies a real zone\n * @param {string} zone - The string to check\n * @example IANAZone.isValidZone(\"America/New_York\") //=> true\n * @example IANAZone.isValidZone(\"Fantasia/Castle\") //=> false\n * @example IANAZone.isValidZone(\"Sport~~blorp\") //=> false\n * @return {boolean}\n */\n static isValidZone(zone) {\n if (!zone) {\n return false;\n }\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: zone }).format();\n return true;\n } catch (e) {\n return false;\n }\n }\n\n constructor(name) {\n super();\n /** @private **/\n this.zoneName = name;\n /** @private **/\n this.valid = IANAZone.isValidZone(name);\n }\n\n /** @override **/\n get type() {\n return \"iana\";\n }\n\n /** @override **/\n get name() {\n return this.zoneName;\n }\n\n /** @override **/\n get isUniversal() {\n return false;\n }\n\n /** @override **/\n offsetName(ts, { format, locale }) {\n return parseZoneInfo(ts, format, locale, this.name);\n }\n\n /** @override **/\n formatOffset(ts, format) {\n return formatOffset(this.offset(ts), format);\n }\n\n /** @override **/\n offset(ts) {\n const date = new Date(ts);\n\n if (isNaN(date)) return NaN;\n\n const dtf = makeDTF(this.name);\n let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts\n ? partsOffset(dtf, date)\n : hackyOffset(dtf, date);\n\n if (adOrBc === \"BC\") {\n year = -Math.abs(year) + 1;\n }\n\n // because we're using hour12 and https://bugs.chromium.org/p/chromium/issues/detail?id=1025564&can=2&q=%2224%3A00%22%20datetimeformat\n const adjustedHour = hour === 24 ? 0 : hour;\n\n const asUTC = objToLocalTS({\n year,\n month,\n day,\n hour: adjustedHour,\n minute,\n second,\n millisecond: 0,\n });\n\n let asTS = +date;\n const over = asTS % 1000;\n asTS -= over >= 0 ? over : 1000 + over;\n return (asUTC - asTS) / (60 * 1000);\n }\n\n /** @override **/\n equals(otherZone) {\n return otherZone.type === \"iana\" && otherZone.name === this.name;\n }\n\n /** @override **/\n get isValid() {\n return this.valid;\n }\n}\n","import { formatOffset, signedOffset } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet singleton = null;\n\n/**\n * A zone with a fixed offset (meaning no DST)\n * @implements {Zone}\n */\nexport default class FixedOffsetZone extends Zone {\n /**\n * Get a singleton instance of UTC\n * @return {FixedOffsetZone}\n */\n static get utcInstance() {\n if (singleton === null) {\n singleton = new FixedOffsetZone(0);\n }\n return singleton;\n }\n\n /**\n * Get an instance with a specified offset\n * @param {number} offset - The offset in minutes\n * @return {FixedOffsetZone}\n */\n static instance(offset) {\n return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset);\n }\n\n /**\n * Get an instance of FixedOffsetZone from a UTC offset string, like \"UTC+6\"\n * @param {string} s - The offset string to parse\n * @example FixedOffsetZone.parseSpecifier(\"UTC+6\")\n * @example FixedOffsetZone.parseSpecifier(\"UTC+06\")\n * @example FixedOffsetZone.parseSpecifier(\"UTC-6:00\")\n * @return {FixedOffsetZone}\n */\n static parseSpecifier(s) {\n if (s) {\n const r = s.match(/^utc(?:([+-]\\d{1,2})(?::(\\d{2}))?)?$/i);\n if (r) {\n return new FixedOffsetZone(signedOffset(r[1], r[2]));\n }\n }\n return null;\n }\n\n constructor(offset) {\n super();\n /** @private **/\n this.fixed = offset;\n }\n\n /** @override **/\n get type() {\n return \"fixed\";\n }\n\n /** @override **/\n get name() {\n return this.fixed === 0 ? \"UTC\" : `UTC${formatOffset(this.fixed, \"narrow\")}`;\n }\n\n get ianaName() {\n if (this.fixed === 0) {\n return \"Etc/UTC\";\n } else {\n return `Etc/GMT${formatOffset(-this.fixed, \"narrow\")}`;\n }\n }\n\n /** @override **/\n offsetName() {\n return this.name;\n }\n\n /** @override **/\n formatOffset(ts, format) {\n return formatOffset(this.fixed, format);\n }\n\n /** @override **/\n get isUniversal() {\n return true;\n }\n\n /** @override **/\n offset() {\n return this.fixed;\n }\n\n /** @override **/\n equals(otherZone) {\n return otherZone.type === \"fixed\" && otherZone.fixed === this.fixed;\n }\n\n /** @override **/\n get isValid() {\n return true;\n }\n}\n","import Zone from \"../zone.js\";\n\n/**\n * A zone that failed to parse. You should never need to instantiate this.\n * @implements {Zone}\n */\nexport default class InvalidZone extends Zone {\n constructor(zoneName) {\n super();\n /** @private */\n this.zoneName = zoneName;\n }\n\n /** @override **/\n get type() {\n return \"invalid\";\n }\n\n /** @override **/\n get name() {\n return this.zoneName;\n }\n\n /** @override **/\n get isUniversal() {\n return false;\n }\n\n /** @override **/\n offsetName() {\n return null;\n }\n\n /** @override **/\n formatOffset() {\n return \"\";\n }\n\n /** @override **/\n offset() {\n return NaN;\n }\n\n /** @override **/\n equals() {\n return false;\n }\n\n /** @override **/\n get isValid() {\n return false;\n }\n}\n","/**\n * @private\n */\n\nimport Zone from \"../zone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport InvalidZone from \"../zones/invalidZone.js\";\n\nimport { isUndefined, isString, isNumber } from \"./util.js\";\n\nexport function normalizeZone(input, defaultZone) {\n let offset;\n if (isUndefined(input) || input === null) {\n return defaultZone;\n } else if (input instanceof Zone) {\n return input;\n } else if (isString(input)) {\n const lowered = input.toLowerCase();\n if (lowered === \"local\" || lowered === \"system\") return defaultZone;\n else if (lowered === \"utc\" || lowered === \"gmt\") return FixedOffsetZone.utcInstance;\n else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input);\n } else if (isNumber(input)) {\n return FixedOffsetZone.instance(input);\n } else if (typeof input === \"object\" && input.offset && typeof input.offset === \"number\") {\n // This is dumb, but the instanceof check above doesn't seem to really work\n // so we're duck checking it\n return input;\n } else {\n return new InvalidZone(input);\n }\n}\n","import SystemZone from \"./zones/systemZone.js\";\nimport IANAZone from \"./zones/IANAZone.js\";\nimport Locale from \"./impl/locale.js\";\n\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\n\nlet now = () => Date.now(),\n defaultZone = \"system\",\n defaultLocale = null,\n defaultNumberingSystem = null,\n defaultOutputCalendar = null,\n throwOnInvalid;\n\n/**\n * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here.\n */\nexport default class Settings {\n /**\n * Get the callback for returning the current timestamp.\n * @type {function}\n */\n static get now() {\n return now;\n }\n\n /**\n * Set the callback for returning the current timestamp.\n * The function should return a number, which will be interpreted as an Epoch millisecond count\n * @type {function}\n * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future\n * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time\n */\n static set now(n) {\n now = n;\n }\n\n /**\n * Set the default time zone to create DateTimes in. Does not affect existing instances.\n * Use the value \"system\" to reset this value to the system's time zone.\n * @type {string}\n */\n static set defaultZone(zone) {\n defaultZone = zone;\n }\n\n /**\n * Get the default time zone object currently used to create DateTimes. Does not affect existing instances.\n * The default value is the system's time zone (the one set on the machine that runs this code).\n * @type {Zone}\n */\n static get defaultZone() {\n return normalizeZone(defaultZone, SystemZone.instance);\n }\n\n /**\n * Get the default locale to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static get defaultLocale() {\n return defaultLocale;\n }\n\n /**\n * Set the default locale to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static set defaultLocale(locale) {\n defaultLocale = locale;\n }\n\n /**\n * Get the default numbering system to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static get defaultNumberingSystem() {\n return defaultNumberingSystem;\n }\n\n /**\n * Set the default numbering system to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static set defaultNumberingSystem(numberingSystem) {\n defaultNumberingSystem = numberingSystem;\n }\n\n /**\n * Get the default output calendar to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static get defaultOutputCalendar() {\n return defaultOutputCalendar;\n }\n\n /**\n * Set the default output calendar to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static set defaultOutputCalendar(outputCalendar) {\n defaultOutputCalendar = outputCalendar;\n }\n\n /**\n * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals\n * @type {boolean}\n */\n static get throwOnInvalid() {\n return throwOnInvalid;\n }\n\n /**\n * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals\n * @type {boolean}\n */\n static set throwOnInvalid(t) {\n throwOnInvalid = t;\n }\n\n /**\n * Reset Luxon's global caches. Should only be necessary in testing scenarios.\n * @return {void}\n */\n static resetCaches() {\n Locale.resetCache();\n IANAZone.resetCache();\n }\n}\n","import { padStart, roundTo, hasRelative } from \"./util.js\";\nimport * as English from \"./english.js\";\nimport Settings from \"../settings.js\";\nimport DateTime from \"../datetime.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\n\n// todo - remap caching\n\nlet intlLFCache = {};\nfunction getCachedLF(locString, opts = {}) {\n const key = JSON.stringify([locString, opts]);\n let dtf = intlLFCache[key];\n if (!dtf) {\n dtf = new Intl.ListFormat(locString, opts);\n intlLFCache[key] = dtf;\n }\n return dtf;\n}\n\nlet intlDTCache = {};\nfunction getCachedDTF(locString, opts = {}) {\n const key = JSON.stringify([locString, opts]);\n let dtf = intlDTCache[key];\n if (!dtf) {\n dtf = new Intl.DateTimeFormat(locString, opts);\n intlDTCache[key] = dtf;\n }\n return dtf;\n}\n\nlet intlNumCache = {};\nfunction getCachedINF(locString, opts = {}) {\n const key = JSON.stringify([locString, opts]);\n let inf = intlNumCache[key];\n if (!inf) {\n inf = new Intl.NumberFormat(locString, opts);\n intlNumCache[key] = inf;\n }\n return inf;\n}\n\nlet intlRelCache = {};\nfunction getCachedRTF(locString, opts = {}) {\n const { base, ...cacheKeyOpts } = opts; // exclude `base` from the options\n const key = JSON.stringify([locString, cacheKeyOpts]);\n let inf = intlRelCache[key];\n if (!inf) {\n inf = new Intl.RelativeTimeFormat(locString, opts);\n intlRelCache[key] = inf;\n }\n return inf;\n}\n\nlet sysLocaleCache = null;\nfunction systemLocale() {\n if (sysLocaleCache) {\n return sysLocaleCache;\n } else {\n sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale;\n return sysLocaleCache;\n }\n}\n\nfunction parseLocaleString(localeStr) {\n // I really want to avoid writing a BCP 47 parser\n // see, e.g. https://github.com/wooorm/bcp-47\n // Instead, we'll do this:\n\n // a) if the string has no -u extensions, just leave it alone\n // b) if it does, use Intl to resolve everything\n // c) if Intl fails, try again without the -u\n\n const uIndex = localeStr.indexOf(\"-u-\");\n if (uIndex === -1) {\n return [localeStr];\n } else {\n let options;\n const smaller = localeStr.substring(0, uIndex);\n try {\n options = getCachedDTF(localeStr).resolvedOptions();\n } catch (e) {\n options = getCachedDTF(smaller).resolvedOptions();\n }\n\n const { numberingSystem, calendar } = options;\n // return the smaller one so that we can append the calendar and numbering overrides to it\n return [smaller, numberingSystem, calendar];\n }\n}\n\nfunction intlConfigString(localeStr, numberingSystem, outputCalendar) {\n if (outputCalendar || numberingSystem) {\n localeStr += \"-u\";\n\n if (outputCalendar) {\n localeStr += `-ca-${outputCalendar}`;\n }\n\n if (numberingSystem) {\n localeStr += `-nu-${numberingSystem}`;\n }\n return localeStr;\n } else {\n return localeStr;\n }\n}\n\nfunction mapMonths(f) {\n const ms = [];\n for (let i = 1; i <= 12; i++) {\n const dt = DateTime.utc(2016, i, 1);\n ms.push(f(dt));\n }\n return ms;\n}\n\nfunction mapWeekdays(f) {\n const ms = [];\n for (let i = 1; i <= 7; i++) {\n const dt = DateTime.utc(2016, 11, 13 + i);\n ms.push(f(dt));\n }\n return ms;\n}\n\nfunction listStuff(loc, length, defaultOK, englishFn, intlFn) {\n const mode = loc.listingMode(defaultOK);\n\n if (mode === \"error\") {\n return null;\n } else if (mode === \"en\") {\n return englishFn(length);\n } else {\n return intlFn(length);\n }\n}\n\nfunction supportsFastNumbers(loc) {\n if (loc.numberingSystem && loc.numberingSystem !== \"latn\") {\n return false;\n } else {\n return (\n loc.numberingSystem === \"latn\" ||\n !loc.locale ||\n loc.locale.startsWith(\"en\") ||\n new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === \"latn\"\n );\n }\n}\n\n/**\n * @private\n */\n\nclass PolyNumberFormatter {\n constructor(intl, forceSimple, opts) {\n this.padTo = opts.padTo || 0;\n this.floor = opts.floor || false;\n\n const { padTo, floor, ...otherOpts } = opts;\n\n if (!forceSimple || Object.keys(otherOpts).length > 0) {\n const intlOpts = { useGrouping: false, ...opts };\n if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo;\n this.inf = getCachedINF(intl, intlOpts);\n }\n }\n\n format(i) {\n if (this.inf) {\n const fixed = this.floor ? Math.floor(i) : i;\n return this.inf.format(fixed);\n } else {\n // to match the browser's numberformatter defaults\n const fixed = this.floor ? Math.floor(i) : roundTo(i, 3);\n return padStart(fixed, this.padTo);\n }\n }\n}\n\n/**\n * @private\n */\n\nclass PolyDateFormatter {\n constructor(dt, intl, opts) {\n this.opts = opts;\n\n let z;\n if (dt.zone.isUniversal) {\n // UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like.\n // That is why fixed-offset TZ is set to that unless it is:\n // 1. Representing offset 0 when UTC is used to maintain previous behavior and does not become GMT.\n // 2. Unsupported by the browser:\n // - some do not support Etc/\n // - < Etc/GMT-14, > Etc/GMT+12, and 30-minute or 45-minute offsets are not part of tzdata\n const gmtOffset = -1 * (dt.offset / 60);\n const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`;\n if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) {\n z = offsetZ;\n this.dt = dt;\n } else {\n // Not all fixed-offset zones like Etc/+4:30 are present in tzdata.\n // So we have to make do. Two cases:\n // 1. The format options tell us to show the zone. We can't do that, so the best\n // we can do is format the date in UTC.\n // 2. The format options don't tell us to show the zone. Then we can adjust them\n // the time and tell the formatter to show it to us in UTC, so that the time is right\n // and the bad zone doesn't show up.\n z = \"UTC\";\n if (opts.timeZoneName) {\n this.dt = dt;\n } else {\n this.dt = dt.offset === 0 ? dt : DateTime.fromMillis(dt.ts + dt.offset * 60 * 1000);\n }\n }\n } else if (dt.zone.type === \"system\") {\n this.dt = dt;\n } else {\n this.dt = dt;\n z = dt.zone.name;\n }\n\n const intlOpts = { ...this.opts };\n if (z) {\n intlOpts.timeZone = z;\n }\n this.dtf = getCachedDTF(intl, intlOpts);\n }\n\n format() {\n return this.dtf.format(this.dt.toJSDate());\n }\n\n formatToParts() {\n return this.dtf.formatToParts(this.dt.toJSDate());\n }\n\n resolvedOptions() {\n return this.dtf.resolvedOptions();\n }\n}\n\n/**\n * @private\n */\nclass PolyRelFormatter {\n constructor(intl, isEnglish, opts) {\n this.opts = { style: \"long\", ...opts };\n if (!isEnglish && hasRelative()) {\n this.rtf = getCachedRTF(intl, opts);\n }\n }\n\n format(count, unit) {\n if (this.rtf) {\n return this.rtf.format(count, unit);\n } else {\n return English.formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== \"long\");\n }\n }\n\n formatToParts(count, unit) {\n if (this.rtf) {\n return this.rtf.formatToParts(count, unit);\n } else {\n return [];\n }\n }\n}\n\n/**\n * @private\n */\n\nexport default class Locale {\n static fromOpts(opts) {\n return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN);\n }\n\n static create(locale, numberingSystem, outputCalendar, defaultToEN = false) {\n const specifiedLocale = locale || Settings.defaultLocale;\n // the system locale is useful for human readable strings but annoying for parsing/formatting known formats\n const localeR = specifiedLocale || (defaultToEN ? \"en-US\" : systemLocale());\n const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem;\n const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;\n return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale);\n }\n\n static resetCache() {\n sysLocaleCache = null;\n intlDTCache = {};\n intlNumCache = {};\n intlRelCache = {};\n }\n\n static fromObject({ locale, numberingSystem, outputCalendar } = {}) {\n return Locale.create(locale, numberingSystem, outputCalendar);\n }\n\n constructor(locale, numbering, outputCalendar, specifiedLocale) {\n const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale);\n\n this.locale = parsedLocale;\n this.numberingSystem = numbering || parsedNumberingSystem || null;\n this.outputCalendar = outputCalendar || parsedOutputCalendar || null;\n this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);\n\n this.weekdaysCache = { format: {}, standalone: {} };\n this.monthsCache = { format: {}, standalone: {} };\n this.meridiemCache = null;\n this.eraCache = {};\n\n this.specifiedLocale = specifiedLocale;\n this.fastNumbersCached = null;\n }\n\n get fastNumbers() {\n if (this.fastNumbersCached == null) {\n this.fastNumbersCached = supportsFastNumbers(this);\n }\n\n return this.fastNumbersCached;\n }\n\n listingMode() {\n const isActuallyEn = this.isEnglish();\n const hasNoWeirdness =\n (this.numberingSystem === null || this.numberingSystem === \"latn\") &&\n (this.outputCalendar === null || this.outputCalendar === \"gregory\");\n return isActuallyEn && hasNoWeirdness ? \"en\" : \"intl\";\n }\n\n clone(alts) {\n if (!alts || Object.getOwnPropertyNames(alts).length === 0) {\n return this;\n } else {\n return Locale.create(\n alts.locale || this.specifiedLocale,\n alts.numberingSystem || this.numberingSystem,\n alts.outputCalendar || this.outputCalendar,\n alts.defaultToEN || false\n );\n }\n }\n\n redefaultToEN(alts = {}) {\n return this.clone({ ...alts, defaultToEN: true });\n }\n\n redefaultToSystem(alts = {}) {\n return this.clone({ ...alts, defaultToEN: false });\n }\n\n months(length, format = false, defaultOK = true) {\n return listStuff(this, length, defaultOK, English.months, () => {\n const intl = format ? { month: length, day: \"numeric\" } : { month: length },\n formatStr = format ? \"format\" : \"standalone\";\n if (!this.monthsCache[formatStr][length]) {\n this.monthsCache[formatStr][length] = mapMonths((dt) => this.extract(dt, intl, \"month\"));\n }\n return this.monthsCache[formatStr][length];\n });\n }\n\n weekdays(length, format = false, defaultOK = true) {\n return listStuff(this, length, defaultOK, English.weekdays, () => {\n const intl = format\n ? { weekday: length, year: \"numeric\", month: \"long\", day: \"numeric\" }\n : { weekday: length },\n formatStr = format ? \"format\" : \"standalone\";\n if (!this.weekdaysCache[formatStr][length]) {\n this.weekdaysCache[formatStr][length] = mapWeekdays((dt) =>\n this.extract(dt, intl, \"weekday\")\n );\n }\n return this.weekdaysCache[formatStr][length];\n });\n }\n\n meridiems(defaultOK = true) {\n return listStuff(\n this,\n undefined,\n defaultOK,\n () => English.meridiems,\n () => {\n // In theory there could be aribitrary day periods. We're gonna assume there are exactly two\n // for AM and PM. This is probably wrong, but it's makes parsing way easier.\n if (!this.meridiemCache) {\n const intl = { hour: \"numeric\", hourCycle: \"h12\" };\n this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(\n (dt) => this.extract(dt, intl, \"dayperiod\")\n );\n }\n\n return this.meridiemCache;\n }\n );\n }\n\n eras(length, defaultOK = true) {\n return listStuff(this, length, defaultOK, English.eras, () => {\n const intl = { era: length };\n\n // This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates\n // to definitely enumerate them.\n if (!this.eraCache[length]) {\n this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map((dt) =>\n this.extract(dt, intl, \"era\")\n );\n }\n\n return this.eraCache[length];\n });\n }\n\n extract(dt, intlOpts, field) {\n const df = this.dtFormatter(dt, intlOpts),\n results = df.formatToParts(),\n matching = results.find((m) => m.type.toLowerCase() === field);\n return matching ? matching.value : null;\n }\n\n numberFormatter(opts = {}) {\n // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave)\n // (in contrast, the rest of the condition is used heavily)\n return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);\n }\n\n dtFormatter(dt, intlOpts = {}) {\n return new PolyDateFormatter(dt, this.intl, intlOpts);\n }\n\n relFormatter(opts = {}) {\n return new PolyRelFormatter(this.intl, this.isEnglish(), opts);\n }\n\n listFormatter(opts = {}) {\n return getCachedLF(this.intl, opts);\n }\n\n isEnglish() {\n return (\n this.locale === \"en\" ||\n this.locale.toLowerCase() === \"en-us\" ||\n new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith(\"en-us\")\n );\n }\n\n equals(other) {\n return (\n this.locale === other.locale &&\n this.numberingSystem === other.numberingSystem &&\n this.outputCalendar === other.outputCalendar\n );\n }\n}\n","import {\n untruncateYear,\n signedOffset,\n parseInteger,\n parseMillis,\n ianaRegex,\n isUndefined,\n parseFloating\n} from \"./util.js\";\nimport * as English from \"./english.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\n\n/*\n * This file handles parsing for well-specified formats. Here's how it works:\n * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match.\n * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object\n * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence.\n * Extractors can take a \"cursor\" representing the offset in the match to look at. This makes it easy to combine extractors.\n * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions.\n * Some extractions are super dumb and simpleParse and fromStrings help DRY them.\n */\n\nfunction combineRegexes(...regexes) {\n const full = regexes.reduce((f, r) => f + r.source, \"\");\n return RegExp(`^${full}$`);\n}\n\nfunction combineExtractors(...extractors) {\n return m =>\n extractors\n .reduce(\n ([mergedVals, mergedZone, cursor], ex) => {\n const [val, zone, next] = ex(m, cursor);\n return [{ ...mergedVals, ...val }, zone || mergedZone, next];\n },\n [{}, null, 1]\n )\n .slice(0, 2);\n}\n\nfunction parse(s, ...patterns) {\n if (s == null) {\n return [null, null];\n }\n\n for (const [regex, extractor] of patterns) {\n const m = regex.exec(s);\n if (m) {\n return extractor(m);\n }\n }\n return [null, null];\n}\n\nfunction simpleParse(...keys) {\n return (match, cursor) => {\n const ret = {};\n let i;\n\n for (i = 0; i < keys.length; i++) {\n ret[keys[i]] = parseInteger(match[cursor + i]);\n }\n return [ret, null, cursor + i];\n };\n}\n\n// ISO and SQL parsing\nconst offsetRegex = /(?:(Z)|([+-]\\d\\d)(?::?(\\d\\d))?)/;\nconst isoExtendedZone = `(?:${offsetRegex.source}?(?:\\\\[(${ianaRegex.source})\\\\])?)?`;\nconst isoTimeBaseRegex = /(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:[.,](\\d{1,30}))?)?)?/;\nconst isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`);\nconst isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`);\nconst isoYmdRegex = /([+-]\\d{6}|\\d{4})(?:-?(\\d\\d)(?:-?(\\d\\d))?)?/;\nconst isoWeekRegex = /(\\d{4})-?W(\\d\\d)(?:-?(\\d))?/;\nconst isoOrdinalRegex = /(\\d{4})-?(\\d{3})/;\nconst extractISOWeekData = simpleParse(\"weekYear\", \"weekNumber\", \"weekDay\");\nconst extractISOOrdinalData = simpleParse(\"year\", \"ordinal\");\nconst sqlYmdRegex = /(\\d{4})-(\\d\\d)-(\\d\\d)/; // dumbed-down version of the ISO one\nconst sqlTimeRegex = RegExp(\n `${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`\n);\nconst sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`);\n\nfunction int(match, pos, fallback) {\n const m = match[pos];\n return isUndefined(m) ? fallback : parseInteger(m);\n}\n\nfunction extractISOYmd(match, cursor) {\n const item = {\n year: int(match, cursor),\n month: int(match, cursor + 1, 1),\n day: int(match, cursor + 2, 1)\n };\n\n return [item, null, cursor + 3];\n}\n\nfunction extractISOTime(match, cursor) {\n const item = {\n hours: int(match, cursor, 0),\n minutes: int(match, cursor + 1, 0),\n seconds: int(match, cursor + 2, 0),\n milliseconds: parseMillis(match[cursor + 3])\n };\n\n return [item, null, cursor + 4];\n}\n\nfunction extractISOOffset(match, cursor) {\n const local = !match[cursor] && !match[cursor + 1],\n fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]),\n zone = local ? null : FixedOffsetZone.instance(fullOffset);\n return [{}, zone, cursor + 3];\n}\n\nfunction extractIANAZone(match, cursor) {\n const zone = match[cursor] ? IANAZone.create(match[cursor]) : null;\n return [{}, zone, cursor + 1];\n}\n\n// ISO time parsing\n\nconst isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`);\n\n// ISO duration parsing\n\nconst isoDuration = /^-?P(?:(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)Y)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)W)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)D)?(?:T(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)H)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20})(?:[.,](-?\\d{1,20}))?S)?)?)$/;\n\nfunction extractISODuration(match) {\n const [\n s,\n yearStr,\n monthStr,\n weekStr,\n dayStr,\n hourStr,\n minuteStr,\n secondStr,\n millisecondsStr\n ] = match;\n\n const hasNegativePrefix = s[0] === \"-\";\n const negativeSeconds = secondStr && secondStr[0] === \"-\";\n\n const maybeNegate = (num, force = false) =>\n num !== undefined && (force || (num && hasNegativePrefix)) ? -num : num;\n\n return [\n {\n years: maybeNegate(parseFloating(yearStr)),\n months: maybeNegate(parseFloating(monthStr)),\n weeks: maybeNegate(parseFloating(weekStr)),\n days: maybeNegate(parseFloating(dayStr)),\n hours: maybeNegate(parseFloating(hourStr)),\n minutes: maybeNegate(parseFloating(minuteStr)),\n seconds: maybeNegate(parseFloating(secondStr), secondStr === \"-0\"),\n milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds)\n }\n ];\n}\n\n// These are a little braindead. EDT *should* tell us that we're in, say, America/New_York\n// and not just that we're in -240 *right now*. But since I don't think these are used that often\n// I'm just going to ignore that\nconst obsOffsets = {\n GMT: 0,\n EDT: -4 * 60,\n EST: -5 * 60,\n CDT: -5 * 60,\n CST: -6 * 60,\n MDT: -6 * 60,\n MST: -7 * 60,\n PDT: -7 * 60,\n PST: -8 * 60\n};\n\nfunction fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {\n const result = {\n year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),\n month: English.monthsShort.indexOf(monthStr) + 1,\n day: parseInteger(dayStr),\n hour: parseInteger(hourStr),\n minute: parseInteger(minuteStr)\n };\n\n if (secondStr) result.second = parseInteger(secondStr);\n if (weekdayStr) {\n result.weekday =\n weekdayStr.length > 3\n ? English.weekdaysLong.indexOf(weekdayStr) + 1\n : English.weekdaysShort.indexOf(weekdayStr) + 1;\n }\n\n return result;\n}\n\n// RFC 2822/5322\nconst rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s)?(\\d{1,2})\\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s(\\d{2,4})\\s(\\d\\d):(\\d\\d)(?::(\\d\\d))?\\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\\d\\d)(\\d\\d)))$/;\n\nfunction extractRFC2822(match) {\n const [\n ,\n weekdayStr,\n dayStr,\n monthStr,\n yearStr,\n hourStr,\n minuteStr,\n secondStr,\n obsOffset,\n milOffset,\n offHourStr,\n offMinuteStr\n ] = match,\n result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n\n let offset;\n if (obsOffset) {\n offset = obsOffsets[obsOffset];\n } else if (milOffset) {\n offset = 0;\n } else {\n offset = signedOffset(offHourStr, offMinuteStr);\n }\n\n return [result, new FixedOffsetZone(offset)];\n}\n\nfunction preprocessRFC2822(s) {\n // Remove comments and folding whitespace and replace multiple-spaces with a single space\n return s\n .replace(/\\([^()]*\\)|[\\n\\t]/g, \" \")\n .replace(/(\\s\\s+)/g, \" \")\n .trim();\n}\n\n// http date\n\nconst rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d\\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\\d{4}) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,\n rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d\\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,\n ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \\d|\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) (\\d{4})$/;\n\nfunction extractRFC1123Or850(match) {\n const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match,\n result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n return [result, FixedOffsetZone.utcInstance];\n}\n\nfunction extractASCII(match) {\n const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match,\n result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n return [result, FixedOffsetZone.utcInstance];\n}\n\nconst isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);\nconst isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);\nconst isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);\nconst isoTimeCombinedRegex = combineRegexes(isoTimeRegex);\n\nconst extractISOYmdTimeAndOffset = combineExtractors(\n extractISOYmd,\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\nconst extractISOWeekTimeAndOffset = combineExtractors(\n extractISOWeekData,\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\nconst extractISOOrdinalDateAndTime = combineExtractors(\n extractISOOrdinalData,\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\nconst extractISOTimeAndOffset = combineExtractors(\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\n\n/*\n * @private\n */\n\nexport function parseISODate(s) {\n return parse(\n s,\n [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],\n [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset],\n [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime],\n [isoTimeCombinedRegex, extractISOTimeAndOffset]\n );\n}\n\nexport function parseRFC2822Date(s) {\n return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]);\n}\n\nexport function parseHTTPDate(s) {\n return parse(\n s,\n [rfc1123, extractRFC1123Or850],\n [rfc850, extractRFC1123Or850],\n [ascii, extractASCII]\n );\n}\n\nexport function parseISODuration(s) {\n return parse(s, [isoDuration, extractISODuration]);\n}\n\nconst extractISOTimeOnly = combineExtractors(extractISOTime);\n\nexport function parseISOTimeOnly(s) {\n return parse(s, [isoTimeOnly, extractISOTimeOnly]);\n}\n\nconst sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);\nconst sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);\n\nconst extractISOTimeOffsetAndIANAZone = combineExtractors(\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\n\nexport function parseSQL(s) {\n return parse(\n s,\n [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],\n [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]\n );\n}\n","import { InvalidArgumentError, InvalidDurationError, InvalidUnitError } from \"./errors.js\";\nimport Formatter from \"./impl/formatter.js\";\nimport Invalid from \"./impl/invalid.js\";\nimport Locale from \"./impl/locale.js\";\nimport { parseISODuration, parseISOTimeOnly } from \"./impl/regexParser.js\";\nimport {\n asNumber,\n hasOwnProperty,\n isNumber,\n isUndefined,\n normalizeObject,\n roundTo,\n} from \"./impl/util.js\";\nimport Settings from \"./settings.js\";\n\nconst INVALID = \"Invalid Duration\";\n\n// unit conversion constants\nexport const lowOrderMatrix = {\n weeks: {\n days: 7,\n hours: 7 * 24,\n minutes: 7 * 24 * 60,\n seconds: 7 * 24 * 60 * 60,\n milliseconds: 7 * 24 * 60 * 60 * 1000,\n },\n days: {\n hours: 24,\n minutes: 24 * 60,\n seconds: 24 * 60 * 60,\n milliseconds: 24 * 60 * 60 * 1000,\n },\n hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 },\n minutes: { seconds: 60, milliseconds: 60 * 1000 },\n seconds: { milliseconds: 1000 },\n },\n casualMatrix = {\n years: {\n quarters: 4,\n months: 12,\n weeks: 52,\n days: 365,\n hours: 365 * 24,\n minutes: 365 * 24 * 60,\n seconds: 365 * 24 * 60 * 60,\n milliseconds: 365 * 24 * 60 * 60 * 1000,\n },\n quarters: {\n months: 3,\n weeks: 13,\n days: 91,\n hours: 91 * 24,\n minutes: 91 * 24 * 60,\n seconds: 91 * 24 * 60 * 60,\n milliseconds: 91 * 24 * 60 * 60 * 1000,\n },\n months: {\n weeks: 4,\n days: 30,\n hours: 30 * 24,\n minutes: 30 * 24 * 60,\n seconds: 30 * 24 * 60 * 60,\n milliseconds: 30 * 24 * 60 * 60 * 1000,\n },\n\n ...lowOrderMatrix,\n },\n daysInYearAccurate = 146097.0 / 400,\n daysInMonthAccurate = 146097.0 / 4800,\n accurateMatrix = {\n years: {\n quarters: 4,\n months: 12,\n weeks: daysInYearAccurate / 7,\n days: daysInYearAccurate,\n hours: daysInYearAccurate * 24,\n minutes: daysInYearAccurate * 24 * 60,\n seconds: daysInYearAccurate * 24 * 60 * 60,\n milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000,\n },\n quarters: {\n months: 3,\n weeks: daysInYearAccurate / 28,\n days: daysInYearAccurate / 4,\n hours: (daysInYearAccurate * 24) / 4,\n minutes: (daysInYearAccurate * 24 * 60) / 4,\n seconds: (daysInYearAccurate * 24 * 60 * 60) / 4,\n milliseconds: (daysInYearAccurate * 24 * 60 * 60 * 1000) / 4,\n },\n months: {\n weeks: daysInMonthAccurate / 7,\n days: daysInMonthAccurate,\n hours: daysInMonthAccurate * 24,\n minutes: daysInMonthAccurate * 24 * 60,\n seconds: daysInMonthAccurate * 24 * 60 * 60,\n milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000,\n },\n ...lowOrderMatrix,\n };\n\n// units ordered by size\nconst orderedUnits = [\n \"years\",\n \"quarters\",\n \"months\",\n \"weeks\",\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n \"milliseconds\",\n];\n\nconst reverseUnits = orderedUnits.slice(0).reverse();\n\n// clone really means \"create another instance just like this one, but with these changes\"\nfunction clone(dur, alts, clear = false) {\n // deep merge for vals\n const conf = {\n values: clear ? alts.values : { ...dur.values, ...(alts.values || {}) },\n loc: dur.loc.clone(alts.loc),\n conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,\n };\n return new Duration(conf);\n}\n\nfunction antiTrunc(n) {\n return n < 0 ? Math.floor(n) : Math.ceil(n);\n}\n\n// NB: mutates parameters\nfunction convert(matrix, fromMap, fromUnit, toMap, toUnit) {\n const conv = matrix[toUnit][fromUnit],\n raw = fromMap[fromUnit] / conv,\n sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]),\n // ok, so this is wild, but see the matrix in the tests\n added =\n !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw);\n toMap[toUnit] += added;\n fromMap[fromUnit] -= added * conv;\n}\n\n// NB: mutates parameters\nfunction normalizeValues(matrix, vals) {\n reverseUnits.reduce((previous, current) => {\n if (!isUndefined(vals[current])) {\n if (previous) {\n convert(matrix, vals, previous, vals, current);\n }\n return current;\n } else {\n return previous;\n }\n }, null);\n}\n\n/**\n * A Duration object represents a period of time, like \"2 months\" or \"1 day, 1 hour\". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime#plus} to add a Duration object to a DateTime, producing another DateTime.\n *\n * Here is a brief overview of commonly used methods and getters in Duration:\n *\n * * **Creation** To create a Duration, use {@link Duration#fromMillis}, {@link Duration#fromObject}, or {@link Duration#fromISO}.\n * * **Unit values** See the {@link Duration#years}, {@link Duration#months}, {@link Duration#weeks}, {@link Duration#days}, {@link Duration#hours}, {@link Duration#minutes}, {@link Duration#seconds}, {@link Duration#milliseconds} accessors.\n * * **Configuration** See {@link Duration#locale} and {@link Duration#numberingSystem} accessors.\n * * **Transformation** To create new Durations out of old ones use {@link Duration#plus}, {@link Duration#minus}, {@link Duration#normalize}, {@link Duration#set}, {@link Duration#reconfigure}, {@link Duration#shiftTo}, and {@link Duration#negate}.\n * * **Output** To convert the Duration into other representations, see {@link Duration#as}, {@link Duration#toISO}, {@link Duration#toFormat}, and {@link Duration#toJSON}\n *\n * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation.\n */\nexport default class Duration {\n /**\n * @private\n */\n constructor(config) {\n const accurate = config.conversionAccuracy === \"longterm\" || false;\n /**\n * @access private\n */\n this.values = config.values;\n /**\n * @access private\n */\n this.loc = config.loc || Locale.create();\n /**\n * @access private\n */\n this.conversionAccuracy = accurate ? \"longterm\" : \"casual\";\n /**\n * @access private\n */\n this.invalid = config.invalid || null;\n /**\n * @access private\n */\n this.matrix = accurate ? accurateMatrix : casualMatrix;\n /**\n * @access private\n */\n this.isLuxonDuration = true;\n }\n\n /**\n * Create Duration from a number of milliseconds.\n * @param {number} count of milliseconds\n * @param {Object} opts - options for parsing\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @return {Duration}\n */\n static fromMillis(count, opts) {\n return Duration.fromObject({ milliseconds: count }, opts);\n }\n\n /**\n * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.\n * If this object is empty then a zero milliseconds duration is returned.\n * @param {Object} obj - the object to create the DateTime from\n * @param {number} obj.years\n * @param {number} obj.quarters\n * @param {number} obj.months\n * @param {number} obj.weeks\n * @param {number} obj.days\n * @param {number} obj.hours\n * @param {number} obj.minutes\n * @param {number} obj.seconds\n * @param {number} obj.milliseconds\n * @param {Object} [opts=[]] - options for creating this Duration\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @return {Duration}\n */\n static fromObject(obj, opts = {}) {\n if (obj == null || typeof obj !== \"object\") {\n throw new InvalidArgumentError(\n `Duration.fromObject: argument expected to be an object, got ${\n obj === null ? \"null\" : typeof obj\n }`\n );\n }\n\n return new Duration({\n values: normalizeObject(obj, Duration.normalizeUnit),\n loc: Locale.fromObject(opts),\n conversionAccuracy: opts.conversionAccuracy,\n });\n }\n\n /**\n * Create a Duration from DurationLike.\n *\n * @param {Object | number | Duration} durationLike\n * One of:\n * - object with keys like 'years' and 'hours'.\n * - number representing milliseconds\n * - Duration instance\n * @return {Duration}\n */\n static fromDurationLike(durationLike) {\n if (isNumber(durationLike)) {\n return Duration.fromMillis(durationLike);\n } else if (Duration.isDuration(durationLike)) {\n return durationLike;\n } else if (typeof durationLike === \"object\") {\n return Duration.fromObject(durationLike);\n } else {\n throw new InvalidArgumentError(\n `Unknown duration argument ${durationLike} of type ${typeof durationLike}`\n );\n }\n }\n\n /**\n * Create a Duration from an ISO 8601 duration string.\n * @param {string} text - text to parse\n * @param {Object} opts - options for parsing\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @see https://en.wikipedia.org/wiki/ISO_8601#Durations\n * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }\n * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }\n * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }\n * @return {Duration}\n */\n static fromISO(text, opts) {\n const [parsed] = parseISODuration(text);\n if (parsed) {\n return Duration.fromObject(parsed, opts);\n } else {\n return Duration.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n }\n }\n\n /**\n * Create a Duration from an ISO 8601 time string.\n * @param {string} text - text to parse\n * @param {Object} opts - options for parsing\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @see https://en.wikipedia.org/wiki/ISO_8601#Times\n * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }\n * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @return {Duration}\n */\n static fromISOTime(text, opts) {\n const [parsed] = parseISOTimeOnly(text);\n if (parsed) {\n return Duration.fromObject(parsed, opts);\n } else {\n return Duration.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n }\n }\n\n /**\n * Create an invalid Duration.\n * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent\n * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n * @return {Duration}\n */\n static invalid(reason, explanation = null) {\n if (!reason) {\n throw new InvalidArgumentError(\"need to specify a reason the Duration is invalid\");\n }\n\n const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n if (Settings.throwOnInvalid) {\n throw new InvalidDurationError(invalid);\n } else {\n return new Duration({ invalid });\n }\n }\n\n /**\n * @private\n */\n static normalizeUnit(unit) {\n const normalized = {\n year: \"years\",\n years: \"years\",\n quarter: \"quarters\",\n quarters: \"quarters\",\n month: \"months\",\n months: \"months\",\n week: \"weeks\",\n weeks: \"weeks\",\n day: \"days\",\n days: \"days\",\n hour: \"hours\",\n hours: \"hours\",\n minute: \"minutes\",\n minutes: \"minutes\",\n second: \"seconds\",\n seconds: \"seconds\",\n millisecond: \"milliseconds\",\n milliseconds: \"milliseconds\",\n }[unit ? unit.toLowerCase() : unit];\n\n if (!normalized) throw new InvalidUnitError(unit);\n\n return normalized;\n }\n\n /**\n * Check if an object is a Duration. Works across context boundaries\n * @param {object} o\n * @return {boolean}\n */\n static isDuration(o) {\n return (o && o.isLuxonDuration) || false;\n }\n\n /**\n * Get the locale of a Duration, such 'en-GB'\n * @type {string}\n */\n get locale() {\n return this.isValid ? this.loc.locale : null;\n }\n\n /**\n * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration\n *\n * @type {string}\n */\n get numberingSystem() {\n return this.isValid ? this.loc.numberingSystem : null;\n }\n\n /**\n * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:\n * * `S` for milliseconds\n * * `s` for seconds\n * * `m` for minutes\n * * `h` for hours\n * * `d` for days\n * * `w` for weeks\n * * `M` for months\n * * `y` for years\n * Notes:\n * * Add padding by repeating the token, e.g. \"yy\" pads the years to two digits, \"hhhh\" pads the hours out to four digits\n * * Tokens can be escaped by wrapping with single quotes.\n * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.\n * @param {string} fmt - the format string\n * @param {Object} opts - options\n * @param {boolean} [opts.floor=true] - floor numerical values\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"y d s\") //=> \"1 6 2\"\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"yy dd sss\") //=> \"01 06 002\"\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"M S\") //=> \"12 518402000\"\n * @return {string}\n */\n toFormat(fmt, opts = {}) {\n // reverse-compat since 1.2; we always round down now, never up, and we do it by default\n const fmtOpts = {\n ...opts,\n floor: opts.round !== false && opts.floor !== false,\n };\n return this.isValid\n ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt)\n : INVALID;\n }\n\n /**\n * Returns a string representation of a Duration with all units included.\n * To modify its behavior use the `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat\n * @param opts - On option object to override the formatting. Accepts the same keys as the options parameter of the native `Int.NumberFormat` constructor, as well as `listStyle`.\n * @example\n * ```js\n * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 })\n * dur.toHuman() //=> '1 day, 5 hours, 6 minutes'\n * dur.toHuman({ listStyle: \"long\" }) //=> '1 day, 5 hours, and 6 minutes'\n * dur.toHuman({ unitDisplay: \"short\" }) //=> '1 day, 5 hr, 6 min'\n * ```\n */\n toHuman(opts = {}) {\n const l = orderedUnits\n .map((unit) => {\n const val = this.values[unit];\n if (isUndefined(val)) {\n return null;\n }\n return this.loc\n .numberFormatter({ style: \"unit\", unitDisplay: \"long\", ...opts, unit: unit.slice(0, -1) })\n .format(val);\n })\n .filter((n) => n);\n\n return this.loc\n .listFormatter({ type: \"conjunction\", style: opts.listStyle || \"narrow\", ...opts })\n .format(l);\n }\n\n /**\n * Returns a JavaScript object with this Duration's values.\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }\n * @return {Object}\n */\n toObject() {\n if (!this.isValid) return {};\n return { ...this.values };\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this Duration.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Durations\n * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'\n * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'\n * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'\n * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'\n * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'\n * @return {string}\n */\n toISO() {\n // we could use the formatter, but this is an easier way to get the minimum string\n if (!this.isValid) return null;\n\n let s = \"P\";\n if (this.years !== 0) s += this.years + \"Y\";\n if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + \"M\";\n if (this.weeks !== 0) s += this.weeks + \"W\";\n if (this.days !== 0) s += this.days + \"D\";\n if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)\n s += \"T\";\n if (this.hours !== 0) s += this.hours + \"H\";\n if (this.minutes !== 0) s += this.minutes + \"M\";\n if (this.seconds !== 0 || this.milliseconds !== 0)\n // this will handle \"floating point madness\" by removing extra decimal places\n // https://stackoverflow.com/questions/588004/is-floating-point-math-broken\n s += roundTo(this.seconds + this.milliseconds / 1000, 3) + \"S\";\n if (s === \"P\") s += \"T0S\";\n return s;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.\n * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Times\n * @param {Object} opts - options\n * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n * @param {boolean} [opts.includePrefix=false] - include the `T` prefix\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'\n * @return {string}\n */\n toISOTime(opts = {}) {\n if (!this.isValid) return null;\n\n const millis = this.toMillis();\n if (millis < 0 || millis >= 86400000) return null;\n\n opts = {\n suppressMilliseconds: false,\n suppressSeconds: false,\n includePrefix: false,\n format: \"extended\",\n ...opts,\n };\n\n const value = this.shiftTo(\"hours\", \"minutes\", \"seconds\", \"milliseconds\");\n\n let fmt = opts.format === \"basic\" ? \"hhmm\" : \"hh:mm\";\n\n if (!opts.suppressSeconds || value.seconds !== 0 || value.milliseconds !== 0) {\n fmt += opts.format === \"basic\" ? \"ss\" : \":ss\";\n if (!opts.suppressMilliseconds || value.milliseconds !== 0) {\n fmt += \".SSS\";\n }\n }\n\n let str = value.toFormat(fmt);\n\n if (opts.includePrefix) {\n str = \"T\" + str;\n }\n\n return str;\n }\n\n /**\n * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.\n * @return {string}\n */\n toJSON() {\n return this.toISO();\n }\n\n /**\n * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.\n * @return {string}\n */\n toString() {\n return this.toISO();\n }\n\n /**\n * Returns an milliseconds value of this Duration.\n * @return {number}\n */\n toMillis() {\n return this.as(\"milliseconds\");\n }\n\n /**\n * Returns an milliseconds value of this Duration. Alias of {@link toMillis}\n * @return {number}\n */\n valueOf() {\n return this.toMillis();\n }\n\n /**\n * Make this Duration longer by the specified amount. Return a newly-constructed Duration.\n * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n * @return {Duration}\n */\n plus(duration) {\n if (!this.isValid) return this;\n\n const dur = Duration.fromDurationLike(duration),\n result = {};\n\n for (const k of orderedUnits) {\n if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {\n result[k] = dur.get(k) + this.get(k);\n }\n }\n\n return clone(this, { values: result }, true);\n }\n\n /**\n * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.\n * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n * @return {Duration}\n */\n minus(duration) {\n if (!this.isValid) return this;\n\n const dur = Duration.fromDurationLike(duration);\n return this.plus(dur.negate());\n }\n\n /**\n * Scale this Duration by the specified amount. Return a newly-constructed Duration.\n * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.\n * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }\n * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === \"hour\" ? x * 2 : x) //=> { hours: 2, minutes: 30 }\n * @return {Duration}\n */\n mapUnits(fn) {\n if (!this.isValid) return this;\n const result = {};\n for (const k of Object.keys(this.values)) {\n result[k] = asNumber(fn(this.values[k], k));\n }\n return clone(this, { values: result }, true);\n }\n\n /**\n * Get the value of unit.\n * @param {string} unit - a unit such as 'minute' or 'day'\n * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2\n * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0\n * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3\n * @return {number}\n */\n get(unit) {\n return this[Duration.normalizeUnit(unit)];\n }\n\n /**\n * \"Set\" the values of specified units. Return a newly-constructed Duration.\n * @param {Object} values - a mapping of units to numbers\n * @example dur.set({ years: 2017 })\n * @example dur.set({ hours: 8, minutes: 30 })\n * @return {Duration}\n */\n set(values) {\n if (!this.isValid) return this;\n\n const mixed = { ...this.values, ...normalizeObject(values, Duration.normalizeUnit) };\n return clone(this, { values: mixed });\n }\n\n /**\n * \"Set\" the locale and/or numberingSystem. Returns a newly-constructed Duration.\n * @example dur.reconfigure({ locale: 'en-GB' })\n * @return {Duration}\n */\n reconfigure({ locale, numberingSystem, conversionAccuracy } = {}) {\n const loc = this.loc.clone({ locale, numberingSystem }),\n opts = { loc };\n\n if (conversionAccuracy) {\n opts.conversionAccuracy = conversionAccuracy;\n }\n\n return clone(this, opts);\n }\n\n /**\n * Return the length of the duration in the specified unit.\n * @param {string} unit - a unit such as 'minutes' or 'days'\n * @example Duration.fromObject({years: 1}).as('days') //=> 365\n * @example Duration.fromObject({years: 1}).as('months') //=> 12\n * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5\n * @return {number}\n */\n as(unit) {\n return this.isValid ? this.shiftTo(unit).get(unit) : NaN;\n }\n\n /**\n * Reduce this Duration to its canonical representation in its current units.\n * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }\n * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }\n * @return {Duration}\n */\n normalize() {\n if (!this.isValid) return this;\n const vals = this.toObject();\n normalizeValues(this.matrix, vals);\n return clone(this, { values: vals }, true);\n }\n\n /**\n * Convert this Duration into its representation in a different set of units.\n * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }\n * @return {Duration}\n */\n shiftTo(...units) {\n if (!this.isValid) return this;\n\n if (units.length === 0) {\n return this;\n }\n\n units = units.map((u) => Duration.normalizeUnit(u));\n\n const built = {},\n accumulated = {},\n vals = this.toObject();\n let lastUnit;\n\n for (const k of orderedUnits) {\n if (units.indexOf(k) >= 0) {\n lastUnit = k;\n\n let own = 0;\n\n // anything we haven't boiled down yet should get boiled to this unit\n for (const ak in accumulated) {\n own += this.matrix[ak][k] * accumulated[ak];\n accumulated[ak] = 0;\n }\n\n // plus anything that's already in this unit\n if (isNumber(vals[k])) {\n own += vals[k];\n }\n\n const i = Math.trunc(own);\n built[k] = i;\n accumulated[k] = (own * 1000 - i * 1000) / 1000;\n\n // plus anything further down the chain that should be rolled up in to this\n for (const down in vals) {\n if (orderedUnits.indexOf(down) > orderedUnits.indexOf(k)) {\n convert(this.matrix, vals, down, built, k);\n }\n }\n // otherwise, keep it in the wings to boil it later\n } else if (isNumber(vals[k])) {\n accumulated[k] = vals[k];\n }\n }\n\n // anything leftover becomes the decimal for the last unit\n // lastUnit must be defined since units is not empty\n for (const key in accumulated) {\n if (accumulated[key] !== 0) {\n built[lastUnit] +=\n key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];\n }\n }\n\n return clone(this, { values: built }, true).normalize();\n }\n\n /**\n * Return the negative of this Duration.\n * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }\n * @return {Duration}\n */\n negate() {\n if (!this.isValid) return this;\n const negated = {};\n for (const k of Object.keys(this.values)) {\n negated[k] = this.values[k] === 0 ? 0 : -this.values[k];\n }\n return clone(this, { values: negated }, true);\n }\n\n /**\n * Get the years.\n * @type {number}\n */\n get years() {\n return this.isValid ? this.values.years || 0 : NaN;\n }\n\n /**\n * Get the quarters.\n * @type {number}\n */\n get quarters() {\n return this.isValid ? this.values.quarters || 0 : NaN;\n }\n\n /**\n * Get the months.\n * @type {number}\n */\n get months() {\n return this.isValid ? this.values.months || 0 : NaN;\n }\n\n /**\n * Get the weeks\n * @type {number}\n */\n get weeks() {\n return this.isValid ? this.values.weeks || 0 : NaN;\n }\n\n /**\n * Get the days.\n * @type {number}\n */\n get days() {\n return this.isValid ? this.values.days || 0 : NaN;\n }\n\n /**\n * Get the hours.\n * @type {number}\n */\n get hours() {\n return this.isValid ? this.values.hours || 0 : NaN;\n }\n\n /**\n * Get the minutes.\n * @type {number}\n */\n get minutes() {\n return this.isValid ? this.values.minutes || 0 : NaN;\n }\n\n /**\n * Get the seconds.\n * @return {number}\n */\n get seconds() {\n return this.isValid ? this.values.seconds || 0 : NaN;\n }\n\n /**\n * Get the milliseconds.\n * @return {number}\n */\n get milliseconds() {\n return this.isValid ? this.values.milliseconds || 0 : NaN;\n }\n\n /**\n * Returns whether the Duration is invalid. Invalid durations are returned by diff operations\n * on invalid DateTimes or Intervals.\n * @return {boolean}\n */\n get isValid() {\n return this.invalid === null;\n }\n\n /**\n * Returns an error code if this Duration became invalid, or null if the Duration is valid\n * @return {string}\n */\n get invalidReason() {\n return this.invalid ? this.invalid.reason : null;\n }\n\n /**\n * Returns an explanation of why this Duration became invalid, or null if the Duration is valid\n * @type {string}\n */\n get invalidExplanation() {\n return this.invalid ? this.invalid.explanation : null;\n }\n\n /**\n * Equality check\n * Two Durations are equal iff they have the same units and the same values for each unit.\n * @param {Duration} other\n * @return {boolean}\n */\n equals(other) {\n if (!this.isValid || !other.isValid) {\n return false;\n }\n\n if (!this.loc.equals(other.loc)) {\n return false;\n }\n\n function eq(v1, v2) {\n // Consider 0 and undefined as equal\n if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0;\n return v1 === v2;\n }\n\n for (const u of orderedUnits) {\n if (!eq(this.values[u], other.values[u])) {\n return false;\n }\n }\n return true;\n }\n}\n","import DateTime, { friendlyDateTime } from \"./datetime.js\";\nimport Duration from \"./duration.js\";\nimport Settings from \"./settings.js\";\nimport { InvalidArgumentError, InvalidIntervalError } from \"./errors.js\";\nimport Invalid from \"./impl/invalid.js\";\n\nconst INVALID = \"Invalid Interval\";\n\n// checks if the start is equal to or before the end\nfunction validateStartEnd(start, end) {\n if (!start || !start.isValid) {\n return Interval.invalid(\"missing or invalid start\");\n } else if (!end || !end.isValid) {\n return Interval.invalid(\"missing or invalid end\");\n } else if (end < start) {\n return Interval.invalid(\n \"end before start\",\n `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`\n );\n } else {\n return null;\n }\n}\n\n/**\n * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them.\n *\n * Here is a brief overview of the most commonly used methods and getters in Interval:\n *\n * * **Creation** To create an Interval, use {@link Interval#fromDateTimes}, {@link Interval#after}, {@link Interval#before}, or {@link Interval#fromISO}.\n * * **Accessors** Use {@link Interval#start} and {@link Interval#end} to get the start and end.\n * * **Interrogation** To analyze the Interval, use {@link Interval#count}, {@link Interval#length}, {@link Interval#hasSame}, {@link Interval#contains}, {@link Interval#isAfter}, or {@link Interval#isBefore}.\n * * **Transformation** To create other Intervals out of this one, use {@link Interval#set}, {@link Interval#splitAt}, {@link Interval#splitBy}, {@link Interval#divideEqually}, {@link Interval#merge}, {@link Interval#xor}, {@link Interval#union}, {@link Interval#intersection}, or {@link Interval#difference}.\n * * **Comparison** To compare this Interval to another one, use {@link Interval#equals}, {@link Interval#overlaps}, {@link Interval#abutsStart}, {@link Interval#abutsEnd}, {@link Interval#engulfs}\n * * **Output** To convert the Interval into other representations, see {@link Interval#toString}, {@link Interval#toISO}, {@link Interval#toISODate}, {@link Interval#toISOTime}, {@link Interval#toFormat}, and {@link Interval#toDuration}.\n */\nexport default class Interval {\n /**\n * @private\n */\n constructor(config) {\n /**\n * @access private\n */\n this.s = config.start;\n /**\n * @access private\n */\n this.e = config.end;\n /**\n * @access private\n */\n this.invalid = config.invalid || null;\n /**\n * @access private\n */\n this.isLuxonInterval = true;\n }\n\n /**\n * Create an invalid Interval.\n * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent\n * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n * @return {Interval}\n */\n static invalid(reason, explanation = null) {\n if (!reason) {\n throw new InvalidArgumentError(\"need to specify a reason the Interval is invalid\");\n }\n\n const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n if (Settings.throwOnInvalid) {\n throw new InvalidIntervalError(invalid);\n } else {\n return new Interval({ invalid });\n }\n }\n\n /**\n * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.\n * @param {DateTime|Date|Object} start\n * @param {DateTime|Date|Object} end\n * @return {Interval}\n */\n static fromDateTimes(start, end) {\n const builtStart = friendlyDateTime(start),\n builtEnd = friendlyDateTime(end);\n\n const validateError = validateStartEnd(builtStart, builtEnd);\n\n if (validateError == null) {\n return new Interval({\n start: builtStart,\n end: builtEnd,\n });\n } else {\n return validateError;\n }\n }\n\n /**\n * Create an Interval from a start DateTime and a Duration to extend to.\n * @param {DateTime|Date|Object} start\n * @param {Duration|Object|number} duration - the length of the Interval.\n * @return {Interval}\n */\n static after(start, duration) {\n const dur = Duration.fromDurationLike(duration),\n dt = friendlyDateTime(start);\n return Interval.fromDateTimes(dt, dt.plus(dur));\n }\n\n /**\n * Create an Interval from an end DateTime and a Duration to extend backwards to.\n * @param {DateTime|Date|Object} end\n * @param {Duration|Object|number} duration - the length of the Interval.\n * @return {Interval}\n */\n static before(end, duration) {\n const dur = Duration.fromDurationLike(duration),\n dt = friendlyDateTime(end);\n return Interval.fromDateTimes(dt.minus(dur), dt);\n }\n\n /**\n * Create an Interval from an ISO 8601 string.\n * Accepts `/`, `/`, and `/` formats.\n * @param {string} text - the ISO string to parse\n * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO}\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @return {Interval}\n */\n static fromISO(text, opts) {\n const [s, e] = (text || \"\").split(\"/\", 2);\n if (s && e) {\n let start, startIsValid;\n try {\n start = DateTime.fromISO(s, opts);\n startIsValid = start.isValid;\n } catch (e) {\n startIsValid = false;\n }\n\n let end, endIsValid;\n try {\n end = DateTime.fromISO(e, opts);\n endIsValid = end.isValid;\n } catch (e) {\n endIsValid = false;\n }\n\n if (startIsValid && endIsValid) {\n return Interval.fromDateTimes(start, end);\n }\n\n if (startIsValid) {\n const dur = Duration.fromISO(e, opts);\n if (dur.isValid) {\n return Interval.after(start, dur);\n }\n } else if (endIsValid) {\n const dur = Duration.fromISO(s, opts);\n if (dur.isValid) {\n return Interval.before(end, dur);\n }\n }\n }\n return Interval.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n }\n\n /**\n * Check if an object is an Interval. Works across context boundaries\n * @param {object} o\n * @return {boolean}\n */\n static isInterval(o) {\n return (o && o.isLuxonInterval) || false;\n }\n\n /**\n * Returns the start of the Interval\n * @type {DateTime}\n */\n get start() {\n return this.isValid ? this.s : null;\n }\n\n /**\n * Returns the end of the Interval\n * @type {DateTime}\n */\n get end() {\n return this.isValid ? this.e : null;\n }\n\n /**\n * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.\n * @type {boolean}\n */\n get isValid() {\n return this.invalidReason === null;\n }\n\n /**\n * Returns an error code if this Interval is invalid, or null if the Interval is valid\n * @type {string}\n */\n get invalidReason() {\n return this.invalid ? this.invalid.reason : null;\n }\n\n /**\n * Returns an explanation of why this Interval became invalid, or null if the Interval is valid\n * @type {string}\n */\n get invalidExplanation() {\n return this.invalid ? this.invalid.explanation : null;\n }\n\n /**\n * Returns the length of the Interval in the specified unit.\n * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.\n * @return {number}\n */\n length(unit = \"milliseconds\") {\n return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN;\n }\n\n /**\n * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.\n * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'\n * asks 'what dates are included in this interval?', not 'how many days long is this interval?'\n * @param {string} [unit='milliseconds'] - the unit of time to count.\n * @return {number}\n */\n count(unit = \"milliseconds\") {\n if (!this.isValid) return NaN;\n const start = this.start.startOf(unit),\n end = this.end.startOf(unit);\n return Math.floor(end.diff(start, unit).get(unit)) + 1;\n }\n\n /**\n * Returns whether this Interval's start and end are both in the same unit of time\n * @param {string} unit - the unit of time to check sameness on\n * @return {boolean}\n */\n hasSame(unit) {\n return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;\n }\n\n /**\n * Return whether this Interval has the same start and end DateTimes.\n * @return {boolean}\n */\n isEmpty() {\n return this.s.valueOf() === this.e.valueOf();\n }\n\n /**\n * Return whether this Interval's start is after the specified DateTime.\n * @param {DateTime} dateTime\n * @return {boolean}\n */\n isAfter(dateTime) {\n if (!this.isValid) return false;\n return this.s > dateTime;\n }\n\n /**\n * Return whether this Interval's end is before the specified DateTime.\n * @param {DateTime} dateTime\n * @return {boolean}\n */\n isBefore(dateTime) {\n if (!this.isValid) return false;\n return this.e <= dateTime;\n }\n\n /**\n * Return whether this Interval contains the specified DateTime.\n * @param {DateTime} dateTime\n * @return {boolean}\n */\n contains(dateTime) {\n if (!this.isValid) return false;\n return this.s <= dateTime && this.e > dateTime;\n }\n\n /**\n * \"Sets\" the start and/or end dates. Returns a newly-constructed Interval.\n * @param {Object} values - the values to set\n * @param {DateTime} values.start - the starting DateTime\n * @param {DateTime} values.end - the ending DateTime\n * @return {Interval}\n */\n set({ start, end } = {}) {\n if (!this.isValid) return this;\n return Interval.fromDateTimes(start || this.s, end || this.e);\n }\n\n /**\n * Split this Interval at each of the specified DateTimes\n * @param {...DateTime} dateTimes - the unit of time to count.\n * @return {Array}\n */\n splitAt(...dateTimes) {\n if (!this.isValid) return [];\n const sorted = dateTimes\n .map(friendlyDateTime)\n .filter((d) => this.contains(d))\n .sort(),\n results = [];\n let { s } = this,\n i = 0;\n\n while (s < this.e) {\n const added = sorted[i] || this.e,\n next = +added > +this.e ? this.e : added;\n results.push(Interval.fromDateTimes(s, next));\n s = next;\n i += 1;\n }\n\n return results;\n }\n\n /**\n * Split this Interval into smaller Intervals, each of the specified length.\n * Left over time is grouped into a smaller interval\n * @param {Duration|Object|number} duration - The length of each resulting interval.\n * @return {Array}\n */\n splitBy(duration) {\n const dur = Duration.fromDurationLike(duration);\n\n if (!this.isValid || !dur.isValid || dur.as(\"milliseconds\") === 0) {\n return [];\n }\n\n let { s } = this,\n idx = 1,\n next;\n\n const results = [];\n while (s < this.e) {\n const added = this.start.plus(dur.mapUnits((x) => x * idx));\n next = +added > +this.e ? this.e : added;\n results.push(Interval.fromDateTimes(s, next));\n s = next;\n idx += 1;\n }\n\n return results;\n }\n\n /**\n * Split this Interval into the specified number of smaller intervals.\n * @param {number} numberOfParts - The number of Intervals to divide the Interval into.\n * @return {Array}\n */\n divideEqually(numberOfParts) {\n if (!this.isValid) return [];\n return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);\n }\n\n /**\n * Return whether this Interval overlaps with the specified Interval\n * @param {Interval} other\n * @return {boolean}\n */\n overlaps(other) {\n return this.e > other.s && this.s < other.e;\n }\n\n /**\n * Return whether this Interval's end is adjacent to the specified Interval's start.\n * @param {Interval} other\n * @return {boolean}\n */\n abutsStart(other) {\n if (!this.isValid) return false;\n return +this.e === +other.s;\n }\n\n /**\n * Return whether this Interval's start is adjacent to the specified Interval's end.\n * @param {Interval} other\n * @return {boolean}\n */\n abutsEnd(other) {\n if (!this.isValid) return false;\n return +other.e === +this.s;\n }\n\n /**\n * Return whether this Interval engulfs the start and end of the specified Interval.\n * @param {Interval} other\n * @return {boolean}\n */\n engulfs(other) {\n if (!this.isValid) return false;\n return this.s <= other.s && this.e >= other.e;\n }\n\n /**\n * Return whether this Interval has the same start and end as the specified Interval.\n * @param {Interval} other\n * @return {boolean}\n */\n equals(other) {\n if (!this.isValid || !other.isValid) {\n return false;\n }\n\n return this.s.equals(other.s) && this.e.equals(other.e);\n }\n\n /**\n * Return an Interval representing the intersection of this Interval and the specified Interval.\n * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.\n * Returns null if the intersection is empty, meaning, the intervals don't intersect.\n * @param {Interval} other\n * @return {Interval}\n */\n intersection(other) {\n if (!this.isValid) return this;\n const s = this.s > other.s ? this.s : other.s,\n e = this.e < other.e ? this.e : other.e;\n\n if (s >= e) {\n return null;\n } else {\n return Interval.fromDateTimes(s, e);\n }\n }\n\n /**\n * Return an Interval representing the union of this Interval and the specified Interval.\n * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.\n * @param {Interval} other\n * @return {Interval}\n */\n union(other) {\n if (!this.isValid) return this;\n const s = this.s < other.s ? this.s : other.s,\n e = this.e > other.e ? this.e : other.e;\n return Interval.fromDateTimes(s, e);\n }\n\n /**\n * Merge an array of Intervals into a equivalent minimal set of Intervals.\n * Combines overlapping and adjacent Intervals.\n * @param {Array} intervals\n * @return {Array}\n */\n static merge(intervals) {\n const [found, final] = intervals\n .sort((a, b) => a.s - b.s)\n .reduce(\n ([sofar, current], item) => {\n if (!current) {\n return [sofar, item];\n } else if (current.overlaps(item) || current.abutsStart(item)) {\n return [sofar, current.union(item)];\n } else {\n return [sofar.concat([current]), item];\n }\n },\n [[], null]\n );\n if (final) {\n found.push(final);\n }\n return found;\n }\n\n /**\n * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.\n * @param {Array} intervals\n * @return {Array}\n */\n static xor(intervals) {\n let start = null,\n currentCount = 0;\n const results = [],\n ends = intervals.map((i) => [\n { time: i.s, type: \"s\" },\n { time: i.e, type: \"e\" },\n ]),\n flattened = Array.prototype.concat(...ends),\n arr = flattened.sort((a, b) => a.time - b.time);\n\n for (const i of arr) {\n currentCount += i.type === \"s\" ? 1 : -1;\n\n if (currentCount === 1) {\n start = i.time;\n } else {\n if (start && +start !== +i.time) {\n results.push(Interval.fromDateTimes(start, i.time));\n }\n\n start = null;\n }\n }\n\n return Interval.merge(results);\n }\n\n /**\n * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.\n * @param {...Interval} intervals\n * @return {Array}\n */\n difference(...intervals) {\n return Interval.xor([this].concat(intervals))\n .map((i) => this.intersection(i))\n .filter((i) => i && !i.isEmpty());\n }\n\n /**\n * Returns a string representation of this Interval appropriate for debugging.\n * @return {string}\n */\n toString() {\n if (!this.isValid) return INVALID;\n return `[${this.s.toISO()} – ${this.e.toISO()})`;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this Interval.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @param {Object} opts - The same options as {@link DateTime#toISO}\n * @return {string}\n */\n toISO(opts) {\n if (!this.isValid) return INVALID;\n return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of date of this Interval.\n * The time components are ignored.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @return {string}\n */\n toISODate() {\n if (!this.isValid) return INVALID;\n return `${this.s.toISODate()}/${this.e.toISODate()}`;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of time of this Interval.\n * The date components are ignored.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @param {Object} opts - The same options as {@link DateTime#toISO}\n * @return {string}\n */\n toISOTime(opts) {\n if (!this.isValid) return INVALID;\n return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;\n }\n\n /**\n * Returns a string representation of this Interval formatted according to the specified format string.\n * @param {string} dateFormat - the format string. This string formats the start and end time. See {@link DateTime#toFormat} for details.\n * @param {Object} opts - options\n * @param {string} [opts.separator = ' – '] - a separator to place between the start and end representations\n * @return {string}\n */\n toFormat(dateFormat, { separator = \" – \" } = {}) {\n if (!this.isValid) return INVALID;\n return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;\n }\n\n /**\n * Return a Duration representing the time spanned by this interval.\n * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.\n * @param {Object} opts - options that affect the creation of the Duration\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }\n * @return {Duration}\n */\n toDuration(unit, opts) {\n if (!this.isValid) {\n return Duration.invalid(this.invalidReason);\n }\n return this.e.diff(this.s, unit, opts);\n }\n\n /**\n * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes\n * @param {function} mapFn\n * @return {Interval}\n * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())\n * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))\n */\n mapEndpoints(mapFn) {\n return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));\n }\n}\n","import DateTime from \"./datetime.js\";\nimport Settings from \"./settings.js\";\nimport Locale from \"./impl/locale.js\";\nimport IANAZone from \"./zones/IANAZone.js\";\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\n\nimport { hasRelative } from \"./impl/util.js\";\n\n/**\n * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment.\n */\nexport default class Info {\n /**\n * Return whether the specified zone contains a DST.\n * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.\n * @return {boolean}\n */\n static hasDST(zone = Settings.defaultZone) {\n const proto = DateTime.now().setZone(zone).set({ month: 12 });\n\n return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset;\n }\n\n /**\n * Return whether the specified zone is a valid IANA specifier.\n * @param {string} zone - Zone to check\n * @return {boolean}\n */\n static isValidIANAZone(zone) {\n return IANAZone.isValidZone(zone);\n }\n\n /**\n * Converts the input into a {@link Zone} instance.\n *\n * * If `input` is already a Zone instance, it is returned unchanged.\n * * If `input` is a string containing a valid time zone name, a Zone instance\n * with that name is returned.\n * * If `input` is a string that doesn't refer to a known time zone, a Zone\n * instance with {@link Zone#isValid} == false is returned.\n * * If `input is a number, a Zone instance with the specified fixed offset\n * in minutes is returned.\n * * If `input` is `null` or `undefined`, the default zone is returned.\n * @param {string|Zone|number} [input] - the value to be converted\n * @return {Zone}\n */\n static normalizeZone(input) {\n return normalizeZone(input, Settings.defaultZone);\n }\n\n /**\n * Return an array of standalone month names.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param {string} [length='long'] - the length of the month representation, such as \"numeric\", \"2-digit\", \"narrow\", \"short\", \"long\"\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @param {string} [opts.outputCalendar='gregory'] - the calendar\n * @example Info.months()[0] //=> 'January'\n * @example Info.months('short')[0] //=> 'Jan'\n * @example Info.months('numeric')[0] //=> '1'\n * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'\n * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'\n * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'\n * @return {Array}\n */\n static months(\n length = \"long\",\n { locale = null, numberingSystem = null, locObj = null, outputCalendar = \"gregory\" } = {}\n ) {\n return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);\n }\n\n /**\n * Return an array of format month names.\n * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that\n * changes the string.\n * See {@link Info#months}\n * @param {string} [length='long'] - the length of the month representation, such as \"numeric\", \"2-digit\", \"narrow\", \"short\", \"long\"\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @param {string} [opts.outputCalendar='gregory'] - the calendar\n * @return {Array}\n */\n static monthsFormat(\n length = \"long\",\n { locale = null, numberingSystem = null, locObj = null, outputCalendar = \"gregory\" } = {}\n ) {\n return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);\n }\n\n /**\n * Return an array of standalone week names.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param {string} [length='long'] - the length of the weekday representation, such as \"narrow\", \"short\", \"long\".\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @example Info.weekdays()[0] //=> 'Monday'\n * @example Info.weekdays('short')[0] //=> 'Mon'\n * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'\n * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'\n * @return {Array}\n */\n static weekdays(length = \"long\", { locale = null, numberingSystem = null, locObj = null } = {}) {\n return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);\n }\n\n /**\n * Return an array of format week names.\n * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that\n * changes the string.\n * See {@link Info#weekdays}\n * @param {string} [length='long'] - the length of the month representation, such as \"narrow\", \"short\", \"long\".\n * @param {Object} opts - options\n * @param {string} [opts.locale=null] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @return {Array}\n */\n static weekdaysFormat(\n length = \"long\",\n { locale = null, numberingSystem = null, locObj = null } = {}\n ) {\n return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);\n }\n\n /**\n * Return an array of meridiems.\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @example Info.meridiems() //=> [ 'AM', 'PM' ]\n * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]\n * @return {Array}\n */\n static meridiems({ locale = null } = {}) {\n return Locale.create(locale).meridiems();\n }\n\n /**\n * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.\n * @param {string} [length='short'] - the length of the era representation, such as \"short\" or \"long\".\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @example Info.eras() //=> [ 'BC', 'AD' ]\n * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]\n * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]\n * @return {Array}\n */\n static eras(length = \"short\", { locale = null } = {}) {\n return Locale.create(locale, null, \"gregory\").eras(length);\n }\n\n /**\n * Return the set of available features in this environment.\n * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case.\n * Keys:\n * * `relative`: whether this environment supports relative time formatting\n * @example Info.features() //=> { relative: false }\n * @return {Object}\n */\n static features() {\n return { relative: hasRelative() };\n }\n}\n","import Duration from \"../duration.js\";\n\nfunction dayDiff(earlier, later) {\n const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf(\"day\").valueOf(),\n ms = utcDayStart(later) - utcDayStart(earlier);\n return Math.floor(Duration.fromMillis(ms).as(\"days\"));\n}\n\nfunction highOrderDiffs(cursor, later, units) {\n const differs = [\n [\"years\", (a, b) => b.year - a.year],\n [\"quarters\", (a, b) => b.quarter - a.quarter],\n [\"months\", (a, b) => b.month - a.month + (b.year - a.year) * 12],\n [\n \"weeks\",\n (a, b) => {\n const days = dayDiff(a, b);\n return (days - (days % 7)) / 7;\n },\n ],\n [\"days\", dayDiff],\n ];\n\n const results = {};\n let lowestOrder, highWater;\n\n for (const [unit, differ] of differs) {\n if (units.indexOf(unit) >= 0) {\n lowestOrder = unit;\n\n let delta = differ(cursor, later);\n highWater = cursor.plus({ [unit]: delta });\n\n if (highWater > later) {\n cursor = cursor.plus({ [unit]: delta - 1 });\n delta -= 1;\n } else {\n cursor = highWater;\n }\n\n results[unit] = delta;\n }\n }\n\n return [cursor, results, highWater, lowestOrder];\n}\n\nexport default function (earlier, later, units, opts) {\n let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units);\n\n const remainingMillis = later - cursor;\n\n const lowerOrderUnits = units.filter(\n (u) => [\"hours\", \"minutes\", \"seconds\", \"milliseconds\"].indexOf(u) >= 0\n );\n\n if (lowerOrderUnits.length === 0) {\n if (highWater < later) {\n highWater = cursor.plus({ [lowestOrder]: 1 });\n }\n\n if (highWater !== cursor) {\n results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);\n }\n }\n\n const duration = Duration.fromObject(results, opts);\n\n if (lowerOrderUnits.length > 0) {\n return Duration.fromMillis(remainingMillis, opts)\n .shiftTo(...lowerOrderUnits)\n .plus(duration);\n } else {\n return duration;\n }\n}\n","const numberingSystems = {\n arab: \"[\\u0660-\\u0669]\",\n arabext: \"[\\u06F0-\\u06F9]\",\n bali: \"[\\u1B50-\\u1B59]\",\n beng: \"[\\u09E6-\\u09EF]\",\n deva: \"[\\u0966-\\u096F]\",\n fullwide: \"[\\uFF10-\\uFF19]\",\n gujr: \"[\\u0AE6-\\u0AEF]\",\n hanidec: \"[〇|一|二|三|四|五|六|七|八|九]\",\n khmr: \"[\\u17E0-\\u17E9]\",\n knda: \"[\\u0CE6-\\u0CEF]\",\n laoo: \"[\\u0ED0-\\u0ED9]\",\n limb: \"[\\u1946-\\u194F]\",\n mlym: \"[\\u0D66-\\u0D6F]\",\n mong: \"[\\u1810-\\u1819]\",\n mymr: \"[\\u1040-\\u1049]\",\n orya: \"[\\u0B66-\\u0B6F]\",\n tamldec: \"[\\u0BE6-\\u0BEF]\",\n telu: \"[\\u0C66-\\u0C6F]\",\n thai: \"[\\u0E50-\\u0E59]\",\n tibt: \"[\\u0F20-\\u0F29]\",\n latn: \"\\\\d\",\n};\n\nconst numberingSystemsUTF16 = {\n arab: [1632, 1641],\n arabext: [1776, 1785],\n bali: [6992, 7001],\n beng: [2534, 2543],\n deva: [2406, 2415],\n fullwide: [65296, 65303],\n gujr: [2790, 2799],\n khmr: [6112, 6121],\n knda: [3302, 3311],\n laoo: [3792, 3801],\n limb: [6470, 6479],\n mlym: [3430, 3439],\n mong: [6160, 6169],\n mymr: [4160, 4169],\n orya: [2918, 2927],\n tamldec: [3046, 3055],\n telu: [3174, 3183],\n thai: [3664, 3673],\n tibt: [3872, 3881],\n};\n\nconst hanidecChars = numberingSystems.hanidec.replace(/[\\[|\\]]/g, \"\").split(\"\");\n\nexport function parseDigits(str) {\n let value = parseInt(str, 10);\n if (isNaN(value)) {\n value = \"\";\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n\n if (str[i].search(numberingSystems.hanidec) !== -1) {\n value += hanidecChars.indexOf(str[i]);\n } else {\n for (const key in numberingSystemsUTF16) {\n const [min, max] = numberingSystemsUTF16[key];\n if (code >= min && code <= max) {\n value += code - min;\n }\n }\n }\n }\n return parseInt(value, 10);\n } else {\n return value;\n }\n}\n\nexport function digitRegex({ numberingSystem }, append = \"\") {\n return new RegExp(`${numberingSystems[numberingSystem || \"latn\"]}${append}`);\n}\n","import { parseMillis, isUndefined, untruncateYear, signedOffset, hasOwnProperty } from \"./util.js\";\nimport Formatter from \"./formatter.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\nimport DateTime from \"../datetime.js\";\nimport { digitRegex, parseDigits } from \"./digits.js\";\nimport { ConflictingSpecificationError } from \"../errors.js\";\n\nconst MISSING_FTP = \"missing Intl.DateTimeFormat.formatToParts support\";\n\nfunction intUnit(regex, post = (i) => i) {\n return { regex, deser: ([s]) => post(parseDigits(s)) };\n}\n\nconst NBSP = String.fromCharCode(160);\nconst spaceOrNBSP = `[ ${NBSP}]`;\nconst spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, \"g\");\n\nfunction fixListRegex(s) {\n // make dots optional and also make them literal\n // make space and non breakable space characters interchangeable\n return s.replace(/\\./g, \"\\\\.?\").replace(spaceOrNBSPRegExp, spaceOrNBSP);\n}\n\nfunction stripInsensitivities(s) {\n return s\n .replace(/\\./g, \"\") // ignore dots that were made optional\n .replace(spaceOrNBSPRegExp, \" \") // interchange space and nbsp\n .toLowerCase();\n}\n\nfunction oneOf(strings, startIndex) {\n if (strings === null) {\n return null;\n } else {\n return {\n regex: RegExp(strings.map(fixListRegex).join(\"|\")),\n deser: ([s]) =>\n strings.findIndex((i) => stripInsensitivities(s) === stripInsensitivities(i)) + startIndex,\n };\n }\n}\n\nfunction offset(regex, groups) {\n return { regex, deser: ([, h, m]) => signedOffset(h, m), groups };\n}\n\nfunction simple(regex) {\n return { regex, deser: ([s]) => s };\n}\n\nfunction escapeToken(value) {\n return value.replace(/[\\-\\[\\]{}()*+?.,\\\\\\^$|#\\s]/g, \"\\\\$&\");\n}\n\nfunction unitForToken(token, loc) {\n const one = digitRegex(loc),\n two = digitRegex(loc, \"{2}\"),\n three = digitRegex(loc, \"{3}\"),\n four = digitRegex(loc, \"{4}\"),\n six = digitRegex(loc, \"{6}\"),\n oneOrTwo = digitRegex(loc, \"{1,2}\"),\n oneToThree = digitRegex(loc, \"{1,3}\"),\n oneToSix = digitRegex(loc, \"{1,6}\"),\n oneToNine = digitRegex(loc, \"{1,9}\"),\n twoToFour = digitRegex(loc, \"{2,4}\"),\n fourToSix = digitRegex(loc, \"{4,6}\"),\n literal = (t) => ({ regex: RegExp(escapeToken(t.val)), deser: ([s]) => s, literal: true }),\n unitate = (t) => {\n if (token.literal) {\n return literal(t);\n }\n switch (t.val) {\n // era\n case \"G\":\n return oneOf(loc.eras(\"short\", false), 0);\n case \"GG\":\n return oneOf(loc.eras(\"long\", false), 0);\n // years\n case \"y\":\n return intUnit(oneToSix);\n case \"yy\":\n return intUnit(twoToFour, untruncateYear);\n case \"yyyy\":\n return intUnit(four);\n case \"yyyyy\":\n return intUnit(fourToSix);\n case \"yyyyyy\":\n return intUnit(six);\n // months\n case \"M\":\n return intUnit(oneOrTwo);\n case \"MM\":\n return intUnit(two);\n case \"MMM\":\n return oneOf(loc.months(\"short\", true, false), 1);\n case \"MMMM\":\n return oneOf(loc.months(\"long\", true, false), 1);\n case \"L\":\n return intUnit(oneOrTwo);\n case \"LL\":\n return intUnit(two);\n case \"LLL\":\n return oneOf(loc.months(\"short\", false, false), 1);\n case \"LLLL\":\n return oneOf(loc.months(\"long\", false, false), 1);\n // dates\n case \"d\":\n return intUnit(oneOrTwo);\n case \"dd\":\n return intUnit(two);\n // ordinals\n case \"o\":\n return intUnit(oneToThree);\n case \"ooo\":\n return intUnit(three);\n // time\n case \"HH\":\n return intUnit(two);\n case \"H\":\n return intUnit(oneOrTwo);\n case \"hh\":\n return intUnit(two);\n case \"h\":\n return intUnit(oneOrTwo);\n case \"mm\":\n return intUnit(two);\n case \"m\":\n return intUnit(oneOrTwo);\n case \"q\":\n return intUnit(oneOrTwo);\n case \"qq\":\n return intUnit(two);\n case \"s\":\n return intUnit(oneOrTwo);\n case \"ss\":\n return intUnit(two);\n case \"S\":\n return intUnit(oneToThree);\n case \"SSS\":\n return intUnit(three);\n case \"u\":\n return simple(oneToNine);\n case \"uu\":\n return simple(oneOrTwo);\n case \"uuu\":\n return intUnit(one);\n // meridiem\n case \"a\":\n return oneOf(loc.meridiems(), 0);\n // weekYear (k)\n case \"kkkk\":\n return intUnit(four);\n case \"kk\":\n return intUnit(twoToFour, untruncateYear);\n // weekNumber (W)\n case \"W\":\n return intUnit(oneOrTwo);\n case \"WW\":\n return intUnit(two);\n // weekdays\n case \"E\":\n case \"c\":\n return intUnit(one);\n case \"EEE\":\n return oneOf(loc.weekdays(\"short\", false, false), 1);\n case \"EEEE\":\n return oneOf(loc.weekdays(\"long\", false, false), 1);\n case \"ccc\":\n return oneOf(loc.weekdays(\"short\", true, false), 1);\n case \"cccc\":\n return oneOf(loc.weekdays(\"long\", true, false), 1);\n // offset/zone\n case \"Z\":\n case \"ZZ\":\n return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2);\n case \"ZZZ\":\n return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2);\n // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing\n // because we don't have any way to figure out what they are\n case \"z\":\n return simple(/[a-z_+-/]{1,256}?/i);\n default:\n return literal(t);\n }\n };\n\n const unit = unitate(token) || {\n invalidReason: MISSING_FTP,\n };\n\n unit.token = token;\n\n return unit;\n}\n\nconst partTypeStyleToTokenVal = {\n year: {\n \"2-digit\": \"yy\",\n numeric: \"yyyyy\",\n },\n month: {\n numeric: \"M\",\n \"2-digit\": \"MM\",\n short: \"MMM\",\n long: \"MMMM\",\n },\n day: {\n numeric: \"d\",\n \"2-digit\": \"dd\",\n },\n weekday: {\n short: \"EEE\",\n long: \"EEEE\",\n },\n dayperiod: \"a\",\n dayPeriod: \"a\",\n hour: {\n numeric: \"h\",\n \"2-digit\": \"hh\",\n },\n minute: {\n numeric: \"m\",\n \"2-digit\": \"mm\",\n },\n second: {\n numeric: \"s\",\n \"2-digit\": \"ss\",\n },\n};\n\nfunction tokenForPart(part, locale, formatOpts) {\n const { type, value } = part;\n\n if (type === \"literal\") {\n return {\n literal: true,\n val: value,\n };\n }\n\n const style = formatOpts[type];\n\n let val = partTypeStyleToTokenVal[type];\n if (typeof val === \"object\") {\n val = val[style];\n }\n\n if (val) {\n return {\n literal: false,\n val,\n };\n }\n\n return undefined;\n}\n\nfunction buildRegex(units) {\n const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, \"\");\n return [`^${re}$`, units];\n}\n\nfunction match(input, regex, handlers) {\n const matches = input.match(regex);\n\n if (matches) {\n const all = {};\n let matchIndex = 1;\n for (const i in handlers) {\n if (hasOwnProperty(handlers, i)) {\n const h = handlers[i],\n groups = h.groups ? h.groups + 1 : 1;\n if (!h.literal && h.token) {\n all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));\n }\n matchIndex += groups;\n }\n }\n return [matches, all];\n } else {\n return [matches, {}];\n }\n}\n\nfunction dateTimeFromMatches(matches) {\n const toField = (token) => {\n switch (token) {\n case \"S\":\n return \"millisecond\";\n case \"s\":\n return \"second\";\n case \"m\":\n return \"minute\";\n case \"h\":\n case \"H\":\n return \"hour\";\n case \"d\":\n return \"day\";\n case \"o\":\n return \"ordinal\";\n case \"L\":\n case \"M\":\n return \"month\";\n case \"y\":\n return \"year\";\n case \"E\":\n case \"c\":\n return \"weekday\";\n case \"W\":\n return \"weekNumber\";\n case \"k\":\n return \"weekYear\";\n case \"q\":\n return \"quarter\";\n default:\n return null;\n }\n };\n\n let zone = null;\n let specificOffset;\n if (!isUndefined(matches.z)) {\n zone = IANAZone.create(matches.z);\n }\n\n if (!isUndefined(matches.Z)) {\n if (!zone) {\n zone = new FixedOffsetZone(matches.Z);\n }\n specificOffset = matches.Z;\n }\n\n if (!isUndefined(matches.q)) {\n matches.M = (matches.q - 1) * 3 + 1;\n }\n\n if (!isUndefined(matches.h)) {\n if (matches.h < 12 && matches.a === 1) {\n matches.h += 12;\n } else if (matches.h === 12 && matches.a === 0) {\n matches.h = 0;\n }\n }\n\n if (matches.G === 0 && matches.y) {\n matches.y = -matches.y;\n }\n\n if (!isUndefined(matches.u)) {\n matches.S = parseMillis(matches.u);\n }\n\n const vals = Object.keys(matches).reduce((r, k) => {\n const f = toField(k);\n if (f) {\n r[f] = matches[k];\n }\n\n return r;\n }, {});\n\n return [vals, zone, specificOffset];\n}\n\nlet dummyDateTimeCache = null;\n\nfunction getDummyDateTime() {\n if (!dummyDateTimeCache) {\n dummyDateTimeCache = DateTime.fromMillis(1555555555555);\n }\n\n return dummyDateTimeCache;\n}\n\nfunction maybeExpandMacroToken(token, locale) {\n if (token.literal) {\n return token;\n }\n\n const formatOpts = Formatter.macroTokenToFormatOpts(token.val);\n\n if (!formatOpts) {\n return token;\n }\n\n const formatter = Formatter.create(locale, formatOpts);\n const parts = formatter.formatDateTimeParts(getDummyDateTime());\n\n const tokens = parts.map((p) => tokenForPart(p, locale, formatOpts));\n\n if (tokens.includes(undefined)) {\n return token;\n }\n\n return tokens;\n}\n\nfunction expandMacroTokens(tokens, locale) {\n return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale)));\n}\n\n/**\n * @private\n */\n\nexport function explainFromTokens(locale, input, format) {\n const tokens = expandMacroTokens(Formatter.parseFormat(format), locale),\n units = tokens.map((t) => unitForToken(t, locale)),\n disqualifyingUnit = units.find((t) => t.invalidReason);\n\n if (disqualifyingUnit) {\n return { input, tokens, invalidReason: disqualifyingUnit.invalidReason };\n } else {\n const [regexString, handlers] = buildRegex(units),\n regex = RegExp(regexString, \"i\"),\n [rawMatches, matches] = match(input, regex, handlers),\n [result, zone, specificOffset] = matches\n ? dateTimeFromMatches(matches)\n : [null, null, undefined];\n if (hasOwnProperty(matches, \"a\") && hasOwnProperty(matches, \"H\")) {\n throw new ConflictingSpecificationError(\n \"Can't include meridiem when specifying 24-hour format\"\n );\n }\n return { input, tokens, regex, rawMatches, matches, result, zone, specificOffset };\n }\n}\n\nexport function parseFromTokens(locale, input, format) {\n const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format);\n return [result, zone, specificOffset, invalidReason];\n}\n","import {\n integerBetween,\n isLeapYear,\n timeObject,\n daysInYear,\n daysInMonth,\n weeksInWeekYear,\n isInteger,\n} from \"./util.js\";\nimport Invalid from \"./invalid.js\";\n\nconst nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],\n leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];\n\nfunction unitOutOfRange(unit, value) {\n return new Invalid(\n \"unit out of range\",\n `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`\n );\n}\n\nfunction dayOfWeek(year, month, day) {\n const d = new Date(Date.UTC(year, month - 1, day));\n\n if (year < 100 && year >= 0) {\n d.setUTCFullYear(d.getUTCFullYear() - 1900);\n }\n\n const js = d.getUTCDay();\n\n return js === 0 ? 7 : js;\n}\n\nfunction computeOrdinal(year, month, day) {\n return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];\n}\n\nfunction uncomputeOrdinal(year, ordinal) {\n const table = isLeapYear(year) ? leapLadder : nonLeapLadder,\n month0 = table.findIndex((i) => i < ordinal),\n day = ordinal - table[month0];\n return { month: month0 + 1, day };\n}\n\n/**\n * @private\n */\n\nexport function gregorianToWeek(gregObj) {\n const { year, month, day } = gregObj,\n ordinal = computeOrdinal(year, month, day),\n weekday = dayOfWeek(year, month, day);\n\n let weekNumber = Math.floor((ordinal - weekday + 10) / 7),\n weekYear;\n\n if (weekNumber < 1) {\n weekYear = year - 1;\n weekNumber = weeksInWeekYear(weekYear);\n } else if (weekNumber > weeksInWeekYear(year)) {\n weekYear = year + 1;\n weekNumber = 1;\n } else {\n weekYear = year;\n }\n\n return { weekYear, weekNumber, weekday, ...timeObject(gregObj) };\n}\n\nexport function weekToGregorian(weekData) {\n const { weekYear, weekNumber, weekday } = weekData,\n weekdayOfJan4 = dayOfWeek(weekYear, 1, 4),\n yearInDays = daysInYear(weekYear);\n\n let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3,\n year;\n\n if (ordinal < 1) {\n year = weekYear - 1;\n ordinal += daysInYear(year);\n } else if (ordinal > yearInDays) {\n year = weekYear + 1;\n ordinal -= daysInYear(weekYear);\n } else {\n year = weekYear;\n }\n\n const { month, day } = uncomputeOrdinal(year, ordinal);\n return { year, month, day, ...timeObject(weekData) };\n}\n\nexport function gregorianToOrdinal(gregData) {\n const { year, month, day } = gregData;\n const ordinal = computeOrdinal(year, month, day);\n return { year, ordinal, ...timeObject(gregData) };\n}\n\nexport function ordinalToGregorian(ordinalData) {\n const { year, ordinal } = ordinalData;\n const { month, day } = uncomputeOrdinal(year, ordinal);\n return { year, month, day, ...timeObject(ordinalData) };\n}\n\nexport function hasInvalidWeekData(obj) {\n const validYear = isInteger(obj.weekYear),\n validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)),\n validWeekday = integerBetween(obj.weekday, 1, 7);\n\n if (!validYear) {\n return unitOutOfRange(\"weekYear\", obj.weekYear);\n } else if (!validWeek) {\n return unitOutOfRange(\"week\", obj.week);\n } else if (!validWeekday) {\n return unitOutOfRange(\"weekday\", obj.weekday);\n } else return false;\n}\n\nexport function hasInvalidOrdinalData(obj) {\n const validYear = isInteger(obj.year),\n validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));\n\n if (!validYear) {\n return unitOutOfRange(\"year\", obj.year);\n } else if (!validOrdinal) {\n return unitOutOfRange(\"ordinal\", obj.ordinal);\n } else return false;\n}\n\nexport function hasInvalidGregorianData(obj) {\n const validYear = isInteger(obj.year),\n validMonth = integerBetween(obj.month, 1, 12),\n validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));\n\n if (!validYear) {\n return unitOutOfRange(\"year\", obj.year);\n } else if (!validMonth) {\n return unitOutOfRange(\"month\", obj.month);\n } else if (!validDay) {\n return unitOutOfRange(\"day\", obj.day);\n } else return false;\n}\n\nexport function hasInvalidTimeData(obj) {\n const { hour, minute, second, millisecond } = obj;\n const validHour =\n integerBetween(hour, 0, 23) ||\n (hour === 24 && minute === 0 && second === 0 && millisecond === 0),\n validMinute = integerBetween(minute, 0, 59),\n validSecond = integerBetween(second, 0, 59),\n validMillisecond = integerBetween(millisecond, 0, 999);\n\n if (!validHour) {\n return unitOutOfRange(\"hour\", hour);\n } else if (!validMinute) {\n return unitOutOfRange(\"minute\", minute);\n } else if (!validSecond) {\n return unitOutOfRange(\"second\", second);\n } else if (!validMillisecond) {\n return unitOutOfRange(\"millisecond\", millisecond);\n } else return false;\n}\n","import Duration from \"./duration.js\";\nimport Interval from \"./interval.js\";\nimport Settings from \"./settings.js\";\nimport Info from \"./info.js\";\nimport Formatter from \"./impl/formatter.js\";\nimport FixedOffsetZone from \"./zones/fixedOffsetZone.js\";\nimport Locale from \"./impl/locale.js\";\nimport {\n isUndefined,\n maybeArray,\n isDate,\n isNumber,\n bestBy,\n daysInMonth,\n daysInYear,\n isLeapYear,\n weeksInWeekYear,\n normalizeObject,\n roundTo,\n objToLocalTS,\n padStart,\n} from \"./impl/util.js\";\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\nimport diff from \"./impl/diff.js\";\nimport { parseRFC2822Date, parseISODate, parseHTTPDate, parseSQL } from \"./impl/regexParser.js\";\nimport { parseFromTokens, explainFromTokens } from \"./impl/tokenParser.js\";\nimport {\n gregorianToWeek,\n weekToGregorian,\n gregorianToOrdinal,\n ordinalToGregorian,\n hasInvalidGregorianData,\n hasInvalidWeekData,\n hasInvalidOrdinalData,\n hasInvalidTimeData,\n} from \"./impl/conversions.js\";\nimport * as Formats from \"./impl/formats.js\";\nimport {\n InvalidArgumentError,\n ConflictingSpecificationError,\n InvalidUnitError,\n InvalidDateTimeError,\n} from \"./errors.js\";\nimport Invalid from \"./impl/invalid.js\";\n\nconst INVALID = \"Invalid DateTime\";\nconst MAX_DATE = 8.64e15;\n\nfunction unsupportedZone(zone) {\n return new Invalid(\"unsupported zone\", `the zone \"${zone.name}\" is not supported`);\n}\n\n// we cache week data on the DT object and this intermediates the cache\nfunction possiblyCachedWeekData(dt) {\n if (dt.weekData === null) {\n dt.weekData = gregorianToWeek(dt.c);\n }\n return dt.weekData;\n}\n\n// clone really means, \"make a new object with these modifications\". all \"setters\" really use this\n// to create a new object while only changing some of the properties\nfunction clone(inst, alts) {\n const current = {\n ts: inst.ts,\n zone: inst.zone,\n c: inst.c,\n o: inst.o,\n loc: inst.loc,\n invalid: inst.invalid,\n };\n return new DateTime({ ...current, ...alts, old: current });\n}\n\n// find the right offset a given local time. The o input is our guess, which determines which\n// offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)\nfunction fixOffset(localTS, o, tz) {\n // Our UTC time is just a guess because our offset is just a guess\n let utcGuess = localTS - o * 60 * 1000;\n\n // Test whether the zone matches the offset for this ts\n const o2 = tz.offset(utcGuess);\n\n // If so, offset didn't change and we're done\n if (o === o2) {\n return [utcGuess, o];\n }\n\n // If not, change the ts by the difference in the offset\n utcGuess -= (o2 - o) * 60 * 1000;\n\n // If that gives us the local time we want, we're done\n const o3 = tz.offset(utcGuess);\n if (o2 === o3) {\n return [utcGuess, o2];\n }\n\n // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time\n return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];\n}\n\n// convert an epoch timestamp into a calendar object with the given offset\nfunction tsToObj(ts, offset) {\n ts += offset * 60 * 1000;\n\n const d = new Date(ts);\n\n return {\n year: d.getUTCFullYear(),\n month: d.getUTCMonth() + 1,\n day: d.getUTCDate(),\n hour: d.getUTCHours(),\n minute: d.getUTCMinutes(),\n second: d.getUTCSeconds(),\n millisecond: d.getUTCMilliseconds(),\n };\n}\n\n// convert a calendar object to a epoch timestamp\nfunction objToTS(obj, offset, zone) {\n return fixOffset(objToLocalTS(obj), offset, zone);\n}\n\n// create a new DT instance by adding a duration, adjusting for DSTs\nfunction adjustTime(inst, dur) {\n const oPre = inst.o,\n year = inst.c.year + Math.trunc(dur.years),\n month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3,\n c = {\n ...inst.c,\n year,\n month,\n day:\n Math.min(inst.c.day, daysInMonth(year, month)) +\n Math.trunc(dur.days) +\n Math.trunc(dur.weeks) * 7,\n },\n millisToAdd = Duration.fromObject({\n years: dur.years - Math.trunc(dur.years),\n quarters: dur.quarters - Math.trunc(dur.quarters),\n months: dur.months - Math.trunc(dur.months),\n weeks: dur.weeks - Math.trunc(dur.weeks),\n days: dur.days - Math.trunc(dur.days),\n hours: dur.hours,\n minutes: dur.minutes,\n seconds: dur.seconds,\n milliseconds: dur.milliseconds,\n }).as(\"milliseconds\"),\n localTS = objToLocalTS(c);\n\n let [ts, o] = fixOffset(localTS, oPre, inst.zone);\n\n if (millisToAdd !== 0) {\n ts += millisToAdd;\n // that could have changed the offset by going over a DST, but we want to keep the ts the same\n o = inst.zone.offset(ts);\n }\n\n return { ts, o };\n}\n\n// helper useful in turning the results of parsing into real dates\n// by handling the zone options\nfunction parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) {\n const { setZone, zone } = opts;\n if (parsed && Object.keys(parsed).length !== 0) {\n const interpretationZone = parsedZone || zone,\n inst = DateTime.fromObject(parsed, {\n ...opts,\n zone: interpretationZone,\n specificOffset,\n });\n return setZone ? inst : inst.setZone(zone);\n } else {\n return DateTime.invalid(\n new Invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ${format}`)\n );\n }\n}\n\n// if you want to output a technical format (e.g. RFC 2822), this helper\n// helps handle the details\nfunction toTechFormat(dt, format, allowZ = true) {\n return dt.isValid\n ? Formatter.create(Locale.create(\"en-US\"), {\n allowZ,\n forceSimple: true,\n }).formatDateTimeFromString(dt, format)\n : null;\n}\n\nfunction toISODate(o, extended) {\n const longFormat = o.c.year > 9999 || o.c.year < 0;\n let c = \"\";\n if (longFormat && o.c.year >= 0) c += \"+\";\n c += padStart(o.c.year, longFormat ? 6 : 4);\n\n if (extended) {\n c += \"-\";\n c += padStart(o.c.month);\n c += \"-\";\n c += padStart(o.c.day);\n } else {\n c += padStart(o.c.month);\n c += padStart(o.c.day);\n }\n return c;\n}\n\nfunction toISOTime(\n o,\n extended,\n suppressSeconds,\n suppressMilliseconds,\n includeOffset,\n extendedZone\n) {\n let c = padStart(o.c.hour);\n if (extended) {\n c += \":\";\n c += padStart(o.c.minute);\n if (o.c.second !== 0 || !suppressSeconds) {\n c += \":\";\n }\n } else {\n c += padStart(o.c.minute);\n }\n\n if (o.c.second !== 0 || !suppressSeconds) {\n c += padStart(o.c.second);\n\n if (o.c.millisecond !== 0 || !suppressMilliseconds) {\n c += \".\";\n c += padStart(o.c.millisecond, 3);\n }\n }\n\n if (includeOffset) {\n if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {\n c += \"Z\";\n } else if (o.o < 0) {\n c += \"-\";\n c += padStart(Math.trunc(-o.o / 60));\n c += \":\";\n c += padStart(Math.trunc(-o.o % 60));\n } else {\n c += \"+\";\n c += padStart(Math.trunc(o.o / 60));\n c += \":\";\n c += padStart(Math.trunc(o.o % 60));\n }\n }\n\n if (extendedZone) {\n c += \"[\" + o.zone.ianaName + \"]\";\n }\n return c;\n}\n\n// defaults for unspecified units in the supported calendars\nconst defaultUnitValues = {\n month: 1,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n },\n defaultWeekUnitValues = {\n weekNumber: 1,\n weekday: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n },\n defaultOrdinalUnitValues = {\n ordinal: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n };\n\n// Units in the supported calendars, sorted by bigness\nconst orderedUnits = [\"year\", \"month\", \"day\", \"hour\", \"minute\", \"second\", \"millisecond\"],\n orderedWeekUnits = [\n \"weekYear\",\n \"weekNumber\",\n \"weekday\",\n \"hour\",\n \"minute\",\n \"second\",\n \"millisecond\",\n ],\n orderedOrdinalUnits = [\"year\", \"ordinal\", \"hour\", \"minute\", \"second\", \"millisecond\"];\n\n// standardize case and plurality in units\nfunction normalizeUnit(unit) {\n const normalized = {\n year: \"year\",\n years: \"year\",\n month: \"month\",\n months: \"month\",\n day: \"day\",\n days: \"day\",\n hour: \"hour\",\n hours: \"hour\",\n minute: \"minute\",\n minutes: \"minute\",\n quarter: \"quarter\",\n quarters: \"quarter\",\n second: \"second\",\n seconds: \"second\",\n millisecond: \"millisecond\",\n milliseconds: \"millisecond\",\n weekday: \"weekday\",\n weekdays: \"weekday\",\n weeknumber: \"weekNumber\",\n weeksnumber: \"weekNumber\",\n weeknumbers: \"weekNumber\",\n weekyear: \"weekYear\",\n weekyears: \"weekYear\",\n ordinal: \"ordinal\",\n }[unit.toLowerCase()];\n\n if (!normalized) throw new InvalidUnitError(unit);\n\n return normalized;\n}\n\n// this is a dumbed down version of fromObject() that runs about 60% faster\n// but doesn't do any validation, makes a bunch of assumptions about what units\n// are present, and so on.\nfunction quickDT(obj, opts) {\n const zone = normalizeZone(opts.zone, Settings.defaultZone),\n loc = Locale.fromObject(opts),\n tsNow = Settings.now();\n\n let ts, o;\n\n // assume we have the higher-order units\n if (!isUndefined(obj.year)) {\n for (const u of orderedUnits) {\n if (isUndefined(obj[u])) {\n obj[u] = defaultUnitValues[u];\n }\n }\n\n const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);\n if (invalid) {\n return DateTime.invalid(invalid);\n }\n\n const offsetProvis = zone.offset(tsNow);\n [ts, o] = objToTS(obj, offsetProvis, zone);\n } else {\n ts = tsNow;\n }\n\n return new DateTime({ ts, zone, loc, o });\n}\n\nfunction diffRelative(start, end, opts) {\n const round = isUndefined(opts.round) ? true : opts.round,\n format = (c, unit) => {\n c = roundTo(c, round || opts.calendary ? 0 : 2, true);\n const formatter = end.loc.clone(opts).relFormatter(opts);\n return formatter.format(c, unit);\n },\n differ = (unit) => {\n if (opts.calendary) {\n if (!end.hasSame(start, unit)) {\n return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);\n } else return 0;\n } else {\n return end.diff(start, unit).get(unit);\n }\n };\n\n if (opts.unit) {\n return format(differ(opts.unit), opts.unit);\n }\n\n for (const unit of opts.units) {\n const count = differ(unit);\n if (Math.abs(count) >= 1) {\n return format(count, unit);\n }\n }\n return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);\n}\n\nfunction lastOpts(argList) {\n let opts = {},\n args;\n if (argList.length > 0 && typeof argList[argList.length - 1] === \"object\") {\n opts = argList[argList.length - 1];\n args = Array.from(argList).slice(0, argList.length - 1);\n } else {\n args = Array.from(argList);\n }\n return [opts, args];\n}\n\n/**\n * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.\n *\n * A DateTime comprises of:\n * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.\n * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).\n * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.\n *\n * Here is a brief overview of the most commonly used functionality it provides:\n *\n * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link DateTime#local}, {@link DateTime#utc}, and (most flexibly) {@link DateTime#fromObject}. To create one from a standard string format, use {@link DateTime#fromISO}, {@link DateTime#fromHTTP}, and {@link DateTime#fromRFC2822}. To create one from a custom string format, use {@link DateTime#fromFormat}. To create one from a native JS date, use {@link DateTime#fromJSDate}.\n * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link DateTime#toObject}), use the {@link DateTime#year}, {@link DateTime#month},\n * {@link DateTime#day}, {@link DateTime#hour}, {@link DateTime#minute}, {@link DateTime#second}, {@link DateTime#millisecond} accessors.\n * * **Week calendar**: For ISO week calendar attributes, see the {@link DateTime#weekYear}, {@link DateTime#weekNumber}, and {@link DateTime#weekday} accessors.\n * * **Configuration** See the {@link DateTime#locale} and {@link DateTime#numberingSystem} accessors.\n * * **Transformation**: To transform the DateTime into other DateTimes, use {@link DateTime#set}, {@link DateTime#reconfigure}, {@link DateTime#setZone}, {@link DateTime#setLocale}, {@link DateTime.plus}, {@link DateTime#minus}, {@link DateTime#endOf}, {@link DateTime#startOf}, {@link DateTime#toUTC}, and {@link DateTime#toLocal}.\n * * **Output**: To convert the DateTime to other representations, use the {@link DateTime#toRelative}, {@link DateTime#toRelativeCalendar}, {@link DateTime#toJSON}, {@link DateTime#toISO}, {@link DateTime#toHTTP}, {@link DateTime#toObject}, {@link DateTime#toRFC2822}, {@link DateTime#toString}, {@link DateTime#toLocaleString}, {@link DateTime#toFormat}, {@link DateTime#toMillis} and {@link DateTime#toJSDate}.\n *\n * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation.\n */\nexport default class DateTime {\n /**\n * @access private\n */\n constructor(config) {\n const zone = config.zone || Settings.defaultZone;\n\n let invalid =\n config.invalid ||\n (Number.isNaN(config.ts) ? new Invalid(\"invalid input\") : null) ||\n (!zone.isValid ? unsupportedZone(zone) : null);\n /**\n * @access private\n */\n this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;\n\n let c = null,\n o = null;\n if (!invalid) {\n const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);\n\n if (unchanged) {\n [c, o] = [config.old.c, config.old.o];\n } else {\n const ot = zone.offset(this.ts);\n c = tsToObj(this.ts, ot);\n invalid = Number.isNaN(c.year) ? new Invalid(\"invalid input\") : null;\n c = invalid ? null : c;\n o = invalid ? null : ot;\n }\n }\n\n /**\n * @access private\n */\n this._zone = zone;\n /**\n * @access private\n */\n this.loc = config.loc || Locale.create();\n /**\n * @access private\n */\n this.invalid = invalid;\n /**\n * @access private\n */\n this.weekData = null;\n /**\n * @access private\n */\n this.c = c;\n /**\n * @access private\n */\n this.o = o;\n /**\n * @access private\n */\n this.isLuxonDateTime = true;\n }\n\n // CONSTRUCT\n\n /**\n * Create a DateTime for the current instant, in the system's time zone.\n *\n * Use Settings to override these default values if needed.\n * @example DateTime.now().toISO() //~> now in the ISO format\n * @return {DateTime}\n */\n static now() {\n return new DateTime({});\n }\n\n /**\n * Create a local DateTime\n * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used\n * @param {number} [month=1] - The month, 1-indexed\n * @param {number} [day=1] - The day of the month, 1-indexed\n * @param {number} [hour=0] - The hour of the day, in 24-hour time\n * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59\n * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59\n * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999\n * @example DateTime.local() //~> now\n * @example DateTime.local({ zone: \"America/New_York\" }) //~> now, in US east coast time\n * @example DateTime.local(2017) //~> 2017-01-01T00:00:00\n * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00\n * @example DateTime.local(2017, 3, 12, { locale: \"fr\" }) //~> 2017-03-12T00:00:00, with a French locale\n * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00\n * @example DateTime.local(2017, 3, 12, 5, { zone: \"utc\" }) //~> 2017-03-12T05:00:00, in UTC\n * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00\n * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10\n * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765\n * @return {DateTime}\n */\n static local() {\n const [opts, args] = lastOpts(arguments),\n [year, month, day, hour, minute, second, millisecond] = args;\n return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);\n }\n\n /**\n * Create a DateTime in UTC\n * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used\n * @param {number} [month=1] - The month, 1-indexed\n * @param {number} [day=1] - The day of the month\n * @param {number} [hour=0] - The hour of the day, in 24-hour time\n * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59\n * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59\n * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999\n * @param {Object} options - configuration options for the DateTime\n * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance\n * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance\n * @example DateTime.utc() //~> now\n * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z\n * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z\n * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z\n * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z\n * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z\n * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: \"fr\" }) //~> 2017-03-12T05:45:00Z with a French locale\n * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z\n * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: \"fr\" }) //~> 2017-03-12T05:45:10.765Z with a French locale\n * @return {DateTime}\n */\n static utc() {\n const [opts, args] = lastOpts(arguments),\n [year, month, day, hour, minute, second, millisecond] = args;\n\n opts.zone = FixedOffsetZone.utcInstance;\n return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);\n }\n\n /**\n * Create a DateTime from a JavaScript Date object. Uses the default zone.\n * @param {Date} date - a JavaScript Date object\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @return {DateTime}\n */\n static fromJSDate(date, options = {}) {\n const ts = isDate(date) ? date.valueOf() : NaN;\n if (Number.isNaN(ts)) {\n return DateTime.invalid(\"invalid input\");\n }\n\n const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);\n if (!zoneToUse.isValid) {\n return DateTime.invalid(unsupportedZone(zoneToUse));\n }\n\n return new DateTime({\n ts: ts,\n zone: zoneToUse,\n loc: Locale.fromObject(options),\n });\n }\n\n /**\n * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.\n * @param {number} milliseconds - a number of milliseconds since 1970 UTC\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromMillis(milliseconds, options = {}) {\n if (!isNumber(milliseconds)) {\n throw new InvalidArgumentError(\n `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`\n );\n } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {\n // this isn't perfect because because we can still end up out of range because of additional shifting, but it's a start\n return DateTime.invalid(\"Timestamp out of range\");\n } else {\n return new DateTime({\n ts: milliseconds,\n zone: normalizeZone(options.zone, Settings.defaultZone),\n loc: Locale.fromObject(options),\n });\n }\n }\n\n /**\n * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.\n * @param {number} seconds - a number of seconds since 1970 UTC\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromSeconds(seconds, options = {}) {\n if (!isNumber(seconds)) {\n throw new InvalidArgumentError(\"fromSeconds requires a numerical input\");\n } else {\n return new DateTime({\n ts: seconds * 1000,\n zone: normalizeZone(options.zone, Settings.defaultZone),\n loc: Locale.fromObject(options),\n });\n }\n }\n\n /**\n * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.\n * @param {Object} obj - the object to create the DateTime from\n * @param {number} obj.year - a year, such as 1987\n * @param {number} obj.month - a month, 1-12\n * @param {number} obj.day - a day of the month, 1-31, depending on the month\n * @param {number} obj.ordinal - day of the year, 1-365 or 366\n * @param {number} obj.weekYear - an ISO week year\n * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year\n * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday\n * @param {number} obj.hour - hour of the day, 0-23\n * @param {number} obj.minute - minute of the hour, 0-59\n * @param {number} obj.second - second of the minute, 0-59\n * @param {number} obj.millisecond - millisecond of the second, 0-999\n * @param {Object} opts - options for creating this DateTime\n * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'\n * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })\n * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'\n * @return {DateTime}\n */\n static fromObject(obj, opts = {}) {\n obj = obj || {};\n const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);\n if (!zoneToUse.isValid) {\n return DateTime.invalid(unsupportedZone(zoneToUse));\n }\n\n const tsNow = Settings.now(),\n offsetProvis = !isUndefined(opts.specificOffset)\n ? opts.specificOffset\n : zoneToUse.offset(tsNow),\n normalized = normalizeObject(obj, normalizeUnit),\n containsOrdinal = !isUndefined(normalized.ordinal),\n containsGregorYear = !isUndefined(normalized.year),\n containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),\n containsGregor = containsGregorYear || containsGregorMD,\n definiteWeekDef = normalized.weekYear || normalized.weekNumber,\n loc = Locale.fromObject(opts);\n\n // cases:\n // just a weekday -> this week's instance of that weekday, no worries\n // (gregorian data or ordinal) + (weekYear or weekNumber) -> error\n // (gregorian month or day) + ordinal -> error\n // otherwise just use weeks or ordinals or gregorian, depending on what's specified\n\n if ((containsGregor || containsOrdinal) && definiteWeekDef) {\n throw new ConflictingSpecificationError(\n \"Can't mix weekYear/weekNumber units with year/month/day or ordinals\"\n );\n }\n\n if (containsGregorMD && containsOrdinal) {\n throw new ConflictingSpecificationError(\"Can't mix ordinal dates with month/day\");\n }\n\n const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor);\n\n // configure ourselves to deal with gregorian dates or week stuff\n let units,\n defaultValues,\n objNow = tsToObj(tsNow, offsetProvis);\n if (useWeekData) {\n units = orderedWeekUnits;\n defaultValues = defaultWeekUnitValues;\n objNow = gregorianToWeek(objNow);\n } else if (containsOrdinal) {\n units = orderedOrdinalUnits;\n defaultValues = defaultOrdinalUnitValues;\n objNow = gregorianToOrdinal(objNow);\n } else {\n units = orderedUnits;\n defaultValues = defaultUnitValues;\n }\n\n // set default values for missing stuff\n let foundFirst = false;\n for (const u of units) {\n const v = normalized[u];\n if (!isUndefined(v)) {\n foundFirst = true;\n } else if (foundFirst) {\n normalized[u] = defaultValues[u];\n } else {\n normalized[u] = objNow[u];\n }\n }\n\n // make sure the values we have are in range\n const higherOrderInvalid = useWeekData\n ? hasInvalidWeekData(normalized)\n : containsOrdinal\n ? hasInvalidOrdinalData(normalized)\n : hasInvalidGregorianData(normalized),\n invalid = higherOrderInvalid || hasInvalidTimeData(normalized);\n\n if (invalid) {\n return DateTime.invalid(invalid);\n }\n\n // compute the actual time\n const gregorian = useWeekData\n ? weekToGregorian(normalized)\n : containsOrdinal\n ? ordinalToGregorian(normalized)\n : normalized,\n [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse),\n inst = new DateTime({\n ts: tsFinal,\n zone: zoneToUse,\n o: offsetFinal,\n loc,\n });\n\n // gregorian data + weekday serves only to validate\n if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {\n return DateTime.invalid(\n \"mismatched weekday\",\n `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`\n );\n }\n\n return inst;\n }\n\n /**\n * Create a DateTime from an ISO 8601 string\n * @param {string} text - the ISO string\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone\n * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance\n * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromISO('2016-05-25T09:08:34.123')\n * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')\n * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})\n * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})\n * @example DateTime.fromISO('2016-W05-4')\n * @return {DateTime}\n */\n static fromISO(text, opts = {}) {\n const [vals, parsedZone] = parseISODate(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"ISO 8601\", text);\n }\n\n /**\n * Create a DateTime from an RFC 2822 string\n * @param {string} text - the RFC 2822 string\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.\n * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')\n * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')\n * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')\n * @return {DateTime}\n */\n static fromRFC2822(text, opts = {}) {\n const [vals, parsedZone] = parseRFC2822Date(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"RFC 2822\", text);\n }\n\n /**\n * Create a DateTime from an HTTP header date\n * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n * @param {string} text - the HTTP header date\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.\n * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')\n * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')\n * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994')\n * @return {DateTime}\n */\n static fromHTTP(text, opts = {}) {\n const [vals, parsedZone] = parseHTTPDate(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"HTTP\", opts);\n }\n\n /**\n * Create a DateTime from an input string and format string.\n * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).\n * @param {string} text - the string to parse\n * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone\n * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale\n * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromFormat(text, fmt, opts = {}) {\n if (isUndefined(text) || isUndefined(fmt)) {\n throw new InvalidArgumentError(\"fromFormat requires an input string and a format\");\n }\n\n const { locale = null, numberingSystem = null } = opts,\n localeToUse = Locale.fromOpts({\n locale,\n numberingSystem,\n defaultToEN: true,\n }),\n [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt);\n if (invalid) {\n return DateTime.invalid(invalid);\n } else {\n return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset);\n }\n }\n\n /**\n * @deprecated use fromFormat instead\n */\n static fromString(text, fmt, opts = {}) {\n return DateTime.fromFormat(text, fmt, opts);\n }\n\n /**\n * Create a DateTime from a SQL date, time, or datetime\n * Defaults to en-US if no locale has been specified, regardless of the system's locale\n * @param {string} text - the string to parse\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone\n * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale\n * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @example DateTime.fromSQL('2017-05-15')\n * @example DateTime.fromSQL('2017-05-15 09:12:34')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })\n * @example DateTime.fromSQL('09:12:34.342')\n * @return {DateTime}\n */\n static fromSQL(text, opts = {}) {\n const [vals, parsedZone] = parseSQL(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"SQL\", text);\n }\n\n /**\n * Create an invalid DateTime.\n * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent\n * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n * @return {DateTime}\n */\n static invalid(reason, explanation = null) {\n if (!reason) {\n throw new InvalidArgumentError(\"need to specify a reason the DateTime is invalid\");\n }\n\n const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n if (Settings.throwOnInvalid) {\n throw new InvalidDateTimeError(invalid);\n } else {\n return new DateTime({ invalid });\n }\n }\n\n /**\n * Check if an object is an instance of DateTime. Works across context boundaries\n * @param {object} o\n * @return {boolean}\n */\n static isDateTime(o) {\n return (o && o.isLuxonDateTime) || false;\n }\n\n // INFO\n\n /**\n * Get the value of unit.\n * @param {string} unit - a unit such as 'minute' or 'day'\n * @example DateTime.local(2017, 7, 4).get('month'); //=> 7\n * @example DateTime.local(2017, 7, 4).get('day'); //=> 4\n * @return {number}\n */\n get(unit) {\n return this[unit];\n }\n\n /**\n * Returns whether the DateTime is valid. Invalid DateTimes occur when:\n * * The DateTime was created from invalid calendar information, such as the 13th month or February 30\n * * The DateTime was created by an operation on another invalid date\n * @type {boolean}\n */\n get isValid() {\n return this.invalid === null;\n }\n\n /**\n * Returns an error code if this DateTime is invalid, or null if the DateTime is valid\n * @type {string}\n */\n get invalidReason() {\n return this.invalid ? this.invalid.reason : null;\n }\n\n /**\n * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid\n * @type {string}\n */\n get invalidExplanation() {\n return this.invalid ? this.invalid.explanation : null;\n }\n\n /**\n * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime\n *\n * @type {string}\n */\n get locale() {\n return this.isValid ? this.loc.locale : null;\n }\n\n /**\n * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime\n *\n * @type {string}\n */\n get numberingSystem() {\n return this.isValid ? this.loc.numberingSystem : null;\n }\n\n /**\n * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime\n *\n * @type {string}\n */\n get outputCalendar() {\n return this.isValid ? this.loc.outputCalendar : null;\n }\n\n /**\n * Get the time zone associated with this DateTime.\n * @type {Zone}\n */\n get zone() {\n return this._zone;\n }\n\n /**\n * Get the name of the time zone.\n * @type {string}\n */\n get zoneName() {\n return this.isValid ? this.zone.name : null;\n }\n\n /**\n * Get the year\n * @example DateTime.local(2017, 5, 25).year //=> 2017\n * @type {number}\n */\n get year() {\n return this.isValid ? this.c.year : NaN;\n }\n\n /**\n * Get the quarter\n * @example DateTime.local(2017, 5, 25).quarter //=> 2\n * @type {number}\n */\n get quarter() {\n return this.isValid ? Math.ceil(this.c.month / 3) : NaN;\n }\n\n /**\n * Get the month (1-12).\n * @example DateTime.local(2017, 5, 25).month //=> 5\n * @type {number}\n */\n get month() {\n return this.isValid ? this.c.month : NaN;\n }\n\n /**\n * Get the day of the month (1-30ish).\n * @example DateTime.local(2017, 5, 25).day //=> 25\n * @type {number}\n */\n get day() {\n return this.isValid ? this.c.day : NaN;\n }\n\n /**\n * Get the hour of the day (0-23).\n * @example DateTime.local(2017, 5, 25, 9).hour //=> 9\n * @type {number}\n */\n get hour() {\n return this.isValid ? this.c.hour : NaN;\n }\n\n /**\n * Get the minute of the hour (0-59).\n * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30\n * @type {number}\n */\n get minute() {\n return this.isValid ? this.c.minute : NaN;\n }\n\n /**\n * Get the second of the minute (0-59).\n * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52\n * @type {number}\n */\n get second() {\n return this.isValid ? this.c.second : NaN;\n }\n\n /**\n * Get the millisecond of the second (0-999).\n * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654\n * @type {number}\n */\n get millisecond() {\n return this.isValid ? this.c.millisecond : NaN;\n }\n\n /**\n * Get the week year\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2014, 12, 31).weekYear //=> 2015\n * @type {number}\n */\n get weekYear() {\n return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;\n }\n\n /**\n * Get the week number of the week year (1-52ish).\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2017, 5, 25).weekNumber //=> 21\n * @type {number}\n */\n get weekNumber() {\n return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;\n }\n\n /**\n * Get the day of the week.\n * 1 is Monday and 7 is Sunday\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2014, 11, 31).weekday //=> 4\n * @type {number}\n */\n get weekday() {\n return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;\n }\n\n /**\n * Get the ordinal (meaning the day of the year)\n * @example DateTime.local(2017, 5, 25).ordinal //=> 145\n * @type {number|DateTime}\n */\n get ordinal() {\n return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;\n }\n\n /**\n * Get the human readable short month name, such as 'Oct'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).monthShort //=> Oct\n * @type {string}\n */\n get monthShort() {\n return this.isValid ? Info.months(\"short\", { locObj: this.loc })[this.month - 1] : null;\n }\n\n /**\n * Get the human readable long month name, such as 'October'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).monthLong //=> October\n * @type {string}\n */\n get monthLong() {\n return this.isValid ? Info.months(\"long\", { locObj: this.loc })[this.month - 1] : null;\n }\n\n /**\n * Get the human readable short weekday, such as 'Mon'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon\n * @type {string}\n */\n get weekdayShort() {\n return this.isValid ? Info.weekdays(\"short\", { locObj: this.loc })[this.weekday - 1] : null;\n }\n\n /**\n * Get the human readable long weekday, such as 'Monday'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday\n * @type {string}\n */\n get weekdayLong() {\n return this.isValid ? Info.weekdays(\"long\", { locObj: this.loc })[this.weekday - 1] : null;\n }\n\n /**\n * Get the UTC offset of this DateTime in minutes\n * @example DateTime.now().offset //=> -240\n * @example DateTime.utc().offset //=> 0\n * @type {number}\n */\n get offset() {\n return this.isValid ? +this.o : NaN;\n }\n\n /**\n * Get the short human name for the zone's current offset, for example \"EST\" or \"EDT\".\n * Defaults to the system's locale if no locale has been specified\n * @type {string}\n */\n get offsetNameShort() {\n if (this.isValid) {\n return this.zone.offsetName(this.ts, {\n format: \"short\",\n locale: this.locale,\n });\n } else {\n return null;\n }\n }\n\n /**\n * Get the long human name for the zone's current offset, for example \"Eastern Standard Time\" or \"Eastern Daylight Time\".\n * Defaults to the system's locale if no locale has been specified\n * @type {string}\n */\n get offsetNameLong() {\n if (this.isValid) {\n return this.zone.offsetName(this.ts, {\n format: \"long\",\n locale: this.locale,\n });\n } else {\n return null;\n }\n }\n\n /**\n * Get whether this zone's offset ever changes, as in a DST.\n * @type {boolean}\n */\n get isOffsetFixed() {\n return this.isValid ? this.zone.isUniversal : null;\n }\n\n /**\n * Get whether the DateTime is in a DST.\n * @type {boolean}\n */\n get isInDST() {\n if (this.isOffsetFixed) {\n return false;\n } else {\n return (\n this.offset > this.set({ month: 1, day: 1 }).offset ||\n this.offset > this.set({ month: 5 }).offset\n );\n }\n }\n\n /**\n * Returns true if this DateTime is in a leap year, false otherwise\n * @example DateTime.local(2016).isInLeapYear //=> true\n * @example DateTime.local(2013).isInLeapYear //=> false\n * @type {boolean}\n */\n get isInLeapYear() {\n return isLeapYear(this.year);\n }\n\n /**\n * Returns the number of days in this DateTime's month\n * @example DateTime.local(2016, 2).daysInMonth //=> 29\n * @example DateTime.local(2016, 3).daysInMonth //=> 31\n * @type {number}\n */\n get daysInMonth() {\n return daysInMonth(this.year, this.month);\n }\n\n /**\n * Returns the number of days in this DateTime's year\n * @example DateTime.local(2016).daysInYear //=> 366\n * @example DateTime.local(2013).daysInYear //=> 365\n * @type {number}\n */\n get daysInYear() {\n return this.isValid ? daysInYear(this.year) : NaN;\n }\n\n /**\n * Returns the number of weeks in this DateTime's year\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2004).weeksInWeekYear //=> 53\n * @example DateTime.local(2013).weeksInWeekYear //=> 52\n * @type {number}\n */\n get weeksInWeekYear() {\n return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;\n }\n\n /**\n * Returns the resolved Intl options for this DateTime.\n * This is useful in understanding the behavior of formatting methods\n * @param {Object} opts - the same options as toLocaleString\n * @return {Object}\n */\n resolvedLocaleOptions(opts = {}) {\n const { locale, numberingSystem, calendar } = Formatter.create(\n this.loc.clone(opts),\n opts\n ).resolvedOptions(this);\n return { locale, numberingSystem, outputCalendar: calendar };\n }\n\n // TRANSFORM\n\n /**\n * \"Set\" the DateTime's zone to UTC. Returns a newly-constructed DateTime.\n *\n * Equivalent to {@link DateTime#setZone}('utc')\n * @param {number} [offset=0] - optionally, an offset from UTC in minutes\n * @param {Object} [opts={}] - options to pass to `setZone()`\n * @return {DateTime}\n */\n toUTC(offset = 0, opts = {}) {\n return this.setZone(FixedOffsetZone.instance(offset), opts);\n }\n\n /**\n * \"Set\" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.\n *\n * Equivalent to `setZone('local')`\n * @return {DateTime}\n */\n toLocal() {\n return this.setZone(Settings.defaultZone);\n }\n\n /**\n * \"Set\" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.\n *\n * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.\n * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.\n * @param {Object} opts - options\n * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.\n * @return {DateTime}\n */\n setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {\n zone = normalizeZone(zone, Settings.defaultZone);\n if (zone.equals(this.zone)) {\n return this;\n } else if (!zone.isValid) {\n return DateTime.invalid(unsupportedZone(zone));\n } else {\n let newTS = this.ts;\n if (keepLocalTime || keepCalendarTime) {\n const offsetGuess = zone.offset(this.ts);\n const asObj = this.toObject();\n [newTS] = objToTS(asObj, offsetGuess, zone);\n }\n return clone(this, { ts: newTS, zone });\n }\n }\n\n /**\n * \"Set\" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.\n * @param {Object} properties - the properties to set\n * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })\n * @return {DateTime}\n */\n reconfigure({ locale, numberingSystem, outputCalendar } = {}) {\n const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });\n return clone(this, { loc });\n }\n\n /**\n * \"Set\" the locale. Returns a newly-constructed DateTime.\n * Just a convenient alias for reconfigure({ locale })\n * @example DateTime.local(2017, 5, 25).setLocale('en-GB')\n * @return {DateTime}\n */\n setLocale(locale) {\n return this.reconfigure({ locale });\n }\n\n /**\n * \"Set\" the values of specified units. Returns a newly-constructed DateTime.\n * You can only set units with this method; for \"setting\" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.\n * @param {Object} values - a mapping of units to numbers\n * @example dt.set({ year: 2017 })\n * @example dt.set({ hour: 8, minute: 30 })\n * @example dt.set({ weekday: 5 })\n * @example dt.set({ year: 2005, ordinal: 234 })\n * @return {DateTime}\n */\n set(values) {\n if (!this.isValid) return this;\n\n const normalized = normalizeObject(values, normalizeUnit),\n settingWeekStuff =\n !isUndefined(normalized.weekYear) ||\n !isUndefined(normalized.weekNumber) ||\n !isUndefined(normalized.weekday),\n containsOrdinal = !isUndefined(normalized.ordinal),\n containsGregorYear = !isUndefined(normalized.year),\n containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),\n containsGregor = containsGregorYear || containsGregorMD,\n definiteWeekDef = normalized.weekYear || normalized.weekNumber;\n\n if ((containsGregor || containsOrdinal) && definiteWeekDef) {\n throw new ConflictingSpecificationError(\n \"Can't mix weekYear/weekNumber units with year/month/day or ordinals\"\n );\n }\n\n if (containsGregorMD && containsOrdinal) {\n throw new ConflictingSpecificationError(\"Can't mix ordinal dates with month/day\");\n }\n\n let mixed;\n if (settingWeekStuff) {\n mixed = weekToGregorian({ ...gregorianToWeek(this.c), ...normalized });\n } else if (!isUndefined(normalized.ordinal)) {\n mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized });\n } else {\n mixed = { ...this.toObject(), ...normalized };\n\n // if we didn't set the day but we ended up on an overflow date,\n // use the last day of the right month\n if (isUndefined(normalized.day)) {\n mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);\n }\n }\n\n const [ts, o] = objToTS(mixed, this.o, this.zone);\n return clone(this, { ts, o });\n }\n\n /**\n * Add a period of time to this DateTime and return the resulting DateTime\n *\n * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.\n * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n * @example DateTime.now().plus(123) //~> in 123 milliseconds\n * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes\n * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow\n * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday\n * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min\n * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min\n * @return {DateTime}\n */\n plus(duration) {\n if (!this.isValid) return this;\n const dur = Duration.fromDurationLike(duration);\n return clone(this, adjustTime(this, dur));\n }\n\n /**\n * Subtract a period of time to this DateTime and return the resulting DateTime\n * See {@link DateTime#plus}\n * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n @return {DateTime}\n */\n minus(duration) {\n if (!this.isValid) return this;\n const dur = Duration.fromDurationLike(duration).negate();\n return clone(this, adjustTime(this, dur));\n }\n\n /**\n * \"Set\" this DateTime to the beginning of a unit of time.\n * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'\n * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'\n * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays\n * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'\n * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'\n * @return {DateTime}\n */\n startOf(unit) {\n if (!this.isValid) return this;\n const o = {},\n normalizedUnit = Duration.normalizeUnit(unit);\n switch (normalizedUnit) {\n case \"years\":\n o.month = 1;\n // falls through\n case \"quarters\":\n case \"months\":\n o.day = 1;\n // falls through\n case \"weeks\":\n case \"days\":\n o.hour = 0;\n // falls through\n case \"hours\":\n o.minute = 0;\n // falls through\n case \"minutes\":\n o.second = 0;\n // falls through\n case \"seconds\":\n o.millisecond = 0;\n break;\n case \"milliseconds\":\n break;\n // no default, invalid units throw in normalizeUnit()\n }\n\n if (normalizedUnit === \"weeks\") {\n o.weekday = 1;\n }\n\n if (normalizedUnit === \"quarters\") {\n const q = Math.ceil(this.month / 3);\n o.month = (q - 1) * 3 + 1;\n }\n\n return this.set(o);\n }\n\n /**\n * \"Set\" this DateTime to the end (meaning the last millisecond) of a unit of time\n * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays\n * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'\n * @return {DateTime}\n */\n endOf(unit) {\n return this.isValid\n ? this.plus({ [unit]: 1 })\n .startOf(unit)\n .minus(1)\n : this;\n }\n\n // OUTPUT\n\n /**\n * Returns a string representation of this DateTime formatted according to the specified format string.\n * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).\n * Defaults to en-US if no locale has been specified, regardless of the system's locale.\n * @param {string} fmt - the format string\n * @param {Object} opts - opts to override the configuration options on this DateTime\n * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'\n * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'\n * @example DateTime.now().toFormat('yyyy LLL dd', { locale: \"fr\" }) //=> '2017 avr. 22'\n * @example DateTime.now().toFormat(\"HH 'hours and' mm 'minutes'\") //=> '20 hours and 55 minutes'\n * @return {string}\n */\n toFormat(fmt, opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt)\n : INVALID;\n }\n\n /**\n * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.\n * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation\n * of the DateTime in the assigned locale.\n * Defaults to the system's locale if no locale has been specified\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options\n * @param {Object} opts - opts to override the configuration options on this DateTime\n * @example DateTime.now().toLocaleString(); //=> 4/20/2017\n * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'\n * @example DateTime.now().toLocaleString({ locale: 'en-gb' }); //=> '20/04/2017'\n * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'\n * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'\n * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'\n * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'\n * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'\n * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'\n * @return {string}\n */\n toLocaleString(formatOpts = Formats.DATE_SHORT, opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this)\n : INVALID;\n }\n\n /**\n * Returns an array of format \"parts\", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.\n * Defaults to the system's locale if no locale has been specified\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts\n * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.\n * @example DateTime.now().toLocaleParts(); //=> [\n * //=> { type: 'day', value: '25' },\n * //=> { type: 'literal', value: '/' },\n * //=> { type: 'month', value: '05' },\n * //=> { type: 'literal', value: '/' },\n * //=> { type: 'year', value: '1982' }\n * //=> ]\n */\n toLocaleParts(opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this)\n : [];\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime\n * @param {Object} opts - options\n * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.extendedZone=true] - add the time zone format extension\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'\n * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'\n * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'\n * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'\n * @return {string}\n */\n toISO({\n format = \"extended\",\n suppressSeconds = false,\n suppressMilliseconds = false,\n includeOffset = true,\n extendedZone = false,\n } = {}) {\n if (!this.isValid) {\n return null;\n }\n\n const ext = format === \"extended\";\n\n let c = toISODate(this, ext);\n c += \"T\";\n c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);\n return c;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's date component\n * @param {Object} opts - options\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'\n * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'\n * @return {string}\n */\n toISODate({ format = \"extended\" } = {}) {\n if (!this.isValid) {\n return null;\n }\n\n return toISODate(this, format === \"extended\");\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's week date\n * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'\n * @return {string}\n */\n toISOWeekDate() {\n return toTechFormat(this, \"kkkk-'W'WW-c\");\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's time component\n * @param {Object} opts - options\n * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.extendedZone=true] - add the time zone format extension\n * @param {boolean} [opts.includePrefix=false] - include the `T` prefix\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'\n * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'\n * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'\n * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'\n * @return {string}\n */\n toISOTime({\n suppressMilliseconds = false,\n suppressSeconds = false,\n includeOffset = true,\n includePrefix = false,\n extendedZone = false,\n format = \"extended\",\n } = {}) {\n if (!this.isValid) {\n return null;\n }\n\n let c = includePrefix ? \"T\" : \"\";\n return (\n c +\n toISOTime(\n this,\n format === \"extended\",\n suppressSeconds,\n suppressMilliseconds,\n includeOffset,\n extendedZone\n )\n );\n }\n\n /**\n * Returns an RFC 2822-compatible string representation of this DateTime\n * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'\n * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'\n * @return {string}\n */\n toRFC2822() {\n return toTechFormat(this, \"EEE, dd LLL yyyy HH:mm:ss ZZZ\", false);\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.\n * Specifically, the string conforms to RFC 1123.\n * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'\n * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'\n * @return {string}\n */\n toHTTP() {\n return toTechFormat(this.toUTC(), \"EEE, dd LLL yyyy HH:mm:ss 'GMT'\");\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in SQL Date\n * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'\n * @return {string}\n */\n toSQLDate() {\n if (!this.isValid) {\n return null;\n }\n return toISODate(this, true);\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in SQL Time\n * @param {Object} opts - options\n * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'\n * @example DateTime.utc().toSQL() //=> '05:15:16.345'\n * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'\n * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'\n * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'\n * @return {string}\n */\n toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) {\n let fmt = \"HH:mm:ss.SSS\";\n\n if (includeZone || includeOffset) {\n if (includeOffsetSpace) {\n fmt += \" \";\n }\n if (includeZone) {\n fmt += \"z\";\n } else if (includeOffset) {\n fmt += \"ZZ\";\n }\n }\n\n return toTechFormat(this, fmt, true);\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in SQL DateTime\n * @param {Object} opts - options\n * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'\n * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'\n * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'\n * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'\n * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'\n * @return {string}\n */\n toSQL(opts = {}) {\n if (!this.isValid) {\n return null;\n }\n\n return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for debugging\n * @return {string}\n */\n toString() {\n return this.isValid ? this.toISO() : INVALID;\n }\n\n /**\n * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}\n * @return {number}\n */\n valueOf() {\n return this.toMillis();\n }\n\n /**\n * Returns the epoch milliseconds of this DateTime.\n * @return {number}\n */\n toMillis() {\n return this.isValid ? this.ts : NaN;\n }\n\n /**\n * Returns the epoch seconds of this DateTime.\n * @return {number}\n */\n toSeconds() {\n return this.isValid ? this.ts / 1000 : NaN;\n }\n\n /**\n * Returns the epoch seconds (as a whole number) of this DateTime.\n * @return {number}\n */\n toUnixInteger() {\n return this.isValid ? Math.floor(this.ts / 1000) : NaN;\n }\n\n /**\n * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.\n * @return {string}\n */\n toJSON() {\n return this.toISO();\n }\n\n /**\n * Returns a BSON serializable equivalent to this DateTime.\n * @return {Date}\n */\n toBSON() {\n return this.toJSDate();\n }\n\n /**\n * Returns a JavaScript object with this DateTime's year, month, day, and so on.\n * @param opts - options for generating the object\n * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output\n * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }\n * @return {Object}\n */\n toObject(opts = {}) {\n if (!this.isValid) return {};\n\n const base = { ...this.c };\n\n if (opts.includeConfig) {\n base.outputCalendar = this.outputCalendar;\n base.numberingSystem = this.loc.numberingSystem;\n base.locale = this.loc.locale;\n }\n return base;\n }\n\n /**\n * Returns a JavaScript Date equivalent to this DateTime.\n * @return {Date}\n */\n toJSDate() {\n return new Date(this.isValid ? this.ts : NaN);\n }\n\n // COMPARE\n\n /**\n * Return the difference between two DateTimes as a Duration.\n * @param {DateTime} otherDateTime - the DateTime to compare this one to\n * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.\n * @param {Object} opts - options that affect the creation of the Duration\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @example\n * var i1 = DateTime.fromISO('1982-05-25T09:45'),\n * i2 = DateTime.fromISO('1983-10-14T10:30');\n * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }\n * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }\n * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }\n * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }\n * @return {Duration}\n */\n diff(otherDateTime, unit = \"milliseconds\", opts = {}) {\n if (!this.isValid || !otherDateTime.isValid) {\n return Duration.invalid(\"created by diffing an invalid DateTime\");\n }\n\n const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts };\n\n const units = maybeArray(unit).map(Duration.normalizeUnit),\n otherIsLater = otherDateTime.valueOf() > this.valueOf(),\n earlier = otherIsLater ? this : otherDateTime,\n later = otherIsLater ? otherDateTime : this,\n diffed = diff(earlier, later, units, durOpts);\n\n return otherIsLater ? diffed.negate() : diffed;\n }\n\n /**\n * Return the difference between this DateTime and right now.\n * See {@link DateTime#diff}\n * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration\n * @param {Object} opts - options that affect the creation of the Duration\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @return {Duration}\n */\n diffNow(unit = \"milliseconds\", opts = {}) {\n return this.diff(DateTime.now(), unit, opts);\n }\n\n /**\n * Return an Interval spanning between this DateTime and another DateTime\n * @param {DateTime} otherDateTime - the other end point of the Interval\n * @return {Interval}\n */\n until(otherDateTime) {\n return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;\n }\n\n /**\n * Return whether this DateTime is in the same unit of time as another DateTime.\n * Higher-order units must also be identical for this function to return `true`.\n * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.\n * @param {DateTime} otherDateTime - the other DateTime\n * @param {string} unit - the unit of time to check sameness on\n * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day\n * @return {boolean}\n */\n hasSame(otherDateTime, unit) {\n if (!this.isValid) return false;\n\n const inputMs = otherDateTime.valueOf();\n const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true });\n return adjustedToZone.startOf(unit) <= inputMs && inputMs <= adjustedToZone.endOf(unit);\n }\n\n /**\n * Equality check\n * Two DateTimes are equal iff they represent the same millisecond, have the same zone and location, and are both valid.\n * To compare just the millisecond values, use `+dt1 === +dt2`.\n * @param {DateTime} other - the other DateTime\n * @return {boolean}\n */\n equals(other) {\n return (\n this.isValid &&\n other.isValid &&\n this.valueOf() === other.valueOf() &&\n this.zone.equals(other.zone) &&\n this.loc.equals(other.loc)\n );\n }\n\n /**\n * Returns a string representation of a this time relative to now, such as \"in two days\". Can only internationalize if your\n * platform supports Intl.RelativeTimeFormat. Rounds down by default.\n * @param {Object} options - options that affect the output\n * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.\n * @param {string} [options.style=\"long\"] - the style of units, must be \"long\", \"short\", or \"narrow\"\n * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of \"years\", \"quarters\", \"months\", \"weeks\", \"days\", \"hours\", \"minutes\", or \"seconds\"\n * @param {boolean} [options.round=true] - whether to round the numbers in the output.\n * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.\n * @param {string} options.locale - override the locale of this DateTime\n * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this\n * @example DateTime.now().plus({ days: 1 }).toRelative() //=> \"in 1 day\"\n * @example DateTime.now().setLocale(\"es\").toRelative({ days: 1 }) //=> \"dentro de 1 día\"\n * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: \"fr\" }) //=> \"dans 23 heures\"\n * @example DateTime.now().minus({ days: 2 }).toRelative() //=> \"2 days ago\"\n * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: \"hours\" }) //=> \"48 hours ago\"\n * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> \"1.5 days ago\"\n */\n toRelative(options = {}) {\n if (!this.isValid) return null;\n const base = options.base || DateTime.fromObject({}, { zone: this.zone }),\n padding = options.padding ? (this < base ? -options.padding : options.padding) : 0;\n let units = [\"years\", \"months\", \"days\", \"hours\", \"minutes\", \"seconds\"];\n let unit = options.unit;\n if (Array.isArray(options.unit)) {\n units = options.unit;\n unit = undefined;\n }\n return diffRelative(base, this.plus(padding), {\n ...options,\n numeric: \"always\",\n units,\n unit,\n });\n }\n\n /**\n * Returns a string representation of this date relative to today, such as \"yesterday\" or \"next month\".\n * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.\n * @param {Object} options - options that affect the output\n * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.\n * @param {string} options.locale - override the locale of this DateTime\n * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of \"years\", \"quarters\", \"months\", \"weeks\", or \"days\"\n * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this\n * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> \"tomorrow\"\n * @example DateTime.now().setLocale(\"es\").plus({ days: 1 }).toRelative() //=> \"\"mañana\"\n * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: \"fr\" }) //=> \"demain\"\n * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> \"2 days ago\"\n */\n toRelativeCalendar(options = {}) {\n if (!this.isValid) return null;\n\n return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, {\n ...options,\n numeric: \"auto\",\n units: [\"years\", \"months\", \"days\"],\n calendary: true,\n });\n }\n\n /**\n * Return the min of several date times\n * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum\n * @return {DateTime} the min DateTime, or undefined if called with no argument\n */\n static min(...dateTimes) {\n if (!dateTimes.every(DateTime.isDateTime)) {\n throw new InvalidArgumentError(\"min requires all arguments be DateTimes\");\n }\n return bestBy(dateTimes, (i) => i.valueOf(), Math.min);\n }\n\n /**\n * Return the max of several date times\n * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum\n * @return {DateTime} the max DateTime, or undefined if called with no argument\n */\n static max(...dateTimes) {\n if (!dateTimes.every(DateTime.isDateTime)) {\n throw new InvalidArgumentError(\"max requires all arguments be DateTimes\");\n }\n return bestBy(dateTimes, (i) => i.valueOf(), Math.max);\n }\n\n // MISC\n\n /**\n * Explain how a string would be parsed by fromFormat()\n * @param {string} text - the string to parse\n * @param {string} fmt - the format the string is expected to be in (see description)\n * @param {Object} options - options taken by fromFormat()\n * @return {Object}\n */\n static fromFormatExplain(text, fmt, options = {}) {\n const { locale = null, numberingSystem = null } = options,\n localeToUse = Locale.fromOpts({\n locale,\n numberingSystem,\n defaultToEN: true,\n });\n return explainFromTokens(localeToUse, text, fmt);\n }\n\n /**\n * @deprecated use fromFormatExplain instead\n */\n static fromStringExplain(text, fmt, options = {}) {\n return DateTime.fromFormatExplain(text, fmt, options);\n }\n\n // FORMAT PRESETS\n\n /**\n * {@link DateTime#toLocaleString} format like 10/14/1983\n * @type {Object}\n */\n static get DATE_SHORT() {\n return Formats.DATE_SHORT;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'\n * @type {Object}\n */\n static get DATE_MED() {\n return Formats.DATE_MED;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'\n * @type {Object}\n */\n static get DATE_MED_WITH_WEEKDAY() {\n return Formats.DATE_MED_WITH_WEEKDAY;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'October 14, 1983'\n * @type {Object}\n */\n static get DATE_FULL() {\n return Formats.DATE_FULL;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'\n * @type {Object}\n */\n static get DATE_HUGE() {\n return Formats.DATE_HUGE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_SIMPLE() {\n return Formats.TIME_SIMPLE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_WITH_SECONDS() {\n return Formats.TIME_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_WITH_SHORT_OFFSET() {\n return Formats.TIME_WITH_SHORT_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_WITH_LONG_OFFSET() {\n return Formats.TIME_WITH_LONG_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_SIMPLE() {\n return Formats.TIME_24_SIMPLE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_WITH_SECONDS() {\n return Formats.TIME_24_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_WITH_SHORT_OFFSET() {\n return Formats.TIME_24_WITH_SHORT_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_WITH_LONG_OFFSET() {\n return Formats.TIME_24_WITH_LONG_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_SHORT() {\n return Formats.DATETIME_SHORT;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_SHORT_WITH_SECONDS() {\n return Formats.DATETIME_SHORT_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_MED() {\n return Formats.DATETIME_MED;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_MED_WITH_SECONDS() {\n return Formats.DATETIME_MED_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_MED_WITH_WEEKDAY() {\n return Formats.DATETIME_MED_WITH_WEEKDAY;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_FULL() {\n return Formats.DATETIME_FULL;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_FULL_WITH_SECONDS() {\n return Formats.DATETIME_FULL_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_HUGE() {\n return Formats.DATETIME_HUGE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_HUGE_WITH_SECONDS() {\n return Formats.DATETIME_HUGE_WITH_SECONDS;\n }\n}\n\n/**\n * @private\n */\nexport function friendlyDateTime(dateTimeish) {\n if (DateTime.isDateTime(dateTimeish)) {\n return dateTimeish;\n } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {\n return DateTime.fromJSDate(dateTimeish);\n } else if (dateTimeish && typeof dateTimeish === \"object\") {\n return DateTime.fromObject(dateTimeish);\n } else {\n throw new InvalidArgumentError(\n `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`\n );\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n/**\n * Tag that allows expressions to be used in localized non-HTML template\n * strings.\n *\n * Example: msg(str`Hello ${this.user}!`);\n *\n * The Lit html tag can also be used for this purpose, but HTML will need to be\n * escaped, and there is a small overhead for HTML parsing.\n *\n * Untagged template strings with expressions aren't supported by lit-localize\n * because they don't allow for values to be captured at runtime.\n */\nconst _str = (strings, ...values) => ({\n strTag: true,\n strings,\n values,\n});\nexport const str = _str;\nexport const isStrTagged = (val) => typeof val !== 'string' && 'strTag' in val;\n/**\n * Render the result of a `str` tagged template to a string. Note we don't need\n * to do this for Lit templates, since Lit itself handles rendering.\n */\nexport const joinStringsAndValues = (strings, values, valueOrder) => {\n let concat = strings[0];\n for (let i = 1; i < strings.length; i++) {\n concat += values[valueOrder ? valueOrder[i - 1] : i - 1];\n concat += strings[i];\n }\n return concat;\n};\n//# sourceMappingURL=str-tag.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport { isStrTagged, joinStringsAndValues } from './str-tag.js';\n/**\n * Default identity msg implementation. Simply returns the input template with\n * no awareness of translations. If the template is str-tagged, returns it in\n * string form.\n */\nexport const defaultMsg = ((template) => isStrTagged(template)\n ? joinStringsAndValues(template.strings, template.values)\n : template);\n//# sourceMappingURL=default-msg.js.map","/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nexport class Deferred {\n constructor() {\n this.settled = false;\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n resolve(value) {\n this.settled = true;\n this._resolve(value);\n }\n reject(error) {\n this.settled = true;\n this._reject(error);\n }\n}\n//# sourceMappingURL=deferred.js.map","/**\n * @license\n * Copyright 2014 Travis Webb\n * SPDX-License-Identifier: MIT\n */\n// This module is derived from the file:\n// https://github.com/tjwebb/fnv-plus/blob/1e2ce68a07cb7dd4c3c85364f3d8d96c95919474/index.js#L309\n//\n// Changes:\n// - Only the _hash64_1a_fast function is included.\n// - Removed loop unrolling.\n// - Converted to TypeScript ES module.\n// - var -> let/const\n//\n// TODO(aomarks) Upstream improvements to https://github.com/tjwebb/fnv-plus/.\nconst hl = [];\nfor (let i = 0; i < 256; i++) {\n hl[i] = ((i >> 4) & 15).toString(16) + (i & 15).toString(16);\n}\n/**\n * Perform a FNV-1A 64-bit hash of the given string (as UTF-16 code units), and\n * return a hexadecimal digest (left zero padded to 16 characters).\n *\n * @see {@link http://tools.ietf.org/html/draft-eastlake-fnv-06}\n */\nexport function fnv1a64(str) {\n let t0 = 0, v0 = 0x2325, t1 = 0, v1 = 0x8422, t2 = 0, v2 = 0x9ce4, t3 = 0, v3 = 0xcbf2;\n for (let i = 0; i < str.length; i++) {\n v0 ^= str.charCodeAt(i);\n t0 = v0 * 435;\n t1 = v1 * 435;\n t2 = v2 * 435;\n t3 = v3 * 435;\n t2 += v0 << 8;\n t3 += v1 << 8;\n t1 += t0 >>> 16;\n v0 = t0 & 65535;\n t2 += t1 >>> 16;\n v1 = t1 & 65535;\n v3 = (t3 + (t2 >>> 16)) & 65535;\n v2 = t2 & 65535;\n }\n return (hl[v3 >> 8] +\n hl[v3 & 255] +\n hl[v2 >> 8] +\n hl[v2 & 255] +\n hl[v1 >> 8] +\n hl[v1 & 255] +\n hl[v0 >> 8] +\n hl[v0 & 255]);\n}\n//# sourceMappingURL=fnv1a64.js.map","/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport { fnv1a64 } from './fnv1a64.js';\n/**\n * Delimiter used between each template string component before hashing. Used to\n * prevent e.g. \"foobar\" and \"foo${baz}bar\" from sharing a hash.\n *\n * This is the \"record separator\" ASCII character.\n */\nexport const HASH_DELIMITER = '\\x1e';\n/**\n * Id prefix on html-tagged templates to distinguish e.g. `x` from\n * html`x`.\n */\nconst HTML_PREFIX = 'h';\n/**\n * Id prefix on plain string templates to distinguish e.g. `x` from\n * html`x`.\n */\nconst STRING_PREFIX = 's';\n/**\n * Generate a unique ID for a lit-localize message.\n *\n * Example:\n * Template: html`Hello ${who}!`\n * Params: [\"Hello \", \"!\"], true\n * Output: h82ccc38d4d46eaa9\n *\n * The ID is constructed as:\n *\n * [0] Kind of template: [h]tml or [s]tring.\n * [1,16] 64-bit FNV-1a hash hex digest of the template strings, as UTF-16\n * code points, delineated by an ASCII \"record separator\" character.\n *\n * We choose FNV-1a because:\n *\n * 1. It's pretty fast (e.g. much faster than SHA-1).\n * 2. It's pretty small (0.25 KiB minified + brotli).\n * 3. We don't require cryptographic security, and 64 bits should give\n * sufficient collision resistance for any one application. Worst\n * case, we will always detect collisions during analysis.\n * 4. We can't use Web Crypto API (e.g. SHA-1), because it's asynchronous.\n * 5. It's a well known non-cryptographic hash with implementations in many\n * languages.\n * 6. There was an existing JavaScript implementation that doesn't require\n * BigInt, for IE11 compatibility.\n */\nexport function generateMsgId(strings, isHtmlTagged) {\n return ((isHtmlTagged ? HTML_PREFIX : STRING_PREFIX) +\n fnv1a64(typeof strings === 'string' ? strings : strings.join(HASH_DELIMITER)));\n}\n//# sourceMappingURL=id-generation.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport { defaultMsg } from './default-msg.js';\nimport { joinStringsAndValues } from './str-tag.js';\nimport { generateMsgId } from './id-generation.js';\nconst expressionOrders = new WeakMap();\nconst hashCache = new Map();\nexport function runtimeMsg(templates, template, options) {\n if (templates) {\n const id = options?.id ?? generateId(template);\n const localized = templates[id];\n if (localized) {\n if (typeof localized === 'string') {\n // E.g. \"Hello World!\"\n return localized;\n }\n else if ('strTag' in localized) {\n // E.g. str`Hello ${name}!`\n //\n // Localized templates have ${number} in place of real template\n // expressions. They can't have real template values, because the\n // variable scope would be wrong. The number tells us the index of the\n // source value to substitute in its place, because expressions can be\n // moved to a different position during translation.\n return joinStringsAndValues(localized.strings, \n // Cast `template` because its type wasn't automatically narrowed (but\n // we know it must be the same type as `localized`).\n template.values, localized.values);\n }\n else {\n // E.g. html`Hello ${name}!`\n //\n // We have to keep our own mapping of expression ordering because we do\n // an in-place update of `values`, and otherwise we'd lose ordering for\n // subsequent renders.\n let order = expressionOrders.get(localized);\n if (order === undefined) {\n order = localized.values;\n expressionOrders.set(localized, order);\n }\n return {\n ...localized,\n values: order.map((i) => template.values[i]),\n };\n }\n }\n }\n return defaultMsg(template);\n}\nfunction generateId(template) {\n const strings = typeof template === 'string' ? template : template.strings;\n let id = hashCache.get(strings);\n if (id === undefined) {\n id = generateMsgId(strings, typeof template !== 'string' && !('strTag' in template));\n hashCache.set(strings, id);\n }\n return id;\n}\n//# sourceMappingURL=runtime-msg.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport { _installMsgImplementation } from '../lit-localize.js';\nimport { Deferred } from '../internal/deferred.js';\nimport { LOCALE_STATUS_EVENT } from '../internal/locale-status-event.js';\nimport { runtimeMsg } from '../internal/runtime-msg.js';\n/**\n * Dispatch a \"lit-localize-status\" event to `window` with the given detail.\n */\nfunction dispatchStatusEvent(detail) {\n window.dispatchEvent(new CustomEvent(LOCALE_STATUS_EVENT, { detail }));\n}\nlet activeLocale = '';\nlet loadingLocale;\nlet sourceLocale;\nlet validLocales;\nlet loadLocale;\nlet templates;\nlet loading = new Deferred();\n// The loading promise must be initially resolved, because that's what we should\n// return if the user immediately calls setLocale(sourceLocale).\nloading.resolve();\nlet requestId = 0;\n/**\n * Set configuration parameters for lit-localize when in runtime mode. Returns\n * an object with functions:\n *\n * - `getLocale`: Return the active locale code.\n * - `setLocale`: Set the active locale code.\n *\n * Throws if called more than once.\n */\nexport const configureLocalization = (config) => {\n _installMsgImplementation(((template, options) => runtimeMsg(templates, template, options)));\n activeLocale = sourceLocale = config.sourceLocale;\n validLocales = new Set(config.targetLocales);\n validLocales.add(config.sourceLocale);\n loadLocale = config.loadLocale;\n return { getLocale, setLocale };\n};\n/**\n * Return the active locale code.\n */\nconst getLocale = () => {\n return activeLocale;\n};\n/**\n * Set the active locale code, and begin loading templates for that locale using\n * the `loadLocale` function that was passed to `configureLocalization`. Returns\n * a promise that resolves when the next locale is ready to be rendered.\n *\n * Note that if a second call to `setLocale` is made while the first requested\n * locale is still loading, then the second call takes precedence, and the\n * promise returned from the first call will resolve when second locale is\n * ready. If you need to know whether a particular locale was loaded, check\n * `getLocale` after the promise resolves.\n *\n * Throws if the given locale is not contained by the configured `sourceLocale`\n * or `targetLocales`.\n */\nconst setLocale = (newLocale) => {\n if (newLocale === (loadingLocale ?? activeLocale)) {\n return loading.promise;\n }\n if (!validLocales || !loadLocale) {\n throw new Error('Internal error');\n }\n if (!validLocales.has(newLocale)) {\n throw new Error('Invalid locale code');\n }\n requestId++;\n const thisRequestId = requestId;\n loadingLocale = newLocale;\n if (loading.settled) {\n loading = new Deferred();\n }\n dispatchStatusEvent({ status: 'loading', loadingLocale: newLocale });\n const localePromise = newLocale === sourceLocale\n ? // We could switch to the source locale synchronously, but we prefer to\n // queue it on a microtask so that switching locales is consistently\n // asynchronous.\n Promise.resolve({ templates: undefined })\n : loadLocale(newLocale);\n localePromise.then((mod) => {\n if (requestId === thisRequestId) {\n activeLocale = newLocale;\n loadingLocale = undefined;\n templates = mod.templates;\n dispatchStatusEvent({ status: 'ready', readyLocale: newLocale });\n loading.resolve();\n }\n // Else another locale was requested in the meantime. Don't resolve or\n // reject, because the newer load call is going to use the same promise.\n // Note the user can call getLocale() after the promise resolves if they\n // need to check if the locale is still the one they expected to load.\n }, (err) => {\n if (requestId === thisRequestId) {\n dispatchStatusEvent({\n status: 'error',\n errorLocale: newLocale,\n errorMessage: err.toString(),\n });\n loading.reject(err);\n }\n });\n return loading.promise;\n};\n//# sourceMappingURL=runtime.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n/**\n * Name of the event dispatched to `window` whenever a locale change starts,\n * finishes successfully, or fails. Only relevant to runtime mode.\n *\n * The `detail` of this event is an object with a `status` string that can be:\n * \"loading\", \"ready\", or \"error\", along with the relevant locale code, and\n * error message if applicable.\n *\n * You can listen for this event to know when your application should be\n * re-rendered following a locale change. See also the Localized mixin, which\n * automatically re-renders LitElement classes using this event.\n */\nexport const LOCALE_STATUS_EVENT = 'lit-localize-status';\n//# sourceMappingURL=locale-status-event.js.map","/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport { defaultMsg } from './internal/default-msg.js';\nexport * from './internal/locale-status-event.js';\nexport * from './internal/str-tag.js';\nexport * from './internal/types.js';\n// TODO(aomarks) In a future breaking version, remove these imports so that the\n// bulk of the code isn't included in bundles by default. In particular imagine\n// the component library use-case where msg() calls are made, but there is no\n// need to actually initialize any of the localization runtime.\nexport * from './internal/localized-controller.js';\nexport * from './internal/localized-decorator.js';\nexport * from './init/runtime.js';\nexport * from './init/transform.js';\n/**\n * Make a string or lit-html template localizable.\n *\n * @param template A string, a lit-html template, or a function that returns\n * either a string or lit-html template.\n * @param options Optional configuration object with the following properties:\n * - id: Optional project-wide unique identifier for this template. If\n * omitted, an id will be automatically generated from the template strings.\n * - desc: Optional description\n */\nexport let msg = defaultMsg;\nlet installed = false;\n/**\n * Internal only. Do not use this function.\n *\n * Installs an implementation of the msg function to replace the default\n * identity function. Throws if called more than once.\n *\n * @internal\n */\nexport function _installMsgImplementation(impl) {\n if (installed) {\n throw new Error('lit-localize can only be configured once');\n }\n msg = impl;\n installed = true;\n}\n//# sourceMappingURL=lit-localize.js.map","// Do not modify this file by hand!\n// Re-generate this file by running lit-localize.\n\n/**\n * The locale code that templates in this source code are written in.\n */\nexport const sourceLocale = `en`;\n\n/**\n * The other locale codes that this application is localized into. Sorted\n * lexicographically.\n */\nexport const targetLocales = [`es`, `fr`, `pt`] as const;\n\n/**\n * All valid project locale codes. Sorted lexicographically.\n */\nexport const allLocales = [`en`, `es`, `fr`, `pt`] as const;\n","import { property } from 'lit/decorators.js';\nimport {\n fetchResults,\n getUrl,\n getAssets,\n Asset,\n WebResponse,\n postUrl,\n postJSON,\n postForm,\n getCookie,\n} from '../utils';\nimport {\n ContactField,\n ContactGroup,\n CompletionOption,\n CompletionSchema,\n KeyedAssets,\n CustomEventType,\n Workspace,\n User,\n} from '../interfaces';\nimport { RapidElement } from '../RapidElement';\nimport { lru } from 'tiny-lru';\nimport { DateTime } from 'luxon';\nimport { css, html } from 'lit';\nimport { configureLocalization } from '@lit/localize';\nimport { sourceLocale, targetLocales } from '../locales/locale-codes';\n\nconst { setLocale } = configureLocalization({\n sourceLocale,\n targetLocales,\n loadLocale: locale => import(`./locales/${locale}.js`),\n});\n\nexport class Store extends RapidElement {\n public static get styles() {\n return css`\n :host {\n position: fixed;\n z-index: 1000;\n text-align: center;\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n top: 0.5em;\n }\n `;\n }\n\n settings = {};\n\n @property({ type: Number })\n ttl = 60000;\n\n @property({ type: Number })\n max = 20;\n\n @property({ type: Boolean })\n ready = false;\n\n @property({ type: Boolean })\n loader = false;\n\n @property({ type: String, attribute: 'completion' })\n completionEndpoint: string;\n\n @property({ type: String, attribute: 'fields' })\n fieldsEndpoint: string;\n\n @property({ type: String, attribute: 'groups' })\n groupsEndpoint: string;\n\n @property({ type: String, attribute: 'globals' })\n globalsEndpoint: string;\n\n @property({ type: String, attribute: 'languages' })\n languagesEndpoint: string;\n\n @property({ type: String, attribute: 'workspace' })\n workspaceEndpoint: string;\n\n @property({ type: String, attribute: 'users' })\n usersEndpoint: string;\n\n @property({ type: Object, attribute: false })\n private schema: CompletionSchema;\n\n @property({ type: Object, attribute: false })\n private fnOptions: CompletionOption[];\n\n @property({ type: Object, attribute: false })\n private keyedAssets: KeyedAssets = {};\n\n private locale = [...navigator.languages];\n\n private fields: { [key: string]: ContactField } = {};\n private groups: { [uuid: string]: ContactGroup } = {};\n private languages: any = {};\n private users: User[];\n private workspace: Workspace;\n private featuredFields: ContactField[] = [];\n\n // http promise to monitor for completeness\n public initialHttpComplete: Promise;\n\n private cache: any;\n\n public getLocale() {\n return this.locale[0];\n }\n\n public clearCache() {\n this.cache = lru(this.max, this.ttl);\n }\n\n public reset() {\n this.ready = false;\n this.clearCache();\n this.settings = JSON.parse(getCookie('settings') || '{}');\n\n /* \n // This will create a shorthand unit\n this.humanizer.addLanguage(\"en\", {\n y: () => \"y\",\n mo: () => \"mo\",\n w: () => \"w\",\n d: () => \"d\",\n h: () => \"h\",\n m: () => \"m\",\n s: () => \"s\",\n ms: () => \"ms\",\n decimal: \".\",\n });\n */\n\n const fetches = [];\n if (this.completionEndpoint) {\n fetches.push(\n getUrl(this.completionEndpoint).then(response => {\n this.schema = response.json['context'] as CompletionSchema;\n this.fnOptions = response.json['functions'] as CompletionOption[];\n })\n );\n }\n\n if (this.fieldsEndpoint) {\n fetches.push(this.refreshFields());\n }\n\n if (this.globalsEndpoint) {\n fetches.push(\n getAssets(this.globalsEndpoint).then((assets: Asset[]) => {\n this.keyedAssets['globals'] = assets.map((asset: Asset) => asset.key);\n })\n );\n }\n\n if (this.languagesEndpoint) {\n fetches.push(\n getAssets(this.languagesEndpoint).then((results: any[]) => {\n // convert array of objects to lookup\n this.languages = results.reduce(function (\n languages: any,\n result: any\n ) {\n languages[result.value] = result.name;\n return languages;\n },\n {});\n })\n );\n }\n\n if (this.groupsEndpoint) {\n fetches.push(\n getAssets(this.groupsEndpoint).then((groups: any[]) => {\n groups.forEach((group: any) => {\n this.groups[group.uuid] = group;\n });\n })\n );\n }\n\n if (this.workspaceEndpoint) {\n fetches.push(\n getUrl(this.workspaceEndpoint).then((response: WebResponse) => {\n this.workspace = response.json;\n const lang = response.headers.get('content-language');\n if (lang) {\n this.locale = [lang, ...this.locale];\n }\n })\n );\n }\n\n if (this.usersEndpoint) {\n fetches.push(\n getAssets(this.usersEndpoint).then((users: any[]) => {\n this.users = users;\n })\n );\n }\n\n this.initialHttpComplete = Promise.all(fetches);\n\n this.initialHttpComplete.then(() => {\n this.ready = true;\n });\n }\n\n public getAssignableUsers() {\n return this.users.filter((user: User) =>\n ['administrator', 'editor', 'agent'].includes(user.role)\n );\n }\n\n public getUser(email: string) {\n return this.users.find((user: User) => user.email === email);\n }\n\n public firstUpdated() {\n this.reset();\n }\n\n public getLanguageCode() {\n if (this.locale.length > 0) {\n return this.locale[0].split('-')[0];\n }\n return 'en';\n }\n\n public refreshGlobals() {\n getAssets(this.globalsEndpoint).then((assets: Asset[]) => {\n this.keyedAssets['globals'] = assets.map((asset: Asset) => asset.key);\n });\n }\n\n public refreshFields() {\n return getAssets(this.fieldsEndpoint).then((assets: Asset[]) => {\n this.keyedAssets['fields'] = [];\n this.featuredFields = [];\n\n assets.forEach((field: ContactField) => {\n this.keyedAssets['fields'].push(field.key);\n this.fields[field.key] = field;\n if (field.featured) {\n this.featuredFields.push(field);\n }\n });\n\n this.featuredFields.sort((a, b) => {\n return b.priority - a.priority;\n });\n\n this.keyedAssets['fields'].sort();\n\n this.fireCustomEvent(CustomEventType.StoreUpdated, {\n url: this.fieldsEndpoint,\n data: this.keyedAssets['fields'],\n });\n });\n }\n\n public getShortDuration(scheduled: DateTime, compareDate: DateTime = null) {\n const now = compareDate || DateTime.now();\n return scheduled\n .setLocale(this.locale[0])\n .toRelative({ base: now, style: 'long' });\n }\n\n public getShortDurationFromIso(isoDateA: string, isoDateB: string = null) {\n const scheduled = DateTime.fromISO(isoDateA);\n const now = isoDateB ? DateTime.fromISO(isoDateB) : DateTime.now();\n return this.getShortDuration(scheduled, now);\n }\n\n public setKeyedAssets(name: string, values: string[]): void {\n this.keyedAssets[name] = values;\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n if (changedProperties.has('ready') && this.ready) {\n const locale = this.getLanguageCode();\n const target = targetLocales.find(\n targetLocale => targetLocale === locale\n );\n\n if (target) {\n setLocale(target);\n }\n }\n }\n\n public getCompletionSchema(): CompletionSchema {\n return this.schema;\n }\n\n public getFunctions(): CompletionOption[] {\n return this.fnOptions;\n }\n\n public getKeyedAssets(): KeyedAssets {\n return this.keyedAssets;\n }\n\n public getFieldKeys(): string[] {\n return this.keyedAssets['fields'] || [];\n }\n\n public getContactField(key: string): ContactField {\n return this.fields[key];\n }\n\n public getFeaturedFields(): ContactField[] {\n return this.featuredFields;\n }\n\n public getLanguageName(iso: string) {\n return this.languages[iso];\n }\n\n public isDynamicGroup(uuid: string): boolean {\n const group = this.groups[uuid];\n // we treat missing groups as dynamic since the\n // api excludes initializing groups\n if (!group) {\n console.warn('No group for ' + uuid);\n }\n\n if (!group || group.query) {\n return true;\n }\n return false;\n }\n\n public getWorkspace(): Workspace {\n return this.workspace;\n }\n\n public formatDate(dateString: string) {\n return DateTime.fromISO(dateString)\n .setLocale(this.getLocale())\n .toLocaleString(DateTime.DATETIME_SHORT);\n }\n\n public postJSON(url: string, payload: any = '') {\n return postJSON(url, payload);\n }\n\n public postForm(url: string, payload: any | FormData) {\n return postForm(url, payload);\n }\n\n public postUrl(\n url: string,\n payload: any = '',\n headers: any = {},\n contentType = null\n ) {\n return postUrl(url, payload, headers, contentType);\n }\n\n public getUrl(\n url: string,\n options?: {\n force?: boolean;\n controller?: AbortController;\n headers?: { [key: string]: string };\n }\n ): Promise {\n options = options || {};\n if (!options.force && this.cache.has(url)) {\n return new Promise(resolve => {\n resolve(this.cache.get(url));\n });\n }\n\n return getUrl(url, options.controller, options.headers || {}).then(\n (response: WebResponse) => {\n return new Promise((resolve, reject) => {\n if (response.status >= 200 && response.status <= 300) {\n this.cache.set(url, response);\n resolve(response);\n } else {\n reject('Status: ' + response.status);\n }\n });\n }\n );\n }\n\n private pendingResolves = {};\n\n /**\n * Fetches all of the results for a given API endpoint with caching\n * @param url\n */\n public getResults(\n url: string,\n options?: { force?: boolean }\n ): Promise {\n options = options || {};\n const key = 'results_' + url;\n const results = this.cache.get(key);\n\n if (!options.force && results) {\n return new Promise(resolve => {\n resolve(results);\n });\n }\n\n return new Promise(resolve => {\n const pending = this.pendingResolves[url] || [];\n pending.push(resolve);\n this.pendingResolves[url] = pending;\n if (pending.length <= 1) {\n fetchResults(url).then((results: any[]) => {\n this.cache.set(key, results);\n const pending = this.pendingResolves[url] || [];\n while (pending.length > 0) {\n const resolve = pending.pop();\n resolve(results);\n }\n });\n }\n });\n }\n\n public fetching: { [url: string]: number } = {};\n\n public updateCache(url: string, data: any) {\n this.cache.set(url, data);\n this.fireCustomEvent(CustomEventType.StoreUpdated, { url, data });\n }\n\n public makeRequest(\n url: string,\n options?: { force?: boolean; prepareData?: (data: any) => any }\n ) {\n const previousRequest = this.fetching[url];\n const now = new Date().getTime();\n // if the request was recently made, don't do anything\n if (previousRequest && now - previousRequest < 500) {\n return;\n }\n\n this.fetching[url] = now;\n options = options || {};\n const cached = this.cache.get(url);\n if (cached && !options.force) {\n this.fireCustomEvent(CustomEventType.StoreUpdated, { url, data: cached });\n } else {\n fetchResults(url).then(data => {\n if (!data) {\n delete this.fetching[url];\n return;\n }\n\n data = options.prepareData ? options.prepareData(data) : data;\n this.cache.set(url, data);\n this.fireCustomEvent(CustomEventType.StoreUpdated, { url, data });\n delete this.fetching[url];\n });\n }\n }\n\n public get(key: string, defaultValue: any = null) {\n return this.settings[key] || defaultValue;\n }\n\n public set(key: string, value: string) {\n this.settings[key] = value;\n // not sure yet if we really want to perist these\n // setCookie(COOKIE_KEYS.SETTINGS, JSON.stringify(this.settings), '/');\n }\n\n public render() {\n if (!this.ready && this.loader) {\n return html``;\n }\n }\n}\n","import { TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { RapidElement, EventHandler } from '../RapidElement';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport {\n getClasses,\n getScrollParent,\n isElementVisible,\n throttle,\n} from '../utils';\n\nexport class Options extends RapidElement {\n static get styles() {\n return css`\n .options-container {\n background: var(--color-options-bg);\n user-select: none;\n border-radius: var(--curvature-widget);\n overflow: hidden;\n margin-top: var(--options-margin-top);\n display: flex;\n flex-direction: column;\n transform: scaleY(0.5) translateY(-5em);\n transition: transform var(--transition-speed)\n cubic-bezier(0.71, 0.18, 0.61, 1.33),\n opacity var(--transition-speed) cubic-bezier(0.71, 0.18, 0.61, 1.33);\n opacity: 0;\n border: 1px transparent;\n }\n\n .shadow {\n box-shadow: var(--options-shadow);\n }\n\n .anchored {\n position: fixed;\n }\n\n :host([block]) .options-container {\n flex-grow: 1;\n height: 100%;\n border: none;\n }\n\n :host([block]) .options-scroll {\n height: 100%;\n visibility: visible;\n overflow-y: auto;\n flex-grow: 1;\n -webkit-mask-image: -webkit-radial-gradient(white, black);\n }\n\n :host([block]) {\n border-radius: var(--curvature);\n display: block;\n height: 100%;\n }\n\n :host([block]) .shadow {\n box-shadow: var(--options-block-shadow);\n }\n\n .bordered {\n border: 1px solid var(--color-widget-border) !important;\n }\n\n :host([block]) .options {\n margin-bottom: 1.5em;\n }\n\n .options-scroll {\n display: flex;\n flex-direction: column;\n }\n\n :host([collapsed]) temba-icon {\n flex-grow: 1;\n margin-right: 0px !important;\n padding-top: 0.25em;\n padding-bottom: 0.25em;\n }\n\n :host([collapsed]) .name {\n display: none;\n }\n\n :host([collapsed]) .count {\n display: none;\n }\n\n .options {\n border-radius: var(--curvature-widget);\n overflow-y: auto;\n max-height: 225px;\n border: none;\n }\n\n .show {\n transform: scaleY(1) translateY(0);\n border: 1px solid var(--color-widget-border);\n opacity: 1;\n z-index: 1;\n }\n\n .option {\n font-size: var(--temba-options-font-size);\n padding: 5px 10px;\n border-radius: 4px;\n margin: 0.3em;\n cursor: pointer;\n color: var(--color-text-dark);\n }\n\n .option * {\n user-select: none;\n -webkit-user-select: none;\n -ms-user-select: none;\n overflow-wrap: break-word;\n word-wrap: break-word;\n -ms-word-break: break-all;\n word-break: break-word;\n -ms-hyphens: auto;\n -moz-hyphens: auto;\n -webkit-hyphens: auto;\n hyphens: auto;\n }\n\n .option .detail {\n font-size: 85%;\n color: rgba(0, 0, 0, 0.4);\n }\n\n code {\n background: rgba(0, 0, 0, 0.05);\n padding: 1px 5px;\n border-radius: var(--curvature-widget);\n }\n\n :host([block]) {\n position: relative;\n }\n\n :host([block]) .options {\n overflow-y: initial;\n }\n\n temba-loading {\n align-self: center;\n margin-top: 0.025em;\n }\n\n .loader-bar {\n pointer-events: none;\n align-items: center;\n background: #eee;\n max-height: 0;\n transition: max-height var(--transition-speed) ease-in-out;\n border-bottom-left-radius: var(--curvature-widget);\n border-bottom-right-radius: var(--curvature-widget);\n display: flex;\n overflow: hidden;\n }\n\n .loading .loader-bar {\n max-height: 1.1em;\n }\n\n .option:hover {\n background: var(--option-hover-bg);\n color: var(--option-hover-text);\n }\n\n .option.focused {\n background: var(--color-selection);\n color: var(--color-text-dark);\n }\n `;\n }\n\n @property({ type: Number })\n top: number;\n\n @property({ type: Number })\n left: number;\n\n @property({ type: Number })\n width: number;\n\n @property({ type: Number, attribute: 'static-width' })\n staticWidth: number;\n\n @property({ type: Boolean, attribute: 'anchor-right' })\n anchorRight: boolean;\n\n @property({ type: Number })\n marginHorizontal = 0;\n\n @property({ type: Number })\n marginVertical = 7;\n\n @property({ type: Object })\n anchorTo: HTMLElement;\n\n @property({ type: Boolean })\n visible: boolean;\n\n @property({ type: Boolean })\n block: boolean;\n\n @property({ type: Number })\n scrollPct = 75;\n\n @property({ type: Number })\n cursorIndex = -1;\n\n @property({ type: Boolean })\n internalFocusDisabled = false;\n\n @property({ type: Array })\n options: any[];\n\n @property({ type: Array })\n tempOptions: any[];\n\n @property({ type: Boolean })\n poppedTop: boolean;\n\n @property({ type: Boolean })\n spaceSelect: boolean;\n\n @property({ type: String })\n nameKey = 'name';\n\n @property({ type: Boolean })\n loading = false;\n\n @property({ type: Boolean })\n collapsed: boolean;\n\n @property({ type: Boolean })\n hideShadow = false;\n\n @property({ attribute: false })\n getName: { (option: any): string } = function (option: any) {\n return option[this.nameKey || 'name'];\n };\n\n @property({ attribute: false })\n renderInputOption: { (): TemplateResult } = function () {\n return null;\n };\n\n @property({ attribute: false })\n renderOption: { (option: any, selected: boolean): TemplateResult };\n\n @property({ attribute: false })\n renderOptionName: { (option: any, selected: boolean): TemplateResult };\n\n @property({ attribute: false })\n renderOptionDetail: { (option: any, selected: boolean): TemplateResult };\n\n @property({ type: Number })\n scrollHeight = 0;\n\n @property({ type: Boolean })\n triggerScroll = false;\n\n scrollParent: HTMLElement = null;\n\n resolvedRenderOption: { (option: any, selected: boolean): TemplateResult };\n\n public firstUpdated() {\n if (!this.block) {\n this.scrollParent = getScrollParent(this);\n this.calculatePosition = this.calculatePosition.bind(this);\n if (this.scrollParent) {\n this.scrollParent.addEventListener('scroll', this.calculatePosition);\n }\n this.calculatePosition();\n }\n\n this.resolvedRenderOption = (\n this.renderOption || this.renderOptionDefault\n ).bind(this);\n }\n\n public disconnectedCallback() {\n if (!this.block) {\n if (this.scrollParent) {\n this.scrollParent.removeEventListener('scroll', this.calculatePosition);\n }\n }\n }\n\n private isFocused() {\n const focused =\n this.closestElement(document.activeElement.tagName) ===\n document.activeElement;\n\n return focused;\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n // if our cursor changed, lets make sure our scrollbox is showing it\n if (!this.internalFocusDisabled && changedProperties.has('cursorIndex')) {\n const focusedOption = this.shadowRoot.querySelector(\n `div[data-option-index=\"${this.cursorIndex}\"]`\n ) as HTMLDivElement;\n\n if (focusedOption) {\n const scrollBox = this.shadowRoot.querySelector('.options-container');\n const scrollBoxRect = scrollBox.getBoundingClientRect();\n const scrollBoxHeight = scrollBoxRect.height;\n const focusedEleHeight = focusedOption.getBoundingClientRect().height;\n\n if (\n focusedOption.offsetTop + focusedEleHeight >\n scrollBox.scrollTop + scrollBoxHeight - 5\n ) {\n const scrollTo =\n focusedOption.offsetTop - scrollBoxHeight + focusedEleHeight + 5;\n scrollBox.scrollTop = scrollTo;\n } else if (focusedOption.offsetTop < scrollBox.scrollTop) {\n const scrollTo = focusedOption.offsetTop - 5;\n scrollBox.scrollTop = scrollTo;\n }\n }\n\n this.fireCustomEvent(CustomEventType.CursorChanged, {\n index: this.cursorIndex,\n });\n }\n\n if (changedProperties.has('visible') && changedProperties.has('options')) {\n if (!this.visible && this.options.length == 0) {\n this.tempOptions = changedProperties.get('options');\n window.setTimeout(() => {\n this.tempOptions = [];\n }, 300);\n }\n }\n\n if (changedProperties.has('options')) {\n this.calculatePosition();\n\n // allow scrolls to trigger again\n this.triggerScroll = true;\n\n const prevOptions = changedProperties.get('options');\n const previousCount = prevOptions ? prevOptions.length : 0;\n const newCount = this.options ? this.options.length : 0;\n\n if (\n this.cursorIndex === -1 ||\n newCount < previousCount ||\n (previousCount === 0 &&\n newCount > 0 &&\n !changedProperties.has('cursorIndex'))\n ) {\n if (!this.internalFocusDisabled) {\n if (!this.block) {\n this.cursorIndex = 0;\n } else {\n if (this.cursorIndex >= newCount) {\n this.cursorIndex = newCount - 1;\n }\n }\n\n if (this.block) {\n this.handleSelection(false);\n }\n }\n }\n\n // if on initial load we don't have enough options to load, trigger a scroll\n // threshold event in case the page size is smaller than our control height\n const scrollBox = this.shadowRoot.querySelector('.options');\n if (scrollBox.scrollHeight == scrollBox.clientHeight) {\n this.fireCustomEvent(CustomEventType.ScrollThreshold);\n }\n }\n\n if (changedProperties.has('visible')) {\n window.setTimeout(() => {\n this.calculatePosition();\n }, 100);\n }\n }\n\n private renderOptionDefault(option: any, selected: boolean): TemplateResult {\n const renderOptionName = (\n this.renderOptionName || this.renderOptionNameDefault\n ).bind(this);\n const renderOptionDetail = (\n this.renderOptionDetail || this.renderOptionDetailDefault\n ).bind(this);\n\n if (selected) {\n return html`\n
${renderOptionName(option, selected)}
\n
${renderOptionDetail(option, selected)}
\n `;\n } else {\n return html`\n
${renderOptionName(option, selected)}
\n `;\n }\n }\n\n private renderOptionNameDefault(option: any): TemplateResult {\n return html`
\n ${option.icon\n ? html``\n : null}\n
${option.prefix}${this.getName(option)}
\n
`;\n }\n\n private renderOptionDetailDefault(option: any): TemplateResult {\n return html` ${option.detail} `;\n }\n\n private handleSelection(tabbed = false, index = -1) {\n if (!this.internalFocusDisabled) {\n if (index === -1) {\n index = this.cursorIndex;\n }\n }\n\n const selected = this.options[index];\n this.fireCustomEvent(CustomEventType.Selection, {\n selected,\n tabbed,\n index,\n });\n }\n\n private moveCursor(direction: number): void {\n if (!this.internalFocusDisabled) {\n const newIndex = Math.max(\n Math.min(this.cursorIndex + direction, this.options.length - 1),\n 0\n );\n this.setCursor(newIndex);\n }\n }\n\n private setCursor: (index: number) => void = throttle(function (\n index: number\n ) {\n if (!this.internalFocusDisabled) {\n if (index !== this.cursorIndex) {\n this.cursorIndex = index;\n }\n }\n },\n 50);\n\n public scrollToTop() {\n const scrollBox = this.shadowRoot.querySelector('.options-scroll');\n scrollBox.scrollTop = 0;\n }\n\n private handleKeyDown(evt: KeyboardEvent) {\n if (this.internalFocusDisabled || (this.block && !this.isFocused())) {\n return;\n }\n\n if (this.options && this.options.length > 0) {\n if ((evt.ctrlKey && evt.key === 'n') || evt.key === 'ArrowDown') {\n this.moveCursor(1);\n evt.preventDefault();\n evt.stopPropagation();\n if (this.block) {\n this.handleSelection(false);\n }\n } else if ((evt.ctrlKey && evt.key === 'p') || evt.key === 'ArrowUp') {\n this.moveCursor(-1);\n evt.preventDefault();\n if (this.block) {\n this.handleSelection(false);\n }\n } else if (\n evt.key === 'Enter' ||\n evt.key === 'Tab' ||\n (this.spaceSelect && evt.key === ' ')\n ) {\n evt.preventDefault();\n evt.stopPropagation();\n this.handleSelection(evt.key === 'Tab');\n }\n\n if (evt.key === 'Escape') {\n this.fireCustomEvent(CustomEventType.Canceled);\n }\n }\n }\n\n private handleInnerScroll(evt: Event) {\n const scrollbox = evt.target as HTMLDivElement;\n\n // scroll height has changed, enable scroll trigger\n if (scrollbox.scrollHeight > this.scrollHeight) {\n this.scrollHeight = scrollbox.scrollHeight;\n this.triggerScroll = true;\n }\n\n if (this.triggerScroll) {\n const scrollPct =\n scrollbox.scrollTop / (scrollbox.scrollHeight - scrollbox.clientHeight);\n if (scrollPct * 100 > this.scrollPct) {\n this.fireCustomEvent(CustomEventType.ScrollThreshold);\n this.triggerScroll = false;\n }\n }\n }\n\n private calculatePosition() {\n if (this.visible && !this.block) {\n const optionsBounds = this.shadowRoot\n .querySelector('.options-container')\n .getBoundingClientRect();\n\n if (this.anchorTo) {\n const anchorBounds = this.anchorTo.getBoundingClientRect();\n const topTop = anchorBounds.top - optionsBounds.height;\n\n if (this.anchorTo && this.scrollParent) {\n if (!isElementVisible(this.anchorTo, this.scrollParent)) {\n // this.fireCustomEvent(CustomEventType.Canceled);\n }\n }\n\n if (\n topTop > 0 &&\n anchorBounds.bottom + optionsBounds.height > window.innerHeight\n ) {\n this.top = topTop; // + window.pageYOffset;\n this.poppedTop = true;\n } else {\n this.top = anchorBounds.bottom; // + window.pageYOffset;\n this.poppedTop = false;\n }\n\n this.left = anchorBounds.left;\n this.width =\n this.staticWidth > 0\n ? this.staticWidth\n : anchorBounds.width - 2 - this.marginHorizontal * 2;\n\n if (this.anchorRight) {\n this.left = anchorBounds.right - this.width;\n }\n }\n }\n }\n\n public getEventHandlers(): EventHandler[] {\n return [\n {\n event: 'keydown',\n method: this.handleKeyDown,\n isDocument: true,\n },\n {\n event: 'scroll',\n method: this.calculatePosition,\n isDocument: true,\n },\n ];\n }\n\n private handleMouseMove(evt: MouseEvent) {\n if (!this.block) {\n if (Math.abs(evt.movementX) + Math.abs(evt.movementY) > 0) {\n const index = (evt.currentTarget as HTMLElement).getAttribute(\n 'data-option-index'\n );\n this.setCursor(parseInt(index));\n }\n }\n }\n\n // we need to swallow mouse down so we don't grab focus\n private handleMouseDown(evt: MouseEvent) {\n evt.preventDefault();\n evt.stopPropagation();\n }\n\n private handleOptionClick(evt: MouseEvent) {\n evt.preventDefault();\n evt.stopPropagation();\n\n const index = (evt.currentTarget as HTMLElement).getAttribute(\n 'data-option-index'\n );\n\n if (index) {\n const newIndex = parseInt(index);\n this.setCursor(newIndex);\n this.handleSelection(false, newIndex);\n }\n }\n\n public render(): TemplateResult {\n let vertical = this.block ? 0 : this.marginVertical;\n if (this.poppedTop) {\n vertical *= -1;\n }\n\n const containerStyle = {\n 'margin-left': `${this.marginHorizontal}px`,\n 'margin-top': `${vertical}px`,\n };\n\n if (this.top) {\n containerStyle['top'] = `${this.top}px`;\n }\n\n if (this.left) {\n containerStyle['left'] = `${this.left}px`;\n }\n\n const optionsStyle = {};\n if (this.width) {\n optionsStyle['width'] = `${this.width}px`;\n }\n\n const classes = getClasses({\n 'options-container': true,\n show: this.visible,\n top: this.poppedTop,\n anchored: !this.block,\n loading: this.loading,\n shadow: !this.hideShadow,\n bordered: this.hideShadow,\n });\n\n const classesInner = getClasses({\n options: true,\n });\n\n let options = this.options || [];\n if (\n options.length == 0 &&\n this.tempOptions &&\n this.tempOptions.length > 0\n ) {\n options = this.tempOptions;\n }\n\n return html`\n
\n \n
\n ${options.map((option, index) => {\n return html`\n ${this.resolvedRenderOption(option, index === this.cursorIndex)}\n
`;\n })}\n ${this.block ? html`
` : null}\n
\n \n
\n\n
\n \n
\n \n `;\n }\n}\n","import{nothing as t,noChange as i}from\"../lit-html.js\";import{Directive as r,PartType as s,directive as n}from\"../directive.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */class e extends r{constructor(i){if(super(i),this.it=t,i.type!==s.CHILD)throw Error(this.constructor.directiveName+\"() can only be used in child bindings\")}render(r){if(r===t||null==r)return this._t=void 0,this.it=r;if(r===i)return r;if(\"string\"!=typeof r)throw Error(this.constructor.directiveName+\"() called with a non-string value\");if(r===this.it)return this._t;this.it=r;const s=[r];return s.raw=s,this._t={_$litType$:this.constructor.resultType,strings:s,values:[]}}}e.directiveName=\"unsafeHTML\",e.resultType=1;const o=n(e);export{e as UnsafeHTMLDirective,o as unsafeHTML};\n//# sourceMappingURL=unsafe-html.js.map\n","const STATE_BODY = 0; // not in a expression\nconst STATE_PREFIX = 1; // '@' prefix that denotes the start of an expression\nconst STATE_IDENTIFIER = 2; // the identifier part, e.g. 'contact.age' in '@contact.age'\nconst STATE_BALANCED = 3; // the balanced parentheses delimited part, e.g. '(1 + 2)' in '@(1 + 2)'\nconst STATE_STRING_LITERAL = 4; // a string literal which could contain )\nconst STATE_ESCAPED_PREFIX = 5; // a '@' prefix preceded by another '@'\nconst STATE_IGNORE = 6;\n\nexport interface Expression {\n start: number;\n end: number;\n text: string;\n closed: boolean;\n}\n\n/**\n * Determines whether the given string starts with the given text\n */\nconst startsWith = (str: string, start: string): boolean => {\n return str.indexOf(start, 0) === 0;\n};\n\n/**\n * Checks the parsed (possibly partial) expression to determine if it's valid based on how it starts\n */\nconst isValidStart = (\n partialExpression: string,\n allowedTopLevels: string[],\n allowIncomplete: boolean\n): boolean => {\n const body = partialExpression.substring(1); // strip prefix\n\n if (body[0] === '(') {\n return true;\n } else {\n // if expression doesn't start with ( then check it's an allowed top level context reference\n const topLevel = body.split('.')[0].toLowerCase();\n\n if (allowIncomplete) {\n for (const allowed of allowedTopLevels) {\n if (startsWith(allowed, topLevel)) {\n return true;\n }\n }\n } else {\n return allowedTopLevels.indexOf(topLevel) >= 0;\n }\n return false;\n }\n};\n\n/**\n * Determines whether the given character is a word character, i.e. \\w in a regex\n */\nexport const isWordChar = (ch: string | 0): boolean => {\n return (\n (ch >= 'a' && ch <= 'z') ||\n (ch >= 'A' && ch <= 'Z') ||\n (ch >= '0' && ch <= '9') ||\n ch === '_'\n );\n};\n\n/**\n * Determines whether we are in a string literal\n */\nconst isInStringLiteral = (partialExpression: string): boolean => {\n // count number quotation marks\n let numQuotes = 0;\n for (const pos of partialExpression) {\n if (pos === '\"') {\n numQuotes++;\n }\n }\n return numQuotes % 2 !== 0; // odd means last string literal is open\n};\n\nexport default class ExcellentParser {\n private expressionPrefix: string;\n private allowedTopLevels: string[];\n\n /**\n * Creates a new parser\n * @param expressionPrefix the prefix for expressions, e.g. '@'\n * @param allowedTopLevels the context names that are allowed without parentheses, e.g. [\"contact\", \"flow\", ...]\n */\n constructor(expressionPrefix: string, allowedTopLevels: string[]) {\n this.expressionPrefix = expressionPrefix;\n this.allowedTopLevels = allowedTopLevels;\n }\n\n /**\n * Given the text up to the caret position, returns the expression currently being edited, without its prefix\n */\n public expressionContext(textToCaret: string): string {\n const expressions = this.findExpressions(textToCaret);\n if (expressions.length === 0) {\n // no expressions found\n return null;\n }\n\n const lastExpression = expressions[expressions.length - 1];\n\n // has last expression already ended or is it closed (i.e. has balanced parentheses)\n if (lastExpression.end < textToCaret.length || lastExpression.closed) {\n return null;\n }\n\n return lastExpression.text.substring(1); // return without prefix\n }\n\n /**\n * Given the partial expression currently being edited, returns the current auto-completable identifier\n * which may be a function name or a context reference.\n */\n public autoCompleteContext(partialExpression: string): string {\n if (isInStringLiteral(partialExpression)) {\n return null;\n }\n\n const neededParentheses = [];\n let fragment = '';\n let skipChar = false;\n let inQuotes = false;\n let prependFlag = '';\n\n for (let pos = partialExpression.length - 1; pos >= 0; pos--) {\n const ch = partialExpression[pos];\n\n if (ch === ' ') {\n skipChar = true;\n }\n\n if (ch === ',') {\n skipChar = true;\n if (neededParentheses[neededParentheses.length - 1] !== '(') {\n neededParentheses.push('(');\n }\n }\n\n if (ch === ')' && !inQuotes) {\n skipChar = true;\n neededParentheses.push('(');\n neededParentheses.push('(');\n }\n\n if (ch === '\"') {\n inQuotes = !inQuotes;\n }\n\n if (skipChar) {\n if (ch === '(' && !inQuotes) {\n if (neededParentheses[neededParentheses.length - 1] === '(') {\n neededParentheses.pop();\n }\n\n if (neededParentheses.length === 0) {\n skipChar = false;\n }\n }\n }\n\n if (ch === '(' && fragment === '') {\n prependFlag = '#';\n }\n\n if (skipChar || inQuotes || (ch === '(' && fragment === '')) {\n continue;\n }\n\n if (isWordChar(ch) || ch === '.') {\n fragment = ch + fragment;\n } else {\n break;\n }\n }\n\n if (fragment.match(/[A-Za-z][\\w]*(\\.[\\w]+)*/)) {\n return prependFlag + fragment;\n } else {\n return null;\n }\n }\n\n /**\n * TODO find the function context\n */\n public functionContext(partialExpression: string): string {\n const inString = isInStringLiteral(partialExpression);\n\n // initial state is string literal if number of quotes is odd\n let state = inString ? STATE_STRING_LITERAL : STATE_IGNORE;\n let identifier = '';\n let parenthesesLevel = partialExpression[-1] === '(' ? 0 : 1;\n\n for (let pos = partialExpression.length - 1; pos >= 0; pos--) {\n const ch = partialExpression[pos];\n\n if (ch === '@') {\n return '';\n }\n\n if (state === STATE_IGNORE) {\n if (parenthesesLevel === 0 && (isWordChar(ch) || ch === '.')) {\n state = STATE_IDENTIFIER;\n identifier = ch + identifier;\n } else if (ch === '\"') {\n state = STATE_STRING_LITERAL;\n } else if (ch === '(') {\n parenthesesLevel--;\n } else if (ch === ')') {\n parenthesesLevel++;\n }\n } else if (state === STATE_IDENTIFIER) {\n if (isWordChar(ch) || ch === '.') {\n identifier = ch + identifier;\n } else {\n return identifier;\n }\n } else if (state === STATE_STRING_LITERAL) {\n if (ch === '\"') {\n state = STATE_IGNORE;\n }\n }\n }\n return '';\n }\n\n public getContactFields(text: string): string[] {\n const fields = {};\n const re = /((parent|child\\.)*contact\\.)*fields\\.([a-z0-9_]+)/g;\n const expressions = this.findExpressions(text);\n for (const expression of expressions) {\n let match;\n // tslint:disable-next-line:no-conditional-assignment\n while ((match = re.exec(expression.text))) {\n (fields as any)[match[3]] = true;\n }\n }\n return Object.keys(fields);\n }\n\n /**\n * Finds all expressions in the given text, including any partially complete expression at the end of the input\n */\n public findExpressions(text: string): Expression[] {\n const expressions: Expression[] = [];\n let state = STATE_BODY;\n let currentExpression: Expression = null;\n let parenthesesLevel = 0;\n\n for (let pos = 0; pos < text.length; pos++) {\n const ch = text[pos];\n // in order to determine if the b in a.b terminates an identifier, we have to peek two characters ahead as\n // it could be a.b. (b terminates) or a.b.c (b doesn't terminate)\n const nextCh = pos < text.length - 1 ? text[pos + 1] : 0;\n const nextNextCh = pos < text.length - 2 ? text[pos + 2] : 0;\n\n if (state === STATE_BODY) {\n if (\n ch === this.expressionPrefix &&\n (isWordChar(nextCh) || nextCh === '(')\n ) {\n state = STATE_PREFIX;\n currentExpression = {\n start: pos,\n end: null,\n text: ch,\n closed: false,\n };\n } else if (\n ch === this.expressionPrefix &&\n nextCh === this.expressionPrefix\n ) {\n state = STATE_ESCAPED_PREFIX;\n }\n } else if (state === STATE_PREFIX) {\n if (isWordChar(ch)) {\n state = STATE_IDENTIFIER; // we're parsing an expression like @XXX\n } else if (ch === '(') {\n // we're parsing an expression like @(1 + 2)\n state = STATE_BALANCED;\n parenthesesLevel += 1;\n }\n currentExpression.text += ch;\n } else if (state === STATE_IDENTIFIER) {\n currentExpression.text += ch;\n } else if (state === STATE_BALANCED) {\n if (ch === '(') {\n parenthesesLevel += 1;\n } else if (ch === ')') {\n parenthesesLevel -= 1;\n } else if (ch === '\"') {\n state = STATE_STRING_LITERAL;\n }\n\n currentExpression.text += ch;\n\n // expression terminates if parentheses balance\n if (parenthesesLevel === 0) {\n currentExpression.end = pos + 1;\n }\n } else if (state === STATE_STRING_LITERAL) {\n if (ch === '\"') {\n state = STATE_BALANCED;\n }\n currentExpression.text += ch;\n } else if (state === STATE_ESCAPED_PREFIX) {\n state = STATE_BODY;\n }\n\n // identifier can terminate expression in 3 ways:\n // 1. next char is null (i.e. end of the input)\n // 2. next char is not a word character or period\n // 3. next char is a period, but it's not followed by a word character\n if (state === STATE_IDENTIFIER) {\n if (\n (!isWordChar(nextCh) && nextCh !== '.') ||\n (nextCh === '.' && !isWordChar(nextNextCh))\n ) {\n currentExpression.end = pos + 1;\n }\n }\n\n if (\n currentExpression != null &&\n (currentExpression.end != null || nextCh === 0)\n ) {\n const allowIncomplete = nextCh === 0; // if we're at the end of the input, allow incomplete expressions\n if (\n isValidStart(\n currentExpression.text,\n this.allowedTopLevels,\n allowIncomplete\n )\n ) {\n currentExpression.closed =\n currentExpression.text[1] === '(' && parenthesesLevel === 0;\n currentExpression.end = pos + 1;\n expressions.push(currentExpression);\n }\n\n currentExpression = null;\n state = STATE_BODY;\n }\n }\n\n return expressions;\n }\n}\n","// List of valid entities\n//\n// Generate with ./support/entities.js script\n//\n\n/*eslint quotes:0*/\nvar entities = {\n \"Aacute\":\"\\u00C1\",\n \"aacute\":\"\\u00E1\",\n \"Abreve\":\"\\u0102\",\n \"abreve\":\"\\u0103\",\n \"ac\":\"\\u223E\",\n \"acd\":\"\\u223F\",\n \"acE\":\"\\u223E\\u0333\",\n \"Acirc\":\"\\u00C2\",\n \"acirc\":\"\\u00E2\",\n \"acute\":\"\\u00B4\",\n \"Acy\":\"\\u0410\",\n \"acy\":\"\\u0430\",\n \"AElig\":\"\\u00C6\",\n \"aelig\":\"\\u00E6\",\n \"af\":\"\\u2061\",\n \"Afr\":\"\\uD835\\uDD04\",\n \"afr\":\"\\uD835\\uDD1E\",\n \"Agrave\":\"\\u00C0\",\n \"agrave\":\"\\u00E0\",\n \"alefsym\":\"\\u2135\",\n \"aleph\":\"\\u2135\",\n \"Alpha\":\"\\u0391\",\n \"alpha\":\"\\u03B1\",\n \"Amacr\":\"\\u0100\",\n \"amacr\":\"\\u0101\",\n \"amalg\":\"\\u2A3F\",\n \"AMP\":\"\\u0026\",\n \"amp\":\"\\u0026\",\n \"And\":\"\\u2A53\",\n \"and\":\"\\u2227\",\n \"andand\":\"\\u2A55\",\n \"andd\":\"\\u2A5C\",\n \"andslope\":\"\\u2A58\",\n \"andv\":\"\\u2A5A\",\n \"ang\":\"\\u2220\",\n \"ange\":\"\\u29A4\",\n \"angle\":\"\\u2220\",\n \"angmsd\":\"\\u2221\",\n \"angmsdaa\":\"\\u29A8\",\n \"angmsdab\":\"\\u29A9\",\n \"angmsdac\":\"\\u29AA\",\n \"angmsdad\":\"\\u29AB\",\n \"angmsdae\":\"\\u29AC\",\n \"angmsdaf\":\"\\u29AD\",\n \"angmsdag\":\"\\u29AE\",\n \"angmsdah\":\"\\u29AF\",\n \"angrt\":\"\\u221F\",\n \"angrtvb\":\"\\u22BE\",\n \"angrtvbd\":\"\\u299D\",\n \"angsph\":\"\\u2222\",\n \"angst\":\"\\u00C5\",\n \"angzarr\":\"\\u237C\",\n \"Aogon\":\"\\u0104\",\n \"aogon\":\"\\u0105\",\n \"Aopf\":\"\\uD835\\uDD38\",\n \"aopf\":\"\\uD835\\uDD52\",\n \"ap\":\"\\u2248\",\n \"apacir\":\"\\u2A6F\",\n \"apE\":\"\\u2A70\",\n \"ape\":\"\\u224A\",\n \"apid\":\"\\u224B\",\n \"apos\":\"\\u0027\",\n \"ApplyFunction\":\"\\u2061\",\n \"approx\":\"\\u2248\",\n \"approxeq\":\"\\u224A\",\n \"Aring\":\"\\u00C5\",\n \"aring\":\"\\u00E5\",\n \"Ascr\":\"\\uD835\\uDC9C\",\n \"ascr\":\"\\uD835\\uDCB6\",\n \"Assign\":\"\\u2254\",\n \"ast\":\"\\u002A\",\n \"asymp\":\"\\u2248\",\n \"asympeq\":\"\\u224D\",\n \"Atilde\":\"\\u00C3\",\n \"atilde\":\"\\u00E3\",\n \"Auml\":\"\\u00C4\",\n \"auml\":\"\\u00E4\",\n \"awconint\":\"\\u2233\",\n \"awint\":\"\\u2A11\",\n \"backcong\":\"\\u224C\",\n \"backepsilon\":\"\\u03F6\",\n \"backprime\":\"\\u2035\",\n \"backsim\":\"\\u223D\",\n \"backsimeq\":\"\\u22CD\",\n \"Backslash\":\"\\u2216\",\n \"Barv\":\"\\u2AE7\",\n \"barvee\":\"\\u22BD\",\n \"Barwed\":\"\\u2306\",\n \"barwed\":\"\\u2305\",\n \"barwedge\":\"\\u2305\",\n \"bbrk\":\"\\u23B5\",\n \"bbrktbrk\":\"\\u23B6\",\n \"bcong\":\"\\u224C\",\n \"Bcy\":\"\\u0411\",\n \"bcy\":\"\\u0431\",\n \"bdquo\":\"\\u201E\",\n \"becaus\":\"\\u2235\",\n \"Because\":\"\\u2235\",\n \"because\":\"\\u2235\",\n \"bemptyv\":\"\\u29B0\",\n \"bepsi\":\"\\u03F6\",\n \"bernou\":\"\\u212C\",\n \"Bernoullis\":\"\\u212C\",\n \"Beta\":\"\\u0392\",\n \"beta\":\"\\u03B2\",\n \"beth\":\"\\u2136\",\n \"between\":\"\\u226C\",\n \"Bfr\":\"\\uD835\\uDD05\",\n \"bfr\":\"\\uD835\\uDD1F\",\n \"bigcap\":\"\\u22C2\",\n \"bigcirc\":\"\\u25EF\",\n \"bigcup\":\"\\u22C3\",\n \"bigodot\":\"\\u2A00\",\n \"bigoplus\":\"\\u2A01\",\n \"bigotimes\":\"\\u2A02\",\n \"bigsqcup\":\"\\u2A06\",\n \"bigstar\":\"\\u2605\",\n \"bigtriangledown\":\"\\u25BD\",\n \"bigtriangleup\":\"\\u25B3\",\n \"biguplus\":\"\\u2A04\",\n \"bigvee\":\"\\u22C1\",\n \"bigwedge\":\"\\u22C0\",\n \"bkarow\":\"\\u290D\",\n \"blacklozenge\":\"\\u29EB\",\n \"blacksquare\":\"\\u25AA\",\n \"blacktriangle\":\"\\u25B4\",\n \"blacktriangledown\":\"\\u25BE\",\n \"blacktriangleleft\":\"\\u25C2\",\n \"blacktriangleright\":\"\\u25B8\",\n \"blank\":\"\\u2423\",\n \"blk12\":\"\\u2592\",\n \"blk14\":\"\\u2591\",\n \"blk34\":\"\\u2593\",\n \"block\":\"\\u2588\",\n \"bne\":\"\\u003D\\u20E5\",\n \"bnequiv\":\"\\u2261\\u20E5\",\n \"bNot\":\"\\u2AED\",\n \"bnot\":\"\\u2310\",\n \"Bopf\":\"\\uD835\\uDD39\",\n \"bopf\":\"\\uD835\\uDD53\",\n \"bot\":\"\\u22A5\",\n \"bottom\":\"\\u22A5\",\n \"bowtie\":\"\\u22C8\",\n \"boxbox\":\"\\u29C9\",\n \"boxDL\":\"\\u2557\",\n \"boxDl\":\"\\u2556\",\n \"boxdL\":\"\\u2555\",\n \"boxdl\":\"\\u2510\",\n \"boxDR\":\"\\u2554\",\n \"boxDr\":\"\\u2553\",\n \"boxdR\":\"\\u2552\",\n \"boxdr\":\"\\u250C\",\n \"boxH\":\"\\u2550\",\n \"boxh\":\"\\u2500\",\n \"boxHD\":\"\\u2566\",\n \"boxHd\":\"\\u2564\",\n \"boxhD\":\"\\u2565\",\n \"boxhd\":\"\\u252C\",\n \"boxHU\":\"\\u2569\",\n \"boxHu\":\"\\u2567\",\n \"boxhU\":\"\\u2568\",\n \"boxhu\":\"\\u2534\",\n \"boxminus\":\"\\u229F\",\n \"boxplus\":\"\\u229E\",\n \"boxtimes\":\"\\u22A0\",\n \"boxUL\":\"\\u255D\",\n \"boxUl\":\"\\u255C\",\n \"boxuL\":\"\\u255B\",\n \"boxul\":\"\\u2518\",\n \"boxUR\":\"\\u255A\",\n \"boxUr\":\"\\u2559\",\n \"boxuR\":\"\\u2558\",\n \"boxur\":\"\\u2514\",\n \"boxV\":\"\\u2551\",\n \"boxv\":\"\\u2502\",\n \"boxVH\":\"\\u256C\",\n \"boxVh\":\"\\u256B\",\n \"boxvH\":\"\\u256A\",\n \"boxvh\":\"\\u253C\",\n \"boxVL\":\"\\u2563\",\n \"boxVl\":\"\\u2562\",\n \"boxvL\":\"\\u2561\",\n \"boxvl\":\"\\u2524\",\n \"boxVR\":\"\\u2560\",\n \"boxVr\":\"\\u255F\",\n \"boxvR\":\"\\u255E\",\n \"boxvr\":\"\\u251C\",\n \"bprime\":\"\\u2035\",\n \"Breve\":\"\\u02D8\",\n \"breve\":\"\\u02D8\",\n \"brvbar\":\"\\u00A6\",\n \"Bscr\":\"\\u212C\",\n \"bscr\":\"\\uD835\\uDCB7\",\n \"bsemi\":\"\\u204F\",\n \"bsim\":\"\\u223D\",\n \"bsime\":\"\\u22CD\",\n \"bsol\":\"\\u005C\",\n \"bsolb\":\"\\u29C5\",\n \"bsolhsub\":\"\\u27C8\",\n \"bull\":\"\\u2022\",\n \"bullet\":\"\\u2022\",\n \"bump\":\"\\u224E\",\n \"bumpE\":\"\\u2AAE\",\n \"bumpe\":\"\\u224F\",\n \"Bumpeq\":\"\\u224E\",\n \"bumpeq\":\"\\u224F\",\n \"Cacute\":\"\\u0106\",\n \"cacute\":\"\\u0107\",\n \"Cap\":\"\\u22D2\",\n \"cap\":\"\\u2229\",\n \"capand\":\"\\u2A44\",\n \"capbrcup\":\"\\u2A49\",\n \"capcap\":\"\\u2A4B\",\n \"capcup\":\"\\u2A47\",\n \"capdot\":\"\\u2A40\",\n \"CapitalDifferentialD\":\"\\u2145\",\n \"caps\":\"\\u2229\\uFE00\",\n \"caret\":\"\\u2041\",\n \"caron\":\"\\u02C7\",\n \"Cayleys\":\"\\u212D\",\n \"ccaps\":\"\\u2A4D\",\n \"Ccaron\":\"\\u010C\",\n \"ccaron\":\"\\u010D\",\n \"Ccedil\":\"\\u00C7\",\n \"ccedil\":\"\\u00E7\",\n \"Ccirc\":\"\\u0108\",\n \"ccirc\":\"\\u0109\",\n \"Cconint\":\"\\u2230\",\n \"ccups\":\"\\u2A4C\",\n \"ccupssm\":\"\\u2A50\",\n \"Cdot\":\"\\u010A\",\n \"cdot\":\"\\u010B\",\n \"cedil\":\"\\u00B8\",\n \"Cedilla\":\"\\u00B8\",\n \"cemptyv\":\"\\u29B2\",\n \"cent\":\"\\u00A2\",\n \"CenterDot\":\"\\u00B7\",\n \"centerdot\":\"\\u00B7\",\n \"Cfr\":\"\\u212D\",\n \"cfr\":\"\\uD835\\uDD20\",\n \"CHcy\":\"\\u0427\",\n \"chcy\":\"\\u0447\",\n \"check\":\"\\u2713\",\n \"checkmark\":\"\\u2713\",\n \"Chi\":\"\\u03A7\",\n \"chi\":\"\\u03C7\",\n \"cir\":\"\\u25CB\",\n \"circ\":\"\\u02C6\",\n \"circeq\":\"\\u2257\",\n \"circlearrowleft\":\"\\u21BA\",\n \"circlearrowright\":\"\\u21BB\",\n \"circledast\":\"\\u229B\",\n \"circledcirc\":\"\\u229A\",\n \"circleddash\":\"\\u229D\",\n \"CircleDot\":\"\\u2299\",\n \"circledR\":\"\\u00AE\",\n \"circledS\":\"\\u24C8\",\n \"CircleMinus\":\"\\u2296\",\n \"CirclePlus\":\"\\u2295\",\n \"CircleTimes\":\"\\u2297\",\n \"cirE\":\"\\u29C3\",\n \"cire\":\"\\u2257\",\n \"cirfnint\":\"\\u2A10\",\n \"cirmid\":\"\\u2AEF\",\n \"cirscir\":\"\\u29C2\",\n \"ClockwiseContourIntegral\":\"\\u2232\",\n \"CloseCurlyDoubleQuote\":\"\\u201D\",\n \"CloseCurlyQuote\":\"\\u2019\",\n \"clubs\":\"\\u2663\",\n \"clubsuit\":\"\\u2663\",\n \"Colon\":\"\\u2237\",\n \"colon\":\"\\u003A\",\n \"Colone\":\"\\u2A74\",\n \"colone\":\"\\u2254\",\n \"coloneq\":\"\\u2254\",\n \"comma\":\"\\u002C\",\n \"commat\":\"\\u0040\",\n \"comp\":\"\\u2201\",\n \"compfn\":\"\\u2218\",\n \"complement\":\"\\u2201\",\n \"complexes\":\"\\u2102\",\n \"cong\":\"\\u2245\",\n \"congdot\":\"\\u2A6D\",\n \"Congruent\":\"\\u2261\",\n \"Conint\":\"\\u222F\",\n \"conint\":\"\\u222E\",\n \"ContourIntegral\":\"\\u222E\",\n \"Copf\":\"\\u2102\",\n \"copf\":\"\\uD835\\uDD54\",\n \"coprod\":\"\\u2210\",\n \"Coproduct\":\"\\u2210\",\n \"COPY\":\"\\u00A9\",\n \"copy\":\"\\u00A9\",\n \"copysr\":\"\\u2117\",\n \"CounterClockwiseContourIntegral\":\"\\u2233\",\n \"crarr\":\"\\u21B5\",\n \"Cross\":\"\\u2A2F\",\n \"cross\":\"\\u2717\",\n \"Cscr\":\"\\uD835\\uDC9E\",\n \"cscr\":\"\\uD835\\uDCB8\",\n \"csub\":\"\\u2ACF\",\n \"csube\":\"\\u2AD1\",\n \"csup\":\"\\u2AD0\",\n \"csupe\":\"\\u2AD2\",\n \"ctdot\":\"\\u22EF\",\n \"cudarrl\":\"\\u2938\",\n \"cudarrr\":\"\\u2935\",\n \"cuepr\":\"\\u22DE\",\n \"cuesc\":\"\\u22DF\",\n \"cularr\":\"\\u21B6\",\n \"cularrp\":\"\\u293D\",\n \"Cup\":\"\\u22D3\",\n \"cup\":\"\\u222A\",\n \"cupbrcap\":\"\\u2A48\",\n \"CupCap\":\"\\u224D\",\n \"cupcap\":\"\\u2A46\",\n \"cupcup\":\"\\u2A4A\",\n \"cupdot\":\"\\u228D\",\n \"cupor\":\"\\u2A45\",\n \"cups\":\"\\u222A\\uFE00\",\n \"curarr\":\"\\u21B7\",\n \"curarrm\":\"\\u293C\",\n \"curlyeqprec\":\"\\u22DE\",\n \"curlyeqsucc\":\"\\u22DF\",\n \"curlyvee\":\"\\u22CE\",\n \"curlywedge\":\"\\u22CF\",\n \"curren\":\"\\u00A4\",\n \"curvearrowleft\":\"\\u21B6\",\n \"curvearrowright\":\"\\u21B7\",\n \"cuvee\":\"\\u22CE\",\n \"cuwed\":\"\\u22CF\",\n \"cwconint\":\"\\u2232\",\n \"cwint\":\"\\u2231\",\n \"cylcty\":\"\\u232D\",\n \"Dagger\":\"\\u2021\",\n \"dagger\":\"\\u2020\",\n \"daleth\":\"\\u2138\",\n \"Darr\":\"\\u21A1\",\n \"dArr\":\"\\u21D3\",\n \"darr\":\"\\u2193\",\n \"dash\":\"\\u2010\",\n \"Dashv\":\"\\u2AE4\",\n \"dashv\":\"\\u22A3\",\n \"dbkarow\":\"\\u290F\",\n \"dblac\":\"\\u02DD\",\n \"Dcaron\":\"\\u010E\",\n \"dcaron\":\"\\u010F\",\n \"Dcy\":\"\\u0414\",\n \"dcy\":\"\\u0434\",\n \"DD\":\"\\u2145\",\n \"dd\":\"\\u2146\",\n \"ddagger\":\"\\u2021\",\n \"ddarr\":\"\\u21CA\",\n \"DDotrahd\":\"\\u2911\",\n \"ddotseq\":\"\\u2A77\",\n \"deg\":\"\\u00B0\",\n \"Del\":\"\\u2207\",\n \"Delta\":\"\\u0394\",\n \"delta\":\"\\u03B4\",\n \"demptyv\":\"\\u29B1\",\n \"dfisht\":\"\\u297F\",\n \"Dfr\":\"\\uD835\\uDD07\",\n \"dfr\":\"\\uD835\\uDD21\",\n \"dHar\":\"\\u2965\",\n \"dharl\":\"\\u21C3\",\n \"dharr\":\"\\u21C2\",\n \"DiacriticalAcute\":\"\\u00B4\",\n \"DiacriticalDot\":\"\\u02D9\",\n \"DiacriticalDoubleAcute\":\"\\u02DD\",\n \"DiacriticalGrave\":\"\\u0060\",\n \"DiacriticalTilde\":\"\\u02DC\",\n \"diam\":\"\\u22C4\",\n \"Diamond\":\"\\u22C4\",\n \"diamond\":\"\\u22C4\",\n \"diamondsuit\":\"\\u2666\",\n \"diams\":\"\\u2666\",\n \"die\":\"\\u00A8\",\n \"DifferentialD\":\"\\u2146\",\n \"digamma\":\"\\u03DD\",\n \"disin\":\"\\u22F2\",\n \"div\":\"\\u00F7\",\n \"divide\":\"\\u00F7\",\n \"divideontimes\":\"\\u22C7\",\n \"divonx\":\"\\u22C7\",\n \"DJcy\":\"\\u0402\",\n \"djcy\":\"\\u0452\",\n \"dlcorn\":\"\\u231E\",\n \"dlcrop\":\"\\u230D\",\n \"dollar\":\"\\u0024\",\n \"Dopf\":\"\\uD835\\uDD3B\",\n \"dopf\":\"\\uD835\\uDD55\",\n \"Dot\":\"\\u00A8\",\n \"dot\":\"\\u02D9\",\n \"DotDot\":\"\\u20DC\",\n \"doteq\":\"\\u2250\",\n \"doteqdot\":\"\\u2251\",\n \"DotEqual\":\"\\u2250\",\n \"dotminus\":\"\\u2238\",\n \"dotplus\":\"\\u2214\",\n \"dotsquare\":\"\\u22A1\",\n \"doublebarwedge\":\"\\u2306\",\n \"DoubleContourIntegral\":\"\\u222F\",\n \"DoubleDot\":\"\\u00A8\",\n \"DoubleDownArrow\":\"\\u21D3\",\n \"DoubleLeftArrow\":\"\\u21D0\",\n \"DoubleLeftRightArrow\":\"\\u21D4\",\n \"DoubleLeftTee\":\"\\u2AE4\",\n \"DoubleLongLeftArrow\":\"\\u27F8\",\n \"DoubleLongLeftRightArrow\":\"\\u27FA\",\n \"DoubleLongRightArrow\":\"\\u27F9\",\n \"DoubleRightArrow\":\"\\u21D2\",\n \"DoubleRightTee\":\"\\u22A8\",\n \"DoubleUpArrow\":\"\\u21D1\",\n \"DoubleUpDownArrow\":\"\\u21D5\",\n \"DoubleVerticalBar\":\"\\u2225\",\n \"DownArrow\":\"\\u2193\",\n \"Downarrow\":\"\\u21D3\",\n \"downarrow\":\"\\u2193\",\n \"DownArrowBar\":\"\\u2913\",\n \"DownArrowUpArrow\":\"\\u21F5\",\n \"DownBreve\":\"\\u0311\",\n \"downdownarrows\":\"\\u21CA\",\n \"downharpoonleft\":\"\\u21C3\",\n \"downharpoonright\":\"\\u21C2\",\n \"DownLeftRightVector\":\"\\u2950\",\n \"DownLeftTeeVector\":\"\\u295E\",\n \"DownLeftVector\":\"\\u21BD\",\n \"DownLeftVectorBar\":\"\\u2956\",\n \"DownRightTeeVector\":\"\\u295F\",\n \"DownRightVector\":\"\\u21C1\",\n \"DownRightVectorBar\":\"\\u2957\",\n \"DownTee\":\"\\u22A4\",\n \"DownTeeArrow\":\"\\u21A7\",\n \"drbkarow\":\"\\u2910\",\n \"drcorn\":\"\\u231F\",\n \"drcrop\":\"\\u230C\",\n \"Dscr\":\"\\uD835\\uDC9F\",\n \"dscr\":\"\\uD835\\uDCB9\",\n \"DScy\":\"\\u0405\",\n \"dscy\":\"\\u0455\",\n \"dsol\":\"\\u29F6\",\n \"Dstrok\":\"\\u0110\",\n \"dstrok\":\"\\u0111\",\n \"dtdot\":\"\\u22F1\",\n \"dtri\":\"\\u25BF\",\n \"dtrif\":\"\\u25BE\",\n \"duarr\":\"\\u21F5\",\n \"duhar\":\"\\u296F\",\n \"dwangle\":\"\\u29A6\",\n \"DZcy\":\"\\u040F\",\n \"dzcy\":\"\\u045F\",\n \"dzigrarr\":\"\\u27FF\",\n \"Eacute\":\"\\u00C9\",\n \"eacute\":\"\\u00E9\",\n \"easter\":\"\\u2A6E\",\n \"Ecaron\":\"\\u011A\",\n \"ecaron\":\"\\u011B\",\n \"ecir\":\"\\u2256\",\n \"Ecirc\":\"\\u00CA\",\n \"ecirc\":\"\\u00EA\",\n \"ecolon\":\"\\u2255\",\n \"Ecy\":\"\\u042D\",\n \"ecy\":\"\\u044D\",\n \"eDDot\":\"\\u2A77\",\n \"Edot\":\"\\u0116\",\n \"eDot\":\"\\u2251\",\n \"edot\":\"\\u0117\",\n \"ee\":\"\\u2147\",\n \"efDot\":\"\\u2252\",\n \"Efr\":\"\\uD835\\uDD08\",\n \"efr\":\"\\uD835\\uDD22\",\n \"eg\":\"\\u2A9A\",\n \"Egrave\":\"\\u00C8\",\n \"egrave\":\"\\u00E8\",\n \"egs\":\"\\u2A96\",\n \"egsdot\":\"\\u2A98\",\n \"el\":\"\\u2A99\",\n \"Element\":\"\\u2208\",\n \"elinters\":\"\\u23E7\",\n \"ell\":\"\\u2113\",\n \"els\":\"\\u2A95\",\n \"elsdot\":\"\\u2A97\",\n \"Emacr\":\"\\u0112\",\n \"emacr\":\"\\u0113\",\n \"empty\":\"\\u2205\",\n \"emptyset\":\"\\u2205\",\n \"EmptySmallSquare\":\"\\u25FB\",\n \"emptyv\":\"\\u2205\",\n \"EmptyVerySmallSquare\":\"\\u25AB\",\n \"emsp\":\"\\u2003\",\n \"emsp13\":\"\\u2004\",\n \"emsp14\":\"\\u2005\",\n \"ENG\":\"\\u014A\",\n \"eng\":\"\\u014B\",\n \"ensp\":\"\\u2002\",\n \"Eogon\":\"\\u0118\",\n \"eogon\":\"\\u0119\",\n \"Eopf\":\"\\uD835\\uDD3C\",\n \"eopf\":\"\\uD835\\uDD56\",\n \"epar\":\"\\u22D5\",\n \"eparsl\":\"\\u29E3\",\n \"eplus\":\"\\u2A71\",\n \"epsi\":\"\\u03B5\",\n \"Epsilon\":\"\\u0395\",\n \"epsilon\":\"\\u03B5\",\n \"epsiv\":\"\\u03F5\",\n \"eqcirc\":\"\\u2256\",\n \"eqcolon\":\"\\u2255\",\n \"eqsim\":\"\\u2242\",\n \"eqslantgtr\":\"\\u2A96\",\n \"eqslantless\":\"\\u2A95\",\n \"Equal\":\"\\u2A75\",\n \"equals\":\"\\u003D\",\n \"EqualTilde\":\"\\u2242\",\n \"equest\":\"\\u225F\",\n \"Equilibrium\":\"\\u21CC\",\n \"equiv\":\"\\u2261\",\n \"equivDD\":\"\\u2A78\",\n \"eqvparsl\":\"\\u29E5\",\n \"erarr\":\"\\u2971\",\n \"erDot\":\"\\u2253\",\n \"Escr\":\"\\u2130\",\n \"escr\":\"\\u212F\",\n \"esdot\":\"\\u2250\",\n \"Esim\":\"\\u2A73\",\n \"esim\":\"\\u2242\",\n \"Eta\":\"\\u0397\",\n \"eta\":\"\\u03B7\",\n \"ETH\":\"\\u00D0\",\n \"eth\":\"\\u00F0\",\n \"Euml\":\"\\u00CB\",\n \"euml\":\"\\u00EB\",\n \"euro\":\"\\u20AC\",\n \"excl\":\"\\u0021\",\n \"exist\":\"\\u2203\",\n \"Exists\":\"\\u2203\",\n \"expectation\":\"\\u2130\",\n \"ExponentialE\":\"\\u2147\",\n \"exponentiale\":\"\\u2147\",\n \"fallingdotseq\":\"\\u2252\",\n \"Fcy\":\"\\u0424\",\n \"fcy\":\"\\u0444\",\n \"female\":\"\\u2640\",\n \"ffilig\":\"\\uFB03\",\n \"fflig\":\"\\uFB00\",\n \"ffllig\":\"\\uFB04\",\n \"Ffr\":\"\\uD835\\uDD09\",\n \"ffr\":\"\\uD835\\uDD23\",\n \"filig\":\"\\uFB01\",\n \"FilledSmallSquare\":\"\\u25FC\",\n \"FilledVerySmallSquare\":\"\\u25AA\",\n \"fjlig\":\"\\u0066\\u006A\",\n \"flat\":\"\\u266D\",\n \"fllig\":\"\\uFB02\",\n \"fltns\":\"\\u25B1\",\n \"fnof\":\"\\u0192\",\n \"Fopf\":\"\\uD835\\uDD3D\",\n \"fopf\":\"\\uD835\\uDD57\",\n \"ForAll\":\"\\u2200\",\n \"forall\":\"\\u2200\",\n \"fork\":\"\\u22D4\",\n \"forkv\":\"\\u2AD9\",\n \"Fouriertrf\":\"\\u2131\",\n \"fpartint\":\"\\u2A0D\",\n \"frac12\":\"\\u00BD\",\n \"frac13\":\"\\u2153\",\n \"frac14\":\"\\u00BC\",\n \"frac15\":\"\\u2155\",\n \"frac16\":\"\\u2159\",\n \"frac18\":\"\\u215B\",\n \"frac23\":\"\\u2154\",\n \"frac25\":\"\\u2156\",\n \"frac34\":\"\\u00BE\",\n \"frac35\":\"\\u2157\",\n \"frac38\":\"\\u215C\",\n \"frac45\":\"\\u2158\",\n \"frac56\":\"\\u215A\",\n \"frac58\":\"\\u215D\",\n \"frac78\":\"\\u215E\",\n \"frasl\":\"\\u2044\",\n \"frown\":\"\\u2322\",\n \"Fscr\":\"\\u2131\",\n \"fscr\":\"\\uD835\\uDCBB\",\n \"gacute\":\"\\u01F5\",\n \"Gamma\":\"\\u0393\",\n \"gamma\":\"\\u03B3\",\n \"Gammad\":\"\\u03DC\",\n \"gammad\":\"\\u03DD\",\n \"gap\":\"\\u2A86\",\n \"Gbreve\":\"\\u011E\",\n \"gbreve\":\"\\u011F\",\n \"Gcedil\":\"\\u0122\",\n \"Gcirc\":\"\\u011C\",\n \"gcirc\":\"\\u011D\",\n \"Gcy\":\"\\u0413\",\n \"gcy\":\"\\u0433\",\n \"Gdot\":\"\\u0120\",\n \"gdot\":\"\\u0121\",\n \"gE\":\"\\u2267\",\n \"ge\":\"\\u2265\",\n \"gEl\":\"\\u2A8C\",\n \"gel\":\"\\u22DB\",\n \"geq\":\"\\u2265\",\n \"geqq\":\"\\u2267\",\n \"geqslant\":\"\\u2A7E\",\n \"ges\":\"\\u2A7E\",\n \"gescc\":\"\\u2AA9\",\n \"gesdot\":\"\\u2A80\",\n \"gesdoto\":\"\\u2A82\",\n \"gesdotol\":\"\\u2A84\",\n \"gesl\":\"\\u22DB\\uFE00\",\n \"gesles\":\"\\u2A94\",\n \"Gfr\":\"\\uD835\\uDD0A\",\n \"gfr\":\"\\uD835\\uDD24\",\n \"Gg\":\"\\u22D9\",\n \"gg\":\"\\u226B\",\n \"ggg\":\"\\u22D9\",\n \"gimel\":\"\\u2137\",\n \"GJcy\":\"\\u0403\",\n \"gjcy\":\"\\u0453\",\n \"gl\":\"\\u2277\",\n \"gla\":\"\\u2AA5\",\n \"glE\":\"\\u2A92\",\n \"glj\":\"\\u2AA4\",\n \"gnap\":\"\\u2A8A\",\n \"gnapprox\":\"\\u2A8A\",\n \"gnE\":\"\\u2269\",\n \"gne\":\"\\u2A88\",\n \"gneq\":\"\\u2A88\",\n \"gneqq\":\"\\u2269\",\n \"gnsim\":\"\\u22E7\",\n \"Gopf\":\"\\uD835\\uDD3E\",\n \"gopf\":\"\\uD835\\uDD58\",\n \"grave\":\"\\u0060\",\n \"GreaterEqual\":\"\\u2265\",\n \"GreaterEqualLess\":\"\\u22DB\",\n \"GreaterFullEqual\":\"\\u2267\",\n \"GreaterGreater\":\"\\u2AA2\",\n \"GreaterLess\":\"\\u2277\",\n \"GreaterSlantEqual\":\"\\u2A7E\",\n \"GreaterTilde\":\"\\u2273\",\n \"Gscr\":\"\\uD835\\uDCA2\",\n \"gscr\":\"\\u210A\",\n \"gsim\":\"\\u2273\",\n \"gsime\":\"\\u2A8E\",\n \"gsiml\":\"\\u2A90\",\n \"GT\":\"\\u003E\",\n \"Gt\":\"\\u226B\",\n \"gt\":\"\\u003E\",\n \"gtcc\":\"\\u2AA7\",\n \"gtcir\":\"\\u2A7A\",\n \"gtdot\":\"\\u22D7\",\n \"gtlPar\":\"\\u2995\",\n \"gtquest\":\"\\u2A7C\",\n \"gtrapprox\":\"\\u2A86\",\n \"gtrarr\":\"\\u2978\",\n \"gtrdot\":\"\\u22D7\",\n \"gtreqless\":\"\\u22DB\",\n \"gtreqqless\":\"\\u2A8C\",\n \"gtrless\":\"\\u2277\",\n \"gtrsim\":\"\\u2273\",\n \"gvertneqq\":\"\\u2269\\uFE00\",\n \"gvnE\":\"\\u2269\\uFE00\",\n \"Hacek\":\"\\u02C7\",\n \"hairsp\":\"\\u200A\",\n \"half\":\"\\u00BD\",\n \"hamilt\":\"\\u210B\",\n \"HARDcy\":\"\\u042A\",\n \"hardcy\":\"\\u044A\",\n \"hArr\":\"\\u21D4\",\n \"harr\":\"\\u2194\",\n \"harrcir\":\"\\u2948\",\n \"harrw\":\"\\u21AD\",\n \"Hat\":\"\\u005E\",\n \"hbar\":\"\\u210F\",\n \"Hcirc\":\"\\u0124\",\n \"hcirc\":\"\\u0125\",\n \"hearts\":\"\\u2665\",\n \"heartsuit\":\"\\u2665\",\n \"hellip\":\"\\u2026\",\n \"hercon\":\"\\u22B9\",\n \"Hfr\":\"\\u210C\",\n \"hfr\":\"\\uD835\\uDD25\",\n \"HilbertSpace\":\"\\u210B\",\n \"hksearow\":\"\\u2925\",\n \"hkswarow\":\"\\u2926\",\n \"hoarr\":\"\\u21FF\",\n \"homtht\":\"\\u223B\",\n \"hookleftarrow\":\"\\u21A9\",\n \"hookrightarrow\":\"\\u21AA\",\n \"Hopf\":\"\\u210D\",\n \"hopf\":\"\\uD835\\uDD59\",\n \"horbar\":\"\\u2015\",\n \"HorizontalLine\":\"\\u2500\",\n \"Hscr\":\"\\u210B\",\n \"hscr\":\"\\uD835\\uDCBD\",\n \"hslash\":\"\\u210F\",\n \"Hstrok\":\"\\u0126\",\n \"hstrok\":\"\\u0127\",\n \"HumpDownHump\":\"\\u224E\",\n \"HumpEqual\":\"\\u224F\",\n \"hybull\":\"\\u2043\",\n \"hyphen\":\"\\u2010\",\n \"Iacute\":\"\\u00CD\",\n \"iacute\":\"\\u00ED\",\n \"ic\":\"\\u2063\",\n \"Icirc\":\"\\u00CE\",\n \"icirc\":\"\\u00EE\",\n \"Icy\":\"\\u0418\",\n \"icy\":\"\\u0438\",\n \"Idot\":\"\\u0130\",\n \"IEcy\":\"\\u0415\",\n \"iecy\":\"\\u0435\",\n \"iexcl\":\"\\u00A1\",\n \"iff\":\"\\u21D4\",\n \"Ifr\":\"\\u2111\",\n \"ifr\":\"\\uD835\\uDD26\",\n \"Igrave\":\"\\u00CC\",\n \"igrave\":\"\\u00EC\",\n \"ii\":\"\\u2148\",\n \"iiiint\":\"\\u2A0C\",\n \"iiint\":\"\\u222D\",\n \"iinfin\":\"\\u29DC\",\n \"iiota\":\"\\u2129\",\n \"IJlig\":\"\\u0132\",\n \"ijlig\":\"\\u0133\",\n \"Im\":\"\\u2111\",\n \"Imacr\":\"\\u012A\",\n \"imacr\":\"\\u012B\",\n \"image\":\"\\u2111\",\n \"ImaginaryI\":\"\\u2148\",\n \"imagline\":\"\\u2110\",\n \"imagpart\":\"\\u2111\",\n \"imath\":\"\\u0131\",\n \"imof\":\"\\u22B7\",\n \"imped\":\"\\u01B5\",\n \"Implies\":\"\\u21D2\",\n \"in\":\"\\u2208\",\n \"incare\":\"\\u2105\",\n \"infin\":\"\\u221E\",\n \"infintie\":\"\\u29DD\",\n \"inodot\":\"\\u0131\",\n \"Int\":\"\\u222C\",\n \"int\":\"\\u222B\",\n \"intcal\":\"\\u22BA\",\n \"integers\":\"\\u2124\",\n \"Integral\":\"\\u222B\",\n \"intercal\":\"\\u22BA\",\n \"Intersection\":\"\\u22C2\",\n \"intlarhk\":\"\\u2A17\",\n \"intprod\":\"\\u2A3C\",\n \"InvisibleComma\":\"\\u2063\",\n \"InvisibleTimes\":\"\\u2062\",\n \"IOcy\":\"\\u0401\",\n \"iocy\":\"\\u0451\",\n \"Iogon\":\"\\u012E\",\n \"iogon\":\"\\u012F\",\n \"Iopf\":\"\\uD835\\uDD40\",\n \"iopf\":\"\\uD835\\uDD5A\",\n \"Iota\":\"\\u0399\",\n \"iota\":\"\\u03B9\",\n \"iprod\":\"\\u2A3C\",\n \"iquest\":\"\\u00BF\",\n \"Iscr\":\"\\u2110\",\n \"iscr\":\"\\uD835\\uDCBE\",\n \"isin\":\"\\u2208\",\n \"isindot\":\"\\u22F5\",\n \"isinE\":\"\\u22F9\",\n \"isins\":\"\\u22F4\",\n \"isinsv\":\"\\u22F3\",\n \"isinv\":\"\\u2208\",\n \"it\":\"\\u2062\",\n \"Itilde\":\"\\u0128\",\n \"itilde\":\"\\u0129\",\n \"Iukcy\":\"\\u0406\",\n \"iukcy\":\"\\u0456\",\n \"Iuml\":\"\\u00CF\",\n \"iuml\":\"\\u00EF\",\n \"Jcirc\":\"\\u0134\",\n \"jcirc\":\"\\u0135\",\n \"Jcy\":\"\\u0419\",\n \"jcy\":\"\\u0439\",\n \"Jfr\":\"\\uD835\\uDD0D\",\n \"jfr\":\"\\uD835\\uDD27\",\n \"jmath\":\"\\u0237\",\n \"Jopf\":\"\\uD835\\uDD41\",\n \"jopf\":\"\\uD835\\uDD5B\",\n \"Jscr\":\"\\uD835\\uDCA5\",\n \"jscr\":\"\\uD835\\uDCBF\",\n \"Jsercy\":\"\\u0408\",\n \"jsercy\":\"\\u0458\",\n \"Jukcy\":\"\\u0404\",\n \"jukcy\":\"\\u0454\",\n \"Kappa\":\"\\u039A\",\n \"kappa\":\"\\u03BA\",\n \"kappav\":\"\\u03F0\",\n \"Kcedil\":\"\\u0136\",\n \"kcedil\":\"\\u0137\",\n \"Kcy\":\"\\u041A\",\n \"kcy\":\"\\u043A\",\n \"Kfr\":\"\\uD835\\uDD0E\",\n \"kfr\":\"\\uD835\\uDD28\",\n \"kgreen\":\"\\u0138\",\n \"KHcy\":\"\\u0425\",\n \"khcy\":\"\\u0445\",\n \"KJcy\":\"\\u040C\",\n \"kjcy\":\"\\u045C\",\n \"Kopf\":\"\\uD835\\uDD42\",\n \"kopf\":\"\\uD835\\uDD5C\",\n \"Kscr\":\"\\uD835\\uDCA6\",\n \"kscr\":\"\\uD835\\uDCC0\",\n \"lAarr\":\"\\u21DA\",\n \"Lacute\":\"\\u0139\",\n \"lacute\":\"\\u013A\",\n \"laemptyv\":\"\\u29B4\",\n \"lagran\":\"\\u2112\",\n \"Lambda\":\"\\u039B\",\n \"lambda\":\"\\u03BB\",\n \"Lang\":\"\\u27EA\",\n \"lang\":\"\\u27E8\",\n \"langd\":\"\\u2991\",\n \"langle\":\"\\u27E8\",\n \"lap\":\"\\u2A85\",\n \"Laplacetrf\":\"\\u2112\",\n \"laquo\":\"\\u00AB\",\n \"Larr\":\"\\u219E\",\n \"lArr\":\"\\u21D0\",\n \"larr\":\"\\u2190\",\n \"larrb\":\"\\u21E4\",\n \"larrbfs\":\"\\u291F\",\n \"larrfs\":\"\\u291D\",\n \"larrhk\":\"\\u21A9\",\n \"larrlp\":\"\\u21AB\",\n \"larrpl\":\"\\u2939\",\n \"larrsim\":\"\\u2973\",\n \"larrtl\":\"\\u21A2\",\n \"lat\":\"\\u2AAB\",\n \"lAtail\":\"\\u291B\",\n \"latail\":\"\\u2919\",\n \"late\":\"\\u2AAD\",\n \"lates\":\"\\u2AAD\\uFE00\",\n \"lBarr\":\"\\u290E\",\n \"lbarr\":\"\\u290C\",\n \"lbbrk\":\"\\u2772\",\n \"lbrace\":\"\\u007B\",\n \"lbrack\":\"\\u005B\",\n \"lbrke\":\"\\u298B\",\n \"lbrksld\":\"\\u298F\",\n \"lbrkslu\":\"\\u298D\",\n \"Lcaron\":\"\\u013D\",\n \"lcaron\":\"\\u013E\",\n \"Lcedil\":\"\\u013B\",\n \"lcedil\":\"\\u013C\",\n \"lceil\":\"\\u2308\",\n \"lcub\":\"\\u007B\",\n \"Lcy\":\"\\u041B\",\n \"lcy\":\"\\u043B\",\n \"ldca\":\"\\u2936\",\n \"ldquo\":\"\\u201C\",\n \"ldquor\":\"\\u201E\",\n \"ldrdhar\":\"\\u2967\",\n \"ldrushar\":\"\\u294B\",\n \"ldsh\":\"\\u21B2\",\n \"lE\":\"\\u2266\",\n \"le\":\"\\u2264\",\n \"LeftAngleBracket\":\"\\u27E8\",\n \"LeftArrow\":\"\\u2190\",\n \"Leftarrow\":\"\\u21D0\",\n \"leftarrow\":\"\\u2190\",\n \"LeftArrowBar\":\"\\u21E4\",\n \"LeftArrowRightArrow\":\"\\u21C6\",\n \"leftarrowtail\":\"\\u21A2\",\n \"LeftCeiling\":\"\\u2308\",\n \"LeftDoubleBracket\":\"\\u27E6\",\n \"LeftDownTeeVector\":\"\\u2961\",\n \"LeftDownVector\":\"\\u21C3\",\n \"LeftDownVectorBar\":\"\\u2959\",\n \"LeftFloor\":\"\\u230A\",\n \"leftharpoondown\":\"\\u21BD\",\n \"leftharpoonup\":\"\\u21BC\",\n \"leftleftarrows\":\"\\u21C7\",\n \"LeftRightArrow\":\"\\u2194\",\n \"Leftrightarrow\":\"\\u21D4\",\n \"leftrightarrow\":\"\\u2194\",\n \"leftrightarrows\":\"\\u21C6\",\n \"leftrightharpoons\":\"\\u21CB\",\n \"leftrightsquigarrow\":\"\\u21AD\",\n \"LeftRightVector\":\"\\u294E\",\n \"LeftTee\":\"\\u22A3\",\n \"LeftTeeArrow\":\"\\u21A4\",\n \"LeftTeeVector\":\"\\u295A\",\n \"leftthreetimes\":\"\\u22CB\",\n \"LeftTriangle\":\"\\u22B2\",\n \"LeftTriangleBar\":\"\\u29CF\",\n \"LeftTriangleEqual\":\"\\u22B4\",\n \"LeftUpDownVector\":\"\\u2951\",\n \"LeftUpTeeVector\":\"\\u2960\",\n \"LeftUpVector\":\"\\u21BF\",\n \"LeftUpVectorBar\":\"\\u2958\",\n \"LeftVector\":\"\\u21BC\",\n \"LeftVectorBar\":\"\\u2952\",\n \"lEg\":\"\\u2A8B\",\n \"leg\":\"\\u22DA\",\n \"leq\":\"\\u2264\",\n \"leqq\":\"\\u2266\",\n \"leqslant\":\"\\u2A7D\",\n \"les\":\"\\u2A7D\",\n \"lescc\":\"\\u2AA8\",\n \"lesdot\":\"\\u2A7F\",\n \"lesdoto\":\"\\u2A81\",\n \"lesdotor\":\"\\u2A83\",\n \"lesg\":\"\\u22DA\\uFE00\",\n \"lesges\":\"\\u2A93\",\n \"lessapprox\":\"\\u2A85\",\n \"lessdot\":\"\\u22D6\",\n \"lesseqgtr\":\"\\u22DA\",\n \"lesseqqgtr\":\"\\u2A8B\",\n \"LessEqualGreater\":\"\\u22DA\",\n \"LessFullEqual\":\"\\u2266\",\n \"LessGreater\":\"\\u2276\",\n \"lessgtr\":\"\\u2276\",\n \"LessLess\":\"\\u2AA1\",\n \"lesssim\":\"\\u2272\",\n \"LessSlantEqual\":\"\\u2A7D\",\n \"LessTilde\":\"\\u2272\",\n \"lfisht\":\"\\u297C\",\n \"lfloor\":\"\\u230A\",\n \"Lfr\":\"\\uD835\\uDD0F\",\n \"lfr\":\"\\uD835\\uDD29\",\n \"lg\":\"\\u2276\",\n \"lgE\":\"\\u2A91\",\n \"lHar\":\"\\u2962\",\n \"lhard\":\"\\u21BD\",\n \"lharu\":\"\\u21BC\",\n \"lharul\":\"\\u296A\",\n \"lhblk\":\"\\u2584\",\n \"LJcy\":\"\\u0409\",\n \"ljcy\":\"\\u0459\",\n \"Ll\":\"\\u22D8\",\n \"ll\":\"\\u226A\",\n \"llarr\":\"\\u21C7\",\n \"llcorner\":\"\\u231E\",\n \"Lleftarrow\":\"\\u21DA\",\n \"llhard\":\"\\u296B\",\n \"lltri\":\"\\u25FA\",\n \"Lmidot\":\"\\u013F\",\n \"lmidot\":\"\\u0140\",\n \"lmoust\":\"\\u23B0\",\n \"lmoustache\":\"\\u23B0\",\n \"lnap\":\"\\u2A89\",\n \"lnapprox\":\"\\u2A89\",\n \"lnE\":\"\\u2268\",\n \"lne\":\"\\u2A87\",\n \"lneq\":\"\\u2A87\",\n \"lneqq\":\"\\u2268\",\n \"lnsim\":\"\\u22E6\",\n \"loang\":\"\\u27EC\",\n \"loarr\":\"\\u21FD\",\n \"lobrk\":\"\\u27E6\",\n \"LongLeftArrow\":\"\\u27F5\",\n \"Longleftarrow\":\"\\u27F8\",\n \"longleftarrow\":\"\\u27F5\",\n \"LongLeftRightArrow\":\"\\u27F7\",\n \"Longleftrightarrow\":\"\\u27FA\",\n \"longleftrightarrow\":\"\\u27F7\",\n \"longmapsto\":\"\\u27FC\",\n \"LongRightArrow\":\"\\u27F6\",\n \"Longrightarrow\":\"\\u27F9\",\n \"longrightarrow\":\"\\u27F6\",\n \"looparrowleft\":\"\\u21AB\",\n \"looparrowright\":\"\\u21AC\",\n \"lopar\":\"\\u2985\",\n \"Lopf\":\"\\uD835\\uDD43\",\n \"lopf\":\"\\uD835\\uDD5D\",\n \"loplus\":\"\\u2A2D\",\n \"lotimes\":\"\\u2A34\",\n \"lowast\":\"\\u2217\",\n \"lowbar\":\"\\u005F\",\n \"LowerLeftArrow\":\"\\u2199\",\n \"LowerRightArrow\":\"\\u2198\",\n \"loz\":\"\\u25CA\",\n \"lozenge\":\"\\u25CA\",\n \"lozf\":\"\\u29EB\",\n \"lpar\":\"\\u0028\",\n \"lparlt\":\"\\u2993\",\n \"lrarr\":\"\\u21C6\",\n \"lrcorner\":\"\\u231F\",\n \"lrhar\":\"\\u21CB\",\n \"lrhard\":\"\\u296D\",\n \"lrm\":\"\\u200E\",\n \"lrtri\":\"\\u22BF\",\n \"lsaquo\":\"\\u2039\",\n \"Lscr\":\"\\u2112\",\n \"lscr\":\"\\uD835\\uDCC1\",\n \"Lsh\":\"\\u21B0\",\n \"lsh\":\"\\u21B0\",\n \"lsim\":\"\\u2272\",\n \"lsime\":\"\\u2A8D\",\n \"lsimg\":\"\\u2A8F\",\n \"lsqb\":\"\\u005B\",\n \"lsquo\":\"\\u2018\",\n \"lsquor\":\"\\u201A\",\n \"Lstrok\":\"\\u0141\",\n \"lstrok\":\"\\u0142\",\n \"LT\":\"\\u003C\",\n \"Lt\":\"\\u226A\",\n \"lt\":\"\\u003C\",\n \"ltcc\":\"\\u2AA6\",\n \"ltcir\":\"\\u2A79\",\n \"ltdot\":\"\\u22D6\",\n \"lthree\":\"\\u22CB\",\n \"ltimes\":\"\\u22C9\",\n \"ltlarr\":\"\\u2976\",\n \"ltquest\":\"\\u2A7B\",\n \"ltri\":\"\\u25C3\",\n \"ltrie\":\"\\u22B4\",\n \"ltrif\":\"\\u25C2\",\n \"ltrPar\":\"\\u2996\",\n \"lurdshar\":\"\\u294A\",\n \"luruhar\":\"\\u2966\",\n \"lvertneqq\":\"\\u2268\\uFE00\",\n \"lvnE\":\"\\u2268\\uFE00\",\n \"macr\":\"\\u00AF\",\n \"male\":\"\\u2642\",\n \"malt\":\"\\u2720\",\n \"maltese\":\"\\u2720\",\n \"Map\":\"\\u2905\",\n \"map\":\"\\u21A6\",\n \"mapsto\":\"\\u21A6\",\n \"mapstodown\":\"\\u21A7\",\n \"mapstoleft\":\"\\u21A4\",\n \"mapstoup\":\"\\u21A5\",\n \"marker\":\"\\u25AE\",\n \"mcomma\":\"\\u2A29\",\n \"Mcy\":\"\\u041C\",\n \"mcy\":\"\\u043C\",\n \"mdash\":\"\\u2014\",\n \"mDDot\":\"\\u223A\",\n \"measuredangle\":\"\\u2221\",\n \"MediumSpace\":\"\\u205F\",\n \"Mellintrf\":\"\\u2133\",\n \"Mfr\":\"\\uD835\\uDD10\",\n \"mfr\":\"\\uD835\\uDD2A\",\n \"mho\":\"\\u2127\",\n \"micro\":\"\\u00B5\",\n \"mid\":\"\\u2223\",\n \"midast\":\"\\u002A\",\n \"midcir\":\"\\u2AF0\",\n \"middot\":\"\\u00B7\",\n \"minus\":\"\\u2212\",\n \"minusb\":\"\\u229F\",\n \"minusd\":\"\\u2238\",\n \"minusdu\":\"\\u2A2A\",\n \"MinusPlus\":\"\\u2213\",\n \"mlcp\":\"\\u2ADB\",\n \"mldr\":\"\\u2026\",\n \"mnplus\":\"\\u2213\",\n \"models\":\"\\u22A7\",\n \"Mopf\":\"\\uD835\\uDD44\",\n \"mopf\":\"\\uD835\\uDD5E\",\n \"mp\":\"\\u2213\",\n \"Mscr\":\"\\u2133\",\n \"mscr\":\"\\uD835\\uDCC2\",\n \"mstpos\":\"\\u223E\",\n \"Mu\":\"\\u039C\",\n \"mu\":\"\\u03BC\",\n \"multimap\":\"\\u22B8\",\n \"mumap\":\"\\u22B8\",\n \"nabla\":\"\\u2207\",\n \"Nacute\":\"\\u0143\",\n \"nacute\":\"\\u0144\",\n \"nang\":\"\\u2220\\u20D2\",\n \"nap\":\"\\u2249\",\n \"napE\":\"\\u2A70\\u0338\",\n \"napid\":\"\\u224B\\u0338\",\n \"napos\":\"\\u0149\",\n \"napprox\":\"\\u2249\",\n \"natur\":\"\\u266E\",\n \"natural\":\"\\u266E\",\n \"naturals\":\"\\u2115\",\n \"nbsp\":\"\\u00A0\",\n \"nbump\":\"\\u224E\\u0338\",\n \"nbumpe\":\"\\u224F\\u0338\",\n \"ncap\":\"\\u2A43\",\n \"Ncaron\":\"\\u0147\",\n \"ncaron\":\"\\u0148\",\n \"Ncedil\":\"\\u0145\",\n \"ncedil\":\"\\u0146\",\n \"ncong\":\"\\u2247\",\n \"ncongdot\":\"\\u2A6D\\u0338\",\n \"ncup\":\"\\u2A42\",\n \"Ncy\":\"\\u041D\",\n \"ncy\":\"\\u043D\",\n \"ndash\":\"\\u2013\",\n \"ne\":\"\\u2260\",\n \"nearhk\":\"\\u2924\",\n \"neArr\":\"\\u21D7\",\n \"nearr\":\"\\u2197\",\n \"nearrow\":\"\\u2197\",\n \"nedot\":\"\\u2250\\u0338\",\n \"NegativeMediumSpace\":\"\\u200B\",\n \"NegativeThickSpace\":\"\\u200B\",\n \"NegativeThinSpace\":\"\\u200B\",\n \"NegativeVeryThinSpace\":\"\\u200B\",\n \"nequiv\":\"\\u2262\",\n \"nesear\":\"\\u2928\",\n \"nesim\":\"\\u2242\\u0338\",\n \"NestedGreaterGreater\":\"\\u226B\",\n \"NestedLessLess\":\"\\u226A\",\n \"NewLine\":\"\\u000A\",\n \"nexist\":\"\\u2204\",\n \"nexists\":\"\\u2204\",\n \"Nfr\":\"\\uD835\\uDD11\",\n \"nfr\":\"\\uD835\\uDD2B\",\n \"ngE\":\"\\u2267\\u0338\",\n \"nge\":\"\\u2271\",\n \"ngeq\":\"\\u2271\",\n \"ngeqq\":\"\\u2267\\u0338\",\n \"ngeqslant\":\"\\u2A7E\\u0338\",\n \"nges\":\"\\u2A7E\\u0338\",\n \"nGg\":\"\\u22D9\\u0338\",\n \"ngsim\":\"\\u2275\",\n \"nGt\":\"\\u226B\\u20D2\",\n \"ngt\":\"\\u226F\",\n \"ngtr\":\"\\u226F\",\n \"nGtv\":\"\\u226B\\u0338\",\n \"nhArr\":\"\\u21CE\",\n \"nharr\":\"\\u21AE\",\n \"nhpar\":\"\\u2AF2\",\n \"ni\":\"\\u220B\",\n \"nis\":\"\\u22FC\",\n \"nisd\":\"\\u22FA\",\n \"niv\":\"\\u220B\",\n \"NJcy\":\"\\u040A\",\n \"njcy\":\"\\u045A\",\n \"nlArr\":\"\\u21CD\",\n \"nlarr\":\"\\u219A\",\n \"nldr\":\"\\u2025\",\n \"nlE\":\"\\u2266\\u0338\",\n \"nle\":\"\\u2270\",\n \"nLeftarrow\":\"\\u21CD\",\n \"nleftarrow\":\"\\u219A\",\n \"nLeftrightarrow\":\"\\u21CE\",\n \"nleftrightarrow\":\"\\u21AE\",\n \"nleq\":\"\\u2270\",\n \"nleqq\":\"\\u2266\\u0338\",\n \"nleqslant\":\"\\u2A7D\\u0338\",\n \"nles\":\"\\u2A7D\\u0338\",\n \"nless\":\"\\u226E\",\n \"nLl\":\"\\u22D8\\u0338\",\n \"nlsim\":\"\\u2274\",\n \"nLt\":\"\\u226A\\u20D2\",\n \"nlt\":\"\\u226E\",\n \"nltri\":\"\\u22EA\",\n \"nltrie\":\"\\u22EC\",\n \"nLtv\":\"\\u226A\\u0338\",\n \"nmid\":\"\\u2224\",\n \"NoBreak\":\"\\u2060\",\n \"NonBreakingSpace\":\"\\u00A0\",\n \"Nopf\":\"\\u2115\",\n \"nopf\":\"\\uD835\\uDD5F\",\n \"Not\":\"\\u2AEC\",\n \"not\":\"\\u00AC\",\n \"NotCongruent\":\"\\u2262\",\n \"NotCupCap\":\"\\u226D\",\n \"NotDoubleVerticalBar\":\"\\u2226\",\n \"NotElement\":\"\\u2209\",\n \"NotEqual\":\"\\u2260\",\n \"NotEqualTilde\":\"\\u2242\\u0338\",\n \"NotExists\":\"\\u2204\",\n \"NotGreater\":\"\\u226F\",\n \"NotGreaterEqual\":\"\\u2271\",\n \"NotGreaterFullEqual\":\"\\u2267\\u0338\",\n \"NotGreaterGreater\":\"\\u226B\\u0338\",\n \"NotGreaterLess\":\"\\u2279\",\n \"NotGreaterSlantEqual\":\"\\u2A7E\\u0338\",\n \"NotGreaterTilde\":\"\\u2275\",\n \"NotHumpDownHump\":\"\\u224E\\u0338\",\n \"NotHumpEqual\":\"\\u224F\\u0338\",\n \"notin\":\"\\u2209\",\n \"notindot\":\"\\u22F5\\u0338\",\n \"notinE\":\"\\u22F9\\u0338\",\n \"notinva\":\"\\u2209\",\n \"notinvb\":\"\\u22F7\",\n \"notinvc\":\"\\u22F6\",\n \"NotLeftTriangle\":\"\\u22EA\",\n \"NotLeftTriangleBar\":\"\\u29CF\\u0338\",\n \"NotLeftTriangleEqual\":\"\\u22EC\",\n \"NotLess\":\"\\u226E\",\n \"NotLessEqual\":\"\\u2270\",\n \"NotLessGreater\":\"\\u2278\",\n \"NotLessLess\":\"\\u226A\\u0338\",\n \"NotLessSlantEqual\":\"\\u2A7D\\u0338\",\n \"NotLessTilde\":\"\\u2274\",\n \"NotNestedGreaterGreater\":\"\\u2AA2\\u0338\",\n \"NotNestedLessLess\":\"\\u2AA1\\u0338\",\n \"notni\":\"\\u220C\",\n \"notniva\":\"\\u220C\",\n \"notnivb\":\"\\u22FE\",\n \"notnivc\":\"\\u22FD\",\n \"NotPrecedes\":\"\\u2280\",\n \"NotPrecedesEqual\":\"\\u2AAF\\u0338\",\n \"NotPrecedesSlantEqual\":\"\\u22E0\",\n \"NotReverseElement\":\"\\u220C\",\n \"NotRightTriangle\":\"\\u22EB\",\n \"NotRightTriangleBar\":\"\\u29D0\\u0338\",\n \"NotRightTriangleEqual\":\"\\u22ED\",\n \"NotSquareSubset\":\"\\u228F\\u0338\",\n \"NotSquareSubsetEqual\":\"\\u22E2\",\n \"NotSquareSuperset\":\"\\u2290\\u0338\",\n \"NotSquareSupersetEqual\":\"\\u22E3\",\n \"NotSubset\":\"\\u2282\\u20D2\",\n \"NotSubsetEqual\":\"\\u2288\",\n \"NotSucceeds\":\"\\u2281\",\n \"NotSucceedsEqual\":\"\\u2AB0\\u0338\",\n \"NotSucceedsSlantEqual\":\"\\u22E1\",\n \"NotSucceedsTilde\":\"\\u227F\\u0338\",\n \"NotSuperset\":\"\\u2283\\u20D2\",\n \"NotSupersetEqual\":\"\\u2289\",\n \"NotTilde\":\"\\u2241\",\n \"NotTildeEqual\":\"\\u2244\",\n \"NotTildeFullEqual\":\"\\u2247\",\n \"NotTildeTilde\":\"\\u2249\",\n \"NotVerticalBar\":\"\\u2224\",\n \"npar\":\"\\u2226\",\n \"nparallel\":\"\\u2226\",\n \"nparsl\":\"\\u2AFD\\u20E5\",\n \"npart\":\"\\u2202\\u0338\",\n \"npolint\":\"\\u2A14\",\n \"npr\":\"\\u2280\",\n \"nprcue\":\"\\u22E0\",\n \"npre\":\"\\u2AAF\\u0338\",\n \"nprec\":\"\\u2280\",\n \"npreceq\":\"\\u2AAF\\u0338\",\n \"nrArr\":\"\\u21CF\",\n \"nrarr\":\"\\u219B\",\n \"nrarrc\":\"\\u2933\\u0338\",\n \"nrarrw\":\"\\u219D\\u0338\",\n \"nRightarrow\":\"\\u21CF\",\n \"nrightarrow\":\"\\u219B\",\n \"nrtri\":\"\\u22EB\",\n \"nrtrie\":\"\\u22ED\",\n \"nsc\":\"\\u2281\",\n \"nsccue\":\"\\u22E1\",\n \"nsce\":\"\\u2AB0\\u0338\",\n \"Nscr\":\"\\uD835\\uDCA9\",\n \"nscr\":\"\\uD835\\uDCC3\",\n \"nshortmid\":\"\\u2224\",\n \"nshortparallel\":\"\\u2226\",\n \"nsim\":\"\\u2241\",\n \"nsime\":\"\\u2244\",\n \"nsimeq\":\"\\u2244\",\n \"nsmid\":\"\\u2224\",\n \"nspar\":\"\\u2226\",\n \"nsqsube\":\"\\u22E2\",\n \"nsqsupe\":\"\\u22E3\",\n \"nsub\":\"\\u2284\",\n \"nsubE\":\"\\u2AC5\\u0338\",\n \"nsube\":\"\\u2288\",\n \"nsubset\":\"\\u2282\\u20D2\",\n \"nsubseteq\":\"\\u2288\",\n \"nsubseteqq\":\"\\u2AC5\\u0338\",\n \"nsucc\":\"\\u2281\",\n \"nsucceq\":\"\\u2AB0\\u0338\",\n \"nsup\":\"\\u2285\",\n \"nsupE\":\"\\u2AC6\\u0338\",\n \"nsupe\":\"\\u2289\",\n \"nsupset\":\"\\u2283\\u20D2\",\n \"nsupseteq\":\"\\u2289\",\n \"nsupseteqq\":\"\\u2AC6\\u0338\",\n \"ntgl\":\"\\u2279\",\n \"Ntilde\":\"\\u00D1\",\n \"ntilde\":\"\\u00F1\",\n \"ntlg\":\"\\u2278\",\n \"ntriangleleft\":\"\\u22EA\",\n \"ntrianglelefteq\":\"\\u22EC\",\n \"ntriangleright\":\"\\u22EB\",\n \"ntrianglerighteq\":\"\\u22ED\",\n \"Nu\":\"\\u039D\",\n \"nu\":\"\\u03BD\",\n \"num\":\"\\u0023\",\n \"numero\":\"\\u2116\",\n \"numsp\":\"\\u2007\",\n \"nvap\":\"\\u224D\\u20D2\",\n \"nVDash\":\"\\u22AF\",\n \"nVdash\":\"\\u22AE\",\n \"nvDash\":\"\\u22AD\",\n \"nvdash\":\"\\u22AC\",\n \"nvge\":\"\\u2265\\u20D2\",\n \"nvgt\":\"\\u003E\\u20D2\",\n \"nvHarr\":\"\\u2904\",\n \"nvinfin\":\"\\u29DE\",\n \"nvlArr\":\"\\u2902\",\n \"nvle\":\"\\u2264\\u20D2\",\n \"nvlt\":\"\\u003C\\u20D2\",\n \"nvltrie\":\"\\u22B4\\u20D2\",\n \"nvrArr\":\"\\u2903\",\n \"nvrtrie\":\"\\u22B5\\u20D2\",\n \"nvsim\":\"\\u223C\\u20D2\",\n \"nwarhk\":\"\\u2923\",\n \"nwArr\":\"\\u21D6\",\n \"nwarr\":\"\\u2196\",\n \"nwarrow\":\"\\u2196\",\n \"nwnear\":\"\\u2927\",\n \"Oacute\":\"\\u00D3\",\n \"oacute\":\"\\u00F3\",\n \"oast\":\"\\u229B\",\n \"ocir\":\"\\u229A\",\n \"Ocirc\":\"\\u00D4\",\n \"ocirc\":\"\\u00F4\",\n \"Ocy\":\"\\u041E\",\n \"ocy\":\"\\u043E\",\n \"odash\":\"\\u229D\",\n \"Odblac\":\"\\u0150\",\n \"odblac\":\"\\u0151\",\n \"odiv\":\"\\u2A38\",\n \"odot\":\"\\u2299\",\n \"odsold\":\"\\u29BC\",\n \"OElig\":\"\\u0152\",\n \"oelig\":\"\\u0153\",\n \"ofcir\":\"\\u29BF\",\n \"Ofr\":\"\\uD835\\uDD12\",\n \"ofr\":\"\\uD835\\uDD2C\",\n \"ogon\":\"\\u02DB\",\n \"Ograve\":\"\\u00D2\",\n \"ograve\":\"\\u00F2\",\n \"ogt\":\"\\u29C1\",\n \"ohbar\":\"\\u29B5\",\n \"ohm\":\"\\u03A9\",\n \"oint\":\"\\u222E\",\n \"olarr\":\"\\u21BA\",\n \"olcir\":\"\\u29BE\",\n \"olcross\":\"\\u29BB\",\n \"oline\":\"\\u203E\",\n \"olt\":\"\\u29C0\",\n \"Omacr\":\"\\u014C\",\n \"omacr\":\"\\u014D\",\n \"Omega\":\"\\u03A9\",\n \"omega\":\"\\u03C9\",\n \"Omicron\":\"\\u039F\",\n \"omicron\":\"\\u03BF\",\n \"omid\":\"\\u29B6\",\n \"ominus\":\"\\u2296\",\n \"Oopf\":\"\\uD835\\uDD46\",\n \"oopf\":\"\\uD835\\uDD60\",\n \"opar\":\"\\u29B7\",\n \"OpenCurlyDoubleQuote\":\"\\u201C\",\n \"OpenCurlyQuote\":\"\\u2018\",\n \"operp\":\"\\u29B9\",\n \"oplus\":\"\\u2295\",\n \"Or\":\"\\u2A54\",\n \"or\":\"\\u2228\",\n \"orarr\":\"\\u21BB\",\n \"ord\":\"\\u2A5D\",\n \"order\":\"\\u2134\",\n \"orderof\":\"\\u2134\",\n \"ordf\":\"\\u00AA\",\n \"ordm\":\"\\u00BA\",\n \"origof\":\"\\u22B6\",\n \"oror\":\"\\u2A56\",\n \"orslope\":\"\\u2A57\",\n \"orv\":\"\\u2A5B\",\n \"oS\":\"\\u24C8\",\n \"Oscr\":\"\\uD835\\uDCAA\",\n \"oscr\":\"\\u2134\",\n \"Oslash\":\"\\u00D8\",\n \"oslash\":\"\\u00F8\",\n \"osol\":\"\\u2298\",\n \"Otilde\":\"\\u00D5\",\n \"otilde\":\"\\u00F5\",\n \"Otimes\":\"\\u2A37\",\n \"otimes\":\"\\u2297\",\n \"otimesas\":\"\\u2A36\",\n \"Ouml\":\"\\u00D6\",\n \"ouml\":\"\\u00F6\",\n \"ovbar\":\"\\u233D\",\n \"OverBar\":\"\\u203E\",\n \"OverBrace\":\"\\u23DE\",\n \"OverBracket\":\"\\u23B4\",\n \"OverParenthesis\":\"\\u23DC\",\n \"par\":\"\\u2225\",\n \"para\":\"\\u00B6\",\n \"parallel\":\"\\u2225\",\n \"parsim\":\"\\u2AF3\",\n \"parsl\":\"\\u2AFD\",\n \"part\":\"\\u2202\",\n \"PartialD\":\"\\u2202\",\n \"Pcy\":\"\\u041F\",\n \"pcy\":\"\\u043F\",\n \"percnt\":\"\\u0025\",\n \"period\":\"\\u002E\",\n \"permil\":\"\\u2030\",\n \"perp\":\"\\u22A5\",\n \"pertenk\":\"\\u2031\",\n \"Pfr\":\"\\uD835\\uDD13\",\n \"pfr\":\"\\uD835\\uDD2D\",\n \"Phi\":\"\\u03A6\",\n \"phi\":\"\\u03C6\",\n \"phiv\":\"\\u03D5\",\n \"phmmat\":\"\\u2133\",\n \"phone\":\"\\u260E\",\n \"Pi\":\"\\u03A0\",\n \"pi\":\"\\u03C0\",\n \"pitchfork\":\"\\u22D4\",\n \"piv\":\"\\u03D6\",\n \"planck\":\"\\u210F\",\n \"planckh\":\"\\u210E\",\n \"plankv\":\"\\u210F\",\n \"plus\":\"\\u002B\",\n \"plusacir\":\"\\u2A23\",\n \"plusb\":\"\\u229E\",\n \"pluscir\":\"\\u2A22\",\n \"plusdo\":\"\\u2214\",\n \"plusdu\":\"\\u2A25\",\n \"pluse\":\"\\u2A72\",\n \"PlusMinus\":\"\\u00B1\",\n \"plusmn\":\"\\u00B1\",\n \"plussim\":\"\\u2A26\",\n \"plustwo\":\"\\u2A27\",\n \"pm\":\"\\u00B1\",\n \"Poincareplane\":\"\\u210C\",\n \"pointint\":\"\\u2A15\",\n \"Popf\":\"\\u2119\",\n \"popf\":\"\\uD835\\uDD61\",\n \"pound\":\"\\u00A3\",\n \"Pr\":\"\\u2ABB\",\n \"pr\":\"\\u227A\",\n \"prap\":\"\\u2AB7\",\n \"prcue\":\"\\u227C\",\n \"prE\":\"\\u2AB3\",\n \"pre\":\"\\u2AAF\",\n \"prec\":\"\\u227A\",\n \"precapprox\":\"\\u2AB7\",\n \"preccurlyeq\":\"\\u227C\",\n \"Precedes\":\"\\u227A\",\n \"PrecedesEqual\":\"\\u2AAF\",\n \"PrecedesSlantEqual\":\"\\u227C\",\n \"PrecedesTilde\":\"\\u227E\",\n \"preceq\":\"\\u2AAF\",\n \"precnapprox\":\"\\u2AB9\",\n \"precneqq\":\"\\u2AB5\",\n \"precnsim\":\"\\u22E8\",\n \"precsim\":\"\\u227E\",\n \"Prime\":\"\\u2033\",\n \"prime\":\"\\u2032\",\n \"primes\":\"\\u2119\",\n \"prnap\":\"\\u2AB9\",\n \"prnE\":\"\\u2AB5\",\n \"prnsim\":\"\\u22E8\",\n \"prod\":\"\\u220F\",\n \"Product\":\"\\u220F\",\n \"profalar\":\"\\u232E\",\n \"profline\":\"\\u2312\",\n \"profsurf\":\"\\u2313\",\n \"prop\":\"\\u221D\",\n \"Proportion\":\"\\u2237\",\n \"Proportional\":\"\\u221D\",\n \"propto\":\"\\u221D\",\n \"prsim\":\"\\u227E\",\n \"prurel\":\"\\u22B0\",\n \"Pscr\":\"\\uD835\\uDCAB\",\n \"pscr\":\"\\uD835\\uDCC5\",\n \"Psi\":\"\\u03A8\",\n \"psi\":\"\\u03C8\",\n \"puncsp\":\"\\u2008\",\n \"Qfr\":\"\\uD835\\uDD14\",\n \"qfr\":\"\\uD835\\uDD2E\",\n \"qint\":\"\\u2A0C\",\n \"Qopf\":\"\\u211A\",\n \"qopf\":\"\\uD835\\uDD62\",\n \"qprime\":\"\\u2057\",\n \"Qscr\":\"\\uD835\\uDCAC\",\n \"qscr\":\"\\uD835\\uDCC6\",\n \"quaternions\":\"\\u210D\",\n \"quatint\":\"\\u2A16\",\n \"quest\":\"\\u003F\",\n \"questeq\":\"\\u225F\",\n \"QUOT\":\"\\u0022\",\n \"quot\":\"\\u0022\",\n \"rAarr\":\"\\u21DB\",\n \"race\":\"\\u223D\\u0331\",\n \"Racute\":\"\\u0154\",\n \"racute\":\"\\u0155\",\n \"radic\":\"\\u221A\",\n \"raemptyv\":\"\\u29B3\",\n \"Rang\":\"\\u27EB\",\n \"rang\":\"\\u27E9\",\n \"rangd\":\"\\u2992\",\n \"range\":\"\\u29A5\",\n \"rangle\":\"\\u27E9\",\n \"raquo\":\"\\u00BB\",\n \"Rarr\":\"\\u21A0\",\n \"rArr\":\"\\u21D2\",\n \"rarr\":\"\\u2192\",\n \"rarrap\":\"\\u2975\",\n \"rarrb\":\"\\u21E5\",\n \"rarrbfs\":\"\\u2920\",\n \"rarrc\":\"\\u2933\",\n \"rarrfs\":\"\\u291E\",\n \"rarrhk\":\"\\u21AA\",\n \"rarrlp\":\"\\u21AC\",\n \"rarrpl\":\"\\u2945\",\n \"rarrsim\":\"\\u2974\",\n \"Rarrtl\":\"\\u2916\",\n \"rarrtl\":\"\\u21A3\",\n \"rarrw\":\"\\u219D\",\n \"rAtail\":\"\\u291C\",\n \"ratail\":\"\\u291A\",\n \"ratio\":\"\\u2236\",\n \"rationals\":\"\\u211A\",\n \"RBarr\":\"\\u2910\",\n \"rBarr\":\"\\u290F\",\n \"rbarr\":\"\\u290D\",\n \"rbbrk\":\"\\u2773\",\n \"rbrace\":\"\\u007D\",\n \"rbrack\":\"\\u005D\",\n \"rbrke\":\"\\u298C\",\n \"rbrksld\":\"\\u298E\",\n \"rbrkslu\":\"\\u2990\",\n \"Rcaron\":\"\\u0158\",\n \"rcaron\":\"\\u0159\",\n \"Rcedil\":\"\\u0156\",\n \"rcedil\":\"\\u0157\",\n \"rceil\":\"\\u2309\",\n \"rcub\":\"\\u007D\",\n \"Rcy\":\"\\u0420\",\n \"rcy\":\"\\u0440\",\n \"rdca\":\"\\u2937\",\n \"rdldhar\":\"\\u2969\",\n \"rdquo\":\"\\u201D\",\n \"rdquor\":\"\\u201D\",\n \"rdsh\":\"\\u21B3\",\n \"Re\":\"\\u211C\",\n \"real\":\"\\u211C\",\n \"realine\":\"\\u211B\",\n \"realpart\":\"\\u211C\",\n \"reals\":\"\\u211D\",\n \"rect\":\"\\u25AD\",\n \"REG\":\"\\u00AE\",\n \"reg\":\"\\u00AE\",\n \"ReverseElement\":\"\\u220B\",\n \"ReverseEquilibrium\":\"\\u21CB\",\n \"ReverseUpEquilibrium\":\"\\u296F\",\n \"rfisht\":\"\\u297D\",\n \"rfloor\":\"\\u230B\",\n \"Rfr\":\"\\u211C\",\n \"rfr\":\"\\uD835\\uDD2F\",\n \"rHar\":\"\\u2964\",\n \"rhard\":\"\\u21C1\",\n \"rharu\":\"\\u21C0\",\n \"rharul\":\"\\u296C\",\n \"Rho\":\"\\u03A1\",\n \"rho\":\"\\u03C1\",\n \"rhov\":\"\\u03F1\",\n \"RightAngleBracket\":\"\\u27E9\",\n \"RightArrow\":\"\\u2192\",\n \"Rightarrow\":\"\\u21D2\",\n \"rightarrow\":\"\\u2192\",\n \"RightArrowBar\":\"\\u21E5\",\n \"RightArrowLeftArrow\":\"\\u21C4\",\n \"rightarrowtail\":\"\\u21A3\",\n \"RightCeiling\":\"\\u2309\",\n \"RightDoubleBracket\":\"\\u27E7\",\n \"RightDownTeeVector\":\"\\u295D\",\n \"RightDownVector\":\"\\u21C2\",\n \"RightDownVectorBar\":\"\\u2955\",\n \"RightFloor\":\"\\u230B\",\n \"rightharpoondown\":\"\\u21C1\",\n \"rightharpoonup\":\"\\u21C0\",\n \"rightleftarrows\":\"\\u21C4\",\n \"rightleftharpoons\":\"\\u21CC\",\n \"rightrightarrows\":\"\\u21C9\",\n \"rightsquigarrow\":\"\\u219D\",\n \"RightTee\":\"\\u22A2\",\n \"RightTeeArrow\":\"\\u21A6\",\n \"RightTeeVector\":\"\\u295B\",\n \"rightthreetimes\":\"\\u22CC\",\n \"RightTriangle\":\"\\u22B3\",\n \"RightTriangleBar\":\"\\u29D0\",\n \"RightTriangleEqual\":\"\\u22B5\",\n \"RightUpDownVector\":\"\\u294F\",\n \"RightUpTeeVector\":\"\\u295C\",\n \"RightUpVector\":\"\\u21BE\",\n \"RightUpVectorBar\":\"\\u2954\",\n \"RightVector\":\"\\u21C0\",\n \"RightVectorBar\":\"\\u2953\",\n \"ring\":\"\\u02DA\",\n \"risingdotseq\":\"\\u2253\",\n \"rlarr\":\"\\u21C4\",\n \"rlhar\":\"\\u21CC\",\n \"rlm\":\"\\u200F\",\n \"rmoust\":\"\\u23B1\",\n \"rmoustache\":\"\\u23B1\",\n \"rnmid\":\"\\u2AEE\",\n \"roang\":\"\\u27ED\",\n \"roarr\":\"\\u21FE\",\n \"robrk\":\"\\u27E7\",\n \"ropar\":\"\\u2986\",\n \"Ropf\":\"\\u211D\",\n \"ropf\":\"\\uD835\\uDD63\",\n \"roplus\":\"\\u2A2E\",\n \"rotimes\":\"\\u2A35\",\n \"RoundImplies\":\"\\u2970\",\n \"rpar\":\"\\u0029\",\n \"rpargt\":\"\\u2994\",\n \"rppolint\":\"\\u2A12\",\n \"rrarr\":\"\\u21C9\",\n \"Rrightarrow\":\"\\u21DB\",\n \"rsaquo\":\"\\u203A\",\n \"Rscr\":\"\\u211B\",\n \"rscr\":\"\\uD835\\uDCC7\",\n \"Rsh\":\"\\u21B1\",\n \"rsh\":\"\\u21B1\",\n \"rsqb\":\"\\u005D\",\n \"rsquo\":\"\\u2019\",\n \"rsquor\":\"\\u2019\",\n \"rthree\":\"\\u22CC\",\n \"rtimes\":\"\\u22CA\",\n \"rtri\":\"\\u25B9\",\n \"rtrie\":\"\\u22B5\",\n \"rtrif\":\"\\u25B8\",\n \"rtriltri\":\"\\u29CE\",\n \"RuleDelayed\":\"\\u29F4\",\n \"ruluhar\":\"\\u2968\",\n \"rx\":\"\\u211E\",\n \"Sacute\":\"\\u015A\",\n \"sacute\":\"\\u015B\",\n \"sbquo\":\"\\u201A\",\n \"Sc\":\"\\u2ABC\",\n \"sc\":\"\\u227B\",\n \"scap\":\"\\u2AB8\",\n \"Scaron\":\"\\u0160\",\n \"scaron\":\"\\u0161\",\n \"sccue\":\"\\u227D\",\n \"scE\":\"\\u2AB4\",\n \"sce\":\"\\u2AB0\",\n \"Scedil\":\"\\u015E\",\n \"scedil\":\"\\u015F\",\n \"Scirc\":\"\\u015C\",\n \"scirc\":\"\\u015D\",\n \"scnap\":\"\\u2ABA\",\n \"scnE\":\"\\u2AB6\",\n \"scnsim\":\"\\u22E9\",\n \"scpolint\":\"\\u2A13\",\n \"scsim\":\"\\u227F\",\n \"Scy\":\"\\u0421\",\n \"scy\":\"\\u0441\",\n \"sdot\":\"\\u22C5\",\n \"sdotb\":\"\\u22A1\",\n \"sdote\":\"\\u2A66\",\n \"searhk\":\"\\u2925\",\n \"seArr\":\"\\u21D8\",\n \"searr\":\"\\u2198\",\n \"searrow\":\"\\u2198\",\n \"sect\":\"\\u00A7\",\n \"semi\":\"\\u003B\",\n \"seswar\":\"\\u2929\",\n \"setminus\":\"\\u2216\",\n \"setmn\":\"\\u2216\",\n \"sext\":\"\\u2736\",\n \"Sfr\":\"\\uD835\\uDD16\",\n \"sfr\":\"\\uD835\\uDD30\",\n \"sfrown\":\"\\u2322\",\n \"sharp\":\"\\u266F\",\n \"SHCHcy\":\"\\u0429\",\n \"shchcy\":\"\\u0449\",\n \"SHcy\":\"\\u0428\",\n \"shcy\":\"\\u0448\",\n \"ShortDownArrow\":\"\\u2193\",\n \"ShortLeftArrow\":\"\\u2190\",\n \"shortmid\":\"\\u2223\",\n \"shortparallel\":\"\\u2225\",\n \"ShortRightArrow\":\"\\u2192\",\n \"ShortUpArrow\":\"\\u2191\",\n \"shy\":\"\\u00AD\",\n \"Sigma\":\"\\u03A3\",\n \"sigma\":\"\\u03C3\",\n \"sigmaf\":\"\\u03C2\",\n \"sigmav\":\"\\u03C2\",\n \"sim\":\"\\u223C\",\n \"simdot\":\"\\u2A6A\",\n \"sime\":\"\\u2243\",\n \"simeq\":\"\\u2243\",\n \"simg\":\"\\u2A9E\",\n \"simgE\":\"\\u2AA0\",\n \"siml\":\"\\u2A9D\",\n \"simlE\":\"\\u2A9F\",\n \"simne\":\"\\u2246\",\n \"simplus\":\"\\u2A24\",\n \"simrarr\":\"\\u2972\",\n \"slarr\":\"\\u2190\",\n \"SmallCircle\":\"\\u2218\",\n \"smallsetminus\":\"\\u2216\",\n \"smashp\":\"\\u2A33\",\n \"smeparsl\":\"\\u29E4\",\n \"smid\":\"\\u2223\",\n \"smile\":\"\\u2323\",\n \"smt\":\"\\u2AAA\",\n \"smte\":\"\\u2AAC\",\n \"smtes\":\"\\u2AAC\\uFE00\",\n \"SOFTcy\":\"\\u042C\",\n \"softcy\":\"\\u044C\",\n \"sol\":\"\\u002F\",\n \"solb\":\"\\u29C4\",\n \"solbar\":\"\\u233F\",\n \"Sopf\":\"\\uD835\\uDD4A\",\n \"sopf\":\"\\uD835\\uDD64\",\n \"spades\":\"\\u2660\",\n \"spadesuit\":\"\\u2660\",\n \"spar\":\"\\u2225\",\n \"sqcap\":\"\\u2293\",\n \"sqcaps\":\"\\u2293\\uFE00\",\n \"sqcup\":\"\\u2294\",\n \"sqcups\":\"\\u2294\\uFE00\",\n \"Sqrt\":\"\\u221A\",\n \"sqsub\":\"\\u228F\",\n \"sqsube\":\"\\u2291\",\n \"sqsubset\":\"\\u228F\",\n \"sqsubseteq\":\"\\u2291\",\n \"sqsup\":\"\\u2290\",\n \"sqsupe\":\"\\u2292\",\n \"sqsupset\":\"\\u2290\",\n \"sqsupseteq\":\"\\u2292\",\n \"squ\":\"\\u25A1\",\n \"Square\":\"\\u25A1\",\n \"square\":\"\\u25A1\",\n \"SquareIntersection\":\"\\u2293\",\n \"SquareSubset\":\"\\u228F\",\n \"SquareSubsetEqual\":\"\\u2291\",\n \"SquareSuperset\":\"\\u2290\",\n \"SquareSupersetEqual\":\"\\u2292\",\n \"SquareUnion\":\"\\u2294\",\n \"squarf\":\"\\u25AA\",\n \"squf\":\"\\u25AA\",\n \"srarr\":\"\\u2192\",\n \"Sscr\":\"\\uD835\\uDCAE\",\n \"sscr\":\"\\uD835\\uDCC8\",\n \"ssetmn\":\"\\u2216\",\n \"ssmile\":\"\\u2323\",\n \"sstarf\":\"\\u22C6\",\n \"Star\":\"\\u22C6\",\n \"star\":\"\\u2606\",\n \"starf\":\"\\u2605\",\n \"straightepsilon\":\"\\u03F5\",\n \"straightphi\":\"\\u03D5\",\n \"strns\":\"\\u00AF\",\n \"Sub\":\"\\u22D0\",\n \"sub\":\"\\u2282\",\n \"subdot\":\"\\u2ABD\",\n \"subE\":\"\\u2AC5\",\n \"sube\":\"\\u2286\",\n \"subedot\":\"\\u2AC3\",\n \"submult\":\"\\u2AC1\",\n \"subnE\":\"\\u2ACB\",\n \"subne\":\"\\u228A\",\n \"subplus\":\"\\u2ABF\",\n \"subrarr\":\"\\u2979\",\n \"Subset\":\"\\u22D0\",\n \"subset\":\"\\u2282\",\n \"subseteq\":\"\\u2286\",\n \"subseteqq\":\"\\u2AC5\",\n \"SubsetEqual\":\"\\u2286\",\n \"subsetneq\":\"\\u228A\",\n \"subsetneqq\":\"\\u2ACB\",\n \"subsim\":\"\\u2AC7\",\n \"subsub\":\"\\u2AD5\",\n \"subsup\":\"\\u2AD3\",\n \"succ\":\"\\u227B\",\n \"succapprox\":\"\\u2AB8\",\n \"succcurlyeq\":\"\\u227D\",\n \"Succeeds\":\"\\u227B\",\n \"SucceedsEqual\":\"\\u2AB0\",\n \"SucceedsSlantEqual\":\"\\u227D\",\n \"SucceedsTilde\":\"\\u227F\",\n \"succeq\":\"\\u2AB0\",\n \"succnapprox\":\"\\u2ABA\",\n \"succneqq\":\"\\u2AB6\",\n \"succnsim\":\"\\u22E9\",\n \"succsim\":\"\\u227F\",\n \"SuchThat\":\"\\u220B\",\n \"Sum\":\"\\u2211\",\n \"sum\":\"\\u2211\",\n \"sung\":\"\\u266A\",\n \"Sup\":\"\\u22D1\",\n \"sup\":\"\\u2283\",\n \"sup1\":\"\\u00B9\",\n \"sup2\":\"\\u00B2\",\n \"sup3\":\"\\u00B3\",\n \"supdot\":\"\\u2ABE\",\n \"supdsub\":\"\\u2AD8\",\n \"supE\":\"\\u2AC6\",\n \"supe\":\"\\u2287\",\n \"supedot\":\"\\u2AC4\",\n \"Superset\":\"\\u2283\",\n \"SupersetEqual\":\"\\u2287\",\n \"suphsol\":\"\\u27C9\",\n \"suphsub\":\"\\u2AD7\",\n \"suplarr\":\"\\u297B\",\n \"supmult\":\"\\u2AC2\",\n \"supnE\":\"\\u2ACC\",\n \"supne\":\"\\u228B\",\n \"supplus\":\"\\u2AC0\",\n \"Supset\":\"\\u22D1\",\n \"supset\":\"\\u2283\",\n \"supseteq\":\"\\u2287\",\n \"supseteqq\":\"\\u2AC6\",\n \"supsetneq\":\"\\u228B\",\n \"supsetneqq\":\"\\u2ACC\",\n \"supsim\":\"\\u2AC8\",\n \"supsub\":\"\\u2AD4\",\n \"supsup\":\"\\u2AD6\",\n \"swarhk\":\"\\u2926\",\n \"swArr\":\"\\u21D9\",\n \"swarr\":\"\\u2199\",\n \"swarrow\":\"\\u2199\",\n \"swnwar\":\"\\u292A\",\n \"szlig\":\"\\u00DF\",\n \"Tab\":\"\\u0009\",\n \"target\":\"\\u2316\",\n \"Tau\":\"\\u03A4\",\n \"tau\":\"\\u03C4\",\n \"tbrk\":\"\\u23B4\",\n \"Tcaron\":\"\\u0164\",\n \"tcaron\":\"\\u0165\",\n \"Tcedil\":\"\\u0162\",\n \"tcedil\":\"\\u0163\",\n \"Tcy\":\"\\u0422\",\n \"tcy\":\"\\u0442\",\n \"tdot\":\"\\u20DB\",\n \"telrec\":\"\\u2315\",\n \"Tfr\":\"\\uD835\\uDD17\",\n \"tfr\":\"\\uD835\\uDD31\",\n \"there4\":\"\\u2234\",\n \"Therefore\":\"\\u2234\",\n \"therefore\":\"\\u2234\",\n \"Theta\":\"\\u0398\",\n \"theta\":\"\\u03B8\",\n \"thetasym\":\"\\u03D1\",\n \"thetav\":\"\\u03D1\",\n \"thickapprox\":\"\\u2248\",\n \"thicksim\":\"\\u223C\",\n \"ThickSpace\":\"\\u205F\\u200A\",\n \"thinsp\":\"\\u2009\",\n \"ThinSpace\":\"\\u2009\",\n \"thkap\":\"\\u2248\",\n \"thksim\":\"\\u223C\",\n \"THORN\":\"\\u00DE\",\n \"thorn\":\"\\u00FE\",\n \"Tilde\":\"\\u223C\",\n \"tilde\":\"\\u02DC\",\n \"TildeEqual\":\"\\u2243\",\n \"TildeFullEqual\":\"\\u2245\",\n \"TildeTilde\":\"\\u2248\",\n \"times\":\"\\u00D7\",\n \"timesb\":\"\\u22A0\",\n \"timesbar\":\"\\u2A31\",\n \"timesd\":\"\\u2A30\",\n \"tint\":\"\\u222D\",\n \"toea\":\"\\u2928\",\n \"top\":\"\\u22A4\",\n \"topbot\":\"\\u2336\",\n \"topcir\":\"\\u2AF1\",\n \"Topf\":\"\\uD835\\uDD4B\",\n \"topf\":\"\\uD835\\uDD65\",\n \"topfork\":\"\\u2ADA\",\n \"tosa\":\"\\u2929\",\n \"tprime\":\"\\u2034\",\n \"TRADE\":\"\\u2122\",\n \"trade\":\"\\u2122\",\n \"triangle\":\"\\u25B5\",\n \"triangledown\":\"\\u25BF\",\n \"triangleleft\":\"\\u25C3\",\n \"trianglelefteq\":\"\\u22B4\",\n \"triangleq\":\"\\u225C\",\n \"triangleright\":\"\\u25B9\",\n \"trianglerighteq\":\"\\u22B5\",\n \"tridot\":\"\\u25EC\",\n \"trie\":\"\\u225C\",\n \"triminus\":\"\\u2A3A\",\n \"TripleDot\":\"\\u20DB\",\n \"triplus\":\"\\u2A39\",\n \"trisb\":\"\\u29CD\",\n \"tritime\":\"\\u2A3B\",\n \"trpezium\":\"\\u23E2\",\n \"Tscr\":\"\\uD835\\uDCAF\",\n \"tscr\":\"\\uD835\\uDCC9\",\n \"TScy\":\"\\u0426\",\n \"tscy\":\"\\u0446\",\n \"TSHcy\":\"\\u040B\",\n \"tshcy\":\"\\u045B\",\n \"Tstrok\":\"\\u0166\",\n \"tstrok\":\"\\u0167\",\n \"twixt\":\"\\u226C\",\n \"twoheadleftarrow\":\"\\u219E\",\n \"twoheadrightarrow\":\"\\u21A0\",\n \"Uacute\":\"\\u00DA\",\n \"uacute\":\"\\u00FA\",\n \"Uarr\":\"\\u219F\",\n \"uArr\":\"\\u21D1\",\n \"uarr\":\"\\u2191\",\n \"Uarrocir\":\"\\u2949\",\n \"Ubrcy\":\"\\u040E\",\n \"ubrcy\":\"\\u045E\",\n \"Ubreve\":\"\\u016C\",\n \"ubreve\":\"\\u016D\",\n \"Ucirc\":\"\\u00DB\",\n \"ucirc\":\"\\u00FB\",\n \"Ucy\":\"\\u0423\",\n \"ucy\":\"\\u0443\",\n \"udarr\":\"\\u21C5\",\n \"Udblac\":\"\\u0170\",\n \"udblac\":\"\\u0171\",\n \"udhar\":\"\\u296E\",\n \"ufisht\":\"\\u297E\",\n \"Ufr\":\"\\uD835\\uDD18\",\n \"ufr\":\"\\uD835\\uDD32\",\n \"Ugrave\":\"\\u00D9\",\n \"ugrave\":\"\\u00F9\",\n \"uHar\":\"\\u2963\",\n \"uharl\":\"\\u21BF\",\n \"uharr\":\"\\u21BE\",\n \"uhblk\":\"\\u2580\",\n \"ulcorn\":\"\\u231C\",\n \"ulcorner\":\"\\u231C\",\n \"ulcrop\":\"\\u230F\",\n \"ultri\":\"\\u25F8\",\n \"Umacr\":\"\\u016A\",\n \"umacr\":\"\\u016B\",\n \"uml\":\"\\u00A8\",\n \"UnderBar\":\"\\u005F\",\n \"UnderBrace\":\"\\u23DF\",\n \"UnderBracket\":\"\\u23B5\",\n \"UnderParenthesis\":\"\\u23DD\",\n \"Union\":\"\\u22C3\",\n \"UnionPlus\":\"\\u228E\",\n \"Uogon\":\"\\u0172\",\n \"uogon\":\"\\u0173\",\n \"Uopf\":\"\\uD835\\uDD4C\",\n \"uopf\":\"\\uD835\\uDD66\",\n \"UpArrow\":\"\\u2191\",\n \"Uparrow\":\"\\u21D1\",\n \"uparrow\":\"\\u2191\",\n \"UpArrowBar\":\"\\u2912\",\n \"UpArrowDownArrow\":\"\\u21C5\",\n \"UpDownArrow\":\"\\u2195\",\n \"Updownarrow\":\"\\u21D5\",\n \"updownarrow\":\"\\u2195\",\n \"UpEquilibrium\":\"\\u296E\",\n \"upharpoonleft\":\"\\u21BF\",\n \"upharpoonright\":\"\\u21BE\",\n \"uplus\":\"\\u228E\",\n \"UpperLeftArrow\":\"\\u2196\",\n \"UpperRightArrow\":\"\\u2197\",\n \"Upsi\":\"\\u03D2\",\n \"upsi\":\"\\u03C5\",\n \"upsih\":\"\\u03D2\",\n \"Upsilon\":\"\\u03A5\",\n \"upsilon\":\"\\u03C5\",\n \"UpTee\":\"\\u22A5\",\n \"UpTeeArrow\":\"\\u21A5\",\n \"upuparrows\":\"\\u21C8\",\n \"urcorn\":\"\\u231D\",\n \"urcorner\":\"\\u231D\",\n \"urcrop\":\"\\u230E\",\n \"Uring\":\"\\u016E\",\n \"uring\":\"\\u016F\",\n \"urtri\":\"\\u25F9\",\n \"Uscr\":\"\\uD835\\uDCB0\",\n \"uscr\":\"\\uD835\\uDCCA\",\n \"utdot\":\"\\u22F0\",\n \"Utilde\":\"\\u0168\",\n \"utilde\":\"\\u0169\",\n \"utri\":\"\\u25B5\",\n \"utrif\":\"\\u25B4\",\n \"uuarr\":\"\\u21C8\",\n \"Uuml\":\"\\u00DC\",\n \"uuml\":\"\\u00FC\",\n \"uwangle\":\"\\u29A7\",\n \"vangrt\":\"\\u299C\",\n \"varepsilon\":\"\\u03F5\",\n \"varkappa\":\"\\u03F0\",\n \"varnothing\":\"\\u2205\",\n \"varphi\":\"\\u03D5\",\n \"varpi\":\"\\u03D6\",\n \"varpropto\":\"\\u221D\",\n \"vArr\":\"\\u21D5\",\n \"varr\":\"\\u2195\",\n \"varrho\":\"\\u03F1\",\n \"varsigma\":\"\\u03C2\",\n \"varsubsetneq\":\"\\u228A\\uFE00\",\n \"varsubsetneqq\":\"\\u2ACB\\uFE00\",\n \"varsupsetneq\":\"\\u228B\\uFE00\",\n \"varsupsetneqq\":\"\\u2ACC\\uFE00\",\n \"vartheta\":\"\\u03D1\",\n \"vartriangleleft\":\"\\u22B2\",\n \"vartriangleright\":\"\\u22B3\",\n \"Vbar\":\"\\u2AEB\",\n \"vBar\":\"\\u2AE8\",\n \"vBarv\":\"\\u2AE9\",\n \"Vcy\":\"\\u0412\",\n \"vcy\":\"\\u0432\",\n \"VDash\":\"\\u22AB\",\n \"Vdash\":\"\\u22A9\",\n \"vDash\":\"\\u22A8\",\n \"vdash\":\"\\u22A2\",\n \"Vdashl\":\"\\u2AE6\",\n \"Vee\":\"\\u22C1\",\n \"vee\":\"\\u2228\",\n \"veebar\":\"\\u22BB\",\n \"veeeq\":\"\\u225A\",\n \"vellip\":\"\\u22EE\",\n \"Verbar\":\"\\u2016\",\n \"verbar\":\"\\u007C\",\n \"Vert\":\"\\u2016\",\n \"vert\":\"\\u007C\",\n \"VerticalBar\":\"\\u2223\",\n \"VerticalLine\":\"\\u007C\",\n \"VerticalSeparator\":\"\\u2758\",\n \"VerticalTilde\":\"\\u2240\",\n \"VeryThinSpace\":\"\\u200A\",\n \"Vfr\":\"\\uD835\\uDD19\",\n \"vfr\":\"\\uD835\\uDD33\",\n \"vltri\":\"\\u22B2\",\n \"vnsub\":\"\\u2282\\u20D2\",\n \"vnsup\":\"\\u2283\\u20D2\",\n \"Vopf\":\"\\uD835\\uDD4D\",\n \"vopf\":\"\\uD835\\uDD67\",\n \"vprop\":\"\\u221D\",\n \"vrtri\":\"\\u22B3\",\n \"Vscr\":\"\\uD835\\uDCB1\",\n \"vscr\":\"\\uD835\\uDCCB\",\n \"vsubnE\":\"\\u2ACB\\uFE00\",\n \"vsubne\":\"\\u228A\\uFE00\",\n \"vsupnE\":\"\\u2ACC\\uFE00\",\n \"vsupne\":\"\\u228B\\uFE00\",\n \"Vvdash\":\"\\u22AA\",\n \"vzigzag\":\"\\u299A\",\n \"Wcirc\":\"\\u0174\",\n \"wcirc\":\"\\u0175\",\n \"wedbar\":\"\\u2A5F\",\n \"Wedge\":\"\\u22C0\",\n \"wedge\":\"\\u2227\",\n \"wedgeq\":\"\\u2259\",\n \"weierp\":\"\\u2118\",\n \"Wfr\":\"\\uD835\\uDD1A\",\n \"wfr\":\"\\uD835\\uDD34\",\n \"Wopf\":\"\\uD835\\uDD4E\",\n \"wopf\":\"\\uD835\\uDD68\",\n \"wp\":\"\\u2118\",\n \"wr\":\"\\u2240\",\n \"wreath\":\"\\u2240\",\n \"Wscr\":\"\\uD835\\uDCB2\",\n \"wscr\":\"\\uD835\\uDCCC\",\n \"xcap\":\"\\u22C2\",\n \"xcirc\":\"\\u25EF\",\n \"xcup\":\"\\u22C3\",\n \"xdtri\":\"\\u25BD\",\n \"Xfr\":\"\\uD835\\uDD1B\",\n \"xfr\":\"\\uD835\\uDD35\",\n \"xhArr\":\"\\u27FA\",\n \"xharr\":\"\\u27F7\",\n \"Xi\":\"\\u039E\",\n \"xi\":\"\\u03BE\",\n \"xlArr\":\"\\u27F8\",\n \"xlarr\":\"\\u27F5\",\n \"xmap\":\"\\u27FC\",\n \"xnis\":\"\\u22FB\",\n \"xodot\":\"\\u2A00\",\n \"Xopf\":\"\\uD835\\uDD4F\",\n \"xopf\":\"\\uD835\\uDD69\",\n \"xoplus\":\"\\u2A01\",\n \"xotime\":\"\\u2A02\",\n \"xrArr\":\"\\u27F9\",\n \"xrarr\":\"\\u27F6\",\n \"Xscr\":\"\\uD835\\uDCB3\",\n \"xscr\":\"\\uD835\\uDCCD\",\n \"xsqcup\":\"\\u2A06\",\n \"xuplus\":\"\\u2A04\",\n \"xutri\":\"\\u25B3\",\n \"xvee\":\"\\u22C1\",\n \"xwedge\":\"\\u22C0\",\n \"Yacute\":\"\\u00DD\",\n \"yacute\":\"\\u00FD\",\n \"YAcy\":\"\\u042F\",\n \"yacy\":\"\\u044F\",\n \"Ycirc\":\"\\u0176\",\n \"ycirc\":\"\\u0177\",\n \"Ycy\":\"\\u042B\",\n \"ycy\":\"\\u044B\",\n \"yen\":\"\\u00A5\",\n \"Yfr\":\"\\uD835\\uDD1C\",\n \"yfr\":\"\\uD835\\uDD36\",\n \"YIcy\":\"\\u0407\",\n \"yicy\":\"\\u0457\",\n \"Yopf\":\"\\uD835\\uDD50\",\n \"yopf\":\"\\uD835\\uDD6A\",\n \"Yscr\":\"\\uD835\\uDCB4\",\n \"yscr\":\"\\uD835\\uDCCE\",\n \"YUcy\":\"\\u042E\",\n \"yucy\":\"\\u044E\",\n \"Yuml\":\"\\u0178\",\n \"yuml\":\"\\u00FF\",\n \"Zacute\":\"\\u0179\",\n \"zacute\":\"\\u017A\",\n \"Zcaron\":\"\\u017D\",\n \"zcaron\":\"\\u017E\",\n \"Zcy\":\"\\u0417\",\n \"zcy\":\"\\u0437\",\n \"Zdot\":\"\\u017B\",\n \"zdot\":\"\\u017C\",\n \"zeetrf\":\"\\u2128\",\n \"ZeroWidthSpace\":\"\\u200B\",\n \"Zeta\":\"\\u0396\",\n \"zeta\":\"\\u03B6\",\n \"Zfr\":\"\\u2128\",\n \"zfr\":\"\\uD835\\uDD37\",\n \"ZHcy\":\"\\u0416\",\n \"zhcy\":\"\\u0436\",\n \"zigrarr\":\"\\u21DD\",\n \"Zopf\":\"\\u2124\",\n \"zopf\":\"\\uD835\\uDD6B\",\n \"Zscr\":\"\\uD835\\uDCB5\",\n \"zscr\":\"\\uD835\\uDCCF\",\n \"zwj\":\"\\u200D\",\n \"zwnj\":\"\\u200C\"\n};\n\nvar hasOwn = Object.prototype.hasOwnProperty;\n\nfunction has(object, key) {\n return object\n ? hasOwn.call(object, key)\n : false;\n}\n\nfunction decodeEntity(name) {\n if (has(entities, name)) {\n return entities[name]\n } else {\n return name;\n }\n}\n\n/**\n * Utility functions\n */\n\nfunction typeOf(obj) {\n return Object.prototype.toString.call(obj);\n}\n\nfunction isString(obj) {\n return typeOf(obj) === '[object String]';\n}\n\nvar hasOwn$1 = Object.prototype.hasOwnProperty;\n\nfunction has$1(object, key) {\n return object\n ? hasOwn$1.call(object, key)\n : false;\n}\n\n// Extend objects\n//\nfunction assign(obj /*from1, from2, from3, ...*/) {\n var sources = [].slice.call(arguments, 1);\n\n sources.forEach(function (source) {\n if (!source) { return; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be object');\n }\n\n Object.keys(source).forEach(function (key) {\n obj[key] = source[key];\n });\n });\n\n return obj;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nvar UNESCAPE_MD_RE = /\\\\([\\\\!\"#$%&'()*+,.\\/:;<=>?@[\\]^_`{|}~-])/g;\n\nfunction unescapeMd(str) {\n if (str.indexOf('\\\\') < 0) { return str; }\n return str.replace(UNESCAPE_MD_RE, '$1');\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nfunction isValidEntityCode(c) {\n /*eslint no-bitwise:0*/\n // broken sequence\n if (c >= 0xD800 && c <= 0xDFFF) { return false; }\n // never used\n if (c >= 0xFDD0 && c <= 0xFDEF) { return false; }\n if ((c & 0xFFFF) === 0xFFFF || (c & 0xFFFF) === 0xFFFE) { return false; }\n // control codes\n if (c >= 0x00 && c <= 0x08) { return false; }\n if (c === 0x0B) { return false; }\n if (c >= 0x0E && c <= 0x1F) { return false; }\n if (c >= 0x7F && c <= 0x9F) { return false; }\n // out of range\n if (c > 0x10FFFF) { return false; }\n return true;\n}\n\nfunction fromCodePoint(c) {\n /*eslint no-bitwise:0*/\n if (c > 0xffff) {\n c -= 0x10000;\n var surrogate1 = 0xd800 + (c >> 10),\n surrogate2 = 0xdc00 + (c & 0x3ff);\n\n return String.fromCharCode(surrogate1, surrogate2);\n }\n return String.fromCharCode(c);\n}\n\nvar NAMED_ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi;\nvar DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;\n\nfunction replaceEntityPattern(match, name) {\n var code = 0;\n var decoded = decodeEntity(name);\n\n if (name !== decoded) {\n return decoded;\n } else if (name.charCodeAt(0) === 0x23/* # */ && DIGITAL_ENTITY_TEST_RE.test(name)) {\n code = name[1].toLowerCase() === 'x' ?\n parseInt(name.slice(2), 16)\n :\n parseInt(name.slice(1), 10);\n if (isValidEntityCode(code)) {\n return fromCodePoint(code);\n }\n }\n return match;\n}\n\nfunction replaceEntities(str) {\n if (str.indexOf('&') < 0) { return str; }\n\n return str.replace(NAMED_ENTITY_RE, replaceEntityPattern);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nvar HTML_ESCAPE_TEST_RE = /[&<>\"]/;\nvar HTML_ESCAPE_REPLACE_RE = /[&<>\"]/g;\nvar HTML_REPLACEMENTS = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"'\n};\n\nfunction replaceUnsafeChar(ch) {\n return HTML_REPLACEMENTS[ch];\n}\n\nfunction escapeHtml(str) {\n if (HTML_ESCAPE_TEST_RE.test(str)) {\n return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar);\n }\n return str;\n}\n\nvar utils = /*#__PURE__*/Object.freeze({\n isString: isString,\n has: has$1,\n assign: assign,\n unescapeMd: unescapeMd,\n isValidEntityCode: isValidEntityCode,\n fromCodePoint: fromCodePoint,\n replaceEntities: replaceEntities,\n escapeHtml: escapeHtml\n});\n\n/**\n * Renderer rules cache\n */\n\nvar rules = {};\n\n/**\n * Blockquotes\n */\n\nrules.blockquote_open = function(/* tokens, idx, options, env */) {\n return '
\\n';\n};\n\nrules.blockquote_close = function(tokens, idx /*, options, env */) {\n return '
' + getBreak(tokens, idx);\n};\n\n/**\n * Code\n */\n\nrules.code = function(tokens, idx /*, options, env */) {\n if (tokens[idx].block) {\n return '
' + escapeHtml(tokens[idx].content) + '
' + getBreak(tokens, idx);\n }\n return '' + escapeHtml(tokens[idx].content) + '';\n};\n\n/**\n * Fenced code blocks\n */\n\nrules.fence = function(tokens, idx, options, env, instance) {\n var token = tokens[idx];\n var langClass = '';\n var langPrefix = options.langPrefix;\n var langName = '', fences, fenceName;\n var highlighted;\n\n if (token.params) {\n\n //\n // ```foo bar\n //\n // Try custom renderer \"foo\" first. That will simplify overwrite\n // for diagrams, latex, and any other fenced block with custom look\n //\n\n fences = token.params.split(/\\s+/g);\n fenceName = fences.join(' ');\n\n if (has$1(instance.rules.fence_custom, fences[0])) {\n return instance.rules.fence_custom[fences[0]](tokens, idx, options, env, instance);\n }\n\n langName = escapeHtml(replaceEntities(unescapeMd(fenceName)));\n langClass = ' class=\"' + langPrefix + langName + '\"';\n }\n\n if (options.highlight) {\n highlighted = options.highlight.apply(options.highlight, [ token.content ].concat(fences))\n || escapeHtml(token.content);\n } else {\n highlighted = escapeHtml(token.content);\n }\n\n return '
'\n        + highlighted\n        + '
'\n + getBreak(tokens, idx);\n};\n\nrules.fence_custom = {};\n\n/**\n * Headings\n */\n\nrules.heading_open = function(tokens, idx /*, options, env */) {\n return '';\n};\nrules.heading_close = function(tokens, idx /*, options, env */) {\n return '\\n';\n};\n\n/**\n * Horizontal rules\n */\n\nrules.hr = function(tokens, idx, options /*, env */) {\n return (options.xhtmlOut ? '
' : '
') + getBreak(tokens, idx);\n};\n\n/**\n * Bullets\n */\n\nrules.bullet_list_open = function(/* tokens, idx, options, env */) {\n return '' + getBreak(tokens, idx);\n};\n\n/**\n * List items\n */\n\nrules.list_item_open = function(/* tokens, idx, options, env */) {\n return '
  • ';\n};\nrules.list_item_close = function(/* tokens, idx, options, env */) {\n return '
  • \\n';\n};\n\n/**\n * Ordered list items\n */\n\nrules.ordered_list_open = function(tokens, idx /*, options, env */) {\n var token = tokens[idx];\n var order = token.order > 1 ? ' start=\"' + token.order + '\"' : '';\n return '\\n';\n};\nrules.ordered_list_close = function(tokens, idx /*, options, env */) {\n return '' + getBreak(tokens, idx);\n};\n\n/**\n * Paragraphs\n */\n\nrules.paragraph_open = function(tokens, idx /*, options, env */) {\n return tokens[idx].tight ? '' : '

    ';\n};\nrules.paragraph_close = function(tokens, idx /*, options, env */) {\n var addBreak = !(tokens[idx].tight && idx && tokens[idx - 1].type === 'inline' && !tokens[idx - 1].content);\n return (tokens[idx].tight ? '' : '

    ') + (addBreak ? getBreak(tokens, idx) : '');\n};\n\n/**\n * Links\n */\n\nrules.link_open = function(tokens, idx, options /* env */) {\n var title = tokens[idx].title ? (' title=\"' + escapeHtml(replaceEntities(tokens[idx].title)) + '\"') : '';\n var target = options.linkTarget ? (' target=\"' + options.linkTarget + '\"') : '';\n return '';\n};\nrules.link_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Images\n */\n\nrules.image = function(tokens, idx, options /*, env */) {\n var src = ' src=\"' + escapeHtml(tokens[idx].src) + '\"';\n var title = tokens[idx].title ? (' title=\"' + escapeHtml(replaceEntities(tokens[idx].title)) + '\"') : '';\n var alt = ' alt=\"' + (tokens[idx].alt ? escapeHtml(replaceEntities(unescapeMd(tokens[idx].alt))) : '') + '\"';\n var suffix = options.xhtmlOut ? ' /' : '';\n return '';\n};\n\n/**\n * Tables\n */\n\nrules.table_open = function(/* tokens, idx, options, env */) {\n return '\\n';\n};\nrules.table_close = function(/* tokens, idx, options, env */) {\n return '
    \\n';\n};\nrules.thead_open = function(/* tokens, idx, options, env */) {\n return '\\n';\n};\nrules.thead_close = function(/* tokens, idx, options, env */) {\n return '\\n';\n};\nrules.tbody_open = function(/* tokens, idx, options, env */) {\n return '\\n';\n};\nrules.tbody_close = function(/* tokens, idx, options, env */) {\n return '\\n';\n};\nrules.tr_open = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.tr_close = function(/* tokens, idx, options, env */) {\n return '\\n';\n};\nrules.th_open = function(tokens, idx /*, options, env */) {\n var token = tokens[idx];\n return '';\n};\nrules.th_close = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.td_open = function(tokens, idx /*, options, env */) {\n var token = tokens[idx];\n return '';\n};\nrules.td_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Bold\n */\n\nrules.strong_open = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.strong_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Italicize\n */\n\nrules.em_open = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.em_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Strikethrough\n */\n\nrules.del_open = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.del_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Insert\n */\n\nrules.ins_open = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.ins_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Highlight\n */\n\nrules.mark_open = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.mark_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Super- and sub-script\n */\n\nrules.sub = function(tokens, idx /*, options, env */) {\n return '' + escapeHtml(tokens[idx].content) + '';\n};\nrules.sup = function(tokens, idx /*, options, env */) {\n return '' + escapeHtml(tokens[idx].content) + '';\n};\n\n/**\n * Breaks\n */\n\nrules.hardbreak = function(tokens, idx, options /*, env */) {\n return options.xhtmlOut ? '
    \\n' : '
    \\n';\n};\nrules.softbreak = function(tokens, idx, options /*, env */) {\n return options.breaks ? (options.xhtmlOut ? '
    \\n' : '
    \\n') : '\\n';\n};\n\n/**\n * Text\n */\n\nrules.text = function(tokens, idx /*, options, env */) {\n return escapeHtml(tokens[idx].content);\n};\n\n/**\n * Content\n */\n\nrules.htmlblock = function(tokens, idx /*, options, env */) {\n return tokens[idx].content;\n};\nrules.htmltag = function(tokens, idx /*, options, env */) {\n return tokens[idx].content;\n};\n\n/**\n * Abbreviations, initialism\n */\n\nrules.abbr_open = function(tokens, idx /*, options, env */) {\n return '';\n};\nrules.abbr_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Footnotes\n */\n\nrules.footnote_ref = function(tokens, idx) {\n var n = Number(tokens[idx].id + 1).toString();\n var id = 'fnref' + n;\n if (tokens[idx].subId > 0) {\n id += ':' + tokens[idx].subId;\n }\n return '[' + n + ']';\n};\nrules.footnote_block_open = function(tokens, idx, options) {\n var hr = options.xhtmlOut\n ? '
    \\n'\n : '
    \\n';\n return hr + '
    \\n
      \\n';\n};\nrules.footnote_block_close = function() {\n return '
    \\n
    \\n';\n};\nrules.footnote_open = function(tokens, idx) {\n var id = Number(tokens[idx].id + 1).toString();\n return '
  • ';\n};\nrules.footnote_close = function() {\n return '
  • \\n';\n};\nrules.footnote_anchor = function(tokens, idx) {\n var n = Number(tokens[idx].id + 1).toString();\n var id = 'fnref' + n;\n if (tokens[idx].subId > 0) {\n id += ':' + tokens[idx].subId;\n }\n return ' ';\n};\n\n/**\n * Definition lists\n */\n\nrules.dl_open = function() {\n return '
    \\n';\n};\nrules.dt_open = function() {\n return '
    ';\n};\nrules.dd_open = function() {\n return '
    ';\n};\nrules.dl_close = function() {\n return '
    \\n';\n};\nrules.dt_close = function() {\n return '\\n';\n};\nrules.dd_close = function() {\n return '\\n';\n};\n\n/**\n * Helper functions\n */\n\nfunction nextToken(tokens, idx) {\n if (++idx >= tokens.length - 2) {\n return idx;\n }\n if ((tokens[idx].type === 'paragraph_open' && tokens[idx].tight) &&\n (tokens[idx + 1].type === 'inline' && tokens[idx + 1].content.length === 0) &&\n (tokens[idx + 2].type === 'paragraph_close' && tokens[idx + 2].tight)) {\n return nextToken(tokens, idx + 2);\n }\n return idx;\n}\n\n/**\n * Check to see if `\\n` is needed before the next token.\n *\n * @param {Array} `tokens`\n * @param {Number} `idx`\n * @return {String} Empty string or newline\n * @api private\n */\n\nvar getBreak = rules.getBreak = function getBreak(tokens, idx) {\n idx = nextToken(tokens, idx);\n if (idx < tokens.length && tokens[idx].type === 'list_item_close') {\n return '';\n }\n return '\\n';\n};\n\n/**\n * Renderer class. Renders HTML and exposes `rules` to allow\n * local modifications.\n */\n\nfunction Renderer() {\n this.rules = assign({}, rules);\n\n // exported helper, for custom rules only\n this.getBreak = rules.getBreak;\n}\n\n/**\n * Render a string of inline HTML with the given `tokens` and\n * `options`.\n *\n * @param {Array} `tokens`\n * @param {Object} `options`\n * @param {Object} `env`\n * @return {String}\n * @api public\n */\n\nRenderer.prototype.renderInline = function (tokens, options, env) {\n var _rules = this.rules;\n var len = tokens.length, i = 0;\n var result = '';\n\n while (len--) {\n result += _rules[tokens[i].type](tokens, i++, options, env, this);\n }\n\n return result;\n};\n\n/**\n * Render a string of HTML with the given `tokens` and\n * `options`.\n *\n * @param {Array} `tokens`\n * @param {Object} `options`\n * @param {Object} `env`\n * @return {String}\n * @api public\n */\n\nRenderer.prototype.render = function (tokens, options, env) {\n var _rules = this.rules;\n var len = tokens.length, i = -1;\n var result = '';\n\n while (++i < len) {\n if (tokens[i].type === 'inline') {\n result += this.renderInline(tokens[i].children, options, env);\n } else {\n result += _rules[tokens[i].type](tokens, i, options, env, this);\n }\n }\n return result;\n};\n\n/**\n * Ruler is a helper class for building responsibility chains from\n * parse rules. It allows:\n *\n * - easy stack rules chains\n * - getting main chain and named chains content (as arrays of functions)\n *\n * Helper methods, should not be used directly.\n * @api private\n */\n\nfunction Ruler() {\n // List of added rules. Each element is:\n //\n // { name: XXX,\n // enabled: Boolean,\n // fn: Function(),\n // alt: [ name2, name3 ] }\n //\n this.__rules__ = [];\n\n // Cached rule chains.\n //\n // First level - chain name, '' for default.\n // Second level - digital anchor for fast filtering by charcodes.\n //\n this.__cache__ = null;\n}\n\n/**\n * Find the index of a rule by `name`.\n *\n * @param {String} `name`\n * @return {Number} Index of the given `name`\n * @api private\n */\n\nRuler.prototype.__find__ = function (name) {\n var len = this.__rules__.length;\n var i = -1;\n\n while (len--) {\n if (this.__rules__[++i].name === name) {\n return i;\n }\n }\n return -1;\n};\n\n/**\n * Build the rules lookup cache\n *\n * @api private\n */\n\nRuler.prototype.__compile__ = function () {\n var self = this;\n var chains = [ '' ];\n\n // collect unique names\n self.__rules__.forEach(function (rule) {\n if (!rule.enabled) {\n return;\n }\n\n rule.alt.forEach(function (altName) {\n if (chains.indexOf(altName) < 0) {\n chains.push(altName);\n }\n });\n });\n\n self.__cache__ = {};\n\n chains.forEach(function (chain) {\n self.__cache__[chain] = [];\n self.__rules__.forEach(function (rule) {\n if (!rule.enabled) {\n return;\n }\n\n if (chain && rule.alt.indexOf(chain) < 0) {\n return;\n }\n self.__cache__[chain].push(rule.fn);\n });\n });\n};\n\n/**\n * Ruler public methods\n * ------------------------------------------------\n */\n\n/**\n * Replace rule function\n *\n * @param {String} `name` Rule name\n * @param {Function `fn`\n * @param {Object} `options`\n * @api private\n */\n\nRuler.prototype.at = function (name, fn, options) {\n var idx = this.__find__(name);\n var opt = options || {};\n\n if (idx === -1) {\n throw new Error('Parser rule not found: ' + name);\n }\n\n this.__rules__[idx].fn = fn;\n this.__rules__[idx].alt = opt.alt || [];\n this.__cache__ = null;\n};\n\n/**\n * Add a rule to the chain before given the `ruleName`.\n *\n * @param {String} `beforeName`\n * @param {String} `ruleName`\n * @param {Function} `fn`\n * @param {Object} `options`\n * @api private\n */\n\nRuler.prototype.before = function (beforeName, ruleName, fn, options) {\n var idx = this.__find__(beforeName);\n var opt = options || {};\n\n if (idx === -1) {\n throw new Error('Parser rule not found: ' + beforeName);\n }\n\n this.__rules__.splice(idx, 0, {\n name: ruleName,\n enabled: true,\n fn: fn,\n alt: opt.alt || []\n });\n\n this.__cache__ = null;\n};\n\n/**\n * Add a rule to the chain after the given `ruleName`.\n *\n * @param {String} `afterName`\n * @param {String} `ruleName`\n * @param {Function} `fn`\n * @param {Object} `options`\n * @api private\n */\n\nRuler.prototype.after = function (afterName, ruleName, fn, options) {\n var idx = this.__find__(afterName);\n var opt = options || {};\n\n if (idx === -1) {\n throw new Error('Parser rule not found: ' + afterName);\n }\n\n this.__rules__.splice(idx + 1, 0, {\n name: ruleName,\n enabled: true,\n fn: fn,\n alt: opt.alt || []\n });\n\n this.__cache__ = null;\n};\n\n/**\n * Add a rule to the end of chain.\n *\n * @param {String} `ruleName`\n * @param {Function} `fn`\n * @param {Object} `options`\n * @return {String}\n */\n\nRuler.prototype.push = function (ruleName, fn, options) {\n var opt = options || {};\n\n this.__rules__.push({\n name: ruleName,\n enabled: true,\n fn: fn,\n alt: opt.alt || []\n });\n\n this.__cache__ = null;\n};\n\n/**\n * Enable a rule or list of rules.\n *\n * @param {String|Array} `list` Name or array of rule names to enable\n * @param {Boolean} `strict` If `true`, all non listed rules will be disabled.\n * @api private\n */\n\nRuler.prototype.enable = function (list, strict) {\n list = !Array.isArray(list)\n ? [ list ]\n : list;\n\n // In strict mode disable all existing rules first\n if (strict) {\n this.__rules__.forEach(function (rule) {\n rule.enabled = false;\n });\n }\n\n // Search by name and enable\n list.forEach(function (name) {\n var idx = this.__find__(name);\n if (idx < 0) {\n throw new Error('Rules manager: invalid rule name ' + name);\n }\n this.__rules__[idx].enabled = true;\n }, this);\n\n this.__cache__ = null;\n};\n\n\n/**\n * Disable a rule or list of rules.\n *\n * @param {String|Array} `list` Name or array of rule names to disable\n * @api private\n */\n\nRuler.prototype.disable = function (list) {\n list = !Array.isArray(list)\n ? [ list ]\n : list;\n\n // Search by name and disable\n list.forEach(function (name) {\n var idx = this.__find__(name);\n if (idx < 0) {\n throw new Error('Rules manager: invalid rule name ' + name);\n }\n this.__rules__[idx].enabled = false;\n }, this);\n\n this.__cache__ = null;\n};\n\n/**\n * Get a rules list as an array of functions.\n *\n * @param {String} `chainName`\n * @return {Object}\n * @api private\n */\n\nRuler.prototype.getRules = function (chainName) {\n if (this.__cache__ === null) {\n this.__compile__();\n }\n return this.__cache__[chainName] || [];\n};\n\nfunction block(state) {\n\n if (state.inlineMode) {\n state.tokens.push({\n type: 'inline',\n content: state.src.replace(/\\n/g, ' ').trim(),\n level: 0,\n lines: [ 0, 1 ],\n children: []\n });\n\n } else {\n state.block.parse(state.src, state.options, state.env, state.tokens);\n }\n}\n\n// Inline parser state\n\nfunction StateInline(src, parserInline, options, env, outTokens) {\n this.src = src;\n this.env = env;\n this.options = options;\n this.parser = parserInline;\n this.tokens = outTokens;\n this.pos = 0;\n this.posMax = this.src.length;\n this.level = 0;\n this.pending = '';\n this.pendingLevel = 0;\n\n this.cache = []; // Stores { start: end } pairs. Useful for backtrack\n // optimization of pairs parse (emphasis, strikes).\n\n // Link parser state vars\n\n this.isInLabel = false; // Set true when seek link label - we should disable\n // \"paired\" rules (emphasis, strikes) to not skip\n // tailing `]`\n\n this.linkLevel = 0; // Increment for each nesting link. Used to prevent\n // nesting in definitions\n\n this.linkContent = ''; // Temporary storage for link url\n\n this.labelUnmatchedScopes = 0; // Track unpaired `[` for link labels\n // (backtrack optimization)\n}\n\n// Flush pending text\n//\nStateInline.prototype.pushPending = function () {\n this.tokens.push({\n type: 'text',\n content: this.pending,\n level: this.pendingLevel\n });\n this.pending = '';\n};\n\n// Push new token to \"stream\".\n// If pending text exists - flush it as text token\n//\nStateInline.prototype.push = function (token) {\n if (this.pending) {\n this.pushPending();\n }\n\n this.tokens.push(token);\n this.pendingLevel = this.level;\n};\n\n// Store value to cache.\n// !!! Implementation has parser-specific optimizations\n// !!! keys MUST be integer, >= 0; values MUST be integer, > 0\n//\nStateInline.prototype.cacheSet = function (key, val) {\n for (var i = this.cache.length; i <= key; i++) {\n this.cache.push(0);\n }\n\n this.cache[key] = val;\n};\n\n// Get cache value\n//\nStateInline.prototype.cacheGet = function (key) {\n return key < this.cache.length ? this.cache[key] : 0;\n};\n\n/**\n * Parse link labels\n *\n * This function assumes that first character (`[`) already matches;\n * returns the end of the label.\n *\n * @param {Object} state\n * @param {Number} start\n * @api private\n */\n\nfunction parseLinkLabel(state, start) {\n var level, found, marker,\n labelEnd = -1,\n max = state.posMax,\n oldPos = state.pos,\n oldFlag = state.isInLabel;\n\n if (state.isInLabel) { return -1; }\n\n if (state.labelUnmatchedScopes) {\n state.labelUnmatchedScopes--;\n return -1;\n }\n\n state.pos = start + 1;\n state.isInLabel = true;\n level = 1;\n\n while (state.pos < max) {\n marker = state.src.charCodeAt(state.pos);\n if (marker === 0x5B /* [ */) {\n level++;\n } else if (marker === 0x5D /* ] */) {\n level--;\n if (level === 0) {\n found = true;\n break;\n }\n }\n\n state.parser.skipToken(state);\n }\n\n if (found) {\n labelEnd = state.pos;\n state.labelUnmatchedScopes = 0;\n } else {\n state.labelUnmatchedScopes = level - 1;\n }\n\n // restore old state\n state.pos = oldPos;\n state.isInLabel = oldFlag;\n\n return labelEnd;\n}\n\n// Parse abbreviation definitions, i.e. `*[abbr]: description`\n\n\nfunction parseAbbr(str, parserInline, options, env) {\n var state, labelEnd, pos, max, label, title;\n\n if (str.charCodeAt(0) !== 0x2A/* * */) { return -1; }\n if (str.charCodeAt(1) !== 0x5B/* [ */) { return -1; }\n\n if (str.indexOf(']:') === -1) { return -1; }\n\n state = new StateInline(str, parserInline, options, env, []);\n labelEnd = parseLinkLabel(state, 1);\n\n if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 0x3A/* : */) { return -1; }\n\n max = state.posMax;\n\n // abbr title is always one line, so looking for ending \"\\n\" here\n for (pos = labelEnd + 2; pos < max; pos++) {\n if (state.src.charCodeAt(pos) === 0x0A) { break; }\n }\n\n label = str.slice(2, labelEnd);\n title = str.slice(labelEnd + 2, pos).trim();\n if (title.length === 0) { return -1; }\n if (!env.abbreviations) { env.abbreviations = {}; }\n // prepend ':' to avoid conflict with Object.prototype members\n if (typeof env.abbreviations[':' + label] === 'undefined') {\n env.abbreviations[':' + label] = title;\n }\n\n return pos;\n}\n\nfunction abbr(state) {\n var tokens = state.tokens, i, l, content, pos;\n\n if (state.inlineMode) {\n return;\n }\n\n // Parse inlines\n for (i = 1, l = tokens.length - 1; i < l; i++) {\n if (tokens[i - 1].type === 'paragraph_open' &&\n tokens[i].type === 'inline' &&\n tokens[i + 1].type === 'paragraph_close') {\n\n content = tokens[i].content;\n while (content.length) {\n pos = parseAbbr(content, state.inline, state.options, state.env);\n if (pos < 0) { break; }\n content = content.slice(pos).trim();\n }\n\n tokens[i].content = content;\n if (!content.length) {\n tokens[i - 1].tight = true;\n tokens[i + 1].tight = true;\n }\n }\n }\n}\n\nfunction normalizeLink(url) {\n var normalized = replaceEntities(url);\n // We shouldn't care about the result of malformed URIs,\n // and should not throw an exception.\n try {\n normalized = decodeURI(normalized);\n } catch (err) {}\n return encodeURI(normalized);\n}\n\n/**\n * Parse link destination\n *\n * - on success it returns a string and updates state.pos;\n * - on failure it returns null\n *\n * @param {Object} state\n * @param {Number} pos\n * @api private\n */\n\nfunction parseLinkDestination(state, pos) {\n var code, level, link,\n start = pos,\n max = state.posMax;\n\n if (state.src.charCodeAt(pos) === 0x3C /* < */) {\n pos++;\n while (pos < max) {\n code = state.src.charCodeAt(pos);\n if (code === 0x0A /* \\n */) { return false; }\n if (code === 0x3E /* > */) {\n link = normalizeLink(unescapeMd(state.src.slice(start + 1, pos)));\n if (!state.parser.validateLink(link)) { return false; }\n state.pos = pos + 1;\n state.linkContent = link;\n return true;\n }\n if (code === 0x5C /* \\ */ && pos + 1 < max) {\n pos += 2;\n continue;\n }\n\n pos++;\n }\n\n // no closing '>'\n return false;\n }\n\n // this should be ... } else { ... branch\n\n level = 0;\n while (pos < max) {\n code = state.src.charCodeAt(pos);\n\n if (code === 0x20) { break; }\n\n // ascii control chars\n if (code < 0x20 || code === 0x7F) { break; }\n\n if (code === 0x5C /* \\ */ && pos + 1 < max) {\n pos += 2;\n continue;\n }\n\n if (code === 0x28 /* ( */) {\n level++;\n if (level > 1) { break; }\n }\n\n if (code === 0x29 /* ) */) {\n level--;\n if (level < 0) { break; }\n }\n\n pos++;\n }\n\n if (start === pos) { return false; }\n\n link = unescapeMd(state.src.slice(start, pos));\n if (!state.parser.validateLink(link)) { return false; }\n\n state.linkContent = link;\n state.pos = pos;\n return true;\n}\n\n/**\n * Parse link title\n *\n * - on success it returns a string and updates state.pos;\n * - on failure it returns null\n *\n * @param {Object} state\n * @param {Number} pos\n * @api private\n */\n\nfunction parseLinkTitle(state, pos) {\n var code,\n start = pos,\n max = state.posMax,\n marker = state.src.charCodeAt(pos);\n\n if (marker !== 0x22 /* \" */ && marker !== 0x27 /* ' */ && marker !== 0x28 /* ( */) { return false; }\n\n pos++;\n\n // if opening marker is \"(\", switch it to closing marker \")\"\n if (marker === 0x28) { marker = 0x29; }\n\n while (pos < max) {\n code = state.src.charCodeAt(pos);\n if (code === marker) {\n state.pos = pos + 1;\n state.linkContent = unescapeMd(state.src.slice(start + 1, pos));\n return true;\n }\n if (code === 0x5C /* \\ */ && pos + 1 < max) {\n pos += 2;\n continue;\n }\n\n pos++;\n }\n\n return false;\n}\n\nfunction normalizeReference(str) {\n // use .toUpperCase() instead of .toLowerCase()\n // here to avoid a conflict with Object.prototype\n // members (most notably, `__proto__`)\n return str.trim().replace(/\\s+/g, ' ').toUpperCase();\n}\n\nfunction parseReference(str, parser, options, env) {\n var state, labelEnd, pos, max, code, start, href, title, label;\n\n if (str.charCodeAt(0) !== 0x5B/* [ */) { return -1; }\n\n if (str.indexOf(']:') === -1) { return -1; }\n\n state = new StateInline(str, parser, options, env, []);\n labelEnd = parseLinkLabel(state, 0);\n\n if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 0x3A/* : */) { return -1; }\n\n max = state.posMax;\n\n // [label]: destination 'title'\n // ^^^ skip optional whitespace here\n for (pos = labelEnd + 2; pos < max; pos++) {\n code = state.src.charCodeAt(pos);\n if (code !== 0x20 && code !== 0x0A) { break; }\n }\n\n // [label]: destination 'title'\n // ^^^^^^^^^^^ parse this\n if (!parseLinkDestination(state, pos)) { return -1; }\n href = state.linkContent;\n pos = state.pos;\n\n // [label]: destination 'title'\n // ^^^ skipping those spaces\n start = pos;\n for (pos = pos + 1; pos < max; pos++) {\n code = state.src.charCodeAt(pos);\n if (code !== 0x20 && code !== 0x0A) { break; }\n }\n\n // [label]: destination 'title'\n // ^^^^^^^ parse this\n if (pos < max && start !== pos && parseLinkTitle(state, pos)) {\n title = state.linkContent;\n pos = state.pos;\n } else {\n title = '';\n pos = start;\n }\n\n // ensure that the end of the line is empty\n while (pos < max && state.src.charCodeAt(pos) === 0x20/* space */) { pos++; }\n if (pos < max && state.src.charCodeAt(pos) !== 0x0A) { return -1; }\n\n label = normalizeReference(str.slice(1, labelEnd));\n if (typeof env.references[label] === 'undefined') {\n env.references[label] = { title: title, href: href };\n }\n\n return pos;\n}\n\n\nfunction references(state) {\n var tokens = state.tokens, i, l, content, pos;\n\n state.env.references = state.env.references || {};\n\n if (state.inlineMode) {\n return;\n }\n\n // Scan definitions in paragraph inlines\n for (i = 1, l = tokens.length - 1; i < l; i++) {\n if (tokens[i].type === 'inline' &&\n tokens[i - 1].type === 'paragraph_open' &&\n tokens[i + 1].type === 'paragraph_close') {\n\n content = tokens[i].content;\n while (content.length) {\n pos = parseReference(content, state.inline, state.options, state.env);\n if (pos < 0) { break; }\n content = content.slice(pos).trim();\n }\n\n tokens[i].content = content;\n if (!content.length) {\n tokens[i - 1].tight = true;\n tokens[i + 1].tight = true;\n }\n }\n }\n}\n\nfunction inline(state) {\n var tokens = state.tokens, tok, i, l;\n\n // Parse inlines\n for (i = 0, l = tokens.length; i < l; i++) {\n tok = tokens[i];\n if (tok.type === 'inline') {\n state.inline.parse(tok.content, state.options, state.env, tok.children);\n }\n }\n}\n\nfunction footnote_block(state) {\n var i, l, j, t, lastParagraph, list, tokens, current, currentLabel,\n level = 0,\n insideRef = false,\n refTokens = {};\n\n if (!state.env.footnotes) { return; }\n\n state.tokens = state.tokens.filter(function(tok) {\n if (tok.type === 'footnote_reference_open') {\n insideRef = true;\n current = [];\n currentLabel = tok.label;\n return false;\n }\n if (tok.type === 'footnote_reference_close') {\n insideRef = false;\n // prepend ':' to avoid conflict with Object.prototype members\n refTokens[':' + currentLabel] = current;\n return false;\n }\n if (insideRef) { current.push(tok); }\n return !insideRef;\n });\n\n if (!state.env.footnotes.list) { return; }\n list = state.env.footnotes.list;\n\n state.tokens.push({\n type: 'footnote_block_open',\n level: level++\n });\n for (i = 0, l = list.length; i < l; i++) {\n state.tokens.push({\n type: 'footnote_open',\n id: i,\n level: level++\n });\n\n if (list[i].tokens) {\n tokens = [];\n tokens.push({\n type: 'paragraph_open',\n tight: false,\n level: level++\n });\n tokens.push({\n type: 'inline',\n content: '',\n level: level,\n children: list[i].tokens\n });\n tokens.push({\n type: 'paragraph_close',\n tight: false,\n level: --level\n });\n } else if (list[i].label) {\n tokens = refTokens[':' + list[i].label];\n }\n\n state.tokens = state.tokens.concat(tokens);\n if (state.tokens[state.tokens.length - 1].type === 'paragraph_close') {\n lastParagraph = state.tokens.pop();\n } else {\n lastParagraph = null;\n }\n\n t = list[i].count > 0 ? list[i].count : 1;\n for (j = 0; j < t; j++) {\n state.tokens.push({\n type: 'footnote_anchor',\n id: i,\n subId: j,\n level: level\n });\n }\n\n if (lastParagraph) {\n state.tokens.push(lastParagraph);\n }\n\n state.tokens.push({\n type: 'footnote_close',\n level: --level\n });\n }\n state.tokens.push({\n type: 'footnote_block_close',\n level: --level\n });\n}\n\n// Enclose abbreviations in tags\n//\n\nvar PUNCT_CHARS = ' \\n()[]\\'\".,!?-';\n\n\n// from Google closure library\n// http://closure-library.googlecode.com/git-history/docs/local_closure_goog_string_string.js.source.html#line1021\nfunction regEscape(s) {\n return s.replace(/([-()\\[\\]{}+?*.$\\^|,:#= 0; i--) {\n token = tokens[i];\n if (token.type !== 'text') { continue; }\n\n pos = 0;\n text = token.content;\n reg.lastIndex = 0;\n level = token.level;\n nodes = [];\n\n while ((m = reg.exec(text))) {\n if (reg.lastIndex > pos) {\n nodes.push({\n type: 'text',\n content: text.slice(pos, m.index + m[1].length),\n level: level\n });\n }\n\n nodes.push({\n type: 'abbr_open',\n title: state.env.abbreviations[':' + m[2]],\n level: level++\n });\n nodes.push({\n type: 'text',\n content: m[2],\n level: level\n });\n nodes.push({\n type: 'abbr_close',\n level: --level\n });\n pos = reg.lastIndex - m[3].length;\n }\n\n if (!nodes.length) { continue; }\n\n if (pos < text.length) {\n nodes.push({\n type: 'text',\n content: text.slice(pos),\n level: level\n });\n }\n\n // replace current node\n blockTokens[j].children = tokens = [].concat(tokens.slice(0, i), nodes, tokens.slice(i + 1));\n }\n }\n}\n\n// Simple typographical replacements\n//\n// TODO:\n// - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾\n// - miltiplication 2 x 4 -> 2 × 4\n\nvar RARE_RE = /\\+-|\\.\\.|\\?\\?\\?\\?|!!!!|,,|--/;\n\nvar SCOPED_ABBR_RE = /\\((c|tm|r|p)\\)/ig;\nvar SCOPED_ABBR = {\n 'c': '©',\n 'r': '®',\n 'p': '§',\n 'tm': '™'\n};\n\nfunction replaceScopedAbbr(str) {\n if (str.indexOf('(') < 0) { return str; }\n\n return str.replace(SCOPED_ABBR_RE, function(match, name) {\n return SCOPED_ABBR[name.toLowerCase()];\n });\n}\n\n\nfunction replace(state) {\n var i, token, text, inlineTokens, blkIdx;\n\n if (!state.options.typographer) { return; }\n\n for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {\n\n if (state.tokens[blkIdx].type !== 'inline') { continue; }\n\n inlineTokens = state.tokens[blkIdx].children;\n\n for (i = inlineTokens.length - 1; i >= 0; i--) {\n token = inlineTokens[i];\n if (token.type === 'text') {\n text = token.content;\n\n text = replaceScopedAbbr(text);\n\n if (RARE_RE.test(text)) {\n text = text\n .replace(/\\+-/g, '±')\n // .., ..., ....... -> …\n // but ?..... & !..... -> ?.. & !..\n .replace(/\\.{2,}/g, '…').replace(/([?!])…/g, '$1..')\n .replace(/([?!]){4,}/g, '$1$1$1').replace(/,{2,}/g, ',')\n // em-dash\n .replace(/(^|[^-])---([^-]|$)/mg, '$1\\u2014$2')\n // en-dash\n .replace(/(^|\\s)--(\\s|$)/mg, '$1\\u2013$2')\n .replace(/(^|[^-\\s])--([^-\\s]|$)/mg, '$1\\u2013$2');\n }\n\n token.content = text;\n }\n }\n }\n}\n\n// Convert straight quotation marks to typographic ones\n//\n\nvar QUOTE_TEST_RE = /['\"]/;\nvar QUOTE_RE = /['\"]/g;\nvar PUNCT_RE = /[-\\s()\\[\\]]/;\nvar APOSTROPHE = '’';\n\n// This function returns true if the character at `pos`\n// could be inside a word.\nfunction isLetter(str, pos) {\n if (pos < 0 || pos >= str.length) { return false; }\n return !PUNCT_RE.test(str[pos]);\n}\n\n\nfunction replaceAt(str, index, ch) {\n return str.substr(0, index) + ch + str.substr(index + 1);\n}\n\n\nfunction smartquotes(state) {\n /*eslint max-depth:0*/\n var i, token, text, t, pos, max, thisLevel, lastSpace, nextSpace, item,\n canOpen, canClose, j, isSingle, blkIdx, tokens,\n stack;\n\n if (!state.options.typographer) { return; }\n\n stack = [];\n\n for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {\n\n if (state.tokens[blkIdx].type !== 'inline') { continue; }\n\n tokens = state.tokens[blkIdx].children;\n stack.length = 0;\n\n for (i = 0; i < tokens.length; i++) {\n token = tokens[i];\n\n if (token.type !== 'text' || QUOTE_TEST_RE.test(token.text)) { continue; }\n\n thisLevel = tokens[i].level;\n\n for (j = stack.length - 1; j >= 0; j--) {\n if (stack[j].level <= thisLevel) { break; }\n }\n stack.length = j + 1;\n\n text = token.content;\n pos = 0;\n max = text.length;\n\n /*eslint no-labels:0,block-scoped-var:0*/\n OUTER:\n while (pos < max) {\n QUOTE_RE.lastIndex = pos;\n t = QUOTE_RE.exec(text);\n if (!t) { break; }\n\n lastSpace = !isLetter(text, t.index - 1);\n pos = t.index + 1;\n isSingle = (t[0] === \"'\");\n nextSpace = !isLetter(text, pos);\n\n if (!nextSpace && !lastSpace) {\n // middle of word\n if (isSingle) {\n token.content = replaceAt(token.content, t.index, APOSTROPHE);\n }\n continue;\n }\n\n canOpen = !nextSpace;\n canClose = !lastSpace;\n\n if (canClose) {\n // this could be a closing quote, rewind the stack to get a match\n for (j = stack.length - 1; j >= 0; j--) {\n item = stack[j];\n if (stack[j].level < thisLevel) { break; }\n if (item.single === isSingle && stack[j].level === thisLevel) {\n item = stack[j];\n if (isSingle) {\n tokens[item.token].content = replaceAt(tokens[item.token].content, item.pos, state.options.quotes[2]);\n token.content = replaceAt(token.content, t.index, state.options.quotes[3]);\n } else {\n tokens[item.token].content = replaceAt(tokens[item.token].content, item.pos, state.options.quotes[0]);\n token.content = replaceAt(token.content, t.index, state.options.quotes[1]);\n }\n stack.length = j;\n continue OUTER;\n }\n }\n }\n\n if (canOpen) {\n stack.push({\n token: i,\n pos: t.index,\n single: isSingle,\n level: thisLevel\n });\n } else if (canClose && isSingle) {\n token.content = replaceAt(token.content, t.index, APOSTROPHE);\n }\n }\n }\n }\n}\n\n/**\n * Core parser `rules`\n */\n\nvar _rules = [\n [ 'block', block ],\n [ 'abbr', abbr ],\n [ 'references', references ],\n [ 'inline', inline ],\n [ 'footnote_tail', footnote_block ],\n [ 'abbr2', abbr2 ],\n [ 'replacements', replace ],\n [ 'smartquotes', smartquotes ],\n];\n\n/**\n * Class for top level (`core`) parser rules\n *\n * @api private\n */\n\nfunction Core() {\n this.options = {};\n this.ruler = new Ruler();\n for (var i = 0; i < _rules.length; i++) {\n this.ruler.push(_rules[i][0], _rules[i][1]);\n }\n}\n\n/**\n * Process rules with the given `state`\n *\n * @param {Object} `state`\n * @api private\n */\n\nCore.prototype.process = function (state) {\n var i, l, rules;\n rules = this.ruler.getRules('');\n for (i = 0, l = rules.length; i < l; i++) {\n rules[i](state);\n }\n};\n\n// Parser state class\n\nfunction StateBlock(src, parser, options, env, tokens) {\n var ch, s, start, pos, len, indent, indent_found;\n\n this.src = src;\n\n // Shortcuts to simplify nested calls\n this.parser = parser;\n\n this.options = options;\n\n this.env = env;\n\n //\n // Internal state vartiables\n //\n\n this.tokens = tokens;\n\n this.bMarks = []; // line begin offsets for fast jumps\n this.eMarks = []; // line end offsets for fast jumps\n this.tShift = []; // indent for each line\n\n // block parser variables\n this.blkIndent = 0; // required block content indent\n // (for example, if we are in list)\n this.line = 0; // line index in src\n this.lineMax = 0; // lines count\n this.tight = false; // loose/tight mode for lists\n this.parentType = 'root'; // if `list`, block parser stops on two newlines\n this.ddIndent = -1; // indent of the current dd block (-1 if there isn't any)\n\n this.level = 0;\n\n // renderer\n this.result = '';\n\n // Create caches\n // Generate markers.\n s = this.src;\n indent = 0;\n indent_found = false;\n\n for (start = pos = indent = 0, len = s.length; pos < len; pos++) {\n ch = s.charCodeAt(pos);\n\n if (!indent_found) {\n if (ch === 0x20/* space */) {\n indent++;\n continue;\n } else {\n indent_found = true;\n }\n }\n\n if (ch === 0x0A || pos === len - 1) {\n if (ch !== 0x0A) { pos++; }\n this.bMarks.push(start);\n this.eMarks.push(pos);\n this.tShift.push(indent);\n\n indent_found = false;\n indent = 0;\n start = pos + 1;\n }\n }\n\n // Push fake entry to simplify cache bounds checks\n this.bMarks.push(s.length);\n this.eMarks.push(s.length);\n this.tShift.push(0);\n\n this.lineMax = this.bMarks.length - 1; // don't count last fake line\n}\n\nStateBlock.prototype.isEmpty = function isEmpty(line) {\n return this.bMarks[line] + this.tShift[line] >= this.eMarks[line];\n};\n\nStateBlock.prototype.skipEmptyLines = function skipEmptyLines(from) {\n for (var max = this.lineMax; from < max; from++) {\n if (this.bMarks[from] + this.tShift[from] < this.eMarks[from]) {\n break;\n }\n }\n return from;\n};\n\n// Skip spaces from given position.\nStateBlock.prototype.skipSpaces = function skipSpaces(pos) {\n for (var max = this.src.length; pos < max; pos++) {\n if (this.src.charCodeAt(pos) !== 0x20/* space */) { break; }\n }\n return pos;\n};\n\n// Skip char codes from given position\nStateBlock.prototype.skipChars = function skipChars(pos, code) {\n for (var max = this.src.length; pos < max; pos++) {\n if (this.src.charCodeAt(pos) !== code) { break; }\n }\n return pos;\n};\n\n// Skip char codes reverse from given position - 1\nStateBlock.prototype.skipCharsBack = function skipCharsBack(pos, code, min) {\n if (pos <= min) { return pos; }\n\n while (pos > min) {\n if (code !== this.src.charCodeAt(--pos)) { return pos + 1; }\n }\n return pos;\n};\n\n// cut lines range from source.\nStateBlock.prototype.getLines = function getLines(begin, end, indent, keepLastLF) {\n var i, first, last, queue, shift,\n line = begin;\n\n if (begin >= end) {\n return '';\n }\n\n // Opt: don't use push queue for single line;\n if (line + 1 === end) {\n first = this.bMarks[line] + Math.min(this.tShift[line], indent);\n last = keepLastLF ? this.eMarks[line] + 1 : this.eMarks[line];\n return this.src.slice(first, last);\n }\n\n queue = new Array(end - begin);\n\n for (i = 0; line < end; line++, i++) {\n shift = this.tShift[line];\n if (shift > indent) { shift = indent; }\n if (shift < 0) { shift = 0; }\n\n first = this.bMarks[line] + shift;\n\n if (line + 1 < end || keepLastLF) {\n // No need for bounds check because we have fake entry on tail.\n last = this.eMarks[line] + 1;\n } else {\n last = this.eMarks[line];\n }\n\n queue[i] = this.src.slice(first, last);\n }\n\n return queue.join('');\n};\n\n// Code block (4 spaces padded)\n\nfunction code(state, startLine, endLine/*, silent*/) {\n var nextLine, last;\n\n if (state.tShift[startLine] - state.blkIndent < 4) { return false; }\n\n last = nextLine = startLine + 1;\n\n while (nextLine < endLine) {\n if (state.isEmpty(nextLine)) {\n nextLine++;\n continue;\n }\n if (state.tShift[nextLine] - state.blkIndent >= 4) {\n nextLine++;\n last = nextLine;\n continue;\n }\n break;\n }\n\n state.line = nextLine;\n state.tokens.push({\n type: 'code',\n content: state.getLines(startLine, last, 4 + state.blkIndent, true),\n block: true,\n lines: [ startLine, state.line ],\n level: state.level\n });\n\n return true;\n}\n\n// fences (``` lang, ~~~ lang)\n\nfunction fences(state, startLine, endLine, silent) {\n var marker, len, params, nextLine, mem,\n haveEndMarker = false,\n pos = state.bMarks[startLine] + state.tShift[startLine],\n max = state.eMarks[startLine];\n\n if (pos + 3 > max) { return false; }\n\n marker = state.src.charCodeAt(pos);\n\n if (marker !== 0x7E/* ~ */ && marker !== 0x60 /* ` */) {\n return false;\n }\n\n // scan marker length\n mem = pos;\n pos = state.skipChars(pos, marker);\n\n len = pos - mem;\n\n if (len < 3) { return false; }\n\n params = state.src.slice(pos, max).trim();\n\n if (params.indexOf('`') >= 0) { return false; }\n\n // Since start is found, we can report success here in validation mode\n if (silent) { return true; }\n\n // search end of block\n nextLine = startLine;\n\n for (;;) {\n nextLine++;\n if (nextLine >= endLine) {\n // unclosed block should be autoclosed by end of document.\n // also block seems to be autoclosed by end of parent\n break;\n }\n\n pos = mem = state.bMarks[nextLine] + state.tShift[nextLine];\n max = state.eMarks[nextLine];\n\n if (pos < max && state.tShift[nextLine] < state.blkIndent) {\n // non-empty line with negative indent should stop the list:\n // - ```\n // test\n break;\n }\n\n if (state.src.charCodeAt(pos) !== marker) { continue; }\n\n if (state.tShift[nextLine] - state.blkIndent >= 4) {\n // closing fence should be indented less than 4 spaces\n continue;\n }\n\n pos = state.skipChars(pos, marker);\n\n // closing code fence must be at least as long as the opening one\n if (pos - mem < len) { continue; }\n\n // make sure tail has spaces only\n pos = state.skipSpaces(pos);\n\n if (pos < max) { continue; }\n\n haveEndMarker = true;\n // found!\n break;\n }\n\n // If a fence has heading spaces, they should be removed from its inner block\n len = state.tShift[startLine];\n\n state.line = nextLine + (haveEndMarker ? 1 : 0);\n state.tokens.push({\n type: 'fence',\n params: params,\n content: state.getLines(startLine + 1, nextLine, len, true),\n lines: [ startLine, state.line ],\n level: state.level\n });\n\n return true;\n}\n\n// Block quotes\n\nfunction blockquote(state, startLine, endLine, silent) {\n var nextLine, lastLineEmpty, oldTShift, oldBMarks, oldIndent, oldParentType, lines,\n terminatorRules,\n i, l, terminate,\n pos = state.bMarks[startLine] + state.tShift[startLine],\n max = state.eMarks[startLine];\n\n if (pos > max) { return false; }\n\n // check the block quote marker\n if (state.src.charCodeAt(pos++) !== 0x3E/* > */) { return false; }\n\n if (state.level >= state.options.maxNesting) { return false; }\n\n // we know that it's going to be a valid blockquote,\n // so no point trying to find the end of it in silent mode\n if (silent) { return true; }\n\n // skip one optional space after '>'\n if (state.src.charCodeAt(pos) === 0x20) { pos++; }\n\n oldIndent = state.blkIndent;\n state.blkIndent = 0;\n\n oldBMarks = [ state.bMarks[startLine] ];\n state.bMarks[startLine] = pos;\n\n // check if we have an empty blockquote\n pos = pos < max ? state.skipSpaces(pos) : pos;\n lastLineEmpty = pos >= max;\n\n oldTShift = [ state.tShift[startLine] ];\n state.tShift[startLine] = pos - state.bMarks[startLine];\n\n terminatorRules = state.parser.ruler.getRules('blockquote');\n\n // Search the end of the block\n //\n // Block ends with either:\n // 1. an empty line outside:\n // ```\n // > test\n //\n // ```\n // 2. an empty line inside:\n // ```\n // >\n // test\n // ```\n // 3. another tag\n // ```\n // > test\n // - - -\n // ```\n for (nextLine = startLine + 1; nextLine < endLine; nextLine++) {\n pos = state.bMarks[nextLine] + state.tShift[nextLine];\n max = state.eMarks[nextLine];\n\n if (pos >= max) {\n // Case 1: line is not inside the blockquote, and this line is empty.\n break;\n }\n\n if (state.src.charCodeAt(pos++) === 0x3E/* > */) {\n // This line is inside the blockquote.\n\n // skip one optional space after '>'\n if (state.src.charCodeAt(pos) === 0x20) { pos++; }\n\n oldBMarks.push(state.bMarks[nextLine]);\n state.bMarks[nextLine] = pos;\n\n pos = pos < max ? state.skipSpaces(pos) : pos;\n lastLineEmpty = pos >= max;\n\n oldTShift.push(state.tShift[nextLine]);\n state.tShift[nextLine] = pos - state.bMarks[nextLine];\n continue;\n }\n\n // Case 2: line is not inside the blockquote, and the last line was empty.\n if (lastLineEmpty) { break; }\n\n // Case 3: another tag found.\n terminate = false;\n for (i = 0, l = terminatorRules.length; i < l; i++) {\n if (terminatorRules[i](state, nextLine, endLine, true)) {\n terminate = true;\n break;\n }\n }\n if (terminate) { break; }\n\n oldBMarks.push(state.bMarks[nextLine]);\n oldTShift.push(state.tShift[nextLine]);\n\n // A negative number means that this is a paragraph continuation;\n //\n // Any negative number will do the job here, but it's better for it\n // to be large enough to make any bugs obvious.\n state.tShift[nextLine] = -1337;\n }\n\n oldParentType = state.parentType;\n state.parentType = 'blockquote';\n state.tokens.push({\n type: 'blockquote_open',\n lines: lines = [ startLine, 0 ],\n level: state.level++\n });\n state.parser.tokenize(state, startLine, nextLine);\n state.tokens.push({\n type: 'blockquote_close',\n level: --state.level\n });\n state.parentType = oldParentType;\n lines[1] = state.line;\n\n // Restore original tShift; this might not be necessary since the parser\n // has already been here, but just to make sure we can do that.\n for (i = 0; i < oldTShift.length; i++) {\n state.bMarks[i + startLine] = oldBMarks[i];\n state.tShift[i + startLine] = oldTShift[i];\n }\n state.blkIndent = oldIndent;\n\n return true;\n}\n\n// Horizontal rule\n\nfunction hr(state, startLine, endLine, silent) {\n var marker, cnt, ch,\n pos = state.bMarks[startLine],\n max = state.eMarks[startLine];\n\n pos += state.tShift[startLine];\n\n if (pos > max) { return false; }\n\n marker = state.src.charCodeAt(pos++);\n\n // Check hr marker\n if (marker !== 0x2A/* * */ &&\n marker !== 0x2D/* - */ &&\n marker !== 0x5F/* _ */) {\n return false;\n }\n\n // markers can be mixed with spaces, but there should be at least 3 one\n\n cnt = 1;\n while (pos < max) {\n ch = state.src.charCodeAt(pos++);\n if (ch !== marker && ch !== 0x20/* space */) { return false; }\n if (ch === marker) { cnt++; }\n }\n\n if (cnt < 3) { return false; }\n\n if (silent) { return true; }\n\n state.line = startLine + 1;\n state.tokens.push({\n type: 'hr',\n lines: [ startLine, state.line ],\n level: state.level\n });\n\n return true;\n}\n\n// Lists\n\n// Search `[-+*][\\n ]`, returns next pos arter marker on success\n// or -1 on fail.\nfunction skipBulletListMarker(state, startLine) {\n var marker, pos, max;\n\n pos = state.bMarks[startLine] + state.tShift[startLine];\n max = state.eMarks[startLine];\n\n if (pos >= max) { return -1; }\n\n marker = state.src.charCodeAt(pos++);\n // Check bullet\n if (marker !== 0x2A/* * */ &&\n marker !== 0x2D/* - */ &&\n marker !== 0x2B/* + */) {\n return -1;\n }\n\n if (pos < max && state.src.charCodeAt(pos) !== 0x20) {\n // \" 1.test \" - is not a list item\n return -1;\n }\n\n return pos;\n}\n\n// Search `\\d+[.)][\\n ]`, returns next pos arter marker on success\n// or -1 on fail.\nfunction skipOrderedListMarker(state, startLine) {\n var ch,\n pos = state.bMarks[startLine] + state.tShift[startLine],\n max = state.eMarks[startLine];\n\n if (pos + 1 >= max) { return -1; }\n\n ch = state.src.charCodeAt(pos++);\n\n if (ch < 0x30/* 0 */ || ch > 0x39/* 9 */) { return -1; }\n\n for (;;) {\n // EOL -> fail\n if (pos >= max) { return -1; }\n\n ch = state.src.charCodeAt(pos++);\n\n if (ch >= 0x30/* 0 */ && ch <= 0x39/* 9 */) {\n continue;\n }\n\n // found valid marker\n if (ch === 0x29/* ) */ || ch === 0x2e/* . */) {\n break;\n }\n\n return -1;\n }\n\n\n if (pos < max && state.src.charCodeAt(pos) !== 0x20/* space */) {\n // \" 1.test \" - is not a list item\n return -1;\n }\n return pos;\n}\n\nfunction markTightParagraphs(state, idx) {\n var i, l,\n level = state.level + 2;\n\n for (i = idx + 2, l = state.tokens.length - 2; i < l; i++) {\n if (state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open') {\n state.tokens[i + 2].tight = true;\n state.tokens[i].tight = true;\n i += 2;\n }\n }\n}\n\n\nfunction list(state, startLine, endLine, silent) {\n var nextLine,\n indent,\n oldTShift,\n oldIndent,\n oldTight,\n oldParentType,\n start,\n posAfterMarker,\n max,\n indentAfterMarker,\n markerValue,\n markerCharCode,\n isOrdered,\n contentStart,\n listTokIdx,\n prevEmptyEnd,\n listLines,\n itemLines,\n tight = true,\n terminatorRules,\n i, l, terminate;\n\n // Detect list type and position after marker\n if ((posAfterMarker = skipOrderedListMarker(state, startLine)) >= 0) {\n isOrdered = true;\n } else if ((posAfterMarker = skipBulletListMarker(state, startLine)) >= 0) {\n isOrdered = false;\n } else {\n return false;\n }\n\n if (state.level >= state.options.maxNesting) { return false; }\n\n // We should terminate list on style change. Remember first one to compare.\n markerCharCode = state.src.charCodeAt(posAfterMarker - 1);\n\n // For validation mode we can terminate immediately\n if (silent) { return true; }\n\n // Start list\n listTokIdx = state.tokens.length;\n\n if (isOrdered) {\n start = state.bMarks[startLine] + state.tShift[startLine];\n markerValue = Number(state.src.substr(start, posAfterMarker - start - 1));\n\n state.tokens.push({\n type: 'ordered_list_open',\n order: markerValue,\n lines: listLines = [ startLine, 0 ],\n level: state.level++\n });\n\n } else {\n state.tokens.push({\n type: 'bullet_list_open',\n lines: listLines = [ startLine, 0 ],\n level: state.level++\n });\n }\n\n //\n // Iterate list items\n //\n\n nextLine = startLine;\n prevEmptyEnd = false;\n terminatorRules = state.parser.ruler.getRules('list');\n\n while (nextLine < endLine) {\n contentStart = state.skipSpaces(posAfterMarker);\n max = state.eMarks[nextLine];\n\n if (contentStart >= max) {\n // trimming space in \"- \\n 3\" case, indent is 1 here\n indentAfterMarker = 1;\n } else {\n indentAfterMarker = contentStart - posAfterMarker;\n }\n\n // If we have more than 4 spaces, the indent is 1\n // (the rest is just indented code block)\n if (indentAfterMarker > 4) { indentAfterMarker = 1; }\n\n // If indent is less than 1, assume that it's one, example:\n // \"-\\n test\"\n if (indentAfterMarker < 1) { indentAfterMarker = 1; }\n\n // \" - test\"\n // ^^^^^ - calculating total length of this thing\n indent = (posAfterMarker - state.bMarks[nextLine]) + indentAfterMarker;\n\n // Run subparser & write tokens\n state.tokens.push({\n type: 'list_item_open',\n lines: itemLines = [ startLine, 0 ],\n level: state.level++\n });\n\n oldIndent = state.blkIndent;\n oldTight = state.tight;\n oldTShift = state.tShift[startLine];\n oldParentType = state.parentType;\n state.tShift[startLine] = contentStart - state.bMarks[startLine];\n state.blkIndent = indent;\n state.tight = true;\n state.parentType = 'list';\n\n state.parser.tokenize(state, startLine, endLine, true);\n\n // If any of list item is tight, mark list as tight\n if (!state.tight || prevEmptyEnd) {\n tight = false;\n }\n // Item become loose if finish with empty line,\n // but we should filter last element, because it means list finish\n prevEmptyEnd = (state.line - startLine) > 1 && state.isEmpty(state.line - 1);\n\n state.blkIndent = oldIndent;\n state.tShift[startLine] = oldTShift;\n state.tight = oldTight;\n state.parentType = oldParentType;\n\n state.tokens.push({\n type: 'list_item_close',\n level: --state.level\n });\n\n nextLine = startLine = state.line;\n itemLines[1] = nextLine;\n contentStart = state.bMarks[startLine];\n\n if (nextLine >= endLine) { break; }\n\n if (state.isEmpty(nextLine)) {\n break;\n }\n\n //\n // Try to check if list is terminated or continued.\n //\n if (state.tShift[nextLine] < state.blkIndent) { break; }\n\n // fail if terminating block found\n terminate = false;\n for (i = 0, l = terminatorRules.length; i < l; i++) {\n if (terminatorRules[i](state, nextLine, endLine, true)) {\n terminate = true;\n break;\n }\n }\n if (terminate) { break; }\n\n // fail if list has another type\n if (isOrdered) {\n posAfterMarker = skipOrderedListMarker(state, nextLine);\n if (posAfterMarker < 0) { break; }\n } else {\n posAfterMarker = skipBulletListMarker(state, nextLine);\n if (posAfterMarker < 0) { break; }\n }\n\n if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) { break; }\n }\n\n // Finilize list\n state.tokens.push({\n type: isOrdered ? 'ordered_list_close' : 'bullet_list_close',\n level: --state.level\n });\n listLines[1] = nextLine;\n\n state.line = nextLine;\n\n // mark paragraphs tight if needed\n if (tight) {\n markTightParagraphs(state, listTokIdx);\n }\n\n return true;\n}\n\n// Process footnote reference list\n\nfunction footnote(state, startLine, endLine, silent) {\n var oldBMark, oldTShift, oldParentType, pos, label,\n start = state.bMarks[startLine] + state.tShift[startLine],\n max = state.eMarks[startLine];\n\n // line should be at least 5 chars - \"[^x]:\"\n if (start + 4 > max) { return false; }\n\n if (state.src.charCodeAt(start) !== 0x5B/* [ */) { return false; }\n if (state.src.charCodeAt(start + 1) !== 0x5E/* ^ */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n for (pos = start + 2; pos < max; pos++) {\n if (state.src.charCodeAt(pos) === 0x20) { return false; }\n if (state.src.charCodeAt(pos) === 0x5D /* ] */) {\n break;\n }\n }\n\n if (pos === start + 2) { return false; } // no empty footnote labels\n if (pos + 1 >= max || state.src.charCodeAt(++pos) !== 0x3A /* : */) { return false; }\n if (silent) { return true; }\n pos++;\n\n if (!state.env.footnotes) { state.env.footnotes = {}; }\n if (!state.env.footnotes.refs) { state.env.footnotes.refs = {}; }\n label = state.src.slice(start + 2, pos - 2);\n state.env.footnotes.refs[':' + label] = -1;\n\n state.tokens.push({\n type: 'footnote_reference_open',\n label: label,\n level: state.level++\n });\n\n oldBMark = state.bMarks[startLine];\n oldTShift = state.tShift[startLine];\n oldParentType = state.parentType;\n state.tShift[startLine] = state.skipSpaces(pos) - pos;\n state.bMarks[startLine] = pos;\n state.blkIndent += 4;\n state.parentType = 'footnote';\n\n if (state.tShift[startLine] < state.blkIndent) {\n state.tShift[startLine] += state.blkIndent;\n state.bMarks[startLine] -= state.blkIndent;\n }\n\n state.parser.tokenize(state, startLine, endLine, true);\n\n state.parentType = oldParentType;\n state.blkIndent -= 4;\n state.tShift[startLine] = oldTShift;\n state.bMarks[startLine] = oldBMark;\n\n state.tokens.push({\n type: 'footnote_reference_close',\n level: --state.level\n });\n\n return true;\n}\n\n// heading (#, ##, ...)\n\nfunction heading(state, startLine, endLine, silent) {\n var ch, level, tmp,\n pos = state.bMarks[startLine] + state.tShift[startLine],\n max = state.eMarks[startLine];\n\n if (pos >= max) { return false; }\n\n ch = state.src.charCodeAt(pos);\n\n if (ch !== 0x23/* # */ || pos >= max) { return false; }\n\n // count heading level\n level = 1;\n ch = state.src.charCodeAt(++pos);\n while (ch === 0x23/* # */ && pos < max && level <= 6) {\n level++;\n ch = state.src.charCodeAt(++pos);\n }\n\n if (level > 6 || (pos < max && ch !== 0x20/* space */)) { return false; }\n\n if (silent) { return true; }\n\n // Let's cut tails like ' ### ' from the end of string\n\n max = state.skipCharsBack(max, 0x20, pos); // space\n tmp = state.skipCharsBack(max, 0x23, pos); // #\n if (tmp > pos && state.src.charCodeAt(tmp - 1) === 0x20/* space */) {\n max = tmp;\n }\n\n state.line = startLine + 1;\n\n state.tokens.push({ type: 'heading_open',\n hLevel: level,\n lines: [ startLine, state.line ],\n level: state.level\n });\n\n // only if header is not empty\n if (pos < max) {\n state.tokens.push({\n type: 'inline',\n content: state.src.slice(pos, max).trim(),\n level: state.level + 1,\n lines: [ startLine, state.line ],\n children: []\n });\n }\n state.tokens.push({ type: 'heading_close', hLevel: level, level: state.level });\n\n return true;\n}\n\n// lheading (---, ===)\n\nfunction lheading(state, startLine, endLine/*, silent*/) {\n var marker, pos, max,\n next = startLine + 1;\n\n if (next >= endLine) { return false; }\n if (state.tShift[next] < state.blkIndent) { return false; }\n\n // Scan next line\n\n if (state.tShift[next] - state.blkIndent > 3) { return false; }\n\n pos = state.bMarks[next] + state.tShift[next];\n max = state.eMarks[next];\n\n if (pos >= max) { return false; }\n\n marker = state.src.charCodeAt(pos);\n\n if (marker !== 0x2D/* - */ && marker !== 0x3D/* = */) { return false; }\n\n pos = state.skipChars(pos, marker);\n\n pos = state.skipSpaces(pos);\n\n if (pos < max) { return false; }\n\n pos = state.bMarks[startLine] + state.tShift[startLine];\n\n state.line = next + 1;\n state.tokens.push({\n type: 'heading_open',\n hLevel: marker === 0x3D/* = */ ? 1 : 2,\n lines: [ startLine, state.line ],\n level: state.level\n });\n state.tokens.push({\n type: 'inline',\n content: state.src.slice(pos, state.eMarks[startLine]).trim(),\n level: state.level + 1,\n lines: [ startLine, state.line - 1 ],\n children: []\n });\n state.tokens.push({\n type: 'heading_close',\n hLevel: marker === 0x3D/* = */ ? 1 : 2,\n level: state.level\n });\n\n return true;\n}\n\n// List of valid html blocks names, accorting to commonmark spec\n// http://jgm.github.io/CommonMark/spec.html#html-blocks\n\nvar html_blocks = {};\n\n[\n 'article',\n 'aside',\n 'button',\n 'blockquote',\n 'body',\n 'canvas',\n 'caption',\n 'col',\n 'colgroup',\n 'dd',\n 'div',\n 'dl',\n 'dt',\n 'embed',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'hgroup',\n 'hr',\n 'iframe',\n 'li',\n 'map',\n 'object',\n 'ol',\n 'output',\n 'p',\n 'pre',\n 'progress',\n 'script',\n 'section',\n 'style',\n 'table',\n 'tbody',\n 'td',\n 'textarea',\n 'tfoot',\n 'th',\n 'tr',\n 'thead',\n 'ul',\n 'video'\n].forEach(function (name) { html_blocks[name] = true; });\n\n// HTML block\n\n\nvar HTML_TAG_OPEN_RE = /^<([a-zA-Z]{1,15})[\\s\\/>]/;\nvar HTML_TAG_CLOSE_RE = /^<\\/([a-zA-Z]{1,15})[\\s>]/;\n\nfunction isLetter$1(ch) {\n /*eslint no-bitwise:0*/\n var lc = ch | 0x20; // to lower case\n return (lc >= 0x61/* a */) && (lc <= 0x7a/* z */);\n}\n\nfunction htmlblock(state, startLine, endLine, silent) {\n var ch, match, nextLine,\n pos = state.bMarks[startLine],\n max = state.eMarks[startLine],\n shift = state.tShift[startLine];\n\n pos += shift;\n\n if (!state.options.html) { return false; }\n\n if (shift > 3 || pos + 2 >= max) { return false; }\n\n if (state.src.charCodeAt(pos) !== 0x3C/* < */) { return false; }\n\n ch = state.src.charCodeAt(pos + 1);\n\n if (ch === 0x21/* ! */ || ch === 0x3F/* ? */) {\n // Directive start / comment start / processing instruction start\n if (silent) { return true; }\n\n } else if (ch === 0x2F/* / */ || isLetter$1(ch)) {\n\n // Probably start or end of tag\n if (ch === 0x2F/* \\ */) {\n // closing tag\n match = state.src.slice(pos, max).match(HTML_TAG_CLOSE_RE);\n if (!match) { return false; }\n } else {\n // opening tag\n match = state.src.slice(pos, max).match(HTML_TAG_OPEN_RE);\n if (!match) { return false; }\n }\n // Make sure tag name is valid\n if (html_blocks[match[1].toLowerCase()] !== true) { return false; }\n if (silent) { return true; }\n\n } else {\n return false;\n }\n\n // If we are here - we detected HTML block.\n // Let's roll down till empty line (block end).\n nextLine = startLine + 1;\n while (nextLine < state.lineMax && !state.isEmpty(nextLine)) {\n nextLine++;\n }\n\n state.line = nextLine;\n state.tokens.push({\n type: 'htmlblock',\n level: state.level,\n lines: [ startLine, state.line ],\n content: state.getLines(startLine, nextLine, 0, true)\n });\n\n return true;\n}\n\n// GFM table, non-standard\n\nfunction getLine(state, line) {\n var pos = state.bMarks[line] + state.blkIndent,\n max = state.eMarks[line];\n\n return state.src.substr(pos, max - pos);\n}\n\nfunction table(state, startLine, endLine, silent) {\n var ch, lineText, pos, i, nextLine, rows, cell,\n aligns, t, tableLines, tbodyLines;\n\n // should have at least three lines\n if (startLine + 2 > endLine) { return false; }\n\n nextLine = startLine + 1;\n\n if (state.tShift[nextLine] < state.blkIndent) { return false; }\n\n // first character of the second line should be '|' or '-'\n\n pos = state.bMarks[nextLine] + state.tShift[nextLine];\n if (pos >= state.eMarks[nextLine]) { return false; }\n\n ch = state.src.charCodeAt(pos);\n if (ch !== 0x7C/* | */ && ch !== 0x2D/* - */ && ch !== 0x3A/* : */) { return false; }\n\n lineText = getLine(state, startLine + 1);\n if (!/^[-:| ]+$/.test(lineText)) { return false; }\n\n rows = lineText.split('|');\n if (rows <= 2) { return false; }\n aligns = [];\n for (i = 0; i < rows.length; i++) {\n t = rows[i].trim();\n if (!t) {\n // allow empty columns before and after table, but not in between columns;\n // e.g. allow ` |---| `, disallow ` ---||--- `\n if (i === 0 || i === rows.length - 1) {\n continue;\n } else {\n return false;\n }\n }\n\n if (!/^:?-+:?$/.test(t)) { return false; }\n if (t.charCodeAt(t.length - 1) === 0x3A/* : */) {\n aligns.push(t.charCodeAt(0) === 0x3A/* : */ ? 'center' : 'right');\n } else if (t.charCodeAt(0) === 0x3A/* : */) {\n aligns.push('left');\n } else {\n aligns.push('');\n }\n }\n\n lineText = getLine(state, startLine).trim();\n if (lineText.indexOf('|') === -1) { return false; }\n rows = lineText.replace(/^\\||\\|$/g, '').split('|');\n if (aligns.length !== rows.length) { return false; }\n if (silent) { return true; }\n\n state.tokens.push({\n type: 'table_open',\n lines: tableLines = [ startLine, 0 ],\n level: state.level++\n });\n state.tokens.push({\n type: 'thead_open',\n lines: [ startLine, startLine + 1 ],\n level: state.level++\n });\n\n state.tokens.push({\n type: 'tr_open',\n lines: [ startLine, startLine + 1 ],\n level: state.level++\n });\n for (i = 0; i < rows.length; i++) {\n state.tokens.push({\n type: 'th_open',\n align: aligns[i],\n lines: [ startLine, startLine + 1 ],\n level: state.level++\n });\n state.tokens.push({\n type: 'inline',\n content: rows[i].trim(),\n lines: [ startLine, startLine + 1 ],\n level: state.level,\n children: []\n });\n state.tokens.push({ type: 'th_close', level: --state.level });\n }\n state.tokens.push({ type: 'tr_close', level: --state.level });\n state.tokens.push({ type: 'thead_close', level: --state.level });\n\n state.tokens.push({\n type: 'tbody_open',\n lines: tbodyLines = [ startLine + 2, 0 ],\n level: state.level++\n });\n\n for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {\n if (state.tShift[nextLine] < state.blkIndent) { break; }\n\n lineText = getLine(state, nextLine).trim();\n if (lineText.indexOf('|') === -1) { break; }\n rows = lineText.replace(/^\\||\\|$/g, '').split('|');\n\n state.tokens.push({ type: 'tr_open', level: state.level++ });\n for (i = 0; i < rows.length; i++) {\n state.tokens.push({ type: 'td_open', align: aligns[i], level: state.level++ });\n // 0x7c === '|'\n cell = rows[i].substring(\n rows[i].charCodeAt(0) === 0x7c ? 1 : 0,\n rows[i].charCodeAt(rows[i].length - 1) === 0x7c ? rows[i].length - 1 : rows[i].length\n ).trim();\n state.tokens.push({\n type: 'inline',\n content: cell,\n level: state.level,\n children: []\n });\n state.tokens.push({ type: 'td_close', level: --state.level });\n }\n state.tokens.push({ type: 'tr_close', level: --state.level });\n }\n state.tokens.push({ type: 'tbody_close', level: --state.level });\n state.tokens.push({ type: 'table_close', level: --state.level });\n\n tableLines[1] = tbodyLines[1] = nextLine;\n state.line = nextLine;\n return true;\n}\n\n// Definition lists\n\n// Search `[:~][\\n ]`, returns next pos after marker on success\n// or -1 on fail.\nfunction skipMarker(state, line) {\n var pos, marker,\n start = state.bMarks[line] + state.tShift[line],\n max = state.eMarks[line];\n\n if (start >= max) { return -1; }\n\n // Check bullet\n marker = state.src.charCodeAt(start++);\n if (marker !== 0x7E/* ~ */ && marker !== 0x3A/* : */) { return -1; }\n\n pos = state.skipSpaces(start);\n\n // require space after \":\"\n if (start === pos) { return -1; }\n\n // no empty definitions, e.g. \" : \"\n if (pos >= max) { return -1; }\n\n return pos;\n}\n\nfunction markTightParagraphs$1(state, idx) {\n var i, l,\n level = state.level + 2;\n\n for (i = idx + 2, l = state.tokens.length - 2; i < l; i++) {\n if (state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open') {\n state.tokens[i + 2].tight = true;\n state.tokens[i].tight = true;\n i += 2;\n }\n }\n}\n\nfunction deflist(state, startLine, endLine, silent) {\n var contentStart,\n ddLine,\n dtLine,\n itemLines,\n listLines,\n listTokIdx,\n nextLine,\n oldIndent,\n oldDDIndent,\n oldParentType,\n oldTShift,\n oldTight,\n prevEmptyEnd,\n tight;\n\n if (silent) {\n // quirk: validation mode validates a dd block only, not a whole deflist\n if (state.ddIndent < 0) { return false; }\n return skipMarker(state, startLine) >= 0;\n }\n\n nextLine = startLine + 1;\n if (state.isEmpty(nextLine)) {\n if (++nextLine > endLine) { return false; }\n }\n\n if (state.tShift[nextLine] < state.blkIndent) { return false; }\n contentStart = skipMarker(state, nextLine);\n if (contentStart < 0) { return false; }\n\n if (state.level >= state.options.maxNesting) { return false; }\n\n // Start list\n listTokIdx = state.tokens.length;\n\n state.tokens.push({\n type: 'dl_open',\n lines: listLines = [ startLine, 0 ],\n level: state.level++\n });\n\n //\n // Iterate list items\n //\n\n dtLine = startLine;\n ddLine = nextLine;\n\n // One definition list can contain multiple DTs,\n // and one DT can be followed by multiple DDs.\n //\n // Thus, there is two loops here, and label is\n // needed to break out of the second one\n //\n /*eslint no-labels:0,block-scoped-var:0*/\n OUTER:\n for (;;) {\n tight = true;\n prevEmptyEnd = false;\n\n state.tokens.push({\n type: 'dt_open',\n lines: [ dtLine, dtLine ],\n level: state.level++\n });\n state.tokens.push({\n type: 'inline',\n content: state.getLines(dtLine, dtLine + 1, state.blkIndent, false).trim(),\n level: state.level + 1,\n lines: [ dtLine, dtLine ],\n children: []\n });\n state.tokens.push({\n type: 'dt_close',\n level: --state.level\n });\n\n for (;;) {\n state.tokens.push({\n type: 'dd_open',\n lines: itemLines = [ nextLine, 0 ],\n level: state.level++\n });\n\n oldTight = state.tight;\n oldDDIndent = state.ddIndent;\n oldIndent = state.blkIndent;\n oldTShift = state.tShift[ddLine];\n oldParentType = state.parentType;\n state.blkIndent = state.ddIndent = state.tShift[ddLine] + 2;\n state.tShift[ddLine] = contentStart - state.bMarks[ddLine];\n state.tight = true;\n state.parentType = 'deflist';\n\n state.parser.tokenize(state, ddLine, endLine, true);\n\n // If any of list item is tight, mark list as tight\n if (!state.tight || prevEmptyEnd) {\n tight = false;\n }\n // Item become loose if finish with empty line,\n // but we should filter last element, because it means list finish\n prevEmptyEnd = (state.line - ddLine) > 1 && state.isEmpty(state.line - 1);\n\n state.tShift[ddLine] = oldTShift;\n state.tight = oldTight;\n state.parentType = oldParentType;\n state.blkIndent = oldIndent;\n state.ddIndent = oldDDIndent;\n\n state.tokens.push({\n type: 'dd_close',\n level: --state.level\n });\n\n itemLines[1] = nextLine = state.line;\n\n if (nextLine >= endLine) { break OUTER; }\n\n if (state.tShift[nextLine] < state.blkIndent) { break OUTER; }\n contentStart = skipMarker(state, nextLine);\n if (contentStart < 0) { break; }\n\n ddLine = nextLine;\n\n // go to the next loop iteration:\n // insert DD tag and repeat checking\n }\n\n if (nextLine >= endLine) { break; }\n dtLine = nextLine;\n\n if (state.isEmpty(dtLine)) { break; }\n if (state.tShift[dtLine] < state.blkIndent) { break; }\n\n ddLine = dtLine + 1;\n if (ddLine >= endLine) { break; }\n if (state.isEmpty(ddLine)) { ddLine++; }\n if (ddLine >= endLine) { break; }\n\n if (state.tShift[ddLine] < state.blkIndent) { break; }\n contentStart = skipMarker(state, ddLine);\n if (contentStart < 0) { break; }\n\n // go to the next loop iteration:\n // insert DT and DD tags and repeat checking\n }\n\n // Finilize list\n state.tokens.push({\n type: 'dl_close',\n level: --state.level\n });\n listLines[1] = nextLine;\n\n state.line = nextLine;\n\n // mark paragraphs tight if needed\n if (tight) {\n markTightParagraphs$1(state, listTokIdx);\n }\n\n return true;\n}\n\n// Paragraph\n\nfunction paragraph(state, startLine/*, endLine*/) {\n var endLine, content, terminate, i, l,\n nextLine = startLine + 1,\n terminatorRules;\n\n endLine = state.lineMax;\n\n // jump line-by-line until empty one or EOF\n if (nextLine < endLine && !state.isEmpty(nextLine)) {\n terminatorRules = state.parser.ruler.getRules('paragraph');\n\n for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {\n // this would be a code block normally, but after paragraph\n // it's considered a lazy continuation regardless of what's there\n if (state.tShift[nextLine] - state.blkIndent > 3) { continue; }\n\n // Some tags can terminate paragraph without empty line.\n terminate = false;\n for (i = 0, l = terminatorRules.length; i < l; i++) {\n if (terminatorRules[i](state, nextLine, endLine, true)) {\n terminate = true;\n break;\n }\n }\n if (terminate) { break; }\n }\n }\n\n content = state.getLines(startLine, nextLine, state.blkIndent, false).trim();\n\n state.line = nextLine;\n if (content.length) {\n state.tokens.push({\n type: 'paragraph_open',\n tight: false,\n lines: [ startLine, state.line ],\n level: state.level\n });\n state.tokens.push({\n type: 'inline',\n content: content,\n level: state.level + 1,\n lines: [ startLine, state.line ],\n children: []\n });\n state.tokens.push({\n type: 'paragraph_close',\n tight: false,\n level: state.level\n });\n }\n\n return true;\n}\n\n/**\n * Parser rules\n */\n\nvar _rules$1 = [\n [ 'code', code ],\n [ 'fences', fences, [ 'paragraph', 'blockquote', 'list' ] ],\n [ 'blockquote', blockquote, [ 'paragraph', 'blockquote', 'list' ] ],\n [ 'hr', hr, [ 'paragraph', 'blockquote', 'list' ] ],\n [ 'list', list, [ 'paragraph', 'blockquote' ] ],\n [ 'footnote', footnote, [ 'paragraph' ] ],\n [ 'heading', heading, [ 'paragraph', 'blockquote' ] ],\n [ 'lheading', lheading ],\n [ 'htmlblock', htmlblock, [ 'paragraph', 'blockquote' ] ],\n [ 'table', table, [ 'paragraph' ] ],\n [ 'deflist', deflist, [ 'paragraph' ] ],\n [ 'paragraph', paragraph ]\n];\n\n/**\n * Block Parser class\n *\n * @api private\n */\n\nfunction ParserBlock() {\n this.ruler = new Ruler();\n for (var i = 0; i < _rules$1.length; i++) {\n this.ruler.push(_rules$1[i][0], _rules$1[i][1], {\n alt: (_rules$1[i][2] || []).slice()\n });\n }\n}\n\n/**\n * Generate tokens for the given input range.\n *\n * @param {Object} `state` Has properties like `src`, `parser`, `options` etc\n * @param {Number} `startLine`\n * @param {Number} `endLine`\n * @api private\n */\n\nParserBlock.prototype.tokenize = function (state, startLine, endLine) {\n var rules = this.ruler.getRules('');\n var len = rules.length;\n var line = startLine;\n var hasEmptyLines = false;\n var ok, i;\n\n while (line < endLine) {\n state.line = line = state.skipEmptyLines(line);\n if (line >= endLine) {\n break;\n }\n\n // Termination condition for nested calls.\n // Nested calls currently used for blockquotes & lists\n if (state.tShift[line] < state.blkIndent) {\n break;\n }\n\n // Try all possible rules.\n // On success, rule should:\n //\n // - update `state.line`\n // - update `state.tokens`\n // - return true\n\n for (i = 0; i < len; i++) {\n ok = rules[i](state, line, endLine, false);\n if (ok) {\n break;\n }\n }\n\n // set state.tight iff we had an empty line before current tag\n // i.e. latest empty line should not count\n state.tight = !hasEmptyLines;\n\n // paragraph might \"eat\" one newline after it in nested lists\n if (state.isEmpty(state.line - 1)) {\n hasEmptyLines = true;\n }\n\n line = state.line;\n\n if (line < endLine && state.isEmpty(line)) {\n hasEmptyLines = true;\n line++;\n\n // two empty lines should stop the parser in list mode\n if (line < endLine && state.parentType === 'list' && state.isEmpty(line)) { break; }\n state.line = line;\n }\n }\n};\n\nvar TABS_SCAN_RE = /[\\n\\t]/g;\nvar NEWLINES_RE = /\\r[\\n\\u0085]|[\\u2424\\u2028\\u0085]/g;\nvar SPACES_RE = /\\u00a0/g;\n\n/**\n * Tokenize the given `str`.\n *\n * @param {String} `str` Source string\n * @param {Object} `options`\n * @param {Object} `env`\n * @param {Array} `outTokens`\n * @api private\n */\n\nParserBlock.prototype.parse = function (str, options, env, outTokens) {\n var state, lineStart = 0, lastTabPos = 0;\n if (!str) { return []; }\n\n // Normalize spaces\n str = str.replace(SPACES_RE, ' ');\n\n // Normalize newlines\n str = str.replace(NEWLINES_RE, '\\n');\n\n // Replace tabs with proper number of spaces (1..4)\n if (str.indexOf('\\t') >= 0) {\n str = str.replace(TABS_SCAN_RE, function (match, offset) {\n var result;\n if (str.charCodeAt(offset) === 0x0A) {\n lineStart = offset + 1;\n lastTabPos = 0;\n return match;\n }\n result = ' '.slice((offset - lineStart - lastTabPos) % 4);\n lastTabPos = offset - lineStart + 1;\n return result;\n });\n }\n\n state = new StateBlock(str, this, options, env, outTokens);\n this.tokenize(state, state.line, state.lineMax);\n};\n\n// Skip text characters for text token, place those to pending buffer\n// and increment current pos\n\n// Rule to skip pure text\n// '{}$%@~+=:' reserved for extentions\n\nfunction isTerminatorChar(ch) {\n switch (ch) {\n case 0x0A/* \\n */:\n case 0x5C/* \\ */:\n case 0x60/* ` */:\n case 0x2A/* * */:\n case 0x5F/* _ */:\n case 0x5E/* ^ */:\n case 0x5B/* [ */:\n case 0x5D/* ] */:\n case 0x21/* ! */:\n case 0x26/* & */:\n case 0x3C/* < */:\n case 0x3E/* > */:\n case 0x7B/* { */:\n case 0x7D/* } */:\n case 0x24/* $ */:\n case 0x25/* % */:\n case 0x40/* @ */:\n case 0x7E/* ~ */:\n case 0x2B/* + */:\n case 0x3D/* = */:\n case 0x3A/* : */:\n return true;\n default:\n return false;\n }\n}\n\nfunction text(state, silent) {\n var pos = state.pos;\n\n while (pos < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos))) {\n pos++;\n }\n\n if (pos === state.pos) { return false; }\n\n if (!silent) { state.pending += state.src.slice(state.pos, pos); }\n\n state.pos = pos;\n\n return true;\n}\n\n// Proceess '\\n'\n\nfunction newline(state, silent) {\n var pmax, max, pos = state.pos;\n\n if (state.src.charCodeAt(pos) !== 0x0A/* \\n */) { return false; }\n\n pmax = state.pending.length - 1;\n max = state.posMax;\n\n // ' \\n' -> hardbreak\n // Lookup in pending chars is bad practice! Don't copy to other rules!\n // Pending string is stored in concat mode, indexed lookups will cause\n // convertion to flat mode.\n if (!silent) {\n if (pmax >= 0 && state.pending.charCodeAt(pmax) === 0x20) {\n if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 0x20) {\n // Strip out all trailing spaces on this line.\n for (var i = pmax - 2; i >= 0; i--) {\n if (state.pending.charCodeAt(i) !== 0x20) {\n state.pending = state.pending.substring(0, i + 1);\n break;\n }\n }\n state.push({\n type: 'hardbreak',\n level: state.level\n });\n } else {\n state.pending = state.pending.slice(0, -1);\n state.push({\n type: 'softbreak',\n level: state.level\n });\n }\n\n } else {\n state.push({\n type: 'softbreak',\n level: state.level\n });\n }\n }\n\n pos++;\n\n // skip heading spaces for next line\n while (pos < max && state.src.charCodeAt(pos) === 0x20) { pos++; }\n\n state.pos = pos;\n return true;\n}\n\n// Proceess escaped chars and hardbreaks\n\nvar ESCAPED = [];\n\nfor (var i = 0; i < 256; i++) { ESCAPED.push(0); }\n\n'\\\\!\"#$%&\\'()*+,./:;<=>?@[]^_`{|}~-'\n .split('').forEach(function(ch) { ESCAPED[ch.charCodeAt(0)] = 1; });\n\n\nfunction escape(state, silent) {\n var ch, pos = state.pos, max = state.posMax;\n\n if (state.src.charCodeAt(pos) !== 0x5C/* \\ */) { return false; }\n\n pos++;\n\n if (pos < max) {\n ch = state.src.charCodeAt(pos);\n\n if (ch < 256 && ESCAPED[ch] !== 0) {\n if (!silent) { state.pending += state.src[pos]; }\n state.pos += 2;\n return true;\n }\n\n if (ch === 0x0A) {\n if (!silent) {\n state.push({\n type: 'hardbreak',\n level: state.level\n });\n }\n\n pos++;\n // skip leading whitespaces from next line\n while (pos < max && state.src.charCodeAt(pos) === 0x20) { pos++; }\n\n state.pos = pos;\n return true;\n }\n }\n\n if (!silent) { state.pending += '\\\\'; }\n state.pos++;\n return true;\n}\n\n// Parse backticks\n\nfunction backticks(state, silent) {\n var start, max, marker, matchStart, matchEnd,\n pos = state.pos,\n ch = state.src.charCodeAt(pos);\n\n if (ch !== 0x60/* ` */) { return false; }\n\n start = pos;\n pos++;\n max = state.posMax;\n\n while (pos < max && state.src.charCodeAt(pos) === 0x60/* ` */) { pos++; }\n\n marker = state.src.slice(start, pos);\n\n matchStart = matchEnd = pos;\n\n while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) {\n matchEnd = matchStart + 1;\n\n while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60/* ` */) { matchEnd++; }\n\n if (matchEnd - matchStart === marker.length) {\n if (!silent) {\n state.push({\n type: 'code',\n content: state.src.slice(pos, matchStart)\n .replace(/[ \\n]+/g, ' ')\n .trim(),\n block: false,\n level: state.level\n });\n }\n state.pos = matchEnd;\n return true;\n }\n }\n\n if (!silent) { state.pending += marker; }\n state.pos += marker.length;\n return true;\n}\n\n// Process ~~deleted text~~\n\nfunction del(state, silent) {\n var found,\n pos,\n stack,\n max = state.posMax,\n start = state.pos,\n lastChar,\n nextChar;\n\n if (state.src.charCodeAt(start) !== 0x7E/* ~ */) { return false; }\n if (silent) { return false; } // don't run any pairs in validation mode\n if (start + 4 >= max) { return false; }\n if (state.src.charCodeAt(start + 1) !== 0x7E/* ~ */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n lastChar = start > 0 ? state.src.charCodeAt(start - 1) : -1;\n nextChar = state.src.charCodeAt(start + 2);\n\n if (lastChar === 0x7E/* ~ */) { return false; }\n if (nextChar === 0x7E/* ~ */) { return false; }\n if (nextChar === 0x20 || nextChar === 0x0A) { return false; }\n\n pos = start + 2;\n while (pos < max && state.src.charCodeAt(pos) === 0x7E/* ~ */) { pos++; }\n if (pos > start + 3) {\n // sequence of 4+ markers taking as literal, same as in a emphasis\n state.pos += pos - start;\n if (!silent) { state.pending += state.src.slice(start, pos); }\n return true;\n }\n\n state.pos = start + 2;\n stack = 1;\n\n while (state.pos + 1 < max) {\n if (state.src.charCodeAt(state.pos) === 0x7E/* ~ */) {\n if (state.src.charCodeAt(state.pos + 1) === 0x7E/* ~ */) {\n lastChar = state.src.charCodeAt(state.pos - 1);\n nextChar = state.pos + 2 < max ? state.src.charCodeAt(state.pos + 2) : -1;\n if (nextChar !== 0x7E/* ~ */ && lastChar !== 0x7E/* ~ */) {\n if (lastChar !== 0x20 && lastChar !== 0x0A) {\n // closing '~~'\n stack--;\n } else if (nextChar !== 0x20 && nextChar !== 0x0A) {\n // opening '~~'\n stack++;\n } // else {\n // // standalone ' ~~ ' indented with spaces\n // }\n if (stack <= 0) {\n found = true;\n break;\n }\n }\n }\n }\n\n state.parser.skipToken(state);\n }\n\n if (!found) {\n // parser failed to find ending tag, so it's not valid emphasis\n state.pos = start;\n return false;\n }\n\n // found!\n state.posMax = state.pos;\n state.pos = start + 2;\n\n if (!silent) {\n state.push({ type: 'del_open', level: state.level++ });\n state.parser.tokenize(state);\n state.push({ type: 'del_close', level: --state.level });\n }\n\n state.pos = state.posMax + 2;\n state.posMax = max;\n return true;\n}\n\n// Process ++inserted text++\n\nfunction ins(state, silent) {\n var found,\n pos,\n stack,\n max = state.posMax,\n start = state.pos,\n lastChar,\n nextChar;\n\n if (state.src.charCodeAt(start) !== 0x2B/* + */) { return false; }\n if (silent) { return false; } // don't run any pairs in validation mode\n if (start + 4 >= max) { return false; }\n if (state.src.charCodeAt(start + 1) !== 0x2B/* + */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n lastChar = start > 0 ? state.src.charCodeAt(start - 1) : -1;\n nextChar = state.src.charCodeAt(start + 2);\n\n if (lastChar === 0x2B/* + */) { return false; }\n if (nextChar === 0x2B/* + */) { return false; }\n if (nextChar === 0x20 || nextChar === 0x0A) { return false; }\n\n pos = start + 2;\n while (pos < max && state.src.charCodeAt(pos) === 0x2B/* + */) { pos++; }\n if (pos !== start + 2) {\n // sequence of 3+ markers taking as literal, same as in a emphasis\n state.pos += pos - start;\n if (!silent) { state.pending += state.src.slice(start, pos); }\n return true;\n }\n\n state.pos = start + 2;\n stack = 1;\n\n while (state.pos + 1 < max) {\n if (state.src.charCodeAt(state.pos) === 0x2B/* + */) {\n if (state.src.charCodeAt(state.pos + 1) === 0x2B/* + */) {\n lastChar = state.src.charCodeAt(state.pos - 1);\n nextChar = state.pos + 2 < max ? state.src.charCodeAt(state.pos + 2) : -1;\n if (nextChar !== 0x2B/* + */ && lastChar !== 0x2B/* + */) {\n if (lastChar !== 0x20 && lastChar !== 0x0A) {\n // closing '++'\n stack--;\n } else if (nextChar !== 0x20 && nextChar !== 0x0A) {\n // opening '++'\n stack++;\n } // else {\n // // standalone ' ++ ' indented with spaces\n // }\n if (stack <= 0) {\n found = true;\n break;\n }\n }\n }\n }\n\n state.parser.skipToken(state);\n }\n\n if (!found) {\n // parser failed to find ending tag, so it's not valid emphasis\n state.pos = start;\n return false;\n }\n\n // found!\n state.posMax = state.pos;\n state.pos = start + 2;\n\n if (!silent) {\n state.push({ type: 'ins_open', level: state.level++ });\n state.parser.tokenize(state);\n state.push({ type: 'ins_close', level: --state.level });\n }\n\n state.pos = state.posMax + 2;\n state.posMax = max;\n return true;\n}\n\n// Process ==highlighted text==\n\nfunction mark(state, silent) {\n var found,\n pos,\n stack,\n max = state.posMax,\n start = state.pos,\n lastChar,\n nextChar;\n\n if (state.src.charCodeAt(start) !== 0x3D/* = */) { return false; }\n if (silent) { return false; } // don't run any pairs in validation mode\n if (start + 4 >= max) { return false; }\n if (state.src.charCodeAt(start + 1) !== 0x3D/* = */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n lastChar = start > 0 ? state.src.charCodeAt(start - 1) : -1;\n nextChar = state.src.charCodeAt(start + 2);\n\n if (lastChar === 0x3D/* = */) { return false; }\n if (nextChar === 0x3D/* = */) { return false; }\n if (nextChar === 0x20 || nextChar === 0x0A) { return false; }\n\n pos = start + 2;\n while (pos < max && state.src.charCodeAt(pos) === 0x3D/* = */) { pos++; }\n if (pos !== start + 2) {\n // sequence of 3+ markers taking as literal, same as in a emphasis\n state.pos += pos - start;\n if (!silent) { state.pending += state.src.slice(start, pos); }\n return true;\n }\n\n state.pos = start + 2;\n stack = 1;\n\n while (state.pos + 1 < max) {\n if (state.src.charCodeAt(state.pos) === 0x3D/* = */) {\n if (state.src.charCodeAt(state.pos + 1) === 0x3D/* = */) {\n lastChar = state.src.charCodeAt(state.pos - 1);\n nextChar = state.pos + 2 < max ? state.src.charCodeAt(state.pos + 2) : -1;\n if (nextChar !== 0x3D/* = */ && lastChar !== 0x3D/* = */) {\n if (lastChar !== 0x20 && lastChar !== 0x0A) {\n // closing '=='\n stack--;\n } else if (nextChar !== 0x20 && nextChar !== 0x0A) {\n // opening '=='\n stack++;\n } // else {\n // // standalone ' == ' indented with spaces\n // }\n if (stack <= 0) {\n found = true;\n break;\n }\n }\n }\n }\n\n state.parser.skipToken(state);\n }\n\n if (!found) {\n // parser failed to find ending tag, so it's not valid emphasis\n state.pos = start;\n return false;\n }\n\n // found!\n state.posMax = state.pos;\n state.pos = start + 2;\n\n if (!silent) {\n state.push({ type: 'mark_open', level: state.level++ });\n state.parser.tokenize(state);\n state.push({ type: 'mark_close', level: --state.level });\n }\n\n state.pos = state.posMax + 2;\n state.posMax = max;\n return true;\n}\n\n// Process *this* and _that_\n\nfunction isAlphaNum(code) {\n return (code >= 0x30 /* 0 */ && code <= 0x39 /* 9 */) ||\n (code >= 0x41 /* A */ && code <= 0x5A /* Z */) ||\n (code >= 0x61 /* a */ && code <= 0x7A /* z */);\n}\n\n// parse sequence of emphasis markers,\n// \"start\" should point at a valid marker\nfunction scanDelims(state, start) {\n var pos = start, lastChar, nextChar, count,\n can_open = true,\n can_close = true,\n max = state.posMax,\n marker = state.src.charCodeAt(start);\n\n lastChar = start > 0 ? state.src.charCodeAt(start - 1) : -1;\n\n while (pos < max && state.src.charCodeAt(pos) === marker) { pos++; }\n if (pos >= max) { can_open = false; }\n count = pos - start;\n\n if (count >= 4) {\n // sequence of four or more unescaped markers can't start/end an emphasis\n can_open = can_close = false;\n } else {\n nextChar = pos < max ? state.src.charCodeAt(pos) : -1;\n\n // check whitespace conditions\n if (nextChar === 0x20 || nextChar === 0x0A) { can_open = false; }\n if (lastChar === 0x20 || lastChar === 0x0A) { can_close = false; }\n\n if (marker === 0x5F /* _ */) {\n // check if we aren't inside the word\n if (isAlphaNum(lastChar)) { can_open = false; }\n if (isAlphaNum(nextChar)) { can_close = false; }\n }\n }\n\n return {\n can_open: can_open,\n can_close: can_close,\n delims: count\n };\n}\n\nfunction emphasis(state, silent) {\n var startCount,\n count,\n found,\n oldCount,\n newCount,\n stack,\n res,\n max = state.posMax,\n start = state.pos,\n marker = state.src.charCodeAt(start);\n\n if (marker !== 0x5F/* _ */ && marker !== 0x2A /* * */) { return false; }\n if (silent) { return false; } // don't run any pairs in validation mode\n\n res = scanDelims(state, start);\n startCount = res.delims;\n if (!res.can_open) {\n state.pos += startCount;\n if (!silent) { state.pending += state.src.slice(start, state.pos); }\n return true;\n }\n\n if (state.level >= state.options.maxNesting) { return false; }\n\n state.pos = start + startCount;\n stack = [ startCount ];\n\n while (state.pos < max) {\n if (state.src.charCodeAt(state.pos) === marker) {\n res = scanDelims(state, state.pos);\n count = res.delims;\n if (res.can_close) {\n oldCount = stack.pop();\n newCount = count;\n\n while (oldCount !== newCount) {\n if (newCount < oldCount) {\n stack.push(oldCount - newCount);\n break;\n }\n\n // assert(newCount > oldCount)\n newCount -= oldCount;\n\n if (stack.length === 0) { break; }\n state.pos += oldCount;\n oldCount = stack.pop();\n }\n\n if (stack.length === 0) {\n startCount = oldCount;\n found = true;\n break;\n }\n state.pos += count;\n continue;\n }\n\n if (res.can_open) { stack.push(count); }\n state.pos += count;\n continue;\n }\n\n state.parser.skipToken(state);\n }\n\n if (!found) {\n // parser failed to find ending tag, so it's not valid emphasis\n state.pos = start;\n return false;\n }\n\n // found!\n state.posMax = state.pos;\n state.pos = start + startCount;\n\n if (!silent) {\n if (startCount === 2 || startCount === 3) {\n state.push({ type: 'strong_open', level: state.level++ });\n }\n if (startCount === 1 || startCount === 3) {\n state.push({ type: 'em_open', level: state.level++ });\n }\n\n state.parser.tokenize(state);\n\n if (startCount === 1 || startCount === 3) {\n state.push({ type: 'em_close', level: --state.level });\n }\n if (startCount === 2 || startCount === 3) {\n state.push({ type: 'strong_close', level: --state.level });\n }\n }\n\n state.pos = state.posMax + startCount;\n state.posMax = max;\n return true;\n}\n\n// Process ~subscript~\n\n// same as UNESCAPE_MD_RE plus a space\nvar UNESCAPE_RE = /\\\\([ \\\\!\"#$%&'()*+,.\\/:;<=>?@[\\]^_`{|}~-])/g;\n\nfunction sub(state, silent) {\n var found,\n content,\n max = state.posMax,\n start = state.pos;\n\n if (state.src.charCodeAt(start) !== 0x7E/* ~ */) { return false; }\n if (silent) { return false; } // don't run any pairs in validation mode\n if (start + 2 >= max) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n state.pos = start + 1;\n\n while (state.pos < max) {\n if (state.src.charCodeAt(state.pos) === 0x7E/* ~ */) {\n found = true;\n break;\n }\n\n state.parser.skipToken(state);\n }\n\n if (!found || start + 1 === state.pos) {\n state.pos = start;\n return false;\n }\n\n content = state.src.slice(start + 1, state.pos);\n\n // don't allow unescaped spaces/newlines inside\n if (content.match(/(^|[^\\\\])(\\\\\\\\)*\\s/)) {\n state.pos = start;\n return false;\n }\n\n // found!\n state.posMax = state.pos;\n state.pos = start + 1;\n\n if (!silent) {\n state.push({\n type: 'sub',\n level: state.level,\n content: content.replace(UNESCAPE_RE, '$1')\n });\n }\n\n state.pos = state.posMax + 1;\n state.posMax = max;\n return true;\n}\n\n// Process ^superscript^\n\n// same as UNESCAPE_MD_RE plus a space\nvar UNESCAPE_RE$1 = /\\\\([ \\\\!\"#$%&'()*+,.\\/:;<=>?@[\\]^_`{|}~-])/g;\n\nfunction sup(state, silent) {\n var found,\n content,\n max = state.posMax,\n start = state.pos;\n\n if (state.src.charCodeAt(start) !== 0x5E/* ^ */) { return false; }\n if (silent) { return false; } // don't run any pairs in validation mode\n if (start + 2 >= max) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n state.pos = start + 1;\n\n while (state.pos < max) {\n if (state.src.charCodeAt(state.pos) === 0x5E/* ^ */) {\n found = true;\n break;\n }\n\n state.parser.skipToken(state);\n }\n\n if (!found || start + 1 === state.pos) {\n state.pos = start;\n return false;\n }\n\n content = state.src.slice(start + 1, state.pos);\n\n // don't allow unescaped spaces/newlines inside\n if (content.match(/(^|[^\\\\])(\\\\\\\\)*\\s/)) {\n state.pos = start;\n return false;\n }\n\n // found!\n state.posMax = state.pos;\n state.pos = start + 1;\n\n if (!silent) {\n state.push({\n type: 'sup',\n level: state.level,\n content: content.replace(UNESCAPE_RE$1, '$1')\n });\n }\n\n state.pos = state.posMax + 1;\n state.posMax = max;\n return true;\n}\n\n// Process [links]( \"stuff\")\n\n\nfunction links(state, silent) {\n var labelStart,\n labelEnd,\n label,\n href,\n title,\n pos,\n ref,\n code,\n isImage = false,\n oldPos = state.pos,\n max = state.posMax,\n start = state.pos,\n marker = state.src.charCodeAt(start);\n\n if (marker === 0x21/* ! */) {\n isImage = true;\n marker = state.src.charCodeAt(++start);\n }\n\n if (marker !== 0x5B/* [ */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n labelStart = start + 1;\n labelEnd = parseLinkLabel(state, start);\n\n // parser failed to find ']', so it's not a valid link\n if (labelEnd < 0) { return false; }\n\n pos = labelEnd + 1;\n if (pos < max && state.src.charCodeAt(pos) === 0x28/* ( */) {\n //\n // Inline link\n //\n\n // [link]( \"title\" )\n // ^^ skipping these spaces\n pos++;\n for (; pos < max; pos++) {\n code = state.src.charCodeAt(pos);\n if (code !== 0x20 && code !== 0x0A) { break; }\n }\n if (pos >= max) { return false; }\n\n // [link]( \"title\" )\n // ^^^^^^ parsing link destination\n start = pos;\n if (parseLinkDestination(state, pos)) {\n href = state.linkContent;\n pos = state.pos;\n } else {\n href = '';\n }\n\n // [link]( \"title\" )\n // ^^ skipping these spaces\n start = pos;\n for (; pos < max; pos++) {\n code = state.src.charCodeAt(pos);\n if (code !== 0x20 && code !== 0x0A) { break; }\n }\n\n // [link]( \"title\" )\n // ^^^^^^^ parsing link title\n if (pos < max && start !== pos && parseLinkTitle(state, pos)) {\n title = state.linkContent;\n pos = state.pos;\n\n // [link]( \"title\" )\n // ^^ skipping these spaces\n for (; pos < max; pos++) {\n code = state.src.charCodeAt(pos);\n if (code !== 0x20 && code !== 0x0A) { break; }\n }\n } else {\n title = '';\n }\n\n if (pos >= max || state.src.charCodeAt(pos) !== 0x29/* ) */) {\n state.pos = oldPos;\n return false;\n }\n pos++;\n } else {\n //\n // Link reference\n //\n\n // do not allow nested reference links\n if (state.linkLevel > 0) { return false; }\n\n // [foo] [bar]\n // ^^ optional whitespace (can include newlines)\n for (; pos < max; pos++) {\n code = state.src.charCodeAt(pos);\n if (code !== 0x20 && code !== 0x0A) { break; }\n }\n\n if (pos < max && state.src.charCodeAt(pos) === 0x5B/* [ */) {\n start = pos + 1;\n pos = parseLinkLabel(state, pos);\n if (pos >= 0) {\n label = state.src.slice(start, pos++);\n } else {\n pos = start - 1;\n }\n }\n\n // covers label === '' and label === undefined\n // (collapsed reference link and shortcut reference link respectively)\n if (!label) {\n if (typeof label === 'undefined') {\n pos = labelEnd + 1;\n }\n label = state.src.slice(labelStart, labelEnd);\n }\n\n ref = state.env.references[normalizeReference(label)];\n if (!ref) {\n state.pos = oldPos;\n return false;\n }\n href = ref.href;\n title = ref.title;\n }\n\n //\n // We found the end of the link, and know for a fact it's a valid link;\n // so all that's left to do is to call tokenizer.\n //\n if (!silent) {\n state.pos = labelStart;\n state.posMax = labelEnd;\n\n if (isImage) {\n state.push({\n type: 'image',\n src: href,\n title: title,\n alt: state.src.substr(labelStart, labelEnd - labelStart),\n level: state.level\n });\n } else {\n state.push({\n type: 'link_open',\n href: href,\n title: title,\n level: state.level++\n });\n state.linkLevel++;\n state.parser.tokenize(state);\n state.linkLevel--;\n state.push({ type: 'link_close', level: --state.level });\n }\n }\n\n state.pos = pos;\n state.posMax = max;\n return true;\n}\n\n// Process inline footnotes (^[...])\n\n\nfunction footnote_inline(state, silent) {\n var labelStart,\n labelEnd,\n footnoteId,\n oldLength,\n max = state.posMax,\n start = state.pos;\n\n if (start + 2 >= max) { return false; }\n if (state.src.charCodeAt(start) !== 0x5E/* ^ */) { return false; }\n if (state.src.charCodeAt(start + 1) !== 0x5B/* [ */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n labelStart = start + 2;\n labelEnd = parseLinkLabel(state, start + 1);\n\n // parser failed to find ']', so it's not a valid note\n if (labelEnd < 0) { return false; }\n\n // We found the end of the link, and know for a fact it's a valid link;\n // so all that's left to do is to call tokenizer.\n //\n if (!silent) {\n if (!state.env.footnotes) { state.env.footnotes = {}; }\n if (!state.env.footnotes.list) { state.env.footnotes.list = []; }\n footnoteId = state.env.footnotes.list.length;\n\n state.pos = labelStart;\n state.posMax = labelEnd;\n\n state.push({\n type: 'footnote_ref',\n id: footnoteId,\n level: state.level\n });\n state.linkLevel++;\n oldLength = state.tokens.length;\n state.parser.tokenize(state);\n state.env.footnotes.list[footnoteId] = { tokens: state.tokens.splice(oldLength) };\n state.linkLevel--;\n }\n\n state.pos = labelEnd + 1;\n state.posMax = max;\n return true;\n}\n\n// Process footnote references ([^...])\n\nfunction footnote_ref(state, silent) {\n var label,\n pos,\n footnoteId,\n footnoteSubId,\n max = state.posMax,\n start = state.pos;\n\n // should be at least 4 chars - \"[^x]\"\n if (start + 3 > max) { return false; }\n\n if (!state.env.footnotes || !state.env.footnotes.refs) { return false; }\n if (state.src.charCodeAt(start) !== 0x5B/* [ */) { return false; }\n if (state.src.charCodeAt(start + 1) !== 0x5E/* ^ */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n for (pos = start + 2; pos < max; pos++) {\n if (state.src.charCodeAt(pos) === 0x20) { return false; }\n if (state.src.charCodeAt(pos) === 0x0A) { return false; }\n if (state.src.charCodeAt(pos) === 0x5D /* ] */) {\n break;\n }\n }\n\n if (pos === start + 2) { return false; } // no empty footnote labels\n if (pos >= max) { return false; }\n pos++;\n\n label = state.src.slice(start + 2, pos - 1);\n if (typeof state.env.footnotes.refs[':' + label] === 'undefined') { return false; }\n\n if (!silent) {\n if (!state.env.footnotes.list) { state.env.footnotes.list = []; }\n\n if (state.env.footnotes.refs[':' + label] < 0) {\n footnoteId = state.env.footnotes.list.length;\n state.env.footnotes.list[footnoteId] = { label: label, count: 0 };\n state.env.footnotes.refs[':' + label] = footnoteId;\n } else {\n footnoteId = state.env.footnotes.refs[':' + label];\n }\n\n footnoteSubId = state.env.footnotes.list[footnoteId].count;\n state.env.footnotes.list[footnoteId].count++;\n\n state.push({\n type: 'footnote_ref',\n id: footnoteId,\n subId: footnoteSubId,\n level: state.level\n });\n }\n\n state.pos = pos;\n state.posMax = max;\n return true;\n}\n\n// List of valid url schemas, accorting to commonmark spec\n// http://jgm.github.io/CommonMark/spec.html#autolinks\n\nvar url_schemas = [\n 'coap',\n 'doi',\n 'javascript',\n 'aaa',\n 'aaas',\n 'about',\n 'acap',\n 'cap',\n 'cid',\n 'crid',\n 'data',\n 'dav',\n 'dict',\n 'dns',\n 'file',\n 'ftp',\n 'geo',\n 'go',\n 'gopher',\n 'h323',\n 'http',\n 'https',\n 'iax',\n 'icap',\n 'im',\n 'imap',\n 'info',\n 'ipp',\n 'iris',\n 'iris.beep',\n 'iris.xpc',\n 'iris.xpcs',\n 'iris.lwz',\n 'ldap',\n 'mailto',\n 'mid',\n 'msrp',\n 'msrps',\n 'mtqp',\n 'mupdate',\n 'news',\n 'nfs',\n 'ni',\n 'nih',\n 'nntp',\n 'opaquelocktoken',\n 'pop',\n 'pres',\n 'rtsp',\n 'service',\n 'session',\n 'shttp',\n 'sieve',\n 'sip',\n 'sips',\n 'sms',\n 'snmp',\n 'soap.beep',\n 'soap.beeps',\n 'tag',\n 'tel',\n 'telnet',\n 'tftp',\n 'thismessage',\n 'tn3270',\n 'tip',\n 'tv',\n 'urn',\n 'vemmi',\n 'ws',\n 'wss',\n 'xcon',\n 'xcon-userid',\n 'xmlrpc.beep',\n 'xmlrpc.beeps',\n 'xmpp',\n 'z39.50r',\n 'z39.50s',\n 'adiumxtra',\n 'afp',\n 'afs',\n 'aim',\n 'apt',\n 'attachment',\n 'aw',\n 'beshare',\n 'bitcoin',\n 'bolo',\n 'callto',\n 'chrome',\n 'chrome-extension',\n 'com-eventbrite-attendee',\n 'content',\n 'cvs',\n 'dlna-playsingle',\n 'dlna-playcontainer',\n 'dtn',\n 'dvb',\n 'ed2k',\n 'facetime',\n 'feed',\n 'finger',\n 'fish',\n 'gg',\n 'git',\n 'gizmoproject',\n 'gtalk',\n 'hcp',\n 'icon',\n 'ipn',\n 'irc',\n 'irc6',\n 'ircs',\n 'itms',\n 'jar',\n 'jms',\n 'keyparc',\n 'lastfm',\n 'ldaps',\n 'magnet',\n 'maps',\n 'market',\n 'message',\n 'mms',\n 'ms-help',\n 'msnim',\n 'mumble',\n 'mvn',\n 'notes',\n 'oid',\n 'palm',\n 'paparazzi',\n 'platform',\n 'proxy',\n 'psyc',\n 'query',\n 'res',\n 'resource',\n 'rmi',\n 'rsync',\n 'rtmp',\n 'secondlife',\n 'sftp',\n 'sgn',\n 'skype',\n 'smb',\n 'soldat',\n 'spotify',\n 'ssh',\n 'steam',\n 'svn',\n 'teamspeak',\n 'things',\n 'udp',\n 'unreal',\n 'ut2004',\n 'ventrilo',\n 'view-source',\n 'webcal',\n 'wtai',\n 'wyciwyg',\n 'xfire',\n 'xri',\n 'ymsgr'\n];\n\n// Process autolinks ''\n\n\n/*eslint max-len:0*/\nvar EMAIL_RE = /^<([a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/;\nvar AUTOLINK_RE = /^<([a-zA-Z.\\-]{1,25}):([^<>\\x00-\\x20]*)>/;\n\n\nfunction autolink(state, silent) {\n var tail, linkMatch, emailMatch, url, fullUrl, pos = state.pos;\n\n if (state.src.charCodeAt(pos) !== 0x3C/* < */) { return false; }\n\n tail = state.src.slice(pos);\n\n if (tail.indexOf('>') < 0) { return false; }\n\n linkMatch = tail.match(AUTOLINK_RE);\n\n if (linkMatch) {\n if (url_schemas.indexOf(linkMatch[1].toLowerCase()) < 0) { return false; }\n\n url = linkMatch[0].slice(1, -1);\n fullUrl = normalizeLink(url);\n if (!state.parser.validateLink(url)) { return false; }\n\n if (!silent) {\n state.push({\n type: 'link_open',\n href: fullUrl,\n level: state.level\n });\n state.push({\n type: 'text',\n content: url,\n level: state.level + 1\n });\n state.push({ type: 'link_close', level: state.level });\n }\n\n state.pos += linkMatch[0].length;\n return true;\n }\n\n emailMatch = tail.match(EMAIL_RE);\n\n if (emailMatch) {\n\n url = emailMatch[0].slice(1, -1);\n\n fullUrl = normalizeLink('mailto:' + url);\n if (!state.parser.validateLink(fullUrl)) { return false; }\n\n if (!silent) {\n state.push({\n type: 'link_open',\n href: fullUrl,\n level: state.level\n });\n state.push({\n type: 'text',\n content: url,\n level: state.level + 1\n });\n state.push({ type: 'link_close', level: state.level });\n }\n\n state.pos += emailMatch[0].length;\n return true;\n }\n\n return false;\n}\n\n// Regexps to match html elements\n\nfunction replace$1(regex, options) {\n regex = regex.source;\n options = options || '';\n\n return function self(name, val) {\n if (!name) {\n return new RegExp(regex, options);\n }\n val = val.source || val;\n regex = regex.replace(name, val);\n return self;\n };\n}\n\n\nvar attr_name = /[a-zA-Z_:][a-zA-Z0-9:._-]*/;\n\nvar unquoted = /[^\"'=<>`\\x00-\\x20]+/;\nvar single_quoted = /'[^']*'/;\nvar double_quoted = /\"[^\"]*\"/;\n\n/*eslint no-spaced-func:0*/\nvar attr_value = replace$1(/(?:unquoted|single_quoted|double_quoted)/)\n ('unquoted', unquoted)\n ('single_quoted', single_quoted)\n ('double_quoted', double_quoted)\n ();\n\nvar attribute = replace$1(/(?:\\s+attr_name(?:\\s*=\\s*attr_value)?)/)\n ('attr_name', attr_name)\n ('attr_value', attr_value)\n ();\n\nvar open_tag = replace$1(/<[A-Za-z][A-Za-z0-9]*attribute*\\s*\\/?>/)\n ('attribute', attribute)\n ();\n\nvar close_tag = /<\\/[A-Za-z][A-Za-z0-9]*\\s*>/;\nvar comment = /|/;\nvar processing = /<[?].*?[?]>/;\nvar declaration = /]*>/;\nvar cdata = //;\n\nvar HTML_TAG_RE = replace$1(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)\n ('open_tag', open_tag)\n ('close_tag', close_tag)\n ('comment', comment)\n ('processing', processing)\n ('declaration', declaration)\n ('cdata', cdata)\n ();\n\n// Process html tags\n\n\nfunction isLetter$2(ch) {\n /*eslint no-bitwise:0*/\n var lc = ch | 0x20; // to lower case\n return (lc >= 0x61/* a */) && (lc <= 0x7a/* z */);\n}\n\n\nfunction htmltag(state, silent) {\n var ch, match, max, pos = state.pos;\n\n if (!state.options.html) { return false; }\n\n // Check start\n max = state.posMax;\n if (state.src.charCodeAt(pos) !== 0x3C/* < */ ||\n pos + 2 >= max) {\n return false;\n }\n\n // Quick fail on second char\n ch = state.src.charCodeAt(pos + 1);\n if (ch !== 0x21/* ! */ &&\n ch !== 0x3F/* ? */ &&\n ch !== 0x2F/* / */ &&\n !isLetter$2(ch)) {\n return false;\n }\n\n match = state.src.slice(pos).match(HTML_TAG_RE);\n if (!match) { return false; }\n\n if (!silent) {\n state.push({\n type: 'htmltag',\n content: state.src.slice(pos, pos + match[0].length),\n level: state.level\n });\n }\n state.pos += match[0].length;\n return true;\n}\n\n// Process html entity - {, ¯, ", ...\n\n\nvar DIGITAL_RE = /^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i;\nvar NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i;\n\n\nfunction entity(state, silent) {\n var ch, code, match, pos = state.pos, max = state.posMax;\n\n if (state.src.charCodeAt(pos) !== 0x26/* & */) { return false; }\n\n if (pos + 1 < max) {\n ch = state.src.charCodeAt(pos + 1);\n\n if (ch === 0x23 /* # */) {\n match = state.src.slice(pos).match(DIGITAL_RE);\n if (match) {\n if (!silent) {\n code = match[1][0].toLowerCase() === 'x' ? parseInt(match[1].slice(1), 16) : parseInt(match[1], 10);\n state.pending += isValidEntityCode(code) ? fromCodePoint(code) : fromCodePoint(0xFFFD);\n }\n state.pos += match[0].length;\n return true;\n }\n } else {\n match = state.src.slice(pos).match(NAMED_RE);\n if (match) {\n var decoded = decodeEntity(match[1]);\n if (match[1] !== decoded) {\n if (!silent) { state.pending += decoded; }\n state.pos += match[0].length;\n return true;\n }\n }\n }\n }\n\n if (!silent) { state.pending += '&'; }\n state.pos++;\n return true;\n}\n\n/**\n * Inline Parser `rules`\n */\n\nvar _rules$2 = [\n [ 'text', text ],\n [ 'newline', newline ],\n [ 'escape', escape ],\n [ 'backticks', backticks ],\n [ 'del', del ],\n [ 'ins', ins ],\n [ 'mark', mark ],\n [ 'emphasis', emphasis ],\n [ 'sub', sub ],\n [ 'sup', sup ],\n [ 'links', links ],\n [ 'footnote_inline', footnote_inline ],\n [ 'footnote_ref', footnote_ref ],\n [ 'autolink', autolink ],\n [ 'htmltag', htmltag ],\n [ 'entity', entity ]\n];\n\n/**\n * Inline Parser class. Note that link validation is stricter\n * in Remarkable than what is specified by CommonMark. If you\n * want to change this you can use a custom validator.\n *\n * @api private\n */\n\nfunction ParserInline() {\n this.ruler = new Ruler();\n for (var i = 0; i < _rules$2.length; i++) {\n this.ruler.push(_rules$2[i][0], _rules$2[i][1]);\n }\n\n // Can be overridden with a custom validator\n this.validateLink = validateLink;\n}\n\n/**\n * Skip a single token by running all rules in validation mode.\n * Returns `true` if any rule reports success.\n *\n * @param {Object} `state`\n * @api privage\n */\n\nParserInline.prototype.skipToken = function (state) {\n var rules = this.ruler.getRules('');\n var len = rules.length;\n var pos = state.pos;\n var i, cached_pos;\n\n if ((cached_pos = state.cacheGet(pos)) > 0) {\n state.pos = cached_pos;\n return;\n }\n\n for (i = 0; i < len; i++) {\n if (rules[i](state, true)) {\n state.cacheSet(pos, state.pos);\n return;\n }\n }\n\n state.pos++;\n state.cacheSet(pos, state.pos);\n};\n\n/**\n * Generate tokens for the given input range.\n *\n * @param {Object} `state`\n * @api private\n */\n\nParserInline.prototype.tokenize = function (state) {\n var rules = this.ruler.getRules('');\n var len = rules.length;\n var end = state.posMax;\n var ok, i;\n\n while (state.pos < end) {\n\n // Try all possible rules.\n // On success, the rule should:\n //\n // - update `state.pos`\n // - update `state.tokens`\n // - return true\n for (i = 0; i < len; i++) {\n ok = rules[i](state, false);\n\n if (ok) {\n break;\n }\n }\n\n if (ok) {\n if (state.pos >= end) { break; }\n continue;\n }\n\n state.pending += state.src[state.pos++];\n }\n\n if (state.pending) {\n state.pushPending();\n }\n};\n\n/**\n * Parse the given input string.\n *\n * @param {String} `str`\n * @param {Object} `options`\n * @param {Object} `env`\n * @param {Array} `outTokens`\n * @api private\n */\n\nParserInline.prototype.parse = function (str, options, env, outTokens) {\n var state = new StateInline(str, this, options, env, outTokens);\n this.tokenize(state);\n};\n\n/**\n * Validate the given `url` by checking for bad protocols.\n *\n * @param {String} `url`\n * @return {Boolean}\n */\n\nfunction validateLink(url) {\n var BAD_PROTOCOLS = [ 'vbscript', 'javascript', 'file', 'data' ];\n var str = url.trim().toLowerCase();\n // Care about digital entities \"javascript:alert(1)\"\n str = replaceEntities(str);\n if (str.indexOf(':') !== -1 && BAD_PROTOCOLS.indexOf(str.split(':')[0]) !== -1) {\n return false;\n }\n return true;\n}\n\n// Remarkable default options\n\nvar defaultConfig = {\n options: {\n html: false, // Enable HTML tags in source\n xhtmlOut: false, // Use '/' to close single tags (
    )\n breaks: false, // Convert '\\n' in paragraphs into
    \n langPrefix: 'language-', // CSS language prefix for fenced blocks\n linkTarget: '', // set target to open link in\n\n // Enable some language-neutral replacements + quotes beautification\n typographer: false,\n\n // Double + single quotes replacement pairs, when typographer enabled,\n // and smartquotes on. Set doubles to '«»' for Russian, '„“' for German.\n quotes: '“”‘’',\n\n // Highlighter function. Should return escaped HTML,\n // or '' if input not changed\n //\n // function (/*str, lang*/) { return ''; }\n //\n highlight: null,\n\n maxNesting: 20 // Internal protection, recursion limit\n },\n\n components: {\n\n core: {\n rules: [\n 'block',\n 'inline',\n 'references',\n 'replacements',\n 'smartquotes',\n 'references',\n 'abbr2',\n 'footnote_tail'\n ]\n },\n\n block: {\n rules: [\n 'blockquote',\n 'code',\n 'fences',\n 'footnote',\n 'heading',\n 'hr',\n 'htmlblock',\n 'lheading',\n 'list',\n 'paragraph',\n 'table'\n ]\n },\n\n inline: {\n rules: [\n 'autolink',\n 'backticks',\n 'del',\n 'emphasis',\n 'entity',\n 'escape',\n 'footnote_ref',\n 'htmltag',\n 'links',\n 'newline',\n 'text'\n ]\n }\n }\n};\n\n// Remarkable default options\n\nvar fullConfig = {\n options: {\n html: false, // Enable HTML tags in source\n xhtmlOut: false, // Use '/' to close single tags (
    )\n breaks: false, // Convert '\\n' in paragraphs into
    \n langPrefix: 'language-', // CSS language prefix for fenced blocks\n linkTarget: '', // set target to open link in\n\n // Enable some language-neutral replacements + quotes beautification\n typographer: false,\n\n // Double + single quotes replacement pairs, when typographer enabled,\n // and smartquotes on. Set doubles to '«»' for Russian, '„“' for German.\n quotes: '“”‘’',\n\n // Highlighter function. Should return escaped HTML,\n // or '' if input not changed\n //\n // function (/*str, lang*/) { return ''; }\n //\n highlight: null,\n\n maxNesting: 20 // Internal protection, recursion limit\n },\n\n components: {\n // Don't restrict core/block/inline rules\n core: {},\n block: {},\n inline: {}\n }\n};\n\n// Commonmark default options\n\nvar commonmarkConfig = {\n options: {\n html: true, // Enable HTML tags in source\n xhtmlOut: true, // Use '/' to close single tags (
    )\n breaks: false, // Convert '\\n' in paragraphs into
    \n langPrefix: 'language-', // CSS language prefix for fenced blocks\n linkTarget: '', // set target to open link in\n\n // Enable some language-neutral replacements + quotes beautification\n typographer: false,\n\n // Double + single quotes replacement pairs, when typographer enabled,\n // and smartquotes on. Set doubles to '«»' for Russian, '„“' for German.\n quotes: '“”‘’',\n\n // Highlighter function. Should return escaped HTML,\n // or '' if input not changed\n //\n // function (/*str, lang*/) { return ''; }\n //\n highlight: null,\n\n maxNesting: 20 // Internal protection, recursion limit\n },\n\n components: {\n\n core: {\n rules: [\n 'block',\n 'inline',\n 'references',\n 'abbr2'\n ]\n },\n\n block: {\n rules: [\n 'blockquote',\n 'code',\n 'fences',\n 'heading',\n 'hr',\n 'htmlblock',\n 'lheading',\n 'list',\n 'paragraph'\n ]\n },\n\n inline: {\n rules: [\n 'autolink',\n 'backticks',\n 'emphasis',\n 'entity',\n 'escape',\n 'htmltag',\n 'links',\n 'newline',\n 'text'\n ]\n }\n }\n};\n\n/**\n * Preset configs\n */\n\nvar config = {\n 'default': defaultConfig,\n 'full': fullConfig,\n 'commonmark': commonmarkConfig\n};\n\n/**\n * The `StateCore` class manages state.\n *\n * @param {Object} `instance` Remarkable instance\n * @param {String} `str` Markdown string\n * @param {Object} `env`\n */\n\nfunction StateCore(instance, str, env) {\n this.src = str;\n this.env = env;\n this.options = instance.options;\n this.tokens = [];\n this.inlineMode = false;\n\n this.inline = instance.inline;\n this.block = instance.block;\n this.renderer = instance.renderer;\n this.typographer = instance.typographer;\n}\n\n/**\n * The main `Remarkable` class. Create an instance of\n * `Remarkable` with a `preset` and/or `options`.\n *\n * @param {String} `preset` If no preset is given, `default` is used.\n * @param {Object} `options`\n */\n\nfunction Remarkable(preset, options) {\n if (typeof preset !== 'string') {\n options = preset;\n preset = 'default';\n }\n\n if (options && options.linkify != null) {\n console.warn(\n 'linkify option is removed. Use linkify plugin instead:\\n\\n' +\n 'import Remarkable from \\'remarkable\\';\\n' +\n 'import linkify from \\'remarkable/linkify\\';\\n' +\n 'new Remarkable().use(linkify)\\n'\n );\n }\n\n this.inline = new ParserInline();\n this.block = new ParserBlock();\n this.core = new Core();\n this.renderer = new Renderer();\n this.ruler = new Ruler();\n\n this.options = {};\n this.configure(config[preset]);\n this.set(options || {});\n}\n\n/**\n * Set options as an alternative to passing them\n * to the constructor.\n *\n * ```js\n * md.set({typographer: true});\n * ```\n * @param {Object} `options`\n * @api public\n */\n\nRemarkable.prototype.set = function (options) {\n assign(this.options, options);\n};\n\n/**\n * Batch loader for components rules states, and options\n *\n * @param {Object} `presets`\n */\n\nRemarkable.prototype.configure = function (presets) {\n var self = this;\n\n if (!presets) { throw new Error('Wrong `remarkable` preset, check name/content'); }\n if (presets.options) { self.set(presets.options); }\n if (presets.components) {\n Object.keys(presets.components).forEach(function (name) {\n if (presets.components[name].rules) {\n self[name].ruler.enable(presets.components[name].rules, true);\n }\n });\n }\n};\n\n/**\n * Use a plugin.\n *\n * ```js\n * var md = new Remarkable();\n *\n * md.use(plugin1)\n * .use(plugin2, opts)\n * .use(plugin3);\n * ```\n *\n * @param {Function} `plugin`\n * @param {Object} `options`\n * @return {Object} `Remarkable` for chaining\n */\n\nRemarkable.prototype.use = function (plugin, options) {\n plugin(this, options);\n return this;\n};\n\n\n/**\n * Parse the input `string` and return a tokens array.\n * Modifies `env` with definitions data.\n *\n * @param {String} `string`\n * @param {Object} `env`\n * @return {Array} Array of tokens\n */\n\nRemarkable.prototype.parse = function (str, env) {\n var state = new StateCore(this, str, env);\n this.core.process(state);\n return state.tokens;\n};\n\n/**\n * The main `.render()` method that does all the magic :)\n *\n * @param {String} `string`\n * @param {Object} `env`\n * @return {String} Rendered HTML.\n */\n\nRemarkable.prototype.render = function (str, env) {\n env = env || {};\n return this.renderer.render(this.parse(str, env), this.options, env);\n};\n\n/**\n * Parse the given content `string` as a single string.\n *\n * @param {String} `string`\n * @param {Object} `env`\n * @return {Array} Array of tokens\n */\n\nRemarkable.prototype.parseInline = function (str, env) {\n var state = new StateCore(this, str, env);\n state.inlineMode = true;\n this.core.process(state);\n return state.tokens;\n};\n\n/**\n * Render a single content `string`, without wrapping it\n * to paragraphs\n *\n * @param {String} `str`\n * @param {Object} `env`\n * @return {String}\n */\n\nRemarkable.prototype.renderInline = function (str, env) {\n env = env || {};\n return this.renderer.render(this.parseInline(str, env), this.options, env);\n};\n\nexport { Remarkable, utils };\n","import { html, TemplateResult } from 'lit';\nimport { unsafeHTML } from 'lit-html/directives/unsafe-html.js';\nimport {\n directive,\n Directive,\n Part,\n PartInfo,\n PartType,\n} from 'lit/directive.js';\nimport ExcellentParser, { Expression } from './ExcellentParser';\nimport {\n CompletionOption,\n CompletionProperty,\n CompletionResult,\n CompletionSchema,\n CompletionType,\n KeyedAssets,\n} from '../interfaces';\nimport { Store } from '../store/Store';\nimport { Remarkable } from 'remarkable';\n\nconst md = new Remarkable();\n\nconst messageParser = new ExcellentParser('@', [\n 'contact',\n 'fields',\n 'globals',\n 'urns',\n]);\n\nconst sessionParser = new ExcellentParser('@', [\n 'contact',\n 'fields',\n 'globals',\n 'urns',\n 'results',\n 'input',\n 'run',\n 'child',\n 'parent',\n 'node',\n 'webhook',\n 'ticket',\n 'trigger',\n 'resume',\n]);\n\n// Class-based directive API\nexport class RenderMarkdown extends Directive {\n // State stored in class field\n value: string | undefined;\n constructor(partInfo: PartInfo) {\n super(partInfo);\n // When necessary, validate part in constructor using `part.type`\n if (partInfo.type !== PartType.CHILD) {\n throw new Error('renderMarkdown only supports child expressions');\n }\n }\n // Optional: override update to perform any direct DOM manipulation\n // DirectiveParameters\n update(part: Part, [initialValue]: any) {\n /* Any imperative updates to DOM/parts would go here */\n return this.render(initialValue);\n }\n // Do SSR-compatible rendering (arguments are passed from call site)\n render(initialValue: string) {\n // Previous state available on class field\n if (this.value === undefined) {\n this.value = initialValue;\n }\n return html`${unsafeHTML(md.render(this.value))}`;\n }\n}\n\nexport const renderMarkdown = directive(RenderMarkdown);\n\nexport const renderCompletionOption = (\n option: CompletionOption,\n selected: boolean\n): TemplateResult => {\n if (option.signature) {\n const argStart = option.signature.indexOf('(');\n const name = option.signature.substr(0, argStart);\n const args = option.signature.substr(argStart);\n\n return html`\n
    \n
    ƒ
    \n
    ${name}
    \n ${selected\n ? html`\n \n ${args}\n
    \n
    ${renderMarkdown(option.summary)}
    \n `\n : null}\n \n `;\n }\n\n return html`\n
    \n
    ${option.name}
    \n ${selected\n ? html`
    ${option.summary}
    `\n : null}\n
    \n `;\n};\n\nexport const getFunctions = (\n functions: CompletionOption[],\n query: string\n): CompletionOption[] => {\n if (!query) {\n return functions;\n }\n return functions.filter((option: CompletionOption) => {\n if (option.signature) {\n return option.signature.indexOf((query || '').toLowerCase()) === 0;\n }\n return false;\n });\n};\n\n/**\n * Takes a dot query and returns the completions options at the current level\n * @param dotQuery query such as \"contact.first_n\"\n */\nexport const getCompletions = (\n schema: CompletionSchema,\n dotQuery: string,\n keyedAssets: KeyedAssets = {},\n session: boolean\n): CompletionOption[] => {\n const parts = (dotQuery || '').split('.');\n let currentProps: CompletionProperty[] = session\n ? schema.root\n : schema.root_no_session;\n\n if (!currentProps) {\n return [];\n }\n\n let prefix = '';\n let part = '';\n while (parts.length > 0) {\n part = parts.shift();\n if (part) {\n // eslint-disable-next-line\n const nextProp = currentProps.find(\n (prop: CompletionProperty) => prop.key === part\n );\n if (nextProp) {\n // eslint-disable-next-line\n const nextType = schema.types.find(\n (type: CompletionType) => type.name === nextProp.type\n );\n if (nextType && nextType.properties) {\n currentProps = nextType.properties;\n prefix += part + '.';\n } else if (nextType && nextType.property_template) {\n prefix += part + '.';\n const template = nextType.property_template;\n if (keyedAssets[nextType.name]) {\n currentProps = keyedAssets[nextType.name].map((key: string) => ({\n key: template.key.replace('{key}', key),\n help: template.help.replace('{key}', key),\n type: template.type,\n }));\n } else {\n currentProps = [];\n }\n } else {\n // eslint-disable-next-line\n currentProps = currentProps.filter((prop: CompletionProperty) =>\n prop.key.startsWith(part.toLowerCase())\n );\n break;\n }\n } else {\n // eslint-disable-next-line\n currentProps = currentProps.filter((prop: CompletionProperty) =>\n prop.key.startsWith(part.toLowerCase())\n );\n break;\n }\n }\n }\n\n return currentProps.map((prop: CompletionProperty) => {\n const name =\n prop.key === '__default__'\n ? prefix.substr(0, prefix.length - 1)\n : prefix + prop.key;\n return { name, summary: prop.help };\n });\n};\n\nexport const getOffset = (el: HTMLElement) => {\n const rect = el.getBoundingClientRect(),\n scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,\n scrollTop = window.pageYOffset || document.documentElement.scrollTop;\n return { top: rect.top + scrollTop, left: rect.left + scrollLeft };\n};\n\nexport const getVerticalScroll = (ele: Node) => {\n let current = ele;\n const verticalScroll = 0;\n while (current) {\n current = current.parentNode;\n }\n return verticalScroll;\n};\n\nexport const getCompletionName = (option: CompletionOption): string => {\n return (\n option.name || option.signature.substr(0, option.signature.indexOf('('))\n );\n};\n\nexport const getCompletionSignature = (option: CompletionOption): string => {\n return option.signature.substr(option.signature.indexOf('('));\n};\n\n/**\n * Determines the pixel position of position inside a textarea or input\n * TODO: Explore somethign like contenteditable to avoid this madness\n * see: https://jh3y.medium.com/how-to-where-s-the-caret-getting-the-xy-position-of-the-caret-a24ba372990a\n */\nconst getCursorXY = (input, selectionPoint) => {\n const { offsetLeft: inputX, offsetTop: inputY } = input;\n const div = document.createElement('div');\n const copyStyle = getComputedStyle(input);\n for (const prop of copyStyle) {\n div.style[prop] = copyStyle[prop];\n }\n div.style.position = 'relative';\n const swap = '.';\n const inputValue =\n input.tagName === 'INPUT' ? input.value.replace(/ /g, swap) : input.value;\n const textContent = inputValue.substr(0, selectionPoint);\n div.textContent = textContent;\n if (input.tagName === 'TEXTAREA') div.style.height = 'auto';\n if (input.tagName === 'INPUT') div.style.width = 'auto';\n const span = document.createElement('span');\n span.textContent = inputValue.substr(selectionPoint) || '.';\n div.appendChild(span);\n document.body.appendChild(div);\n const { offsetLeft: spanX, offsetTop: spanY } = span;\n document.body.removeChild(div);\n return {\n left: inputX + spanX,\n top: inputY + spanY,\n };\n};\n\nexport const updateInputElementWithCompletion = (\n currentQuery: string,\n ele: HTMLInputElement,\n option: CompletionOption\n) => {\n let insertText = '';\n\n if (option.signature) {\n // they selected a function\n insertText = option.signature.substr(0, option.signature.indexOf('(') + 1);\n } else {\n insertText = option.name;\n }\n\n const queryLength = currentQuery.length;\n\n if (ele) {\n const value = ele.value;\n const insertionPoint = ele.selectionStart - queryLength;\n\n // strip out our query\n // const insertionPoint = value.lastIndexOf(value.substring(0, this.inputElement.selectionStart));\n const leftSide = value.substr(0, insertionPoint);\n const remaining = value.substr(insertionPoint + queryLength);\n const caret = leftSide.length + insertText.length;\n\n // set our value and our new caret\n ele.value = leftSide + insertText + remaining;\n ele.setSelectionRange(caret, caret);\n\n // now scroll our text box if necessary\n const position = getCursorXY(ele, caret);\n if (position.left > ele.width) {\n ele.scrollLeft = position.left;\n }\n\n ele.dispatchEvent(new Event('input'));\n }\n};\n\nexport const executeCompletionQuery = (\n ele: HTMLInputElement,\n store: Store,\n session: boolean\n): CompletionResult => {\n const result: CompletionResult = {\n currentFunction: null,\n options: [],\n anchorPosition: null,\n query: null,\n };\n\n if (!ele) {\n return;\n }\n\n // we need a store to do anything useful\n if (!store) {\n return result;\n }\n\n const cursor = ele.selectionStart;\n const input = ele.value.substring(0, cursor);\n\n const parser = session ? sessionParser : messageParser;\n const expressions = parser.findExpressions(input);\n const currentExpression = expressions.find(\n (expr: Expression) =>\n expr.start <= cursor &&\n (expr.end > cursor || (expr.end === cursor && !expr.closed))\n );\n\n if (currentExpression) {\n const includeFunctions = currentExpression.text.indexOf('(') > -1;\n if (includeFunctions) {\n const functionQuery = parser.functionContext(currentExpression.text);\n if (functionQuery) {\n const fns = getFunctions(store.getFunctions(), functionQuery);\n if (fns.length > 0) {\n result.currentFunction = fns[0];\n }\n }\n }\n\n for (let i = currentExpression.text.length; i >= 0; i--) {\n const curr = currentExpression.text[i];\n if (\n curr === '@' ||\n curr === '(' ||\n curr === ' ' ||\n curr === ',' ||\n curr === ')' ||\n i === 0\n ) {\n // don't include non-expression chars\n if (\n curr === '(' ||\n curr === ' ' ||\n curr === ',' ||\n curr === ')' ||\n curr === '@'\n ) {\n i++;\n }\n\n const caret = getCursorXY(ele, currentExpression.start + i);\n\n result.anchorPosition = {\n left: caret.left - 2 - ele.scrollLeft,\n top: caret.top - ele.scrollTop,\n };\n\n result.query = currentExpression.text.substr(\n i,\n currentExpression.text.length - i\n );\n\n result.options = [\n ...getCompletions(\n store.getCompletionSchema(),\n result.query,\n store.getKeyedAssets(),\n session\n ),\n ...(includeFunctions\n ? getFunctions(store.getFunctions(), result.query)\n : []),\n ];\n\n return result;\n }\n }\n } else {\n result.options = [];\n result.query = '';\n }\n return result;\n};\n","/* eslint-disable @typescript-eslint/no-empty-function */\nimport { TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport {\n getUrl,\n getClasses,\n fetchResults,\n WebResponse,\n postJSON,\n} from '../utils';\nimport '../options/Options';\nimport { EventHandler } from '../RapidElement';\nimport { FormElement } from '../FormElement';\n\nimport { lru } from 'tiny-lru';\nimport { CompletionOption, CustomEventType, Position } from '../interfaces';\nimport {\n renderCompletionOption,\n updateInputElementWithCompletion,\n executeCompletionQuery,\n} from '../completion/helpers';\nimport { Store } from '../store/Store';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { Icon } from '../vectoricon';\nimport { msg } from '@lit/localize';\n\nconst LOOK_AHEAD = 20;\n\nexport class Select extends FormElement {\n private hiddenInputs: HTMLInputElement[] = [];\n\n static get styles() {\n return css`\n :host {\n font-family: var(--font-family);\n transition: all ease-in-out var(--transition-speed);\n display: inline;\n line-height: normal;\n outline: none;\n position: relative;\n --icon-color: var(--color-text-dark-secondary);\n }\n\n temba-options {\n --temba-options-font-size: var(--temba-select-selected-font-size);\n --icon-color: var(--color-text-dark);\n }\n\n :host:focus {\n outline: none;\n }\n\n #anchor {\n position: absolute;\n visibility: hidden;\n width: 250px;\n height: 25px;\n }\n\n .remove-item {\n cursor: pointer;\n display: inline-block;\n padding: 3px 6px;\n border-right: 1px solid rgba(100, 100, 100, 0.2);\n margin: 0;\n background: rgba(100, 100, 100, 0.05);\n }\n\n .selected-item.multi .remove-item {\n display: none;\n }\n\n .remove-item:hover {\n background: rgba(100, 100, 100, 0.1);\n }\n\n input:focus {\n outline: none;\n box-shadow: none;\n cursor: text;\n }\n\n .wrapper-bg {\n background: #f3f3f3;\n box-shadow: inset 0px 0px 4px rgb(0 0 0 / 10%);\n border-radius: var(--curvature-widget);\n }\n\n .select-container {\n display: flex;\n flex-direction: row;\n flex-wrap: nowrap;\n align-items: center;\n border: 1px solid var(--color-widget-border);\n transition: all ease-in-out var(--transition-speed);\n cursor: pointer;\n border-radius: var(--curvature-widget);\n background: var(--color-widget-bg);\n padding-top: 1px;\n box-shadow: var(--widget-box-shadow);\n position: relative;\n }\n\n temba-icon.select-open:hover,\n .clear-button:hover {\n --icon-color: var(--color-text-dark);\n }\n\n .select-container:focus {\n outline: none;\n }\n\n .select-container.multi {\n /* background: var(--color-widget-bg); */\n }\n\n .select-container.focused {\n background: var(--color-widget-bg-focused);\n border-color: var(--color-focus);\n box-shadow: var(--widget-box-shadow-focused);\n }\n\n .left-side {\n flex: 1;\n overflow: hidden;\n }\n\n .empty .placeholder {\n display: block;\n }\n\n .selected {\n display: flex;\n flex-direction: row;\n align-items: stretch;\n user-select: none;\n padding: var(--temba-select-selected-padding);\n }\n\n .searchable .selected {\n padding: 4px !important;\n }\n\n .multi .selected {\n flex-wrap: wrap;\n padding: 4px;\n }\n\n .multi.empty .selected {\n padding: var(--temba-select-selected-padding);\n }\n\n .selected .selected-item {\n display: flex;\n overflow: hidden;\n color: var(--color-widget-text);\n line-height: var(--temba-select-selected-line-height);\n --icon-color: var(--color-text-dark);\n }\n\n .multi .selected .selected-item {\n vertical-align: middle;\n background: rgba(100, 100, 100, 0.1);\n user-select: none;\n border-radius: 2px;\n align-items: stretch;\n flex-direction: row;\n flex-wrap: nowrap;\n margin: 2px 2px;\n }\n\n .selected-item .option-name {\n padding: 0px;\n font-size: var(--temba-select-selected-font-size);\n align-self: center;\n }\n\n .multi .selected-item .option-name {\n flex: 1 1 auto;\n align-self: center;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n font-size: 12px;\n padding: 2px 8px;\n }\n\n .multi .selected .selected-item.focused {\n background: rgba(100, 100, 100, 0.3);\n }\n\n input {\n font-size: 13px;\n width: 0px;\n cursor: pointer;\n background: none;\n resize: none;\n border: none !important;\n visibility: visible;\n line-height: inherit !important;\n height: var(--search-input-height) !important;\n margin: 0px !important;\n padding: 0px !important;\n box-shadow: none !important;\n font-family: var(--font-family);\n caret-color: var(--input-caret);\n }\n\n input:focus {\n box-shadow: none !important;\n }\n\n .searchable.no-search-input .input-wrapper {\n flex-grow: inherit;\n min-width: 1px;\n }\n\n .searchable.no-search-input.empty .input-wrapper {\n flex-grow: 1;\n min-width: 1px;\n }\n\n .searchable.no-search-input .input-wrapper .searchbox {\n flex-grow: inherit;\n min-width: 1px;\n }\n\n .searchable .input-wrapper .searchbox {\n flex-grow: 1;\n min-width: 80%;\n height: 100%;\n }\n\n .searchable.single.search-input .selected .selected-item {\n display: none;\n }\n\n .searchable.single.no-search-input\n .selected\n .input-wrapper\n input.searchbox {\n padding: 6px 2px !important;\n }\n\n .searchable.single.no-search-input.empty\n .selected\n .input-wrapper\n input.searchbox {\n padding: 6px 6px !important;\n }\n\n .empty input {\n width: 100%;\n }\n\n .searchable input {\n padding: 6px 4px !important;\n }\n\n .searchable input {\n font-weight: 300;\n visibility: visible;\n cursor: pointer;\n background: none;\n color: var(--color-text);\n resize: none;\n box-shadow: none !important;\n flex-grow: 1;\n border: none;\n caret-color: var(--input-caret);\n }\n\n .searchable input:focus {\n box-shadow: none !important;\n }\n\n .input-wrapper {\n flex-grow: 1;\n }\n\n .input-wrapper .searchbox {\n }\n\n .searchbox {\n border: 0px;\n }\n\n .searchbox::placeholder {\n color: var(--color-placeholder);\n font-weight: 300;\n font-size: 1em;\n line-height: var(--temba-select-selected-line-height);\n padding-left: 1px;\n }\n\n .placeholder {\n font-size: var(--temba-select-selected-font-size);\n color: var(--color-placeholder);\n display: none;\n font-weight: 300;\n line-height: var(--temba-select-selected-line-height);\n }\n\n .footer {\n padding: 5px 10px;\n background: var(--color-primary-light);\n color: rgba(0, 0, 0, 0.5);\n font-size: 80%;\n border-bottom-left-radius: var(--curvature-widget);\n border-bottom-right-radius: var(--curvature-widget);\n }\n\n .small {\n --temba-select-selected-padding: 7px;\n --temba-select-selected-line-height: 13px;\n --temba-select-selected-font-size: 12px;\n --search-input-height: 7px !important;\n }\n\n .info-text {\n opacity: 1;\n transition: padding-top var(--transition-speed) ease-in-out,\n padding-bottom var(--transition-speed) ease-in-out;\n margin-bottom: 16px;\n padding: 0.5em 1em;\n border-radius: var(--curvature);\n font-size: 0.9em;\n color: rgba(0, 0, 0, 0.5);\n position: relative;\n }\n\n .info-text.focused {\n opacity: 1;\n }\n\n .info-text.hide {\n opacity: 0;\n max-height: 0;\n margin-bottom: 0px;\n pointer-events: none;\n padding: 0px;\n }\n `;\n }\n\n @property({ type: Boolean })\n multi = false;\n\n @property({ type: Boolean })\n searchOnFocus = false;\n\n @property({ type: String })\n placeholder = '';\n\n @property()\n name = '';\n\n @property()\n endpoint: string;\n\n @property({ type: String })\n nameKey = 'name';\n\n @property({ type: String })\n valueKey = 'value';\n\n @property({ attribute: false })\n currentFunction: CompletionOption;\n\n @property({ type: String })\n queryParam: string = null;\n\n @property({ type: String })\n input = '';\n\n @property({ type: Array })\n visibleOptions: any[] = [];\n\n @property({ type: Array })\n completionOptions: CompletionOption[] = [];\n\n @property({ type: Number })\n quietMillis = 0;\n\n @property({ type: Boolean })\n fetching: boolean;\n\n @property({ type: Boolean })\n searchable = false;\n\n @property({ type: String })\n expressions: string;\n\n @property({ type: Boolean })\n cache = true;\n\n @property({ type: String })\n cacheKey = '';\n\n @property({ type: Boolean })\n focused = false;\n\n @property({ type: Boolean })\n disabled = false;\n\n @property({ attribute: false })\n selectedIndex = -1;\n\n @property({ type: Number })\n cursorIndex: number;\n\n @property({ attribute: false })\n anchorElement: HTMLElement;\n\n @property({ attribute: false })\n anchorExpressions: HTMLElement;\n\n @property({ type: Object })\n anchorPosition: Position = { left: 0, top: 0 };\n\n @property({ type: Boolean })\n tags = false;\n\n @property({ type: Boolean, attribute: 'space_select' })\n spaceSelect: boolean;\n\n @property({ type: Boolean })\n jsonValue: boolean;\n\n @property({ type: Boolean })\n hideErrors: boolean;\n\n @property({ type: Boolean })\n clearable: boolean;\n\n @property({ type: String })\n flavor = 'default';\n\n @property({ type: String, attribute: 'info_text' })\n infoText = '';\n\n @property({ type: Array })\n values: any[] = [];\n\n @property({ type: Object })\n selection: any;\n\n @property({ attribute: false })\n getName: (option: any) => string = (option: any) =>\n option[this.nameKey || 'name'];\n\n @property({ attribute: false })\n isMatch: (option: any, q: string) => boolean = (option: any, q: string) => {\n const name = this.getName(option) || '';\n return name.toLowerCase().indexOf(q) > -1;\n };\n\n @property({ attribute: false })\n getValue: (option: any) => string = (option: any) =>\n option[this.valueKey || 'value'] || option.id;\n\n @property({ type: Number, attribute: 'option-width' })\n optionWidth: number;\n\n @property({ type: Boolean, attribute: 'anchor-right' })\n anchorRight: boolean;\n\n @property({ attribute: false })\n shouldExclude: (option: any) => boolean;\n\n @property({ attribute: false })\n sortFunction: (a: any, b: any) => number;\n\n @property({ attribute: false })\n renderOption: (option: any, selected: boolean) => TemplateResult;\n\n @property({ attribute: false })\n renderOptionName: (option: any, selected: boolean) => TemplateResult;\n\n @property({ attribute: false })\n renderOptionDetail: (option: any, selected: boolean) => TemplateResult = () =>\n html``;\n\n @property({ attribute: false })\n renderSelectedItem: (option: any) => TemplateResult =\n this.renderSelectedItemDefault;\n\n @property({ attribute: false })\n createArbitraryOption: (input: string, options: any[]) => any =\n this.createArbitraryOptionDefault;\n\n @property({ attribute: false })\n getOptions: (response: WebResponse) => any[] = this.getOptionsDefault;\n\n @property({ attribute: false })\n isComplete: (newestOptions: any[], response: WebResponse) => boolean =\n this.isCompleteDefault;\n\n @property({ type: Array, attribute: 'options' })\n private staticOptions: any[] = [];\n\n private lastQuery: number;\n\n // private cancelToken: CancelTokenSource;\n private complete: boolean;\n private page: number;\n private next: string = null;\n private query: string;\n\n private removingSelection: boolean;\n\n private lruCache = lru(20, 60000);\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n if (changedProperties.has('values')) {\n this.updateInputs();\n if (\n this.multi ||\n this.values.length === 1 ||\n // fire change if being cleared\n (this.values.length == 0 &&\n changedProperties.get('values') &&\n changedProperties.get('values').length > 0)\n ) {\n this.fireEvent('change');\n }\n }\n\n // if our cache key changes, clear it out\n if (changedProperties.has('cacheKey')) {\n this.lruCache.clear();\n }\n\n if (\n changedProperties.has('input') &&\n !changedProperties.has('values') &&\n !changedProperties.has('options') &&\n this.focused\n ) {\n if (this.lastQuery) {\n window.clearTimeout(this.lastQuery);\n }\n\n this.lastQuery = window.setTimeout(() => {\n if (this.expressions && this.input.indexOf('@') > -1) {\n this.fetchExpressions();\n } else {\n this.fetchOptions(this.input);\n }\n }, this.quietMillis);\n }\n\n if (this.endpoint && changedProperties.has('fetching')) {\n if (!this.fetching && !this.isPastFetchThreshold()) {\n this.fireCustomEvent(CustomEventType.FetchComplete);\n }\n }\n\n // if our cursor changed, lets make sure our scrollbox is showing it\n if (\n (changedProperties.has('cursorIndex') ||\n changedProperties.has('visibleOptions')) &&\n this.endpoint &&\n !this.fetching\n ) {\n if (this.isPastFetchThreshold()) {\n this.fetchOptions(this.query, this.page + 1);\n }\n }\n\n // if they set an inital value, look through our static options for it\n if (changedProperties.has('value') && this.value && !this.values.length) {\n if (this.staticOptions.length > 0) {\n const existing = this.staticOptions.find(option => {\n return this.getValue(option) === this.value;\n });\n\n if (existing) {\n this.setValues([existing]);\n }\n }\n }\n\n // default to the first option if we don't have a placeholder\n if (\n this.values.length === 0 &&\n !this.placeholder &&\n this.staticOptions.length > 0\n ) {\n this.setValues([this.staticOptions[0]]);\n }\n }\n\n private updateInputs(): void {\n for (let ele = null; (ele = this.hiddenInputs.pop()); ) {\n ele.remove();\n }\n\n if (this.values.length === 0) {\n this.value = null;\n } else {\n const name = this.getAttribute('name');\n\n if (name) {\n if (!this.multi && this.values.length === 1) {\n this.selection = this.values[0];\n this.value = this.serializeValue(this.values[0]);\n } else {\n if (this.inputRoot.parentElement) {\n this.values.forEach(value => {\n const ele = document.createElement('input');\n ele.setAttribute('type', 'hidden');\n ele.setAttribute('name', name);\n ele.setAttribute('value', this.serializeValue(value));\n this.hiddenInputs.push(ele);\n this.inputRoot.parentElement.appendChild(ele);\n });\n }\n }\n }\n }\n }\n\n private setSelectedOption(option: any) {\n if (this.multi) {\n this.addValue(option);\n } else {\n this.setValues([option]);\n }\n\n if (!this.multi || !this.searchable) {\n this.blur();\n this.focused = false;\n }\n\n this.visibleOptions = [];\n this.input = '';\n this.next = null;\n this.complete = true;\n this.selectedIndex = -1;\n }\n\n private isPastFetchThreshold() {\n return (\n (this.visibleOptions.length > 0 || this.next) &&\n !this.complete &&\n (this.cursorIndex || 0) > this.visibleOptions.length - LOOK_AHEAD\n );\n }\n\n public handleOptionSelection(event: CustomEvent) {\n const selected = event.detail.selected;\n // check if we should post it\n if (selected.post && this.endpoint) {\n postJSON(this.endpoint, selected).then(response => {\n if (response.status >= 200 && response.status < 300) {\n this.setSelectedOption(response.json);\n this.lruCache = lru(20, 60000);\n } else {\n // TODO: find a way to share inline errors\n this.blur();\n }\n });\n } else {\n this.setSelectedOption(selected);\n }\n }\n\n private handleExpressionSelection(evt: CustomEvent) {\n const option = evt.detail.selected as CompletionOption;\n const tabbed = evt.detail.tabbed;\n\n const ele = this.shadowRoot.querySelector('.searchbox') as HTMLInputElement;\n updateInputElementWithCompletion(this.query, ele, option);\n\n this.query = '';\n this.completionOptions = [];\n\n if (tabbed) {\n this.fetchExpressions();\n } else if (this.input.indexOf('(') === -1) {\n this.addInputAsValue();\n }\n }\n\n private getNameInternal: (option: any) => string = (option: any) => {\n return this.getName(option);\n };\n\n private getOptionsDefault(response: WebResponse): any[] {\n return response.json['results'];\n }\n\n private isCompleteDefault(\n newestOptions: any[],\n response: WebResponse\n ): boolean {\n const json = response.json;\n return !json['more'] && !json['next'];\n }\n\n public handleRemoveSelection(selectionToRemove: any): void {\n this.removeValue(selectionToRemove);\n this.visibleOptions = [];\n }\n\n private createArbitraryOptionDefault(): any {\n return null;\n }\n\n public open(): void {\n this.requestUpdate('input');\n }\n\n public isOpen(): boolean {\n return this.visibleOptions.length > 0;\n }\n\n public setOptions(options: any[]): void {\n this.staticOptions = options;\n }\n\n private setVisibleOptions(options: any[]) {\n // if we have an exclusion filter apply it\n options = options.filter(option => {\n // exclude unnamed\n if (!this.getNameInternal(option)) {\n return false;\n }\n\n if (this.shouldExclude) {\n return !this.shouldExclude(option);\n }\n return true;\n });\n\n if (this.input) {\n // if we are searching locally, filter for the query\n if (this.searchable && !this.queryParam) {\n const q = this.input.trim().toLowerCase();\n options = options.filter((option: any) => this.isMatch(option, q));\n }\n\n const arbitraryOption: any = this.createArbitraryOption(\n this.input,\n options\n );\n\n if (arbitraryOption) {\n // set our arbitrary flag so we never have more than one\n arbitraryOption.arbitrary = true;\n\n // make sure our id is not already present\n const exists = options.find(\n (option: any) =>\n this.getValue(option) === this.getValue(arbitraryOption)\n );\n\n if (!exists) {\n if (options.length > 0) {\n if (options[0].arbitrary) {\n options[0] = arbitraryOption;\n } else {\n options.unshift(arbitraryOption);\n }\n } else {\n options.unshift(arbitraryOption);\n }\n }\n }\n }\n\n // filter out any options already selected by id\n // TODO: should maybe be doing a deep equals here with option to optimize\n if (this.values.length > 0) {\n if (this.multi) {\n options = options.filter(\n option =>\n !this.values.find(\n selected => this.getValue(selected) === this.getValue(option)\n )\n );\n } else {\n // if no search, single select should set our cursor to the selected item\n if (!this.input) {\n this.cursorIndex = options.findIndex(\n option => this.getValue(option) === this.getValue(this.values[0])\n );\n } else {\n this.cursorIndex = 0;\n }\n this.requestUpdate('cursorIndex');\n }\n }\n\n // finally sort\n if (this.sortFunction) {\n options.sort(this.sortFunction);\n }\n\n this.visibleOptions = options;\n\n this.fireCustomEvent(CustomEventType.ContentChanged, {\n options: this.visibleOptions,\n });\n }\n\n public fetchExpressions() {\n const store: Store = document.querySelector('temba-store');\n if (this.expressions && store) {\n const ele = this.shadowRoot.querySelector(\n '.searchbox'\n ) as HTMLInputElement;\n\n const result = executeCompletionQuery(\n ele,\n store,\n this.expressions === 'session'\n );\n this.query = result.query;\n this.completionOptions = result.options;\n this.visibleOptions = [];\n this.anchorPosition = result.anchorPosition;\n this.fireCustomEvent(CustomEventType.FetchComplete);\n return;\n }\n }\n\n public fetchOptions(query: string, page = 0) {\n this.completionOptions = [];\n\n if (!this.fetching) {\n this.fetching = true;\n\n // make sure we cancel any previous request\n // if (this.cancelToken) {\n // this.cancelToken.cancel();\n // }\n\n const options: any = [...this.staticOptions];\n const q = (query || '').trim().toLowerCase();\n\n if (this.tags && q) {\n if (\n !options.find(\n (option: any) =>\n this.getValue(option) && this.getValue(option).toLowerCase() === q\n )\n ) {\n options.splice(0, 0, { name: query, value: query });\n }\n }\n\n if (this.endpoint) {\n let url = this.endpoint;\n\n if (query && this.queryParam) {\n if (url.indexOf('?') > -1) {\n url += '&';\n } else {\n url += '?';\n }\n\n url += this.queryParam + '=' + encodeURIComponent(query);\n }\n\n if (page) {\n if (url.indexOf('?') > -1) {\n url += '&';\n } else {\n url += '?';\n }\n url += 'page=' + page;\n }\n\n if (this.next) {\n url = this.next;\n }\n\n const cache = this.lruCache.get(url);\n if (this.cache && !this.tags && cache) {\n if (page === 0 && !this.next) {\n this.cursorIndex = 0;\n this.setVisibleOptions([...options, ...cache.options]);\n } else {\n this.setVisibleOptions([...this.visibleOptions, ...cache.options]);\n }\n\n this.complete = cache.complete;\n this.next = cache.next;\n this.fetching = false;\n return;\n }\n\n // if we are searchable, but doing it locally, fetch all the options\n if (this.searchable && !this.queryParam) {\n fetchResults(url).then((results: any) => {\n if (this.cache && !this.tags) {\n this.lruCache.set(url, {\n options: results,\n complete: true,\n next: null,\n });\n\n this.complete = true;\n this.next = null;\n this.setVisibleOptions([...options, ...results]);\n this.fetching = false;\n }\n });\n } else {\n getUrl(url)\n .then((response: WebResponse) => {\n const results = this.getOptions(response).filter(\n (option: any) => {\n return this.isMatch(option, q);\n }\n );\n\n const json = response.json;\n if (json['next']) {\n this.next = json['next'];\n }\n\n if (page === 0 && !this.next) {\n this.cursorIndex = 0;\n this.setVisibleOptions([...options, ...results]);\n this.query = query;\n this.complete = this.isComplete(this.visibleOptions, response);\n } else {\n if (results.length > 0) {\n this.setVisibleOptions([...this.visibleOptions, ...results]);\n }\n this.complete = this.isComplete(results, response);\n }\n\n if (this.cache && !this.tags) {\n this.lruCache.set(url, {\n options: results,\n complete: this.complete,\n next: this.next,\n });\n }\n\n // if (!this.next) {\n this.fetching = false;\n //}\n this.page = page;\n })\n .catch((reason: any) => {\n // cancelled\n this.fetching = false;\n console.error(reason);\n });\n }\n } else {\n this.fetching = false;\n this.setVisibleOptions(options);\n }\n }\n }\n\n private handleFocus(): void {\n if (!this.focused && this.visibleOptions.length === 0) {\n this.focused = true;\n if (this.searchOnFocus && !this.removingSelection) {\n this.requestUpdate('input');\n }\n }\n }\n\n private handleBlur() {\n this.focused = false;\n if (this.visibleOptions.length > 0) {\n this.input = '';\n this.next = null;\n this.complete = true;\n this.visibleOptions = [];\n this.cursorIndex = 0;\n }\n }\n\n private handleClick(): void {\n this.selectedIndex = -1;\n this.requestUpdate('input');\n }\n\n private addInputAsValue() {\n const ele = this.shadowRoot.querySelector('.searchbox') as HTMLInputElement;\n const expression = {\n name: ele.value,\n value: ele.value,\n expression: true,\n };\n\n if (this.multi) {\n if (\n !this.values.find(option => {\n return (\n option.expression &&\n option.value &&\n expression.value &&\n option.value.toLowerCase().trim() ==\n expression.value.toLowerCase().trim()\n );\n })\n ) {\n this.addValue(expression);\n }\n } else {\n this.setValues([expression]);\n }\n\n this.input = '';\n if (!this.multi) {\n this.blur();\n }\n }\n\n private handleKeyDown(evt: KeyboardEvent) {\n // if we are completing an expression, select it\n if (\n evt.key === 'Enter' &&\n this.expressions &&\n this.completionOptions.length === 0 &&\n this.input.indexOf('@') > -1\n ) {\n this.addInputAsValue();\n }\n\n // see if we should open our options on a key event\n if (\n evt.key === 'Enter' ||\n evt.key === 'ArrowDown' ||\n (evt.key === 'n' && evt.ctrlKey)\n ) {\n if (\n this.visibleOptions.length === 0 &&\n this.completionOptions.length === 0\n ) {\n this.requestUpdate('input');\n return;\n }\n }\n\n // focus our last item on delete\n if (this.multi && evt.key === 'Backspace' && !this.input) {\n if (this.visibleOptions.length > 0) {\n this.visibleOptions = [];\n return;\n }\n\n if (this.selectedIndex === -1) {\n this.selectedIndex = this.values.length - 1;\n this.visibleOptions = [];\n } else {\n this.popValue();\n this.selectedIndex = -1;\n }\n } else {\n this.selectedIndex = -1;\n }\n }\n\n public getStaticOptions() {\n return this.staticOptions;\n }\n\n private handleInput(evt: KeyboardEvent) {\n const ele = evt.currentTarget as HTMLInputElement;\n this.input = ele.value;\n }\n\n private handleCancel() {\n this.visibleOptions = [];\n }\n\n private handleCursorChanged(event: CustomEvent) {\n this.cursorIndex = event.detail.index;\n }\n\n private handleContainerClick(event: MouseEvent) {\n this.focused = true;\n\n if ((event.target as any).tagName !== 'INPUT') {\n const input = this.shadowRoot.querySelector('input');\n if (input) {\n input.click();\n input.focus();\n return;\n }\n\n if (this.visibleOptions.length > 0) {\n this.visibleOptions = [];\n event.preventDefault();\n event.stopPropagation();\n } else {\n this.requestUpdate('input');\n }\n }\n }\n\n public getEventHandlers(): EventHandler[] {\n return [\n { event: CustomEventType.Canceled, method: this.handleCancel },\n {\n event: CustomEventType.CursorChanged,\n method: this.handleCursorChanged,\n },\n { event: 'blur', method: this.handleBlur },\n { event: 'focus', method: this.handleFocus },\n ];\n }\n\n public firstUpdated(changedProperties: any) {\n super.firstUpdated(changedProperties);\n\n this.anchorElement = this.shadowRoot.querySelector('.select-container');\n this.anchorExpressions = this.shadowRoot.querySelector('#anchor');\n\n // wait until children are created before adding our static options\n const value = this.value;\n window.setTimeout(() => {\n for (const child of this.children) {\n if (child.tagName === 'TEMBA-OPTION') {\n const option: any = {};\n for (const attribute of child.attributes) {\n option[attribute.name] = attribute.value;\n }\n this.staticOptions.push(option);\n\n if (\n child.getAttribute('selected') !== null ||\n this.getValue(option) == this.value\n ) {\n if (this.getAttribute('multi') !== null) {\n this.addValue(option);\n } else {\n this.setValues([option]);\n }\n }\n }\n }\n\n if (this.values.length === 0 && (!this.placeholder || value)) {\n if (this.staticOptions.length == 0 && this.endpoint) {\n // see if we need to auto select the first item but need to fetch it\n fetchResults(this.endpoint).then((results: any) => {\n if (results && results.length > 0) {\n if (value) {\n // if we started with a value, see if we can find it in the results\n const existing = results.find(option => {\n return this.getValue(option) === value;\n });\n\n if (existing) {\n this.setValues([existing]);\n return;\n }\n }\n this.setValues([results[0]]);\n }\n });\n } else {\n if (this.getAttribute('multi') !== null) {\n this.addValue(this.staticOptions[0]);\n } else {\n this.setValues([this.staticOptions[0]]);\n }\n }\n }\n\n if (this.searchable && this.staticOptions.length === 0) {\n this.quietMillis = 200;\n }\n }, 0);\n }\n\n private handleArrowClick(event: MouseEvent): void {\n if (this.visibleOptions.length > 0) {\n this.visibleOptions = [];\n event.preventDefault();\n event.stopPropagation();\n }\n }\n\n private renderSelectedItemDefault(option: any): TemplateResult {\n if (!option) {\n return null;\n }\n\n return html`\n
    \n ${option.icon\n ? html``\n : null}${this.getName(option)}\n
    \n `;\n }\n\n public serializeValue(value: any): string {\n // static options just use their value\n if (!this.jsonValue && (this.staticOptions.length > 0 || this.tags)) {\n return value.value;\n }\n\n return super.serializeValue(value);\n }\n\n public setSelection(value: string): void {\n for (const option of this.staticOptions) {\n if (this.getValue(option.value) === value) {\n if (this.values.length === 0 || this.values[0].value !== '' + value) {\n this.setValues([option]);\n }\n return;\n }\n }\n }\n\n private handleClear(evt: MouseEvent): void {\n evt.preventDefault();\n evt.stopPropagation();\n this.setValues([]);\n }\n\n public setValues(values: any[]) {\n this.values = values;\n this.requestUpdate('values');\n }\n\n public addValue(value: any) {\n this.values.push(value);\n this.requestUpdate('values');\n }\n\n public removeValue(valueToRemove: any) {\n const idx = this.values.indexOf(valueToRemove);\n if (idx > -1) {\n this.values.splice(idx, 1);\n }\n this.requestUpdate('values');\n }\n\n public popValue() {\n this.values.pop();\n this.requestUpdate('values');\n }\n\n public clear() {\n this.values = [];\n this.requestUpdate('values');\n }\n\n public render(): TemplateResult {\n const placeholder = this.values.length === 0 ? this.placeholder : '';\n const placeholderDiv = html`\n
    ${placeholder}
    \n `;\n\n const clear =\n this.clearable && this.values.length > 0 && !this.multi\n ? html``\n : null;\n\n const classes = getClasses({\n multi: this.multi,\n single: !this.multi,\n searchable: this.searchable,\n empty: this.values.length === 0,\n options: this.visibleOptions.length > 0,\n focused: this.focused,\n 'search-input': this.input.length > 0,\n 'no-search-input': this.input.length === 0,\n [this.flavor]: this.flavor !== null,\n disabled: this.disabled,\n });\n\n const anchorStyles = this.anchorPosition\n ? {\n top: '0px',\n left: `${this.anchorPosition.left - 10}px`,\n }\n : {};\n\n const input = this.searchable\n ? html`\n
    \n \n
    \n
    \n `\n : placeholderDiv;\n\n return html`\n \n \n \n
    \n \n
    \n
    \n ${!this.multi ? input : null}\n ${this.values.map(\n (selected: any, index: number) => html`\n \n ${this.multi\n ? html`\n {\n this.removingSelection = true;\n }}\n @mouseup=${() => {\n this.removingSelection = false;\n }}\n @click=${(evt: MouseEvent) => {\n evt.preventDefault();\n evt.stopPropagation();\n this.handleRemoveSelection(selected);\n }}\n >\n \n
    \n `\n : null}\n ${this.renderSelectedItem(selected)}\n
    \n `\n )}\n ${this.multi ? input : null}\n
    \n\n \n\n ${clear}\n\n \n ${\n !this.tags\n ? html`\n 0\n ? 'open'\n : ''}\"\n >\n `\n : null\n }\n \n \n \n
    ${this.infoText}
    \n\n \n 0}\n >\n\n {}}\n .anchorTo=${this.anchorExpressions}\n .options=${this.completionOptions}\n .renderOption=${renderCompletionOption}\n ?visible=${this.completionOptions.length > 0}\n >\n ${\n this.currentFunction\n ? html`\n
    \n ${renderCompletionOption(this.currentFunction, true)}\n
    \n `\n : null\n }\n ${\n this.completionOptions.length > 0\n ? html`
    \n ${msg('Tab to complete, enter to select')}\n
    `\n : null\n }\n \n \n `;\n }\n}\n","import { TemplateResult, css, html } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { ifDefined } from 'lit-html/directives/if-defined.js';\nimport { TextInput } from '../textinput/TextInput';\nimport {\n renderCompletionOption,\n updateInputElementWithCompletion,\n executeCompletionQuery,\n} from './helpers';\n\nimport { FormElement } from '../FormElement';\nimport { CompletionOption, Position } from '../interfaces';\nimport { Store } from '../store/Store';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { msg } from '@lit/localize';\n\n/**\n * Completion is a text input that handles excellent completion options in a popup\n */\nexport class Completion extends FormElement {\n static get styles() {\n return css`\n :host {\n display: block;\n }\n\n temba-options {\n --widget-box-shadow-focused: 0 0 4px rgba(0, 0, 0, 0.15);\n --color-focus: #e6e6e6;\n }\n\n .comp-container {\n position: relative;\n height: 100%;\n }\n\n #anchor {\n /* background: rgba(132, 40, 158, .1); */\n position: absolute;\n visibility: hidden;\n width: 250px;\n height: 20px;\n }\n\n .fn-marker {\n font-weight: bold;\n font-size: 42px;\n }\n\n .option-slot {\n background: #fff;\n }\n\n .current-fn {\n padding: 10px;\n margin: 5px;\n background: var(--color-primary-light);\n color: rgba(0, 0, 0, 0.5);\n border-radius: var(--curvature-widget);\n font-size: 90%;\n }\n\n .footer {\n padding: 5px 10px;\n background: var(--color-primary-light);\n color: rgba(0, 0, 0, 0.5);\n font-size: 80%;\n border-bottom-left-radius: var(--curvature-widget);\n border-bottom-right-radius: var(--curvature-widget);\n }\n\n code {\n background: rgba(0, 0, 0, 0.1);\n padding: 1px 5px;\n border-radius: var(--curvature);\n }\n `;\n }\n\n @property({ type: Number })\n maxLength: number;\n\n @property({ type: Boolean })\n session: boolean;\n\n @property({ type: Boolean })\n submitOnEnter = false;\n\n @property({ type: Object })\n anchorPosition: Position = { left: 0, top: 0 };\n\n @property({ attribute: false })\n currentFunction: CompletionOption;\n\n @property({ type: String })\n placeholder = '';\n\n @property({ attribute: false })\n textInputElement: TextInput;\n\n @property({ attribute: false })\n anchorElement: HTMLDivElement;\n\n @property({ type: Array })\n options: any[] = [];\n\n @property({ type: String })\n name = '';\n\n @property({ type: String })\n value = '';\n\n @property({ type: Boolean })\n textarea: boolean;\n\n @property({ type: Boolean })\n gsm: boolean;\n\n @property({ type: String })\n counter: string;\n\n @property({ type: Boolean })\n autogrow = false;\n\n private hiddenElement: HTMLInputElement;\n private query: string;\n\n public firstUpdated() {\n this.textInputElement = this.shadowRoot.querySelector(\n 'temba-textinput'\n ) as TextInput;\n this.anchorElement = this.shadowRoot.querySelector('#anchor');\n\n // create our hidden container so it gets included in our host element's form\n this.hiddenElement = document.createElement('input');\n this.hiddenElement.setAttribute('type', 'hidden');\n this.hiddenElement.setAttribute('name', this.getAttribute('name'));\n this.hiddenElement.setAttribute('value', this.getAttribute('value') || '');\n this.appendChild(this.hiddenElement);\n }\n\n private handleKeyUp(evt: KeyboardEvent) {\n // if we have options, ignore keys that are meant for them\n if (this.options && this.options.length > 0) {\n if (evt.key === 'ArrowUp' || evt.key === 'ArrowDown') {\n return;\n }\n\n if (evt.ctrlKey) {\n if (evt.key === 'n' || evt.key === 'p') {\n return;\n }\n }\n\n if (\n evt.key === 'Enter' ||\n evt.key === 'Escape' ||\n evt.key === 'Tab' ||\n evt.key.startsWith('Control')\n ) {\n evt.stopPropagation();\n evt.preventDefault();\n return;\n }\n\n this.executeQuery(evt.currentTarget as TextInput);\n }\n }\n\n public hasVisibleOptions() {\n return this.options.length > 0;\n }\n\n private executeQuery(ele: TextInput) {\n const store: Store = document.querySelector('temba-store');\n if (!ele.inputElement) {\n return;\n }\n const result = executeCompletionQuery(\n ele.inputElement,\n store,\n this.session\n );\n\n this.query = result.query;\n this.options = result.options;\n this.anchorPosition = result.anchorPosition;\n }\n\n private handleClick(evt: MouseEvent) {\n this.executeQuery(evt.currentTarget as TextInput);\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n // if our cursor changed, lets make sure our scrollbox is showing it\n if (changedProperties.has('value')) {\n this.hiddenElement.setAttribute('value', this.value);\n }\n }\n\n private handleInput(evt: KeyboardEvent) {\n const ele = evt.currentTarget as TextInput;\n this.executeQuery(ele);\n this.value = ele.inputElement.value;\n this.fireEvent('change');\n }\n\n private handleOptionCanceled() {\n // delay in case we are actively selecting\n window.setTimeout(() => {\n this.options = [];\n this.query = '';\n }, 100);\n }\n\n private handleOptionSelection(evt: CustomEvent) {\n const option = evt.detail.selected as CompletionOption;\n const tabbed = evt.detail.tabbed;\n\n updateInputElementWithCompletion(\n this.query,\n this.textInputElement.inputElement,\n option\n );\n this.query = '';\n this.options = [];\n\n if (tabbed) {\n this.executeQuery(this.textInputElement);\n }\n }\n\n public click() {\n super.click();\n const input = this.shadowRoot.querySelector('temba-textinput') as TextInput;\n if (input) {\n input.click();\n }\n }\n\n public focus() {\n super.focus();\n const input = this.shadowRoot.querySelector('temba-textinput') as TextInput;\n if (input) {\n input.focus();\n }\n }\n\n public render(): TemplateResult {\n const anchorStyles = this.anchorPosition\n ? {\n top: `${this.anchorPosition.top}px`,\n left: `${this.anchorPosition.left}px`,\n }\n : {};\n\n const visible = this.options && this.options.length > 0;\n\n return html`\n \n
    \n
    \n \n \n \n ${this.currentFunction\n ? html`\n
    \n ${renderCompletionOption(this.currentFunction, true)}\n
    \n `\n : null}\n
    \n ${msg('Tab to complete, enter to select')}\n
    \n \n
    \n \n `;\n }\n}\n","import { RapidElement } from './RapidElement';\nimport { throttle } from './utils';\n\nexport class ResizeElement extends RapidElement {\n public handleResize() {\n this.requestUpdate();\n }\n\n public getEventHandlers() {\n return [\n {\n event: 'resize',\n method: throttle(this.handleResize, 50),\n isWindow: true,\n },\n ];\n }\n}\n","import { property } from 'lit/decorators.js';\nimport { TemplateResult, html, css, PropertyValueMap } from 'lit';\nimport { Button } from '../button/Button';\nimport { RapidElement } from '../RapidElement';\nimport { CustomEventType } from '../interfaces';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { getClasses } from '../utils';\nimport { ResizeElement } from '../ResizeElement';\n\nexport enum ButtonType {\n PRIMARY = 'primary',\n SECONDARY = 'secondary',\n DESTRUCTIVE = 'destructive',\n}\nexport class DialogButton {\n name?: string;\n id?: string;\n details?: any;\n type?: string;\n closes?: boolean;\n}\n\nexport class Dialog extends ResizeElement {\n static get widths(): { [size: string]: string } {\n return {\n small: '400px',\n medium: '600px',\n large: '655px',\n };\n }\n\n static get styles() {\n return css`\n :host {\n position: absolute;\n z-index: 10000;\n font-family: var(--font-family);\n background: white;\n }\n\n .flex-grow {\n flex-grow: 1;\n }\n\n .flex {\n display: flex;\n flex-direction: column;\n width: 100%;\n position: relative;\n left: 0px;\n top: 0px;\n align-items: center;\n height: 100vh;\n }\n\n .mobile .flex {\n height: 100%;\n position: fixed;\n }\n\n .mobile .grow-top {\n flex-grow: 0;\n }\n\n .mobile .grow-bottom {\n flex-grow: 0;\n }\n\n .grow-top {\n flex-grow: 1;\n }\n\n .grow-bottom {\n flex-grow: 3;\n }\n\n .bottom-padding {\n padding: 3rem;\n }\n\n .dialog-mask {\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.5);\n opacity: 0;\n position: fixed;\n top: 0px;\n left: 0px;\n transition: opacity linear calc(var(--transition-speed) / 2ms);\n pointer-events: none;\n }\n\n .mobile.dialog-mask .dialog-container {\n border-radius: 0px;\n }\n\n .dialog-mask .dialog-container {\n position: relative;\n transition: transform var(--transition-speed) var(--bounce),\n opacity ease-in-out calc(var(--transition-speed) - 50ms);\n border-radius: var(--curvature);\n box-shadow: 0px 0px 2px 4px rgba(0, 0, 0, 0.06);\n overflow: hidden;\n transform: scale(0.9) translatey(2em);\n background: white;\n margin: auto;\n display: flex;\n flex-direction: column;\n }\n\n .dialog-body {\n background: #fff;\n overflow-y: auto;\n flex-grow: 1;\n }\n\n .dialog-mask.dialog-open {\n opacity: 1;\n pointer-events: auto;\n }\n\n .dialog-mask.dialog-open .dialog-container {\n top: inherit;\n }\n\n .dialog-mask.dialog-animation-end .dialog-container {\n transform: scale(1) !important;\n }\n\n .dialog-mask.dialog-ready .dialog-container {\n transform: none;\n }\n\n .dialog-mask.dialog-loading .dialog-container {\n margin-top: -10000px;\n }\n\n .header-text {\n display: flex;\n flex-direction: row;\n align-items: center;\n font-size: 20px;\n padding: 12px 20px;\n font-weight: 300;\n color: var(--header-text);\n background: var(--header-bg);\n }\n\n .header-text .title {\n flex-grow: 1;\n }\n\n .header-text .status {\n font-size: 0.6em;\n font-weight: bold;\n }\n\n .dialog-footer {\n background: var(--color-primary-light);\n padding: 10px;\n display: flex;\n flex-flow: row;\n align-items: center;\n }\n\n temba-button {\n margin-left: 10px;\n }\n\n .dialog-body temba-loading {\n position: absolute;\n right: 12px;\n margin-top: -30px;\n padding-bottom: 9px;\n display: none;\n }\n\n #page-loader {\n text-align: center;\n display: block;\n position: relative;\n opacity: 0;\n margin: auto;\n margin-top: 30px;\n width: 154px;\n transition: opacity calc(var(--transition-speed) * 5ms) ease-in\n calc(var(--transition-speed * 2));\n visibility: hidden;\n }\n\n .dialog-mask.dialog-loading #page-loader {\n opacity: 1;\n visibility: visible;\n }\n\n #submit-loader {\n flex-grow: 1;\n text-align: right;\n }\n `;\n }\n\n @property({ type: Boolean })\n open: boolean;\n\n @property()\n header: string;\n\n @property()\n body: string;\n\n @property({ type: Boolean })\n submitting: boolean;\n\n @property({ type: Boolean })\n destructive: boolean;\n\n @property({ type: Boolean })\n disabled: boolean;\n\n @property({ type: Boolean })\n loading: boolean;\n\n @property({ type: Boolean })\n hideOnClick: boolean;\n\n @property({ type: Boolean })\n noFocus: boolean;\n\n @property()\n size = 'medium';\n\n @property({ type: String })\n primaryButtonName = 'Ok';\n\n @property({ type: String })\n cancelButtonName = 'Cancel';\n\n @property({ type: String })\n width = null;\n\n @property()\n submittingName = 'Saving';\n\n @property()\n animationEnd: boolean;\n\n @property()\n ready: boolean;\n\n @property({ type: Array })\n buttons: DialogButton[] = [];\n\n @property({ attribute: false })\n onButtonClicked: (button: Button) => void;\n\n scrollOffset: any = 0;\n\n public constructor() {\n super();\n }\n\n protected firstUpdated(\n changes: PropertyValueMap | Map\n ): void {\n if (changes.has('cancelButtonName') && this.cancelButtonName) {\n this.buttons.push({\n name: this.cancelButtonName,\n type: ButtonType.SECONDARY,\n closes: true,\n });\n }\n\n if (changes.has('primaryButtonName') && this.primaryButtonName) {\n this.buttons.push({\n name: this.primaryButtonName,\n type: ButtonType.PRIMARY,\n });\n }\n }\n\n public updated(changedProperties: Map) {\n if (changedProperties.has('open')) {\n const body = document.querySelector('body');\n\n if (this.open) {\n this.animationEnd = true;\n window.setTimeout(() => {\n this.ready = true;\n this.animationEnd = false;\n }, 400);\n\n this.scrollOffset = -document.documentElement.scrollTop;\n body.style.position = 'fixed';\n body.style.overflowY = 'scroll';\n body.style.top = this.scrollOffset + 'px';\n body.style.width = '100%';\n body.style.overflowY = 'hidden';\n } else {\n body.style.position = '';\n body.style.overflowY = '';\n body.style.width = '';\n body.style.marginRight = '';\n body.style.paddingRight = '0px';\n window.scrollTo(0, parseInt(this.scrollOffset || '0') * -1);\n }\n\n // make sure our buttons aren't in progress on show\n if (this.open && !changedProperties.get('open')) {\n this.shadowRoot\n .querySelectorAll('temba-button')\n .forEach((button: Button) => {\n if (button) button.submitting = false;\n });\n\n if (!this.noFocus) {\n this.focusFirstInput();\n }\n } else {\n window.setTimeout(() => {\n this.ready = false;\n }, 400);\n }\n }\n }\n\n public focusFirstInput(): void {\n window.setTimeout(() => {\n let input = this.querySelector(\n 'temba-textinput, temba-completion, input[type=\"text\"], textarea'\n ) as any;\n if (input) {\n input = input.textInputElement || input.inputElement || input;\n if (!input.readOnly) {\n input.focus();\n input.click();\n }\n }\n }, 100);\n }\n\n public handleClick(evt: MouseEvent) {\n const button = evt.currentTarget as Button;\n if (!button.disabled) {\n let detail: DialogButton = {};\n if (button.index >= 0 && button.index < this.buttons.length) {\n detail = this.buttons[button.index];\n }\n\n this.fireCustomEvent(CustomEventType.ButtonClicked, { button, detail });\n if (button.name === this.cancelButtonName || (detail && detail.closes)) {\n this.open = false;\n }\n }\n }\n\n private getDocumentHeight(): number {\n const body = document.body;\n const html = document.documentElement;\n return Math.max(\n body.scrollHeight,\n body.offsetHeight,\n html.clientHeight,\n html.scrollHeight,\n html.offsetHeight\n );\n }\n\n private clickCancel() {\n const cancel = this.getCancelButton();\n if (cancel) {\n cancel.click();\n }\n }\n\n public getCancelButton(): Button {\n return this.shadowRoot.querySelector(\n `temba-button[name='${this.cancelButtonName}']`\n );\n }\n\n public getPrimaryButton(): Button {\n return this.shadowRoot.querySelector(`temba-button[primary]`);\n }\n\n private handleKeyUp(event: KeyboardEvent) {\n if (event.key === 'Escape') {\n this.clickCancel();\n }\n }\n\n private handleClickMask(event: MouseEvent) {\n if (this.hideOnClick) {\n const id = (event.target as HTMLElement).id;\n if (id === 'dialog-mask' || id === 'dialog-bg') {\n this.fireCustomEvent(CustomEventType.DialogHidden);\n this.clickCancel();\n }\n }\n }\n\n public show(): void {\n this.open = true;\n }\n\n public hide(): void {\n this.open = false;\n }\n\n public render(): TemplateResult {\n const dialogStyle = {\n width: this.width,\n minWidth: '250px',\n maxWidth: '600px',\n };\n if (!this.width) {\n dialogStyle['width'] = Dialog.widths[this.size];\n }\n\n if (this.isMobile()) {\n dialogStyle['width'] = '100%';\n dialogStyle['height'] = '100%';\n delete dialogStyle['maxWidth'];\n }\n\n const header = this.header\n ? html`\n
    \n
    \n
    ${this.header}
    \n
    \n
    \n `\n : null;\n\n return html`\n \n
    \n \n
    \n\n
    \n
    \n \n ${header}\n
    \n ${this.body ? this.body : html``}\n \n
    \n\n
    \n
    \n \n
    \n ${this.buttons.map(\n (button: DialogButton, index) => html`\n \n `\n )}\n
    \n
    \n
    \n \n \n \n `;\n }\n}\n","import { TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { unsafeHTML } from 'lit-html/directives/unsafe-html.js';\n\nimport { RapidElement } from '../RapidElement';\nimport { getUrl, serialize, postUrl, WebResponse, getClasses } from '../utils';\nimport { CustomEventType } from '../interfaces';\nimport { ButtonType, Dialog, DialogButton } from './Dialog';\n\nexport class Modax extends RapidElement {\n static get styles() {\n return css`\n fieldset {\n border: none;\n margin: 0;\n padding: 0;\n }\n\n .control-group {\n margin-bottom: var(--control-margin-bottom);\n }\n\n .form-actions {\n display: none;\n }\n\n button[type='submit'],\n input[type='submit'] {\n display: none;\n }\n\n .modax-body {\n padding: 20px;\n display: block;\n position: relative;\n background: var(--body-bg);\n }\n\n .modax-body.submitting:before {\n display: inline-block;\n content: '';\n height: 100%;\n width: 100%;\n margin-left: -20px;\n margin-top: -20px;\n background: rgba(200, 200, 200, 0.1);\n position: absolute;\n z-index: 10000;\n }\n\n temba-loading {\n margin: 0 auto;\n display: block;\n width: 150px;\n }\n\n ul.errorlist {\n margin-top: 0px;\n list-style-type: none;\n padding-left: 0;\n padding-bottom: 7px;\n }\n\n ul.errorlist li {\n color: var(--color-error);\n background: rgba(255, 181, 181, 0.17);\n box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1),\n 0 1px 2px 0 rgba(0, 0, 0, 0.06);\n color: tomato;\n padding: 10px;\n margin-bottom: 10px;\n border-radius: 6px;\n font-weight: 300;\n }\n\n .step-ball {\n background: rgba(var(--primary-rgb), 0.2);\n width: 1.2em;\n height: 1.2em;\n border-radius: 100%;\n margin-right: 0.5em;\n border: 0.15em solid transparent;\n }\n\n .step-ball.complete {\n background: rgba(var(--primary-rgb), 0.7);\n cursor: pointer;\n }\n .step-ball.complete:hover {\n background: rgba(var(--primary-rgb), 0.8);\n }\n\n .step-ball.active {\n border: 0.15em solid var(--color-primary-dark);\n }\n\n .wizard-steps {\n display: flex;\n flex-direction: row;\n margin-left: 0.6em;\n }\n `;\n }\n\n @property({ type: String })\n header = '';\n\n @property({ type: String })\n endpoint: string;\n\n @property({ type: Boolean, reflect: true })\n open = false;\n\n @property({ type: Boolean })\n fetching = false;\n\n @property({ type: Boolean })\n submitting: boolean;\n\n @property({ type: String })\n primaryName: string;\n\n @property({ type: String })\n cancelName: string;\n\n @property({ type: String })\n onLoaded: string;\n\n @property({ type: Boolean })\n noSubmit: boolean;\n\n @property({ type: Object })\n headers: any = {};\n\n @property({ type: String })\n body: any = this.getLoading();\n\n @property({ type: Boolean })\n disabled = false;\n\n @property({ type: Array })\n buttons: DialogButton[] = [];\n\n @property({ type: Number })\n wizardStep = 0;\n\n @property({ type: Number })\n wizardStepCount = 0;\n\n @property({ type: Boolean })\n suspendSubmit = false;\n // private cancelToken: CancelTokenSource;\n\n private handleSlotClicked(): void {\n this.open = true;\n }\n\n public updated(changes: Map) {\n super.updated(changes);\n\n if (changes.has('open')) {\n if (this.open) {\n this.fetchForm();\n } else {\n // open can get reflected into undefined, make sure we've been open before\n if (changes.get('open') !== undefined) {\n // hide our body after our hiding animation is done\n if (this.open) {\n window.setTimeout(() => {\n this.body = this.getLoading();\n this.submitting = false;\n }, 500);\n } else {\n // clear the modal body out when closed, note that js functions declared on the\n // window will hang around\n this.setBody('');\n }\n }\n }\n }\n\n if (changes.has('body') && this.open && this.body && !this.fetching) {\n const dialog = this.shadowRoot.querySelector('temba-dialog') as Dialog;\n dialog.focusFirstInput();\n }\n }\n\n private getLoading() {\n return html``;\n }\n\n public updatePrimaryButton(): void {\n const wizard = this.shadowRoot.querySelector(\n '#wizard-form'\n ) as HTMLDivElement;\n if (wizard) {\n this.wizardStep = parseInt(wizard.dataset.step);\n this.wizardStepCount = parseInt(wizard.dataset.steps);\n }\n\n if (!this.noSubmit) {\n this.updateComplete.then(() => {\n const submitButton = this.shadowRoot.querySelector(\n \"input[type='submit'],button[type='submit']\"\n ) as any;\n\n if (submitButton) {\n this.buttons = [\n { type: ButtonType.SECONDARY, name: 'Cancel', closes: true },\n { type: ButtonType.PRIMARY, name: submitButton.value },\n ];\n } else {\n this.buttons = [\n { type: ButtonType.SECONDARY, name: 'Ok', closes: true },\n ];\n }\n this.submitting = false;\n });\n }\n }\n\n private setBody(body: string): boolean {\n // remove any existing on our previous body\n const scriptBlock = this.shadowRoot.querySelector('.scripts') as any;\n for (const child of scriptBlock.children) {\n child.remove();\n }\n\n // parse out any scripts in the body\n const div = this.ownerDocument.createElement('div');\n div.innerHTML = body;\n const scripts = div.getElementsByTagName('script');\n const toAdd: any = [];\n // now add them in\n for (let i = scripts.length - 1; i >= 0; i--) {\n // for (let i = 0; i < scripts.length; i++) {\n const script = this.ownerDocument.createElement('script');\n const code = scripts[i].innerText;\n\n if (scripts[i].src && scripts[i].src.indexOf('web-dev-server') === -1) {\n script.src = scripts[i].src;\n script.type = 'text/javascript';\n script.async = true;\n\n // TODO: track and fire event once all scripts are loaded\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n script.onload = function () {};\n toAdd.push(script);\n } else if (code) {\n script.appendChild(this.ownerDocument.createTextNode(code));\n toAdd.push(script);\n // remove it from our current body text\n }\n scripts[i].remove();\n }\n\n const scriptOnly = !!div.querySelector('.success-script');\n\n if (!scriptOnly) {\n this.body = unsafeHTML(div.innerHTML);\n }\n\n this.updateComplete.then(() => {\n for (const script of toAdd) {\n scriptBlock.appendChild(script);\n }\n });\n return !scriptOnly;\n }\n\n public getHeaders(): any {\n const headers = this.headers;\n headers['X-PJAX'] = 1;\n return headers;\n }\n\n private fetchForm() {\n // const CancelToken = axios.CancelToken;\n // this.cancelToken = CancelToken.source();\n this.fetching = true;\n this.body = this.getLoading();\n getUrl(this.endpoint, null, this.getHeaders()).then(\n (response: WebResponse) => {\n // if it's a full page, breakout of the modal\n if (response.body.indexOf('') == 0) {\n document.location = response.url;\n } else {\n this.setBody(response.body);\n this.fetching = false;\n this.updateComplete.then(() => {\n this.updatePrimaryButton();\n this.fireCustomEvent(CustomEventType.Loaded, {\n body: this.getBody(),\n });\n });\n }\n }\n );\n }\n\n public submit(extra = {}): void {\n this.submitting = true;\n const form = this.shadowRoot.querySelector('form');\n\n let postData = form ? serialize(form) : '';\n if (extra) {\n Object.keys(extra).forEach(key => {\n postData +=\n (postData.length > 1 ? '&' : '') +\n encodeURIComponent(key) +\n '=' +\n encodeURIComponent(extra[key]);\n });\n }\n\n postUrl(\n this.endpoint,\n postData,\n this.getHeaders(),\n 'application/x-www-form-urlencoded'\n )\n .then((response: WebResponse) => {\n window.setTimeout(() => {\n let redirect = response.headers.get('temba-success');\n if (\n !redirect &&\n response.url &&\n response.url.indexOf(this.endpoint) === -1\n ) {\n redirect = response.url;\n }\n\n if (redirect) {\n if (redirect === 'hide') {\n this.updateComplete.then(() => {\n this.open = false;\n this.fireCustomEvent(CustomEventType.Submitted);\n });\n } else {\n this.fireCustomEvent(CustomEventType.Redirected, {\n url: redirect,\n });\n this.open = false;\n }\n } else {\n // if we set the body, update our submit button\n if (this.setBody(response.body)) {\n this.updateComplete.then(() => {\n this.updatePrimaryButton();\n });\n }\n }\n }, 1000);\n })\n .catch(error => {\n console.error(error);\n });\n }\n\n private handleDialogClick(evt: CustomEvent) {\n const button = evt.detail.button;\n const detail = evt.detail.detail;\n if (!button.disabled && !button.submitting) {\n if (button.primary || button.destructive) {\n if (!this.suspendSubmit) {\n this.submit();\n }\n }\n }\n\n if (detail.closes) {\n this.open = false;\n this.fetching = false;\n this.cancelName = undefined;\n }\n }\n\n private handleDialogHidden() {\n // this.cancelToken.cancel();\n this.open = false;\n this.fetching = false;\n }\n\n private isDestructive(): boolean {\n return this.endpoint && this.endpoint.indexOf('delete') > -1;\n }\n\n private handleGotoStep(evt: MouseEvent) {\n const step = (evt.target as HTMLDivElement).dataset.gotoStep;\n if (step) {\n this.submit({ wizard_goto_step: step });\n }\n }\n\n public getBody() {\n return this.shadowRoot.querySelector('.modax-body');\n }\n\n public render(): TemplateResult {\n const wizardStepBalls = [];\n\n const wizard = this.shadowRoot.querySelector(\n '#wizard-form'\n ) as HTMLDivElement;\n if (wizard) {\n const completed = (wizard.getAttribute('data-completed') || '')\n .split(',')\n .filter(step => step.length > 0);\n\n for (let i = 0; i < this.wizardStepCount; i++) {\n wizardStepBalls.push(\n html``\n );\n }\n }\n\n return html`\n \n \n ${this.body}\n \n
    \n
    \n
    ${wizardStepBalls}
    \n
    \n \n
    \n \n
    \n `;\n }\n}\n","import { LitElement, TemplateResult, html, css } from 'lit';\nimport { getClasses } from '../utils';\n\nimport { property } from 'lit/decorators.js';\n\nexport class Button extends LitElement {\n static get styles() {\n return css`\n :host {\n display: inline-block;\n font-family: var(--font-family);\n font-weight: 400;\n }\n\n .small {\n font-size: 0.8em;\n --button-y: 0px;\n --button-x: 0.5em;\n }\n\n .v-2.button-container {\n background: var(--button-bg);\n background-image: var(--button-bg-img);\n color: var(--button-text);\n box-shadow: var(--button-shadow);\n transition: all calc(var(--transition-speed) / 2) ease-in;\n }\n\n .button-container {\n color: #fff;\n cursor: pointer;\n display: block;\n border-radius: var(--curvature);\n outline: none;\n transition: background ease-in var(--transition-speed);\n user-select: none;\n -webkit-user-select: none;\n text-align: center;\n }\n\n .button-name {\n white-space: nowrap;\n }\n\n .secondary-button:hover .button-mask {\n border: 1px solid var(--color-button-secondary);\n }\n\n .button-mask:hover {\n background: rgba(0, 0, 0, 0.05);\n }\n\n .button-container:focus {\n outline: none;\n margin: 0;\n }\n\n .button-container:focus {\n box-shadow: var(--widget-box-shadow-focused);\n }\n\n .button-container.secondary-button:focus .button-mask {\n background: transparent;\n }\n\n .button-mask {\n padding: var(--button-y) var(--button-x);\n border-radius: var(--curvature);\n border: 1px solid transparent;\n transition: var(--transition-speed);\n background: var(--button-mask);\n }\n\n .button-container.disabled-button {\n background: rgba(0, 0, 0, 0.05);\n color: rgba(255, 255, 255, 0.45);\n cursor: default;\n }\n\n .button-container.disabled-button .button-mask {\n box-shadow: 0 0 0px 1px var(--color-button-disabled);\n }\n\n .button-container.disabled-button:hover .button-mask {\n box-shadow: 0 0 0px 1px var(--color-button-disabled);\n background: rgba(0, 0, 0, 0.05);\n }\n\n .button-container.active-button .button-mask {\n }\n\n .secondary-button.active-button {\n background: transparent;\n color: var(--color-text);\n }\n\n .secondary-button.active-button .button-mask {\n border: none;\n }\n\n .button-container.secondary-button.active-button:focus .button-mask {\n background: transparent;\n box-shadow: none;\n }\n\n .primary-button {\n background: var(--color-button-primary);\n color: var(--color-button-primary-text);\n }\n\n .light-button {\n background: var(--color-button-light);\n color: var(--color-button-light-text);\n }\n\n .attention-button {\n background: var(--color-button-attention);\n color: var(--color-button-primary-text);\n }\n\n .secondary-button {\n background: transparent;\n color: var(--color-text);\n font-weight: 300;\n }\n\n .destructive-button {\n background: var(--color-button-destructive);\n color: var(--color-button-destructive-text);\n }\n\n .button-mask.disabled-button {\n background: rgba(0, 0, 0, 0.1);\n }\n\n .secondary-button .button-mask:hover {\n background: transparent;\n }\n\n .submit-animation {\n padding: 1px 4px;\n }\n\n .submit-animation temba-loading {\n margin-bottom: -3px;\n line-height: normal;\n }\n `;\n }\n\n @property({ type: Boolean })\n primary: boolean;\n\n @property({ type: Boolean })\n secondary: boolean;\n\n @property({ type: Boolean })\n attention: boolean;\n\n @property({ type: Number })\n v = 1;\n\n @property({ type: Boolean })\n destructive: boolean;\n\n @property({ type: Boolean })\n light: boolean;\n\n @property()\n name: string;\n\n @property({ type: Boolean })\n disabled: boolean;\n\n @property({ type: Boolean })\n submitting: boolean;\n\n @property({ type: Boolean })\n active: boolean;\n\n @property({ type: Boolean })\n small: boolean;\n\n @property({ type: String })\n href: string;\n\n @property({ type: Number })\n index?: number;\n\n private handleClick(evt: MouseEvent) {\n if (this.disabled) {\n evt.preventDefault();\n evt.stopPropagation();\n }\n\n if (this.href && !this.disabled) {\n this.ownerDocument.location.href = this.href;\n evt.preventDefault();\n evt.stopPropagation();\n }\n }\n\n private handleKeyUp(event: KeyboardEvent): void {\n this.active = false;\n if (event.key === 'Enter') {\n this.click();\n }\n }\n\n private handleMouseDown(): void {\n if (!this.disabled && !this.submitting) {\n this.active = true;\n this.classList.add('active');\n }\n }\n\n private handleMouseUp(): void {\n this.active = false;\n this.classList.remove('active');\n }\n\n public render(): TemplateResult {\n const buttonName = this.submitting\n ? html`
    \n \n
    `\n : this.name;\n\n return html`\n \n
    \n
    ${buttonName}
    \n
    \n \n `;\n }\n}\n","import { TemplateResult, html, css, LitElement } from 'lit';\nimport { property } from 'lit/decorators.js';\n\n/**\n * A small wrapper to display labels and help text in a smartmin style.\n * This exists so we can display things consistently before restyling.\n */\nexport class FormField extends LitElement {\n static get styles() {\n return css`\n :host {\n font-family: var(--font-family);\n }\n\n label {\n margin-bottom: 5px;\n margin-left: 4px;\n display: block;\n font-weight: 400;\n font-size: var(--label-size);\n letter-spacing: 0.05em;\n line-height: normal;\n color: #777;\n }\n\n .help-text {\n font-size: var(--help-text-size);\n line-height: normal;\n color: var(--color-text-help);\n margin-left: var(--help-text-margin-left);\n margin-top: -16px;\n opacity: 0;\n transition: opacity ease-in-out 100ms, margin-top ease-in-out 200ms;\n pointer-events: none;\n }\n\n .help-text.help-always {\n opacity: 1;\n margin-top: 6px;\n margin-left: var(--help-text-margin-left);\n }\n\n .field:focus-within .help-text {\n margin-top: 6px;\n opacity: 1;\n }\n\n .alert-error {\n background: rgba(255, 181, 181, 0.17);\n border: none;\n border-left: 0px solid var(--color-error);\n color: var(--color-error);\n padding: 10px;\n margin: 15px 0px;\n border-radius: var(--curvature);\n box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1),\n 0 1px 2px 0 rgba(0, 0, 0, 0.06);\n }\n\n .disabled {\n opacity: var(--disabled-opacity) !important;\n pointer-events: none !important;\n }\n `;\n }\n\n @property({ type: Boolean, attribute: 'hide_label' })\n hideLabel = false;\n\n @property({ type: Boolean, attribute: 'widget_only' })\n widgetOnly = false;\n\n @property({ type: Array, attribute: false })\n errors: string[] = [];\n\n @property({ type: Boolean })\n hideErrors = false;\n\n @property({ type: String, attribute: 'help_text' })\n helpText = '';\n\n @property({ type: Boolean, attribute: 'help_always' })\n helpAlways = true;\n\n @property({ type: String })\n label = '';\n\n @property({ type: String })\n name = '';\n\n @property({ type: Boolean })\n disabled = false;\n\n public render(): TemplateResult {\n const errors = !this.hideErrors\n ? (this.errors || []).map((error: string) => {\n return html`
    ${error}
    `;\n })\n : [];\n\n if (this.widgetOnly) {\n return html`\n
    \n ${errors}\n `;\n }\n\n return html`\n
    \n ${!!this.name && !this.hideLabel && !!this.label\n ? html`\n
    \n `;\n }\n}\n","import { html, TemplateResult, css, LitElement } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { range } from '../utils';\n\nexport class Loading extends LitElement {\n static get styles() {\n return css`\n :host {\n display: block;\n }\n\n .loading-unit {\n border: 1px inset rgba(0, 0, 0, 0.05);\n animation: loading-pulse 0.9s cubic-bezier(0.3, 0, 0.7, 1) infinite;\n }\n\n .loading-container {\n display: flex;\n }\n\n @keyframes loading-pulse {\n 0% {\n transform: scale(0.2);\n opacity: 0.1;\n }\n 20% {\n transform: scale(1);\n opacity: 1;\n }\n 100% {\n transform: scale(0.2);\n opacity: 0.1;\n }\n }\n `;\n }\n\n @property({ type: String })\n color = 'var(--color-primary-dark)';\n\n @property({ type: Number })\n size = 5;\n\n @property({ type: Number })\n units = 5;\n\n @property({ type: Boolean })\n square?: boolean;\n\n @property({ type: String })\n direction = 'row';\n\n public render(): TemplateResult {\n const margin = this.size / 2;\n\n return html`\n
    \n ${range(0, this.units).map((num: number) => {\n const ballStyle = {\n 'border-radius': this.square ? '0' : '50%',\n width: this.size + 'px',\n height: this.size + 'px',\n margin: margin + 'px',\n animationDelay: `-${1 - num * (1 / this.units)}s`,\n background: this.color,\n };\n return html`\n
    \n `;\n })}\n
    \n `;\n }\n}\n","// '@£$¥èéùìòÇ\\nØø\\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ\\x20!\"#¤%&\\'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà\\f^{}\\\\[~]|€'\nconst GSM_charCodes = [\n 10, 12, 13, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66,\n 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85,\n 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97, 98, 99, 100, 101, 102, 103, 104,\n 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,\n 120, 121, 122, 123, 124, 125, 126, 161, 163, 164, 165, 167, 191, 196, 197,\n 198, 199, 201, 209, 214, 216, 220, 223, 224, 228, 229, 230, 232, 233, 236,\n 241, 242, 246, 248, 249, 252, 915, 916, 920, 923, 926, 928, 931, 934, 936,\n 937, 8364,\n];\n\n// '\\f|^€{}[~]\\\\'\nconst GSMe_charCodes = [12, 91, 92, 93, 94, 123, 124, 125, 126, 8364];\n\nfunction existsInArray(code, array) {\n const len = array.length;\n let i = 0;\n while (i < len) {\n const e = array[i];\n if (code === e) return true;\n i++;\n }\n return false;\n}\n\nexport function validateCharacter(character) {\n const code = character.charCodeAt(0);\n return existsInArray(code, GSM_charCodes);\n}\n\nexport function validateMessage(message) {\n for (let i = 0; i < message.length; i++) {\n if (!validateCharacter(message.charAt(i))) return false;\n }\n return true;\n}\n\nexport function validateExtendedCharacter(character) {\n const code = character.charCodeAt(0);\n return existsInArray(code, GSMe_charCodes);\n}\n","import { validateCharacter, validateExtendedCharacter } from './gsmvalidator';\n\nfunction isHighSurrogate(code) {\n return code >= 0xd800 && code <= 0xdbff;\n}\n\nexport const gsmSplit = function (message, options) {\n options = options || { summary: false };\n\n if (message === '') {\n return {\n parts: [\n {\n content: options.summary ? undefined : '',\n length: 0,\n bytes: 0,\n },\n ],\n totalLength: 0,\n totalBytes: 0,\n };\n }\n\n const messages = [];\n let length = 0;\n let bytes = 0;\n let totalBytes = 0;\n let totalLength = 0;\n let messagePart = '';\n\n function bank() {\n const msg = {\n content: options.summary ? undefined : messagePart,\n length: length,\n bytes: bytes,\n };\n messages.push(msg);\n\n totalLength += length;\n length = 0;\n totalBytes += bytes;\n bytes = 0;\n messagePart = '';\n }\n\n for (let i = 0, count = message.length; i < count; i++) {\n let c = message.charAt(i);\n\n if (!validateCharacter(c)) {\n if (isHighSurrogate(c.charCodeAt(0))) {\n i++;\n }\n c = '\\u0020';\n } else if (validateExtendedCharacter(c)) {\n if (bytes === 152) bank();\n bytes++;\n }\n\n bytes++;\n length++;\n\n if (!options.summary) messagePart += c;\n\n if (bytes === 153) bank();\n }\n\n if (bytes > 0) bank();\n\n if (messages[1] && totalBytes <= 160) {\n return {\n parts: [\n {\n content: options.summary\n ? undefined\n : messages[0].content + messages[1].content,\n length: totalLength,\n bytes: totalBytes,\n },\n ],\n totalLength: totalLength,\n totalBytes: totalBytes,\n };\n }\n\n return {\n parts: messages,\n totalLength: totalLength,\n totalBytes: totalBytes,\n };\n};\n","function isHighSurrogate(code) {\n return code >= 0xd800 && code <= 0xdbff;\n}\n\nexport const unicodeSplit = function (message, options) {\n options = options || { summary: false };\n\n if (message === '') {\n return {\n parts: [\n {\n content: options.summary ? undefined : '',\n length: 0,\n bytes: 0,\n },\n ],\n totalLength: 0,\n totalBytes: 0,\n };\n }\n\n const messages = [];\n let length = 0;\n let bytes = 0;\n let totalBytes = 0;\n let totalLength = 0;\n let partStart = 0;\n\n function bank(partEnd = undefined) {\n const msg = {\n content: options.summary\n ? undefined\n : partEnd\n ? message.substring(partStart, partEnd + 1)\n : message.substring(partStart),\n length: length,\n bytes: bytes,\n };\n messages.push(msg);\n\n partStart = partEnd + 1;\n\n totalLength += length;\n length = 0;\n totalBytes += bytes;\n bytes = 0;\n }\n\n for (let i = 0, count = message.length; i < count; i++) {\n const code = message.charCodeAt(i);\n const highSurrogate = isHighSurrogate(code);\n\n if (highSurrogate) {\n if (bytes === 132) bank(i - 1);\n bytes += 2;\n i++;\n }\n\n bytes += 2;\n length++;\n\n if (bytes === 134) bank(i);\n }\n\n if (bytes > 0) bank();\n\n if (messages[1] && totalBytes <= 140) {\n return {\n parts: [\n {\n content: options.summary ? undefined : message,\n length: totalLength,\n bytes: totalBytes,\n },\n ],\n totalLength: totalLength,\n totalBytes: totalBytes,\n };\n }\n\n return {\n parts: messages,\n totalLength: totalLength,\n totalBytes: totalBytes,\n };\n};\n","/**\n * This is the same SMS splitter we've been using but we've\n * updated it here to use it with ESM imports\n * See https://github.com/Codesleuth/split-sms\n */\n\nimport { gsmSplit } from './gsmsplitter';\nimport { validateMessage } from './gsmvalidator';\nimport { unicodeSplit } from './unicodesplitter';\n\nexport const UNICODE = 'Unicode';\nexport const GSM = 'GSM';\n\nfunction calculateRemaining(parts, singleBytes, multiBytes, charBytes) {\n const max = parts.length === 1 ? singleBytes : multiBytes;\n return (max - parts[parts.length - 1].bytes) / charBytes;\n}\n\nexport const splitSMS = function (message: string, options: any = {}) {\n const characterset = options && options.characterset;\n\n options = {\n summary: options && options.summary,\n };\n\n const isGsm =\n (characterset === undefined && validateMessage(message)) ||\n characterset === GSM;\n let splitResult, singleBytes, multiBytes, charBytes;\n\n if (isGsm) {\n splitResult = gsmSplit(message, options);\n singleBytes = 160;\n multiBytes = 153;\n charBytes = 1;\n } else {\n splitResult = unicodeSplit(message, options);\n singleBytes = 140;\n multiBytes = 134;\n charBytes = 2;\n }\n\n const remainingInPart = calculateRemaining(\n splitResult.parts,\n singleBytes,\n multiBytes,\n charBytes\n );\n\n return {\n characterSet: isGsm ? GSM : UNICODE,\n parts: splitResult.parts,\n bytes: splitResult.totalBytes,\n length: splitResult.totalLength,\n remainingInPart: remainingInPart,\n };\n};\n","export const MAX_GSM_SINGLE = 160;\nexport const MAX_GSM_MULTI = 153;\nexport const MAX_UNICODE_SINGLE = 70;\nexport const MAX_UNICODE_MULTI = 67;\n\nexport const COMPLETION_HELP = 'Tab to complete, enter to select';\n\nexport const GSM: { [key: string]: number } = {\n // char: charCode\n 0: 48,\n 1: 49,\n 2: 50,\n 3: 51,\n 4: 52,\n 5: 53,\n 6: 54,\n 7: 55,\n 8: 56,\n 9: 57,\n '\\n': 10,\n '\\f': 12,\n '\\r': 13,\n ' ': 32,\n '!': 33,\n '\"': 34,\n '#': 35,\n $: 36,\n '%': 37,\n '&': 38,\n \"'\": 39,\n '(': 40,\n ')': 41,\n '*': 42,\n '+': 43,\n ',': 44,\n '-': 45,\n '.': 46,\n '/': 47,\n ':': 58,\n ';': 59,\n '<': 60,\n '=': 61,\n '>': 62,\n '?': 63,\n '@': 64,\n A: 65,\n B: 66,\n C: 67,\n D: 68,\n E: 69,\n F: 70,\n G: 71,\n H: 72,\n I: 73,\n J: 74,\n K: 75,\n L: 76,\n M: 77,\n N: 78,\n O: 79,\n P: 80,\n Q: 81,\n R: 82,\n S: 83,\n T: 84,\n U: 85,\n V: 86,\n W: 87,\n X: 88,\n Y: 89,\n Z: 90,\n '[': 91,\n '\\\\': 92,\n ']': 93,\n '^': 94,\n _: 95,\n a: 97,\n b: 98,\n c: 99,\n d: 100,\n e: 101,\n f: 102,\n g: 103,\n h: 104,\n i: 105,\n j: 106,\n k: 107,\n l: 108,\n m: 109,\n n: 110,\n o: 111,\n p: 112,\n q: 113,\n r: 114,\n s: 115,\n t: 116,\n u: 117,\n v: 118,\n w: 119,\n x: 120,\n y: 121,\n z: 122,\n '{': 123,\n '|': 124,\n '}': 125,\n '~': 126,\n '¡': 161,\n '£': 163,\n '¤': 164,\n '¥': 165,\n '§': 167,\n '¿': 191,\n Ä: 196,\n Å: 197,\n Æ: 198,\n Ç: 199,\n É: 201,\n Ñ: 209,\n Ö: 214,\n Ø: 216,\n Ü: 220,\n ß: 223,\n à: 224,\n ä: 228,\n å: 229,\n æ: 230,\n è: 232,\n é: 233,\n ì: 236,\n ñ: 241,\n ò: 242,\n ö: 246,\n ø: 248,\n ù: 249,\n ü: 252,\n Γ: 915,\n Δ: 916,\n Θ: 920,\n Λ: 923,\n Ξ: 926,\n Π: 928,\n Σ: 931,\n Φ: 934,\n Ψ: 936,\n Ω: 937,\n '€': 8364,\n};\n\nexport const isGSM = (char: string): boolean => {\n // eslint-disable-next-line no-prototype-builtins\n return GSM.hasOwnProperty(char);\n};\n\nexport const getExtendedCharacters = (text: string): string[] => {\n const extended: { [ch: string]: boolean } = {};\n for (const ch of text) {\n if (!isGSM(ch)) {\n extended[ch] = true;\n }\n }\n return Object.keys(extended);\n};\n","import { css, html, TemplateResult } from 'lit';\nimport { RapidElement } from '../RapidElement';\nimport { splitSMS } from '../sms';\nimport { getExtendedCharacters } from './helpers';\nimport { property } from 'lit/decorators.js';\n\nexport class CharCount extends RapidElement {\n static get styles() {\n return css`\n :host {\n overflow: auto;\n }\n\n :host::after {\n content: '';\n clear: both;\n display: table;\n }\n\n .counter {\n float: right;\n text-align: right;\n position: relative;\n }\n\n .extended {\n font-size: 14px;\n display: flex;\n margin-top: 4px;\n }\n\n .extended-char {\n border: 1px solid #e6e6e6;\n border-radius: var(--curvature-widget);\n padding: 4px;\n text-align: center;\n line-height: 20px;\n margin-right: 4px;\n }\n\n .summary {\n width: 180px;\n padding: 8px 12px;\n font-size: 12px;\n background: white;\n border-radius: var(--curvature-widget);\n overflow: hidden;\n opacity: 0.3;\n transform: scale(0.7);\n box-shadow: var(--shadow);\n transition: transform cubic-bezier(0.71, 0.18, 0.61, 1.33)\n var(--transition-speed);\n visibility: hidden;\n margin-top: var(--temba-charcount-summary-margin-top);\n right: var(--temba-charcount-summary-right);\n bottom: var(--temba-charcount-summary-bottom);\n text-align: left;\n position: var(--temba-charcount-summary-position);\n z-index: 1000;\n }\n\n .fine-print {\n margin-top: 8px;\n margin-left: -12px;\n margin-right: -12px;\n margin-bottom: -8px;\n padding: 8px 12px;\n color: #999;\n background: #f5f5f5;\n font-size: 10px;\n }\n\n .extended-warning {\n margin-top: 8px;\n }\n\n .note {\n font-weight: 600;\n display: inline-block;\n margin-right: 2px;\n }\n\n .counts {\n cursor: pointer;\n transition: all cubic-bezier(0.71, 0.18, 0.61, 1.33) 200ms;\n transform: scale(0.9);\n display: inline-block;\n padding: 2px 6px;\n border-radius: var(--curvature);\n margin-top: var(--temba-charcount-counts-margin-top);\n }\n\n .segments {\n font-size: 85%;\n display: inline-block;\n }\n\n .attention .counts {\n transform: scale(0.95);\n background: var(--color-overlay-light);\n color: var(--color-overlay-light-text);\n }\n\n .attention .segments {\n font-weight: 600;\n }\n\n .counter:hover .summary {\n opacity: 1;\n transform: scale(1);\n visibility: visible;\n }\n `;\n }\n\n @property({ type: String })\n text: string;\n\n @property({ type: Number })\n count: number;\n\n @property({ type: Number, attribute: false })\n segments: number;\n\n @property({ type: Object, attribute: false })\n extended: string[] = [];\n\n public updated(changes: Map) {\n super.updated(changes);\n if (changes.has('text')) {\n this.updateSegments();\n }\n }\n\n private updateSegments() {\n const sms = splitSMS(this.text);\n this.count = sms.length;\n this.segments = sms.parts.length;\n this.extended = getExtendedCharacters(this.text);\n this.count = this.text.length;\n }\n\n public render(): TemplateResult {\n const hasExpressions = this.text && this.text.indexOf('@') > -1;\n\n let segments = html`.`;\n if (this.segments > 1) {\n segments = html`and will use ${hasExpressions ? html`at least` : null}\n ${this.segments} messages to send over SMS.`;\n } else {\n segments = html`and will use ${hasExpressions ? html`at least` : null} one\n message to send over SMS.`;\n }\n\n let extended = null;\n if (this.extended.length > 0 && (this.segments > 1 || hasExpressions)) {\n extended = this.extended.map(\n (ch: string) => html`
    ${ch}
    `\n );\n extended = html`\n
    \n Some characters require more space over SMS. To save on fees, consider\n replacing them.\n
    ${extended}
    \n
    \n `;\n }\n\n const summary =\n this.count > 1\n ? html`
    \n This message is ${this.count} characters\n ${segments} ${extended}\n ${hasExpressions\n ? html`\n
    \n
    NOTE
    \n Using variables may result in more messages when sending\n over SMS than this estimate.\n
    \n `\n : null}\n
    `\n : null;\n\n return html`
    ${this.count}${\n this.segments > 1 || hasExpressions\n ? html`
    \n  / ${this.segments}${hasExpressions ? html`+` : null}\n
    \n
    `\n : null\n }
    ${summary}
    `;\n }\n}\n","import { html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { RapidElement } from '../RapidElement';\nimport { Store } from './Store';\n\n/**\n * StoreMonitorElement notifies when the store is updated and with what url\n */\nexport class StoreMonitorElement extends RapidElement {\n @property({ type: String })\n url: string;\n\n @property({ type: Boolean })\n showLoading = false;\n\n store: Store;\n\n private handleStoreUpdated(event: CustomEvent) {\n this.store.initialHttpComplete.then(() => {\n this.storeUpdated(event);\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function\n protected storeUpdated(event: CustomEvent) {}\n\n protected updated(\n properties: PropertyValueMap | Map\n ): void {\n super.updated(properties);\n }\n\n connectedCallback(): void {\n super.connectedCallback();\n this.store = document.querySelector('temba-store') as Store;\n this.handleStoreUpdated = this.handleStoreUpdated.bind(this);\n if (this.store) {\n this.store.addEventListener(\n CustomEventType.StoreUpdated,\n this.handleStoreUpdated\n );\n }\n }\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n if (this.store) {\n this.store.removeEventListener(\n CustomEventType.StoreUpdated,\n this.handleStoreUpdated\n );\n }\n }\n\n public render(): TemplateResult {\n if (!this.store.ready && this.showLoading) {\n return html``;\n }\n }\n}\n","import { PropertyValueMap } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\n\nimport { Store } from './Store';\nimport { StoreMonitorElement } from './StoreMonitorElement';\n\n/**\n * StoreElement is a listener for a given endpoint that re-renders\n * when the underlying store element changes\n */\nexport class StoreElement extends StoreMonitorElement {\n @property({ type: String })\n url: string;\n\n @property({ type: Boolean })\n showLoading = false;\n\n @property({ type: Object, attribute: false })\n data: any;\n\n store: Store;\n\n prepareData(data: any): any {\n return data;\n }\n\n public refresh() {\n this.store.makeRequest(this.url, {\n prepareData: this.prepareData,\n force: true,\n });\n }\n\n protected storeUpdated(event: CustomEvent) {\n if (event.detail.url === this.url) {\n const previous = this.data;\n this.data = event.detail.data;\n this.fireCustomEvent(CustomEventType.Refreshed, {\n data: event.detail.data,\n previous,\n });\n }\n }\n\n protected updated(\n properties: PropertyValueMap | Map\n ): void {\n super.updated(properties);\n if (properties.has('url')) {\n if (this.url) {\n this.store.makeRequest(this.url, { prepareData: this.prepareData });\n } else {\n this.data = null;\n }\n }\n }\n\n connectedCallback(): void {\n super.connectedCallback();\n this.prepareData = this.prepareData.bind(this);\n }\n}\n","import { PropertyValueMap } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { Contact, Group } from '../interfaces';\nimport { StoreElement } from '../store/StoreElement';\n\nexport class ContactStoreElement extends StoreElement {\n @property({ type: String })\n contact: string;\n\n @property({ type: Object, attribute: false })\n data: Contact;\n\n @property({ type: String })\n endpoint = '/api/v2/contacts.json?uuid=';\n\n prepareData(data: any) {\n if (data && data.length > 0) {\n data = data[0];\n data.groups.forEach((group: Group) => {\n group.is_dynamic = this.store.isDynamicGroup(group.uuid);\n });\n\n data.groups.sort((a: Group, b: Group) => {\n if (!a.is_dynamic || !b.is_dynamic) {\n if (a.is_dynamic) {\n return -1;\n }\n\n if (b.is_dynamic) {\n return 1;\n }\n }\n\n return a.name.localeCompare(b.name);\n });\n\n return data;\n }\n return null;\n }\n\n public setContact(contact: any) {\n // make sure contact data is properly prepped\n this.data = this.prepareData([contact]);\n this.store.updateCache(`${this.endpoint}${this.contact}`, this.data);\n }\n\n protected updated(\n changes: PropertyValueMap | Map\n ): void {\n super.updated(changes);\n if (changes.has('contact')) {\n if (this.contact) {\n this.url = `${this.endpoint}${this.contact}`;\n } else {\n this.url = null;\n }\n }\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { Contact, CustomEventType, Ticket } from '../interfaces';\nimport { postJSON } from '../utils';\nimport { ContactHistory } from './ContactHistory';\nimport { ContactStoreElement } from './ContactStoreElement';\nimport { Compose } from '../compose/Compose';\n\nconst DEFAULT_REFRESH = 10000;\n\nexport class ContactChat extends ContactStoreElement {\n public static get styles() {\n return css`\n :host {\n flex-grow: 1;\n display: flex;\n flex-direction: row;\n min-height: 0;\n --compose-shadow: none;\n --compose-border: none;\n --compose-padding: 3px;\n --compose-curvature: none;\n }\n\n .chat-wrapper {\n display: flex;\n flex-grow: 1;\n flex-direction: column;\n min-height: 0;\n }\n\n temba-contact-history {\n border-bottom: 1px solid #f6f6f6;\n flex-grow: 1;\n display: flex;\n flex-direction: column;\n min-height: 0;\n }\n\n .chatbox {\n box-shadow: 0px -5px 1rem 0rem rgba(0, 0, 0, 0.07);\n display: flex;\n flex-direction: column;\n --textarea-min-height: 1em;\n --textarea-height: 1.2em;\n --widget-box-shadow-focused: none;\n }\n\n .chatbox:focus-within {\n --textarea-height: 4em;\n }\n\n .chatbox.full {\n border-bottom-right-radius: 0 !important;\n }\n\n .closed-footer {\n padding: 1em;\n background: #f2f2f2;\n border-top: 3px solid #e1e1e1;\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n a {\n color: var(--color-link-primary);\n }\n\n a:hover {\n text-decoration: underline;\n color: var(--color-link-primary-hover);\n }\n\n temba-button#reopen-button {\n --button-y: 1px;\n --button-x: 12px;\n }\n\n temba-completion {\n --widget-box-shadow: none;\n --color-widget-border: transparent;\n --widget-box-shadow-focused: none;\n --color-focus: transparent;\n --color-widget-bg-focused: transparent;\n }\n `;\n }\n\n @property({ type: String, attribute: 'ticket' })\n ticketUUID: string;\n\n @property({ type: String })\n contactsEndpoint = '/api/v2/contacts.json';\n\n @property({ type: String })\n currentNote = '';\n\n @property({ type: Boolean })\n showDetails = true;\n\n @property({ type: Boolean })\n monitor = false;\n\n @property({ type: Object })\n currentTicket: Ticket = null;\n\n @property({ type: Object })\n currentContact: Contact = null;\n\n @property({ type: String })\n agent = '';\n\n // http promise to monitor for completeness\n public httpComplete: Promise;\n\n constructor() {\n super();\n }\n\n refreshInterval = null;\n\n public connectedCallback() {\n super.connectedCallback();\n if (this.monitor) {\n this.refreshInterval = setInterval(() => {\n if (this.currentTicket && this.currentTicket.closed_on) {\n return;\n }\n this.refresh();\n }, DEFAULT_REFRESH);\n }\n }\n\n public disconnectedCallback() {\n if (this.refreshInterval) {\n clearInterval(this.refreshInterval);\n }\n }\n\n public getContactHistory(): ContactHistory {\n return this.shadowRoot.querySelector(\n 'temba-contact-history'\n ) as ContactHistory;\n }\n\n public refresh(scrollToBottom = false): void {\n const contactHistory = this.getContactHistory();\n if (contactHistory) {\n if (scrollToBottom) {\n contactHistory.scrollToBottom();\n }\n contactHistory.refresh();\n // super.refresh();\n }\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n // if we don't have an endpoint infer one\n if (\n changedProperties.has('data') ||\n changedProperties.has('currentContact')\n ) {\n this.currentContact = this.data;\n }\n }\n\n private handleSend(evt: CustomEvent) {\n const buttonName = evt.detail.name;\n if (buttonName === 'Send') {\n const payload = {\n contact: this.currentContact.uuid,\n };\n const compose = evt.currentTarget as Compose;\n if (compose) {\n const text = compose.currentText;\n if (text && text.length > 0) {\n payload['text'] = text;\n }\n const attachments = compose.currentAttachments;\n if (attachments && attachments.length > 0) {\n const attachment_uuids = attachments.map(\n attachment => attachment.uuid\n );\n payload['attachments'] = attachment_uuids;\n }\n }\n if (this.currentTicket) {\n payload['ticket'] = this.currentTicket.uuid;\n }\n\n const genericError = buttonName + ' failed, please try again.';\n\n postJSON(`/api/v2/messages.json`, payload)\n .then(response => {\n if (response.status < 400) {\n compose.reset();\n this.refresh(true);\n this.fireCustomEvent(CustomEventType.MessageSent, { msg: payload });\n } else if (response.status < 500) {\n if (\n response.json.text &&\n response.json.text.length > 0 &&\n response.json.text[0].length > 0\n ) {\n let textError = response.json.text[0];\n textError = textError.replace(\n 'Ensure this field has no more than',\n 'Maximum allowed text is'\n );\n compose.buttonError = textError;\n } else if (\n response.json.attachments &&\n response.json.attachments.length > 0 &&\n response.json.attachments[0].length > 0\n ) {\n let attachmentError = response.json.attachments[0];\n attachmentError = attachmentError\n .replace(\n 'Ensure this field has no more than',\n 'Maximum allowed attachments is'\n )\n .replace('elements', 'files');\n compose.buttonError = attachmentError;\n } else {\n compose.buttonError = genericError;\n }\n } else {\n compose.buttonError = genericError;\n }\n })\n .catch(error => {\n console.error(error);\n compose.buttonError = genericError;\n });\n }\n }\n\n public render(): TemplateResult {\n const contactHistory = this.currentContact\n ? this.getTembaContactHistory()\n : null;\n const chatbox = this.currentContact ? this.getTembaChatbox() : null;\n\n const contactHistoryAndChatbox = html`\n
    ${contactHistory} ${chatbox}
    \n `;\n return html`${contactHistoryAndChatbox}`;\n }\n\n private getTembaContactHistory(): TemplateResult {\n return html` \n `;\n }\n\n private getTembaChatbox(): TemplateResult {\n if (this.currentTicket) {\n if (this.currentContact && this.currentContact.status !== 'active') {\n //no chatbox for archived, blocked, or stopped contacts\n return null;\n } else {\n if (!this.currentTicket.closed_on) {\n //chatbox for active contacts with an open ticket\n return this.getChatbox();\n } else {\n return null;\n }\n }\n }\n\n if (this.currentContact && this.currentContact.status !== 'active') {\n //no chatbox for archived, blocked, or stopped contacts\n return null;\n } else {\n //chatbox for active contacts\n return this.getChatbox();\n }\n }\n\n private getChatbox(): TemplateResult {\n return html`
    \n \n \n
    `;\n }\n}\n","import { Contact, User } from '../interfaces';\nimport { fetchResults, getUrl, postUrl, WebResponse } from '../utils';\nimport { ContactHistoryPage } from './events';\n\nexport const SCROLL_THRESHOLD = 100;\nexport const SIMULATED_WEB_SLOWNESS = 0;\nexport const MAX_CHAT_REFRESH = 10000;\nexport const MIN_CHAT_REFRESH = 500;\nexport const BODY_SNIPPET_LENGTH = 250;\n\nexport const closeTicket = (uuid: string): Promise => {\n const formData = new FormData();\n formData.append('status', 'C');\n return postUrl(`/ticket/update/${uuid}/?_format=json`, formData);\n};\n\nexport const fetchContact = (endpoint: string): Promise => {\n return new Promise((resolve, reject) => {\n fetchResults(endpoint).then((contacts: Contact[]) => {\n if (contacts && contacts.length === 1) {\n resolve(contacts[0]);\n } else {\n reject('No contact found');\n }\n });\n });\n};\n\nlet pendingRequests: AbortController[] = [];\n\nexport const fetchContactHistory = (\n reset: boolean,\n endpoint: string,\n ticket: string,\n before: number = undefined,\n after: number = undefined\n): Promise => {\n if (reset) {\n pendingRequests.forEach(controller => {\n controller.abort();\n });\n pendingRequests = [];\n }\n\n return new Promise(resolve => {\n const controller = new AbortController();\n pendingRequests.push(controller);\n\n let url = endpoint;\n if (before) {\n url += `&before=${before}`;\n }\n\n if (after) {\n url += `&after=${after}`;\n }\n\n if (ticket) {\n url += `&ticket=${ticket}`;\n }\n\n getUrl(url, controller)\n .then((response: WebResponse) => {\n // on success, remove our abort controller\n pendingRequests = pendingRequests.filter(\n (controller: AbortController) => {\n return response.controller === controller;\n }\n );\n resolve(response.json as ContactHistoryPage);\n })\n .catch(() => {\n // canceled\n });\n });\n};\n\nexport const getDisplayName = (user: User) => {\n if (!user) {\n return 'Somebody';\n }\n\n if (user.first_name && user.last_name) {\n return `${user.first_name} ${user.last_name}`;\n }\n\n if (user.first_name) {\n return user.first_name;\n }\n\n return user.email;\n};\n","import { css, html, TemplateResult } from 'lit';\nimport { Msg, ObjectReference, User } from '../interfaces';\nimport { getClasses, oxford, oxfordFn, oxfordNamed } from '../utils';\nimport { Icon } from '../vectoricon';\nimport { getDisplayName } from './helpers';\n\nexport const getEventStyles = () => {\n return css`\n .grouping {\n margin-top: 1em;\n }\n\n .grouping.verbose {\n background: #f9f9f9;\n color: var(--color-dark);\n --color-link-primary: rgba(38, 166, 230, 1);\n pointer-events: none;\n background: #fefefe;\n box-shadow: -8px 0px 8px 1px rgba(0, 0, 0, 0.05) inset;\n margin-right: -16px;\n padding-right: 16px;\n margin-bottom: 1.3em;\n max-width: 100%;\n }\n\n .grouping .items {\n display: block;\n }\n\n .grouping.verbose .items {\n opacity: 0;\n max-height: 0;\n display: flex;\n flex-direction: column;\n user-select: none;\n }\n\n .grouping.flows .items {\n padding: 0;\n }\n\n .grouping.messages .items {\n display: flex;\n flex-direction: column;\n margin: 0em 0.75em;\n }\n\n .grouping.verbose.expanded .items {\n transition: max-height var(--transition-speed) ease-in-out,\n opacity var(--transition-speed) ease-in-out;\n opacity: 1;\n max-height: 1000px;\n padding: 1em 1em;\n }\n\n .grouping.verbose.expanded {\n border-top: 1px solid #f3f3f3;\n border-bottom: 1px solid #f3f3f3;\n }\n\n .grouping.verbose.expanded,\n .grouping.verbose .event-count {\n pointer-events: auto;\n }\n\n .grouping.verbose temba-icon {\n }\n\n .grouping.verbose > .event,\n .grouping.verbose > pre {\n max-height: 0px;\n padding-top: 0;\n padding-bottom: 0;\n margin-top: 0;\n margin-bottom: 0;\n opacity: 0;\n }\n\n .grouping.verbose .attn {\n color: #666;\n }\n\n .event-count {\n position: relative;\n font-size: 0.8em;\n text-align: center;\n margin: 0 auto;\n display: table;\n padding: 3px 10px;\n font-weight: 400;\n color: #999;\n cursor: pointer;\n width: 100%;\n opacity: 1;\n }\n\n .event-count temba-icon {\n display: inline-block;\n position: absolute;\n right: 5px;\n top: 5px;\n }\n\n .event-count:hover {\n color: var(--color-link-primary-hover);\n }\n\n .expanded .event-count {\n padding: 0;\n pointer-events: none;\n }\n\n .grouping.flows {\n margin-left: 1em;\n margin-right: 1em;\n margin-bottom: 1.5em;\n\n border: 1px solid #f2f2f2;\n border-radius: var(--curvature);\n padding: 0.5em 1em;\n }\n\n .grouping.flows .event {\n margin: 0;\n padding: 0;\n }\n\n .grouping.tickets {\n margin-bottom: 2em;\n }\n\n pre {\n white-space: pre-wrap;\n word-wrap: break-word;\n }\n\n .grouping.verbose.expanded .event,\n .grouping.verbose.expanded pre {\n max-height: 500px;\n opacity: 1;\n }\n\n .grouping-close-button {\n position: relative;\n display: inline-block;\n opacity: 0;\n float: right;\n --icon-color: #666;\n }\n\n .grouping.verbose.expanded:hover .grouping-close-button {\n opacity: 1;\n }\n\n .grouping.messages,\n .grouping.tickets {\n display: flex;\n flex-direction: column;\n }\n\n .event {\n margin: 0.25em 0.5em;\n border-radius: var(--curvature);\n flex-grow: 1;\n }\n\n .msg {\n border-radius: calc(var(--curvature) * 2.5);\n border: 2px solid rgba(100, 100, 100, 0.1);\n max-width: 300px;\n word-break: break-word;\n overflow: hidden;\n }\n\n .msg.attachments-1.no-message {\n border: 2px solid transparent;\n background-color: transparent !important;\n }\n\n .msg .text {\n padding: var(--event-padding);\n }\n\n .event.msg_received .msg {\n background: rgba(200, 200, 200, 0.1);\n }\n\n .event.msg_created,\n .event.broadcast_created,\n .event.ivr_created,\n .event.ticket_note_added {\n align-self: flex-end;\n }\n\n .event.msg_created .msg,\n .event.broadcast_created .msg,\n .event.ivr_created .msg {\n background: var(--color-primary-dark);\n color: white;\n font-weight: 400;\n }\n\n .msg.automated {\n background: var(--color-automated) !important;\n }\n\n .queued {\n opacity: 0.3;\n }\n\n .optin_requested {\n --icon-color: var(--color-primary-dark);\n }\n\n .webhook_called {\n --icon-color: #e68628;\n word-break: break-all;\n }\n\n .webhook_called .failed {\n --icon-color: var(--color-error);\n color: var(--color-error);\n }\n\n .input_labels_added,\n .contact_name_changed,\n .contact_field_changed,\n .contact_urns_changed,\n .contact_language_changed,\n .run_result_changed {\n --icon-color: rgba(1, 193, 175, 1);\n }\n\n .email_sent {\n --icon-color: #8e5ea7;\n }\n\n .contact_groups_changed .added {\n --icon-color: #309c42;\n }\n .contact_groups_changed .removed {\n --icon-color: var(--color-error);\n }\n\n .event.error .description,\n .event.failure .description {\n color: var(--color-error);\n }\n\n .description.error {\n color: var(--color-error);\n }\n\n .info {\n border: 1px solid rgba(100, 100, 100, 0.2);\n background: rgba(10, 10, 10, 0.02);\n }\n\n .ticket_note_added {\n max-width: 300px;\n }\n\n .note-summary {\n display: flex;\n flex-direction: row;\n font-size: 85%;\n margin-top: -0.5em;\n color: rgba(0, 0, 0, 0.6);\n padding: 8px 3px;\n }\n\n .ticket_note_added .description {\n border: 2px solid rgba(100, 100, 100, 0.1);\n background: rgb(255, 249, 194);\n padding: var(--event-padding);\n font-weight: 400;\n color: rgba(0, 0, 0, 0.6);\n border-radius: calc(var(--curvature) * 2.5);\n }\n\n .channel_event {\n --icon-color: rgb(200, 200, 200);\n }\n\n .airtime_transferred,\n .flow_exited,\n .flow_entered,\n .ticket_opened,\n .ticket_reopened,\n .ticket_closed,\n .call_started,\n .campaign_fired {\n --icon-color: rgba(223, 65, 159, 1);\n }\n\n .active-ticket.ticket_opened {\n padding: 0em 1em;\n }\n\n .ticket_closed .inactive .subtext {\n display: none;\n }\n\n .attn {\n color: var(--color-text);\n }\n\n .flow_exited,\n .flow_entered {\n align-self: center;\n max-width: 80%;\n display: flex;\n flex-direction: row;\n }\n\n .flow_exited temba-icon,\n .flow_entered temba-icon {\n }\n\n .event {\n display: flex;\n align-items: center;\n }\n\n .event .description {\n flex-grow: 1;\n }\n\n .msg-summary {\n display: flex;\n font-size: 85%;\n color: rgba(0, 0, 0, 0.6);\n padding: 6px 3px;\n margin-bottom: 0.5em;\n margin-top: -0.5em;\n }\n\n .msg-summary temba-icon.log {\n --icon-color: rgba(0, 0, 0, 0.2);\n }\n\n .msg-summary temba-icon.log:hover {\n --icon-color: var(--color-link-primary-hover);\n cursor: pointer;\n }\n\n .msg-summary temba-icon.error {\n --icon-color: rgba(var(--error-rgb), 0.75);\n }\n\n .msg-summary temba-icon.error:hover {\n --icon-color: var(--color-error);\n cursor: pointer;\n }\n\n .msg-summary temba-icon.broadcast {\n --icon-color: rgba(90, 90, 90, 0.5);\n }\n\n .msg-summary * {\n display: flex;\n margin-right: 1px;\n margin-left: 1px;\n }\n\n .unsupported {\n border: 1px solid #f2f2f2;\n color: #999;\n padding: 0.5em 1em;\n border-radius: var(--curvature);\n }\n\n .optin {\n align-items: center;\n padding: 0 0.2em;\n }\n\n .time {\n padding: 0.3em 1px;\n }\n\n .subtext .time {\n padding: 0em;\n }\n\n .status {\n padding: 0.3em 3px;\n }\n\n .separator {\n padding: 0.3em 0px;\n }\n\n .recipients {\n padding: 0.3em 3px;\n }\n\n .verbose temba-icon,\n .flows temba-icon,\n .tickets temba-icon {\n margin-right: 0.75em;\n }\n\n .attn {\n display: inline-block;\n font-weight: 500;\n margin: 0px 2px;\n word-break: break-all;\n white-space: break-spaces;\n }\n\n .subtext {\n font-size: 80%;\n }\n\n .body-pre {\n white-space: pre-wrap;\n word-wrap: break-word;\n font-size: 90%;\n }\n\n a,\n .linked {\n color: var(--color-link-primary);\n cursor: pointer;\n }\n\n a:hover,\n .linked:hover {\n text-decoration: underline;\n color: var(--color-link-primary-hover);\n }\n\n temba-icon.error {\n --icon-color: var(--color-error);\n }\n\n .delivery-error {\n --icon-color: var(--color-error);\n margin-right: 0.25em;\n }\n\n .flow {\n --icon-color: #ddd;\n background: #fff;\n width: 18px;\n height: 18px;\n padding-top: 4px;\n padding-left: 9px;\n border: 0px solid #f3f3f3;\n }\n\n .assigned {\n color: #777;\n max-width: 300px;\n margin-left: auto;\n margin-right: auto;\n display: flex;\n flex-direction: column;\n align-items: center;\n margin-bottom: 10px;\n }\n\n .assigned .attn {\n color: #777;\n }\n\n .attachments {\n display: flex;\n flex-wrap: wrap;\n margin: -0.2em;\n }\n\n .attachment {\n flex: 1 0 45%;\n border-top: 0.05em solid transparent;\n border-left: 0.05em solid transparent;\n margin-top: 0.05em;\n margin-left: 0.05em;\n }\n `;\n};\n\nexport interface EventGroup {\n type: string;\n events: ContactEvent[];\n open: boolean;\n}\n\nexport enum Events {\n MESSAGE_CREATED = 'msg_created',\n MESSAGE_RECEIVED = 'msg_received',\n BROADCAST_CREATED = 'broadcast_created',\n IVR_CREATED = 'ivr_created',\n FLOW_ENTERED = 'flow_entered',\n FLOW_EXITED = 'flow_exited',\n RUN_RESULT_CHANGED = 'run_result_changed',\n CONTACT_FIELD_CHANGED = 'contact_field_changed',\n CONTACT_GROUPS_CHANGED = 'contact_groups_changed',\n CONTACT_NAME_CHANGED = 'contact_name_changed',\n CONTACT_URNS_CHANGED = 'contact_urns_changed',\n CAMPAIGN_FIRED = 'campaign_fired',\n CHANNEL_EVENT = 'channel_event',\n CONTACT_LANGUAGE_CHANGED = 'contact_language_changed',\n WEBHOOK_CALLED = 'webhook_called',\n AIRTIME_TRANSFERRED = 'airtime_transferred',\n CALL_STARTED = 'call_started',\n EMAIL_SENT = 'email_sent',\n INPUT_LABELS_ADDED = 'input_labels_added',\n NOTE_CREATED = 'note_created',\n TICKET_ASSIGNED = 'ticket_assigned',\n TICKET_NOTE_ADDED = 'ticket_note_added',\n TICKET_CLOSED = 'ticket_closed',\n TICKET_OPENED = 'ticket_opened',\n TICKET_REOPENED = 'ticket_reopened',\n OPTIN_REQUESTED = 'optin_requested',\n ERROR = 'error',\n FAILURE = 'failure',\n}\n\nexport interface ContactEvent {\n type: string;\n created_on: string;\n}\n\nexport interface ChannelEvent extends ContactEvent {\n channel_event_type: string;\n duration: number;\n\n event: {\n type: string;\n channel: { uuid: string; name: string };\n duration?: number;\n optin?: {\n uuid: string;\n name: string;\n };\n };\n}\n\nexport interface ContactLanguageChangedEvent extends ContactEvent {\n language: string;\n step_uuid: string;\n session_uuid: string;\n}\n\nexport interface OptinRequestedEvent extends ContactEvent {\n optin: {\n uuid: string;\n name: string;\n };\n}\n\nexport interface MsgEvent extends ContactEvent {\n msg: Msg;\n status: string;\n failed_reason?: string;\n failed_reason_display?: string;\n logs_url: string;\n msg_type: string;\n recipient_count?: number;\n created_by?: User;\n optin?: ObjectReference;\n}\n\nexport interface FlowEvent extends ContactEvent {\n flow: ObjectReference;\n status: string;\n}\n\nexport interface EmailSentEvent extends ContactEvent {\n to: string[];\n subject: string;\n body: string;\n}\n\nexport interface URNsChangedEvent extends ContactEvent {\n urns: string[];\n}\n\nexport interface TicketEvent extends ContactEvent {\n note?: string;\n assignee?: User;\n ticket: {\n uuid: string;\n body: string;\n topic?: ObjectReference;\n closed_on?: string;\n opened_on?: string;\n };\n created_by?: User;\n}\n\nexport interface LabelsAddedEvent extends ContactEvent {\n labels: ObjectReference[];\n}\n\nexport interface NameChangedEvent extends ContactEvent {\n name: string;\n}\n\nexport interface UpdateFieldEvent extends ContactEvent {\n field: { key: string; name: string };\n value: { text: string };\n}\n\nexport interface ErrorMessageEvent extends ContactEvent {\n text: string;\n}\n\nexport interface UpdateResultEvent extends ContactEvent {\n name: string;\n value: string;\n category: string;\n input: string;\n}\n\nexport interface ContactGroupsEvent extends ContactEvent {\n groups_added: ObjectReference[];\n groups_removed: ObjectReference[];\n}\n\nexport interface WebhookEvent extends ContactEvent {\n status: string;\n status_code: number;\n elapsed_ms: number;\n logs_url: string;\n url: string;\n}\n\nexport interface AirtimeTransferredEvent extends ContactEvent {\n sender: string;\n recipient: string;\n currency: string;\n desired_amount: string;\n actual_amount: string;\n logs_url: string;\n}\n\nexport type CallStartedEvent = ContactEvent;\nexport interface CampaignFiredEvent extends ContactEvent {\n campaign: { uuid: string; id: number; name: string };\n campaign_event: {\n id: number;\n offset_display: string;\n relative_to: { key: string; name: string };\n };\n fired_result: string;\n}\n\nexport interface ContactHistoryPage {\n has_older: boolean;\n recent_only: boolean;\n next_before: number;\n next_after: number;\n start_date: Date;\n events: ContactEvent[];\n}\n\nexport const getEventGroupType = (event: ContactEvent, ticket: string) => {\n if (!event) {\n return 'messages';\n }\n\n switch (event.type) {\n case Events.TICKET_ASSIGNED:\n case Events.TICKET_OPENED:\n case Events.TICKET_CLOSED:\n case Events.TICKET_REOPENED:\n if (!ticket) {\n return 'verbose';\n }\n\n if ((event as TicketEvent).ticket.uuid === ticket) {\n return 'tickets';\n }\n\n break;\n case Events.FLOW_ENTERED:\n case Events.FLOW_EXITED:\n return 'flows';\n case Events.BROADCAST_CREATED:\n case Events.MESSAGE_CREATED:\n case Events.MESSAGE_RECEIVED:\n case Events.IVR_CREATED:\n case Events.TICKET_NOTE_ADDED:\n case Events.NOTE_CREATED:\n return 'messages';\n }\n return 'verbose';\n};\n\nexport const renderAttachment = (attachment: string): TemplateResult => {\n const idx = attachment.indexOf(':');\n const attType = attachment.substr(0, idx);\n const url = attachment.substr(idx + 1);\n const [mediaType, ext] = attType.split('/', 2);\n\n let inner = null;\n if (mediaType === 'image') {\n inner = html`\n \n `;\n } else if (ext === 'pdf') {\n return html``;\n } else if (mediaType === 'video') {\n return html`\n \n `;\n } else if (mediaType === 'audio') {\n return html`\n ${url}\n `;\n } else if (attType === 'geo') {\n const [lat, long] = url.split(',');\n const latFloat = parseFloat(lat);\n const longFloat = parseFloat(long);\n const geo = `${lat}000000%2C${long}000000`;\n\n return html` `;\n } else {\n return html`
    \n \n
    Attachment ${ext}
    \n
    `;\n }\n\n return html`
    ${inner}
    `;\n};\n\nexport const renderMsgEvent = (event: MsgEvent): TemplateResult => {\n const isInbound = event.type === Events.MESSAGE_RECEIVED;\n const isError = event.status === 'E';\n const isFailure = event.status === 'F';\n\n // summary items which appear under the message bubble\n const summary: TemplateResult[] = [];\n\n if (event.logs_url) {\n summary.push(html`
    \n \n
    `);\n } else if (isError) {\n summary.push(\n html``\n );\n } else if (isFailure) {\n summary.push(\n html``\n );\n }\n\n if (event.type == 'broadcast_created') {\n summary.push(html``);\n\n if (event.recipient_count > 1) {\n summary.push(\n html`
    ${event.recipient_count} contacts
    `\n );\n }\n summary.push(html`
    `);\n }\n\n if (event.optin) {\n summary.push(\n html`
    ${event.optin.name}
    \n
    `\n );\n }\n\n if (event.status === 'Q') {\n summary.push(html`
    Queued
    `);\n }\n\n summary.push(\n html``\n );\n\n return html`\n
    \n \n ${event.msg.text\n ? html`
    ${event.msg.text}
    `\n : null}\n ${event.msg.attachments\n ? html`
    \n ${event.msg.attachments.map(\n attachment =>\n html`
    \n ${renderAttachment(attachment)}\n
    `\n )}\n
    `\n : null}\n
    \n\n ${!event.msg.text && !event.msg.attachments && !event.optin\n ? html`
    Unsupported Message
    `\n : null}\n\n \n
    \n ${summary}\n \n \n\n ${!isInbound && event.created_by\n ? html``\n : null}\n `;\n};\n\nexport const renderFlowEvent = (event: FlowEvent): TemplateResult => {\n let verb = 'Interrupted';\n let icon = Icon.flow_interrupted;\n\n if (event.status !== 'I') {\n if (event.type === Events.FLOW_ENTERED) {\n verb = 'Started';\n icon = Icon.flow;\n } else {\n verb = 'Completed';\n icon = Icon.flow;\n }\n }\n\n return html`\n \n
    \n ${verb}\n \n ${event.flow.name}\n \n
    \n `;\n};\n\nexport const renderResultEvent = (event: UpdateResultEvent): TemplateResult => {\n if (event.name.startsWith('_')) {\n return null;\n }\n return html`\n \n
    \n Updated\n
    ${event.name}
    \n to\n
    ${event.value}
    \n ${event.category\n ? html`with category\n
    ${event.category}
    `\n : null}\n
    \n `;\n};\n\nexport const renderUpdateEvent = (event: UpdateFieldEvent): TemplateResult => {\n return html`\n \n
    \n ${event.value\n ? html`Updated\n
    ${event.field.name}
    \n to\n
    ${event.value.text}
    `\n : html`Cleared\n
    ${event.field.name}
    `}\n
    \n `;\n};\n\nexport const renderNameChanged = (event: NameChangedEvent): TemplateResult => {\n return html`\n \n
    \n Updated\n
    Name
    \n to\n
    ${event.name}
    \n
    \n `;\n};\n\nexport const renderContactURNsChanged = (\n event: URNsChangedEvent\n): TemplateResult => {\n return html`\n \n
    \n Updated\n
    URNs
    \n to\n ${oxfordFn(\n event.urns,\n (urn: string) =>\n html`
    ${urn.split(':')[1].split('?')[0]}
    `\n )}\n
    \n \n `;\n};\n\nexport const renderEmailSent = (event: EmailSentEvent): TemplateResult => {\n return html`\n \n
    \n Email sent to\n
    ${oxford(event.to, 'and')}
    \n with subject\n
    ${event.subject}
    \n
    \n `;\n};\n\nexport const renderLabelsAdded = (event: LabelsAddedEvent): TemplateResult => {\n return html`\n \n
    \n Message labeled with\n
    ${oxfordNamed(event.labels, 'and')}
    \n
    \n `;\n};\n\nexport const renderNoteCreated = (event: TicketEvent): TemplateResult => {\n return html`
    \n
    \n
    ${event.note}
    \n
    \n
    \n \n
    \n
    \n \n
    `;\n};\n\nexport const renderTicketAction = (\n event: TicketEvent,\n action: string,\n grouped: boolean\n): TemplateResult => {\n if (grouped) {\n return html`
    \n \n
    \n ${getDisplayName(event.created_by)} ${action} a\n \n ticket\n \n
    \n
    `;\n }\n\n return html`\n
    \n
    \n ${event.created_by\n ? html` ${getDisplayName(event.created_by)} ${action} this ticket `\n : html` This ticket was ${action} `}\n
    \n
    \n \n
    \n
    \n `;\n};\n\nexport const renderTicketAssigned = (event: TicketEvent): TemplateResult => {\n return html`\n
    \n
    \n ${event.assignee\n ? event.assignee.id === event.created_by.id\n ? html`${getDisplayName(event.created_by)} took this ticket`\n : html`${getDisplayName(event.created_by)} assigned this ticket to\n
    ${getDisplayName(event.assignee)}
    `\n : html`${getDisplayName(event.created_by)} unassigned this ticket`}\n
    \n
    \n \n
    \n
    \n `;\n};\n\nexport const renderTicketOpened = (\n event: TicketEvent,\n handleClose: (uuid: string) => void,\n grouped: boolean\n): TemplateResult => {\n if (grouped) {\n return html`
    \n \n
    \n ${event.ticket.topic.name}\n ticket\n was opened\n
    \n
    `;\n } else {\n return html`\n
    \n
    \n ${getDisplayName(event.created_by)} opened this ticket\n
    \n
    \n \n
    \n
    \n `;\n }\n};\n\nexport const renderErrorMessage = (\n event: ErrorMessageEvent\n): TemplateResult => {\n return html`\n \n
    \n ${event.text}\n ${event.type === Events.FAILURE\n ? html`
    Run ended prematurely, check the flow design.
    `\n : null}\n
    \n `;\n};\n\nexport const renderWebhookEvent = (event: WebhookEvent): TemplateResult => {\n return html`\n \n \n
    \n ${event.status === 'success'\n ? html`Successfully called ${event.url}`\n : html`Failed to call ${event.url}`}\n
    \n \n `;\n};\n\nexport const renderAirtimeTransferredEvent = (\n event: AirtimeTransferredEvent\n): TemplateResult => {\n if (parseFloat(event.actual_amount) === 0) {\n return html`\n
    Airtime transfer failed
    `;\n }\n\n return html`\n
    \n Transferred\n
    ${event.actual_amount} ${event.currency}
    \n of airtime\n
    `;\n};\n\nexport const renderCallStartedEvent = (): TemplateResult => {\n return html`\n
    Call Started
    `;\n};\n\nexport const renderContactLanguageChangedEvent = (\n event: ContactLanguageChangedEvent\n): TemplateResult => {\n return html`\n
    \n Language updated to ${event.language}\n
    `;\n};\n\nexport const renderOptinRequested = (\n event: OptinRequestedEvent\n): TemplateResult => {\n return html`\n
    \n Requested opt-in for ${event.optin.name}\n
    `;\n};\n\nexport const renderChannelEvent = (event: ChannelEvent): TemplateResult => {\n let eventMessage: string | TemplateResult = '';\n let icon = Icon.call;\n\n if (event.event.type === 'mt_miss') {\n eventMessage = 'Missed outgoing call';\n icon = Icon.call_missed;\n } else if (event.event.type === 'mo_miss') {\n eventMessage = 'Missed incoming call';\n icon = Icon.call_missed;\n } else if (event.event.type === 'new_conversation') {\n eventMessage = 'Started Conversation';\n icon = Icon.event;\n } else if (event.channel_event_type === 'welcome_message') {\n eventMessage = 'Welcome Message Sent';\n icon = Icon.event;\n } else if (event.event.type === 'referral') {\n eventMessage = 'Referred';\n icon = Icon.event;\n } else if (event.event.type === 'follow') {\n eventMessage = 'Followed';\n icon = Icon.event;\n } else if (event.event.type === 'stop_contact') {\n eventMessage = 'Stopped';\n icon = Icon.contact_stopped;\n } else if (event.event.type === 'mt_call') {\n eventMessage = 'Outgoing Phone Call';\n } else if (event.event.type == 'mo_call') {\n eventMessage = 'Incoming Phone call';\n } else if (event.event.type == 'optin') {\n eventMessage = html`Opted in to\n ${event.event.optin?.name}`;\n icon = Icon.optin;\n } else if (event.event.type == 'optout') {\n eventMessage = html`Opted out of\n ${event.event.optin?.name}`;\n icon = Icon.optout;\n }\n\n return html`\n
    ${eventMessage}
    `;\n};\n\nexport const renderCampaignFiredEvent = (\n event: CampaignFiredEvent\n): TemplateResult => {\n return html`\n
    \n Campaign\n ${event.campaign.name}\n ${event.fired_result === 'S' ? 'skipped' : 'triggered'}\n \n ${event.campaign_event.offset_display}\n ${event.campaign_event.relative_to.name}\n
    `;\n};\n\nexport const renderContactGroupsEvent = (\n event: ContactGroupsEvent\n): TemplateResult => {\n const groups = event.groups_added || event.groups_removed;\n const added = !!event.groups_added;\n return html`\n \n
    \n ${added ? 'Added to' : 'Removed from'}\n ${oxfordFn(\n groups,\n (group: ObjectReference) =>\n html`${group.name}`\n )}\n ${event.type === Events.FAILURE\n ? html`
    Run ended prematurely, check the flow design.
    `\n : null}\n
    \n `;\n};\n","import { css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { html, TemplateResult } from 'lit-html';\nimport { Contact, CustomEventType, Msg, Ticket } from '../interfaces';\nimport { RapidElement } from '../RapidElement';\nimport { Asset, getAssets, getClasses, postJSON, throttle } from '../utils';\n\nimport {\n AirtimeTransferredEvent,\n CampaignFiredEvent,\n ChannelEvent,\n ContactEvent,\n ContactGroupsEvent,\n ContactHistoryPage,\n ContactLanguageChangedEvent,\n EmailSentEvent,\n ErrorMessageEvent,\n EventGroup,\n Events,\n FlowEvent,\n getEventGroupType,\n getEventStyles,\n LabelsAddedEvent,\n MsgEvent,\n NameChangedEvent,\n OptinRequestedEvent,\n renderAirtimeTransferredEvent,\n renderCallStartedEvent,\n renderCampaignFiredEvent,\n renderChannelEvent,\n renderContactGroupsEvent,\n renderContactLanguageChangedEvent,\n renderContactURNsChanged,\n renderEmailSent,\n renderErrorMessage,\n renderFlowEvent,\n renderLabelsAdded,\n renderMsgEvent,\n renderNameChanged,\n renderNoteCreated,\n renderOptinRequested,\n renderResultEvent,\n renderTicketAction,\n renderTicketAssigned,\n renderTicketOpened,\n renderUpdateEvent,\n renderWebhookEvent,\n TicketEvent,\n UpdateFieldEvent,\n UpdateResultEvent,\n URNsChangedEvent,\n WebhookEvent,\n} from './events';\nimport {\n fetchContactHistory,\n MAX_CHAT_REFRESH,\n MIN_CHAT_REFRESH,\n SCROLL_THRESHOLD,\n} from './helpers';\nimport { Lightbox } from '../lightbox/Lightbox';\nimport { Store } from '../store/Store';\n\n// when images load, make sure we are on the bottom of the scroll window if necessary\nexport const loadHandler = function (event) {\n const target = event.target as HTMLElement;\n const events = this.host.getEventsPane();\n if (target.tagName == 'IMG') {\n if (!this.host.showMessageAlert) {\n if (\n events.scrollTop > target.offsetTop - 1000 &&\n target.offsetTop > events.scrollHeight - 500\n ) {\n this.host.scrollToBottom();\n }\n }\n }\n};\n\nexport class ContactHistory extends RapidElement {\n public httpComplete: Promise;\n private store: Store;\n\n public constructor() {\n super();\n }\n\n connectedCallback() {\n super.connectedCallback();\n this.shadowRoot.addEventListener('load', loadHandler, true);\n this.store = document.querySelector('temba-store') as Store;\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this.shadowRoot.removeEventListener('load', loadHandler, true);\n }\n\n private getTicketForEvent(event: TicketEvent) {\n return this.getTicket((event as TicketEvent).ticket.uuid);\n }\n\n private getTicket(uuid: string) {\n return (this.tickets || []).find(ticket => ticket.uuid === uuid);\n }\n\n static get styles() {\n return css`\n ${getEventStyles()}\n\n .wrapper {\n border: 0px solid green;\n display: flex;\n flex-direction: column;\n align-items: items-stretch;\n flex-grow: 1;\n min-height: 0;\n }\n\n .events {\n overflow-y: scroll;\n overflow-x: hidden;\n background: #fff;\n display: flex;\n flex-direction: column;\n flex-grow: 1;\n min-height: 0;\n padding-top: 3em;\n padding-bottom: 1em;\n }\n\n temba-loading {\n align-self: center;\n margin-top: 0.025em;\n position: absolute;\n z-index: 250;\n padding-top: 1em;\n }\n\n .new-messages-container {\n display: flex;\n z-index: 1;\n background: pink;\n margin-bottom: 0px;\n }\n\n .new-messages {\n pointer-events: none;\n margin: 0 auto;\n margin-top: 0em;\n margin-bottom: -2.5em;\n padding: 0.25em 1em;\n border-radius: var(--curvature);\n background: var(--color-primary-dark);\n color: var(--color-text-light);\n opacity: 0;\n cursor: pointer;\n transition: all var(--transition-speed) ease-in-out;\n box-shadow: rgb(0 0 0 / 15%) 0px 3px 3px 0px;\n }\n\n .new-messages.expanded {\n margin-top: -2.5em;\n margin-bottom: 0.5em;\n pointer-events: auto;\n opacity: 1;\n pointer: cursor;\n }\n\n .scroll-title {\n display: flex;\n flex-direction: column;\n z-index: 2;\n border-top-left-radius: var(--curvature);\n overflow: hidden;\n box-shadow: 0px 3px 3px 0px rgba(0, 0, 0, 0.15);\n background: rgb(240, 240, 240);\n padding: 1em 1.2em;\n font-size: 1.2em;\n font-weight: 400;\n }\n\n .attachment img {\n cursor: pointer;\n }\n `;\n }\n\n @property({ type: Object })\n contact: Contact;\n\n @property({ type: String })\n uuid: string;\n\n @property({ type: String })\n agent: string;\n\n @property({ type: Array })\n eventGroups: EventGroup[] = [];\n\n @property({ type: Boolean })\n refreshing = false;\n\n @property({ type: Boolean })\n fetching = false;\n\n @property({ type: Boolean })\n complete = false;\n\n @property({ type: String })\n endpoint: string;\n\n @property({ type: Boolean })\n debug = false;\n\n @property({ type: Boolean })\n showMessageAlert = false;\n\n @property({ attribute: false, type: Object })\n mostRecentEvent: ContactEvent;\n\n @property({ type: String })\n ticket: string = null;\n\n @property({ type: String })\n endDate: string = null;\n\n @property({ type: Array })\n tickets: Ticket[] = null;\n\n ticketEvents: { [uuid: string]: TicketEvent } = {};\n\n nextBefore: number;\n nextAfter: number;\n lastHeight = 0;\n lastRefreshAdded: number;\n refreshTimeout: any = null;\n empty = false;\n\n public firstUpdated(changedProperties: Map) {\n super.firstUpdated(changedProperties);\n this.handleClose = this.handleClose.bind(this);\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n // fire an event if we get a new event\n if (\n changedProperties.has('mostRecentEvent') &&\n changedProperties.get('mostRecentEvent') &&\n this.mostRecentEvent\n ) {\n this.fireCustomEvent(CustomEventType.Refreshed);\n }\n\n if (changedProperties.has('endDate')) {\n if (this.refreshTimeout && this.endDate) {\n window.clearTimeout(this.refreshTimeout);\n }\n }\n\n // if we don't have an endpoint infer one\n if (changedProperties.has('uuid')) {\n if (this.uuid == null) {\n this.reset();\n } else {\n const endpoint = `/contact/history/${this.uuid}/?_format=json`;\n\n if (this.endpoint !== endpoint) {\n this.reset();\n\n if (this.endDate) {\n const before = new Date(this.endDate);\n this.nextBefore = before.getTime() * 1000 + 1000;\n }\n\n this.endpoint = endpoint;\n this.refreshTickets();\n }\n }\n }\n\n if (changedProperties.has('ticket')) {\n this.endpoint = null;\n this.requestUpdate('uuid');\n }\n\n if (\n changedProperties.has('refreshing') &&\n this.refreshing &&\n this.endpoint &&\n !this.endDate\n ) {\n const after = (this.getLastEventTime() - 1) * 1000;\n let forceOpen = false;\n\n fetchContactHistory(false, this.endpoint, this.ticket, null, after)\n .then((results: ContactHistoryPage) => {\n if (results.events && results.events.length > 0) {\n this.updateMostRecent(results.events[0]);\n }\n\n // keep track of any ticket events\n results.events.forEach((event: ContactEvent) => {\n if (event.type === Events.TICKET_OPENED) {\n const ticketEvent = event as TicketEvent;\n this.ticketEvents[ticketEvent.ticket.uuid] = ticketEvent;\n }\n });\n\n const fetchedEvents = results.events.reverse();\n\n // dedupe any events we get from the server\n // TODO: perhaps make this a little less crazy\n let removed = 0;\n this.eventGroups.forEach(g => {\n const before = g.events.length;\n g.events = g.events.filter(\n prev =>\n !fetchedEvents.find(fetched => {\n return (\n prev.created_on == fetched.created_on &&\n prev.type === fetched.type\n );\n })\n );\n removed += before - g.events.length;\n });\n\n this.lastRefreshAdded = fetchedEvents.length - removed;\n\n // reflow our most recent event group in case it merges with our new groups\n const previousGroups = [...this.eventGroups];\n\n if (this.eventGroups.length > 0) {\n const sliced = previousGroups.splice(\n previousGroups.length - 1,\n 1\n )[0];\n\n forceOpen = sliced.open;\n fetchedEvents.splice(0, 0, ...sliced.events);\n }\n\n const grouped = this.getEventGroups(fetchedEvents);\n if (grouped.length) {\n if (forceOpen) {\n grouped[grouped.length - 1].open = forceOpen;\n }\n this.eventGroups = [...previousGroups, ...grouped];\n }\n this.refreshing = false;\n this.scheduleRefresh();\n })\n .catch(() => {\n this.refreshing = false;\n this.scheduleRefresh();\n });\n }\n\n if (changedProperties.has('fetching') && this.fetching) {\n if (!this.nextBefore) {\n this.nextBefore = new Date().getTime() * 1000 - 1000;\n }\n\n this.httpComplete = fetchContactHistory(\n this.empty,\n this.endpoint,\n this.ticket,\n this.nextBefore,\n this.nextAfter\n ).then((results: ContactHistoryPage) => {\n // see if we have a new event\n if (results.events && results.events.length > 0) {\n this.updateMostRecent(results.events[0]);\n\n // keep track of any ticket events\n results.events.forEach((event: ContactEvent) => {\n if (event.type === Events.TICKET_OPENED) {\n const ticketEvent = event as TicketEvent;\n this.ticketEvents[ticketEvent.ticket.uuid] = ticketEvent;\n }\n });\n }\n\n let forceOpen = false;\n const fetchedEvents = results.events ? results.events.reverse() : [];\n\n // reflow our last event group in case it merges with our new groups\n if (this.eventGroups.length > 0) {\n const sliced = this.eventGroups.splice(0, 1)[0];\n forceOpen = sliced.open;\n fetchedEvents.push(...sliced.events);\n }\n\n const grouped = this.getEventGroups(fetchedEvents);\n if (grouped.length) {\n if (forceOpen) {\n grouped[grouped.length - 1].open = forceOpen;\n }\n\n this.eventGroups = [...grouped, ...this.eventGroups];\n }\n\n if (results.next_before === this.nextBefore) {\n this.complete = true;\n }\n\n this.nextBefore = results.next_before;\n this.nextAfter = results.next_after;\n this.fetching = false;\n this.empty = false;\n });\n }\n\n if (changedProperties.has('refreshing') && !this.refreshing) {\n if (this.lastRefreshAdded > 0) {\n const events = this.getEventsPane();\n\n // if we are near the bottom, push us to the bottom to show new stuff\n if (this.lastHeight > 0) {\n const addedHeight = events.scrollHeight - this.lastHeight;\n\n const distanceFromBottom =\n events.scrollHeight -\n events.scrollTop -\n addedHeight -\n events.clientHeight;\n\n if (distanceFromBottom < 500) {\n this.scrollToBottom();\n } else {\n this.showMessageAlert = true;\n }\n }\n\n if (this.eventGroups.length > 0) {\n this.lastHeight = events.scrollHeight;\n }\n }\n }\n\n if (\n changedProperties.has('fetching') &&\n !this.fetching &&\n changedProperties.get('fetching') !== undefined\n ) {\n const events = this.getEventsPane();\n\n if (this.lastHeight && events.scrollHeight > this.lastHeight) {\n const scrollTop =\n events.scrollTop + events.scrollHeight - this.lastHeight;\n events.scrollTop = scrollTop;\n }\n\n // scroll to the bottom if it's our first fetch\n if (!this.lastHeight) {\n this.scrollToBottom();\n }\n\n // don't record our scroll height until we have history\n if (this.eventGroups.length > 0) {\n this.lastHeight = events.scrollHeight;\n }\n }\n\n if (changedProperties.has('endpoint') && this.endpoint) {\n this.fetching = true;\n this.empty = true;\n }\n }\n\n private refreshTickets() {\n if (this.ticket) {\n let url = `/api/v2/tickets.json?contact=${this.uuid}`;\n if (this.ticket) {\n url = `${url}&ticket=${this.ticket}`;\n }\n\n getAssets(url).then((tickets: Ticket[]) => {\n this.tickets = tickets.reverse();\n });\n }\n }\n\n public getEventsPane() {\n return this.getDiv('.events');\n }\n\n public scrollToBottom(smooth = false) {\n const events = this.getEventsPane();\n events.scrollTo({\n top: events.scrollHeight,\n behavior: smooth ? 'smooth' : 'auto',\n });\n this.showMessageAlert = false;\n\n window.setTimeout(() => {\n events.scrollTo({\n top: events.scrollHeight,\n behavior: smooth ? 'smooth' : 'auto',\n });\n }, 0);\n }\n\n public refresh(): void {\n this.scheduleRefresh(500);\n }\n\n private getEventGroups(events: ContactEvent[]): EventGroup[] {\n const grouped: EventGroup[] = [];\n let eventGroup: EventGroup = undefined;\n for (const event of events) {\n const currentEventGroupType = getEventGroupType(event, this.ticket);\n // see if we need a new event group\n if (!eventGroup || eventGroup.type !== currentEventGroupType) {\n // we have a new type, save our last group\n if (eventGroup) {\n grouped.push(eventGroup);\n }\n eventGroup = {\n open: false,\n events: [event],\n type: currentEventGroupType,\n };\n } else {\n // our event matches the current group, stuff it in there\n eventGroup.events.push(event);\n }\n }\n\n if (eventGroup && eventGroup.events.length > 0) {\n grouped.push(eventGroup);\n }\n return grouped;\n }\n\n private scheduleRefresh(wait = -1) {\n if (this.endDate) {\n return;\n }\n\n let refreshWait = wait;\n\n if (wait === -1) {\n const lastEventTime = this.getLastEventTime();\n refreshWait = Math.max(\n Math.min((new Date().getTime() - lastEventTime) / 2, MAX_CHAT_REFRESH),\n MIN_CHAT_REFRESH\n );\n }\n\n // cancel any outstanding timeout\n if (wait > -1 && this.refreshTimeout) {\n window.clearTimeout(this.refreshTimeout);\n }\n\n this.refreshTimeout = window.setTimeout(() => {\n if (this.refreshing) {\n this.scheduleRefresh();\n this.refreshing = false;\n } else {\n this.refreshing = true;\n }\n }, refreshWait);\n }\n\n private reset() {\n this.endpoint = null;\n this.tickets = null;\n this.ticketEvents = {};\n this.eventGroups = [];\n this.fetching = false;\n this.complete = false;\n this.nextBefore = null;\n this.nextAfter = null;\n this.lastHeight = 0;\n }\n\n private handleEventGroupShow(event: MouseEvent) {\n const grouping = event.currentTarget as HTMLDivElement;\n const groupIndex = parseInt(grouping.getAttribute('data-group-index'));\n const eventGroup =\n this.eventGroups[this.eventGroups.length - groupIndex - 1];\n eventGroup.open = true;\n this.requestUpdate('eventGroups');\n }\n\n private handleEventGroupHide(event: MouseEvent) {\n event.preventDefault();\n event.stopPropagation();\n\n const grouping = event.currentTarget as HTMLDivElement;\n const groupIndex = parseInt(grouping.getAttribute('data-group-index'));\n const eventGroup =\n this.eventGroups[this.eventGroups.length - groupIndex - 1];\n\n eventGroup.open = false;\n\n this.requestUpdate('eventGroups');\n }\n\n private handleScroll() {\n const events = this.getEventsPane();\n if (events.scrollTop <= SCROLL_THRESHOLD) {\n if (this.eventGroups.length > 0 && !this.fetching && !this.complete) {\n this.fetching = true;\n }\n }\n }\n\n private updateMostRecent(newEvent: ContactEvent) {\n if (\n !this.mostRecentEvent ||\n this.mostRecentEvent.type !== newEvent.type ||\n this.mostRecentEvent.created_on !== newEvent.created_on\n ) {\n this.mostRecentEvent = newEvent;\n }\n }\n\n private getLastEventTime(): number {\n const mostRecentGroup = this.eventGroups[this.eventGroups.length - 1];\n if (mostRecentGroup) {\n const mostRecentEvent =\n mostRecentGroup.events[mostRecentGroup.events.length - 1];\n return new Date(mostRecentEvent.created_on).getTime();\n }\n return 0;\n }\n\n public renderEvent(event: ContactEvent): any {\n switch (event.type) {\n case Events.IVR_CREATED:\n case Events.MESSAGE_CREATED:\n case Events.MESSAGE_RECEIVED:\n case Events.BROADCAST_CREATED:\n if ((event as MsgEvent).created_by) {\n (event as MsgEvent).created_by = this.store.getUser(\n (event as MsgEvent).created_by.email\n );\n }\n\n return renderMsgEvent(event as MsgEvent);\n\n case Events.FLOW_ENTERED:\n case Events.FLOW_EXITED:\n return renderFlowEvent(event as FlowEvent);\n\n case Events.RUN_RESULT_CHANGED:\n return renderResultEvent(event as UpdateResultEvent);\n\n case Events.CONTACT_FIELD_CHANGED:\n return renderUpdateEvent(event as UpdateFieldEvent);\n\n case Events.CONTACT_NAME_CHANGED:\n return renderNameChanged(event as NameChangedEvent);\n\n case Events.CONTACT_URNS_CHANGED:\n return renderContactURNsChanged(event as URNsChangedEvent);\n\n case Events.EMAIL_SENT:\n return renderEmailSent(event as EmailSentEvent);\n\n case Events.INPUT_LABELS_ADDED:\n return renderLabelsAdded(event as LabelsAddedEvent);\n\n case Events.TICKET_OPENED: {\n return renderTicketAction(event as TicketEvent, 'opened', !this.ticket);\n }\n case Events.TICKET_NOTE_ADDED:\n return renderNoteCreated(event as TicketEvent);\n\n case Events.TICKET_ASSIGNED:\n return renderTicketAssigned(event as TicketEvent);\n case Events.TICKET_REOPENED: {\n return renderTicketAction(\n event as TicketEvent,\n 'reopened',\n !this.ticket\n );\n }\n case Events.TICKET_CLOSED:\n return renderTicketAction(event as TicketEvent, 'closed', !this.ticket);\n\n case Events.ERROR:\n case Events.FAILURE:\n return renderErrorMessage(event as ErrorMessageEvent);\n case Events.CONTACT_GROUPS_CHANGED:\n return renderContactGroupsEvent(event as ContactGroupsEvent);\n case Events.WEBHOOK_CALLED:\n return renderWebhookEvent(event as WebhookEvent);\n case Events.AIRTIME_TRANSFERRED:\n return renderAirtimeTransferredEvent(event as AirtimeTransferredEvent);\n case Events.CALL_STARTED:\n return renderCallStartedEvent();\n case Events.CAMPAIGN_FIRED:\n return renderCampaignFiredEvent(event as CampaignFiredEvent);\n case Events.CHANNEL_EVENT:\n return renderChannelEvent(event as ChannelEvent);\n case Events.CONTACT_LANGUAGE_CHANGED:\n return renderContactLanguageChangedEvent(\n event as ContactLanguageChangedEvent\n );\n case Events.OPTIN_REQUESTED:\n return renderOptinRequested(event as OptinRequestedEvent);\n }\n\n return html`\n
    ${event.type}
    `;\n }\n\n private handleClose(uuid: string) {\n this.httpComplete = postJSON(`/api/v2/ticket_actions.json`, {\n tickets: [uuid],\n action: 'close',\n })\n .then(() => {\n this.refreshTickets();\n this.refresh();\n this.fireCustomEvent(CustomEventType.ContentChanged, {\n ticket: { uuid, status: 'closed' },\n });\n })\n .catch((response: any) => {\n console.error(response);\n });\n }\n\n public checkForAgentAssignmentEvent(agent: string) {\n this.httpComplete = getAssets(\n `/api/v2/tickets.json?uuid=${this.ticket}`\n ).then((assets: Asset[]) => {\n if (assets.length === 1) {\n const ticket = assets[0] as Ticket;\n if (ticket.assignee && ticket.assignee.email === agent) {\n this.fireCustomEvent(CustomEventType.ContentChanged, {\n ticket: { uuid: this.ticket, assigned: 'self' },\n });\n } else {\n this.fireCustomEvent(CustomEventType.ContentChanged, {\n ticket: {\n uuid: this.ticket,\n assigned: ticket.assignee ? ticket.assignee : null,\n },\n });\n }\n }\n });\n }\n\n public getEventHandlers() {\n return [\n {\n event: 'scroll',\n method: throttle(this.handleScroll, 50),\n },\n ];\n }\n\n /** Check if a ticket event is no longer represented in a session */\n private isPurged(ticket: Ticket): boolean {\n return !this.ticketEvents[ticket.uuid];\n }\n\n private handleEventClicked(event) {\n const ele = event.target as HTMLDivElement;\n if (ele.tagName == 'IMG') {\n // if we have one, show in our lightbox\n const lightbox = document.querySelector('temba-lightbox') as Lightbox;\n if (lightbox) {\n lightbox.showElement(ele);\n }\n }\n }\n\n private renderEventContainer(event: ContactEvent) {\n const renderedEvent = html`\n \n ${this.renderEvent(event)}\n \n ${this.debug ? html`
    ${JSON.stringify(event, null, 2)}
    ` : null}\n `;\n return renderedEvent;\n }\n\n public render(): TemplateResult {\n return html`\n ${\n this.fetching\n ? html``\n : html`
    `\n }\n
    \n ${this.eventGroups.map((eventGroup: EventGroup, index: number) => {\n const grouping = getEventGroupType(eventGroup.events[0], this.ticket);\n const groupIndex = this.eventGroups.length - index - 1;\n\n const classes = getClasses({\n grouping: true,\n [grouping]: true,\n expanded: eventGroup.open,\n });\n return html`
    \n ${grouping === 'verbose'\n ? html`\n ${eventGroup.open\n ? html``\n : html`${eventGroup.events.length}\n ${eventGroup.events.length === 1\n ? html`event`\n : html`events`} `}\n
    `\n : null}\n\n
    \n ${eventGroup.events.map((event: ContactEvent) => {\n if (\n event.type === Events.TICKET_ASSIGNED &&\n (event as TicketEvent).note\n ) {\n const noteEvent = { ...event };\n noteEvent.type = Events.TICKET_NOTE_ADDED;\n\n return html`${this.renderEventContainer(\n noteEvent\n )}${this.renderEventContainer(event)}`;\n } else {\n return this.renderEventContainer(event);\n }\n })}\n
    \n
    `;\n })}\n \n\n ${\n this.contact && this.contact.status === 'active'\n ? html`
    \n {\n this.scrollToBottom(true);\n }}\n class=\"new-messages ${getClasses({\n expanded: this.showMessageAlert,\n })}\"\n >\n New Messages\n
    \n `\n : null\n }\n \n \n `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { RapidElement } from '../RapidElement';\nimport { Store } from '../store/Store';\nimport { fetchResultsPage, ResultsPage } from '../utils';\n\nconst DEFAULT_REFRESH = 10000;\n\nexport class TembaList extends RapidElement {\n @property({ type: Array, attribute: false })\n items: any[] = [];\n\n @property({ type: Object, attribute: false })\n selected: any;\n\n @property({ type: Number })\n cursorIndex = -1;\n\n @property({ type: String })\n endpoint: string;\n\n @property({ type: String })\n nextSelection: any;\n\n @property({ type: Number })\n tabIndex = 1;\n\n @property({ type: String })\n valueKey = 'id';\n\n @property({ type: String })\n value: string;\n\n @property({ type: Boolean })\n loading = false;\n\n @property({ type: Boolean })\n collapsed: boolean;\n\n @property({ type: Boolean })\n hideShadow: boolean;\n\n @property({ type: Boolean })\n paused = false;\n\n @property({ type: Boolean })\n internalFocusDisabled = false;\n\n @property({ attribute: false })\n getNextRefresh: (firstOption: any) => any;\n\n @property({ attribute: false })\n sanitizeOption: (option: any) => any;\n\n @property({ attribute: false })\n renderOption: (option: any, selected: boolean) => TemplateResult;\n\n @property({ attribute: false })\n renderOptionDetail: (option: any, selected: boolean) => TemplateResult;\n\n @property({ attribute: false, type: Object })\n mostRecentItem: any;\n\n // changes to the refresh key force a refresh\n @property({ type: String })\n refreshKey = '0';\n\n reverseRefresh = true;\n\n // our next page from our endpoint\n nextPage: string = null;\n\n pages = 0;\n clearRefreshTimeout: any;\n pending: AbortController[] = [];\n\n store: Store;\n\n // used for testing only\n preserve: boolean;\n\n static get styles() {\n return css`\n temba-options {\n display: block;\n width: 100%;\n flex-grow: 1;\n }\n `;\n }\n\n constructor() {\n super();\n this.store = document.querySelector('temba-store') as Store;\n this.handleSelection.bind(this);\n }\n\n private reset(): void {\n this.selected = null;\n this.nextPage = null;\n this.cursorIndex = -1;\n this.mostRecentItem = null;\n this.items = [];\n }\n\n refreshInterval = null;\n\n public connectedCallback() {\n super.connectedCallback();\n this.refreshInterval = setInterval(() => {\n if (!this.paused) {\n this.refreshKey = 'default_' + new Date().getTime();\n }\n }, DEFAULT_REFRESH);\n }\n\n public disconnectedCallback() {\n clearInterval(this.refreshInterval);\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n if (changedProperties.has('endpoint') && this.endpoint) {\n this.reset();\n this.loading = true;\n this.fetchItems();\n }\n\n if (changedProperties.has('loading')) {\n if (!this.loading) {\n this.fireCustomEvent(CustomEventType.FetchComplete);\n }\n }\n\n if (\n changedProperties.has('refreshKey') &&\n !changedProperties.has('endpoint')\n ) {\n this.refreshTop();\n }\n\n if (changedProperties.has('mostRecentItem') && this.mostRecentItem) {\n this.fireCustomEvent(CustomEventType.Refreshed);\n }\n\n if (changedProperties.has('cursorIndex')) {\n if (this.cursorIndex > -1) {\n this.selected = this.items[this.cursorIndex];\n this.handleSelected(this.selected);\n }\n }\n\n if (changedProperties.has('items')) {\n //\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n public handleSelected(selected: any) {\n const evt = new Event('change', { bubbles: true });\n this.dispatchEvent(evt);\n }\n\n private getValue(obj: any): any {\n if (!obj) {\n return null;\n }\n\n const path = this.valueKey.split('.');\n let current = obj;\n while (path.length > 0) {\n const key = path.shift();\n current = current[key];\n }\n return current;\n }\n\n public setSelection(value: string) {\n const index = this.items.findIndex(item => {\n return this.getValue(item) === value;\n });\n this.cursorIndex = index;\n this.selected = this.items[index];\n const evt = new Event('change', { bubbles: true });\n this.dispatchEvent(evt);\n }\n\n public getItemIndex(value: string) {\n return this.items.findIndex(option => this.getValue(option) === value);\n }\n\n public removeItem(value: string) {\n const index = this.getItemIndex(value);\n this.items.splice(index, 1);\n this.items = [...this.items];\n\n // if we were at the end, move us down\n this.cursorIndex = Math.max(\n 0,\n Math.min(this.items.length - 1, this.cursorIndex - 1)\n );\n\n // request a change even if it is the same, the item is different\n this.requestUpdate('cursorIndex');\n this.requestUpdate('items');\n }\n\n public getSelection(): any {\n return this.selected;\n }\n\n public refresh(): void {\n this.refreshKey = 'requested_' + new Date().getTime();\n }\n\n public setEndpoint(endpoint: string, nextSelection: any = null) {\n this.endpoint = endpoint;\n this.nextSelection = nextSelection;\n }\n\n public getRefreshEndpoint() {\n return this.endpoint;\n }\n\n /**\n * Refreshes the first page, updating any found items in our list\n */\n private async refreshTop(): Promise {\n const refreshEndpoint = this.getRefreshEndpoint();\n if (!refreshEndpoint) {\n return;\n }\n\n // cancel any outstanding requests\n while (this.pending.length > 0) {\n const pending = this.pending.pop();\n pending.abort();\n }\n\n const controller = new AbortController();\n this.pending.push(controller);\n\n const prevItem = this.items[this.cursorIndex];\n\n try {\n const page = await fetchResultsPage(\n this.getRefreshEndpoint(),\n controller\n );\n\n const items = [...this.items];\n // remove any dupes already in our list\n if (page.results) {\n page.results.forEach((newOption: any) => {\n if (this.sanitizeOption) {\n this.sanitizeOption(newOption);\n }\n const newValue = this.getValue(newOption);\n const removeIndex = items.findIndex(\n option => this.getValue(option) === newValue\n );\n\n if (removeIndex > -1) {\n items.splice(removeIndex, 1);\n }\n });\n\n // insert our new items at the front\n let results = page.results;\n if (this.reverseRefresh) {\n results = page.results.reverse();\n }\n const newItems = [...results, ...items];\n\n const topItem = newItems[0];\n if (\n !this.mostRecentItem ||\n JSON.stringify(this.mostRecentItem) !== JSON.stringify(topItem)\n ) {\n this.mostRecentItem = topItem;\n }\n\n if (prevItem) {\n const newItem = newItems[this.cursorIndex];\n const prevValue = this.getValue(prevItem);\n if (prevValue !== this.getValue(newItem)) {\n const newIndex = newItems.findIndex(\n option => this.getValue(option) === prevValue\n );\n this.cursorIndex = newIndex;\n\n // make sure our focused item is visible\n window.setTimeout(() => {\n const options = this.shadowRoot.querySelector('temba-options');\n if (options) {\n const option =\n options.shadowRoot.querySelector('.option.focused');\n option.scrollIntoView({ block: 'end', inline: 'nearest' });\n }\n }, 0);\n }\n }\n\n this.items = newItems;\n }\n } catch (error) {\n console.error(error);\n }\n }\n\n private async fetchItems(): Promise {\n // cancel any outstanding requests\n while (this.pending.length > 0) {\n const pending = this.pending.pop();\n pending.abort();\n }\n\n let endpoint = this.endpoint;\n let pagesToFetch = this.pages || 1;\n let pages = 0;\n let nextPage = null;\n\n let fetchedItems: any[] = [];\n\n while (pagesToFetch > 0 && endpoint) {\n const controller = new AbortController();\n this.pending.push(controller);\n\n try {\n const page = await fetchResultsPage(endpoint, controller);\n\n // sanitize our options if necessary\n if (this.sanitizeOption) {\n page.results.forEach(this.sanitizeOption);\n }\n\n if (page.results) {\n fetchedItems = fetchedItems.concat(page.results);\n }\n\n // save our next pages\n nextPage = page.next;\n endpoint = nextPage;\n pagesToFetch--;\n pages++;\n } catch (error) {\n // aborted\n this.reset();\n console.log(error);\n return;\n }\n\n this.nextPage = nextPage;\n }\n this.pages = pages;\n\n const topItem = fetchedItems[0];\n if (\n !this.mostRecentItem ||\n JSON.stringify(this.mostRecentItem) !== JSON.stringify(topItem)\n ) {\n this.mostRecentItem = topItem;\n }\n\n // see if our cursor needs to move to stay on the same item\n const newItem = fetchedItems[this.cursorIndex];\n\n if (\n !this.nextSelection &&\n this.selected &&\n newItem &&\n this.getValue(newItem) !== this.getValue(this.selected)\n ) {\n const index = fetchedItems.findIndex(item => {\n return this.getValue(item) === this.getValue(this.selected);\n });\n\n // old selection is in the new fetch\n if (index > -1) {\n this.cursorIndex = index;\n }\n // old selection is missing from the new fetch\n else {\n // if our index didn't change, our item still did, fire change\n if (this.cursorIndex === 0) {\n this.requestUpdate('cursorIndex');\n }\n // otherwise select the first item\n else {\n this.cursorIndex = 0;\n }\n }\n }\n\n // save our results\n this.items = fetchedItems;\n this.loading = false;\n this.pending = [];\n\n if (this.nextSelection) {\n this.setSelection(this.nextSelection);\n this.nextSelection = false;\n } else {\n if (this.cursorIndex === -1 && !this.isMobile()) {\n this.cursorIndex = 0;\n }\n }\n\n // TODO: Not sure why this is needed\n // this.requestUpdate('cursorIndex');\n\n if (this.value) {\n this.setSelection(this.value);\n this.value = null;\n } else if (this.isMobile() && !this.selected) {\n this.cursorIndex = -1;\n this.value = null;\n this.selected = null;\n const evt = new Event('change', { bubbles: true });\n this.dispatchEvent(evt);\n }\n\n return Promise.resolve();\n }\n\n private handleScrollThreshold() {\n if (this.nextPage && !this.loading) {\n this.loading = true;\n fetchResultsPage(this.nextPage).then((page: ResultsPage) => {\n if (this.sanitizeOption) {\n page.results.forEach(this.sanitizeOption);\n }\n\n this.items = [...this.items, ...page.results];\n this.nextPage = page.next;\n this.pages++;\n this.loading = false;\n });\n }\n }\n\n public renderHeader(): TemplateResult {\n return null;\n }\n\n public renderFooter(): TemplateResult {\n return null;\n }\n\n public getListStyle() {\n return '';\n }\n\n protected handleSelection(event: CustomEvent) {\n const { selected, index } = event.detail;\n\n this.selected = selected;\n this.cursorIndex = index;\n\n event.stopPropagation();\n event.preventDefault();\n }\n\n public render(): TemplateResult {\n return html`\n ${this.renderHeader()}\n \n \n \n ${this.renderFooter()}\n `;\n }\n}\n","import { html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { TembaList } from './TembaList';\nimport { Contact } from '../interfaces';\nimport { Icon } from '../vectoricon';\n\nexport class TicketList extends TembaList {\n @property({ type: String })\n agent = '';\n\n public getRefreshEndpoint() {\n if (this.items.length > 0) {\n const lastActivity = this.items[0].ticket.last_activity_on;\n return (\n this.endpoint + '?after=' + new Date(lastActivity).getTime() * 1000\n );\n }\n return this.endpoint;\n }\n\n constructor() {\n super();\n\n this.valueKey = 'ticket.uuid';\n this.renderOption = (contact: Contact): TemplateResult => {\n return html`\n \n \n
    \n \n ${contact.name}\n
    \n ${contact.ticket.closed_on\n ? null\n : contact.last_msg\n ? html`\n \n ${\n contact.last_msg.direction === 'I'\n ? html``\n : null\n }\n ${\n contact.last_msg.text\n ? contact.last_msg.text\n : contact.last_msg.attachments\n ? html`
    \n
    \n \n
    \n Attachment\n
    \n
    \n
    `\n : 'Unsupported Message'\n }\n \n `\n : null}\n \n \n
    \n ${!contact.ticket.closed_on && contact.ticket.assignee\n ? html``\n : null}\n
    \n \n \n\n
    \n \n
    \n \n `;\n };\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { ContactStoreElement } from './ContactStoreElement';\nimport { Icon } from '../vectoricon';\nimport { capitalize } from '../utils';\n\nconst STATUS = {\n active: 'Active',\n blocked: 'Blocked',\n stopped: 'Stopped',\n archived: 'Archived',\n};\n\nconst SCHEMES = {\n tel: 'Phone',\n whatsapp: 'WhatsApp',\n fcm: 'Firebase Cloud Messaging',\n twitter: 'Twitter',\n};\n\nexport class ContactDetails extends ContactStoreElement {\n static get styles() {\n return css`\n .urn {\n display: flex;\n padding: 0.4em 1em 0.8em 1em;\n border-bottom: 1px solid #e6e6e6;\n margin-bottom: 0.5em;\n }\n\n .urn .path {\n margin-left: 0.2em;\n }\n\n .wrapper {\n padding-top: 0em;\n }\n\n .groups {\n padding: 0.4em 0.5em 0.6em 0.5em;\n border-bottom: 1px solid #e6e6e6;\n margin-bottom: 0.4em;\n }\n .group {\n margin-right: 0.7em;\n margin-bottom: 0.7em;\n }\n\n .label {\n font-size: 0.8em;\n color: rgb(136, 136, 136);\n margin-left: 0.5em;\n margin-bottom: 0.4em;\n }\n `;\n }\n\n // Not sure if we want to include name here or not, so hold onto this for the moment\n // ${this.data.name ? html``:null}\n\n public render(): TemplateResult {\n if (!this.data) {\n return;\n }\n\n const lang = this.store.getLanguageName(this.data.language);\n\n return html`\n
    \n ${this.data.groups.length > 0\n ? html`
    \n
    Groups
    \n ${this.data.groups.map(group => {\n return html`\n ${group.name}\n `;\n })}\n
    `\n : null}\n ${this.data.urns.map(urn => {\n const parts = urn.split(':');\n let scheme = SCHEMES[parts[0]];\n if (!scheme) {\n scheme = capitalize(parts[0] as any);\n }\n return html``;\n })}\n\n \n ${lang\n ? html``\n : null}\n\n \n \n
    \n `;\n }\n}\n","import { css, html, LitElement, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\n\nexport class Alert extends LitElement {\n static get styles() {\n return css`\n :host {\n display: block;\n }\n\n .temba-alert {\n color: rgba(0, 0, 0, 0.8);\n padding: 0.65rem 1rem;\n border: 1px solid rgba(0, 0, 0, 0.35);\n border-left: 10px solid rgba(0, 0, 0, 0.35);\n border-radius: var(--curvature-widget);\n box-shadow: var(--shadow);\n }\n\n .temba-info {\n background: var(--color-info);\n border-color: var(--color-info-border);\n }\n\n .temba-warning {\n background: var(--color-warning);\n border-color: var(--color-warning-border);\n }\n\n .temba-error {\n border-color: var(--color-error);\n background: #fff;\n border: 1px solid var(--color-error);\n border-left: 10px solid var(--color-error);\n }\n `;\n }\n\n @property({ type: String })\n level = 'info';\n\n public render(): TemplateResult {\n return html`\n
    \n `;\n }\n}\n","import { TemplateResult, html, css, PropertyValueMap } from 'lit';\nimport { unsafeHTML } from 'lit-html/directives/unsafe-html.js';\nimport { property } from 'lit/decorators.js';\nimport { getClasses, postJSON, stopEvent, WebResponse } from '../utils';\nimport { TextInput } from '../textinput/TextInput';\nimport '../alert/Alert';\nimport { Contact, CustomEventType } from '../interfaces';\nimport { FormElement } from '../FormElement';\nimport { Checkbox } from '../checkbox/Checkbox';\nimport { msg } from '@lit/localize';\nimport { OmniOption, Omnibox } from '../omnibox/Omnibox';\n\nconst QUEIT_MILLIS = 2000;\n\ninterface SummaryResponse {\n total: number;\n sample: Contact[];\n query: string;\n fields: { [uuid: string]: { label: string; type: string } };\n error?: string;\n warnings: string[];\n blockers: string[];\n}\n\nexport class ContactSearch extends FormElement {\n static get styles() {\n return css`\n :host {\n color: var(--color-text);\n }\n\n .urn {\n width: 120px;\n }\n\n .name {\n width: 160px;\n }\n\n .date {\n text-align: right;\n }\n\n .field-header {\n font-size: 80%;\n color: var(--color-text-dark);\n }\n\n .field-header.date {\n text-align: right;\n }\n\n .more {\n font-size: 90%;\n padding-top: 5px;\n padding-right: 3px;\n text-align: right;\n width: 100px;\n vertical-align: top;\n }\n\n table {\n width: 100%;\n }\n\n .contact td {\n border-bottom: 1px solid var(--color-borders);\n padding: 5px 3px;\n }\n\n .table-footer td {\n padding: 10px 3px;\n }\n\n .query-replaced,\n .count-replaced {\n display: inline-block;\n background: var(--color-primary-light);\n color: var(--color-text-dark);\n padding: 3px 6px;\n border-radius: var(--curvature);\n font-size: 85%;\n margin: 0px 3px;\n }\n\n temba-loading {\n transform: scale(0);\n max-width: 0;\n opacity: 0;\n transition: transform 200ms ease-in-out;\n }\n\n .fetching temba-loading {\n transform: scale(1);\n max-width: 500px;\n opacity: 1;\n display: block;\n }\n\n .error {\n margin-top: 10px;\n }\n\n .match-count {\n padding: 4px;\n margin-top: 6px;\n }\n\n .linked {\n color: var(--color-link-primary);\n text-decoration: none;\n cursor: pointer;\n }\n\n .header td {\n border-bottom: 0px solid var(--color-borders);\n padding: 5px 3px;\n }\n\n .expanded .header td {\n border-bottom: 2px solid var(--color-borders);\n }\n\n td.field-header,\n tr.table-footer,\n tr.contact {\n display: none;\n }\n\n .expanded td.field-header {\n display: table-cell;\n }\n\n .expanded tr.contact,\n .expanded tr.table-footer {\n display: table-row;\n }\n\n .query {\n display: var(--contact-search-query-display);\n margin-bottom: 10px;\n }\n\n .results {\n display: none;\n }\n\n .summary {\n min-height: 2.2em;\n display: flex;\n flex-grow: 1;\n align-items: center;\n }\n\n .summary .result-count {\n flex-grow: 1;\n }\n\n .results.empty {\n display: none !important;\n }\n\n .results.initialized {\n display: flex;\n align-items: center;\n margin-top: 0.5em;\n margin-left: 0.6em;\n }\n\n .advanced-icon {\n cursor: pointer;\n margin-right: 0.5em;\n }\n\n .query .advanced-icon {\n margin-top: 1em;\n margin-right: 1em;\n }\n\n .advanced-icon:hover {\n --icon-color: var(--color-link-primary-hover) !important;\n }\n\n .query {\n --textarea-height: 5em;\n }\n\n #recipients {\n margin-bottom: 1em;\n display: block;\n }\n\n temba-alert {\n margin: 1em 0;\n }\n `;\n }\n\n @property({ type: Boolean })\n in_a_flow: boolean;\n\n @property({ type: Boolean })\n started_previously: boolean;\n\n @property({ type: Boolean })\n not_seen_since_days: boolean;\n\n @property({ type: Boolean })\n fetching: boolean;\n\n @property({ type: Boolean })\n expanded: boolean;\n\n @property({ type: String })\n endpoint: string;\n\n @property({ type: String })\n placeholder = '';\n\n @property({ type: String })\n name = '';\n\n @property({ type: String })\n query = '';\n\n @property({ type: Number })\n inactiveThreshold = 1000;\n\n @property({ type: Number })\n inactiveDays = 90;\n\n @property({ type: Object, attribute: false })\n summary: SummaryResponse;\n\n @property({ type: Object, attribute: false })\n flow: any;\n\n @property({ type: Array })\n recipients: OmniOption[] = [];\n\n @property({ type: Boolean })\n advanced = false;\n\n @property({ type: String })\n refreshKey = '0';\n\n public refresh(): void {\n this.refreshKey = 'requested_' + new Date().getTime();\n }\n\n @property({ type: Object })\n private exclusions = {};\n\n private lastQuery: number;\n private initialized = false;\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n if (changedProperties.has('advanced') && this.advanced) {\n return;\n }\n\n // if we remove the in_a_flow option, make sure it's not part of our exclusions\n if (changedProperties.has('in_a_flow') && !this.in_a_flow) {\n delete this.exclusions['in_a_flow'];\n this.requestUpdate('exclusions');\n }\n\n if (\n (changedProperties.has('query') && this.advanced) ||\n (changedProperties.has('refreshKey') && this.refreshKey !== '0')\n ) {\n this.summary = null;\n // this.errors = [];\n this.fireCustomEvent(CustomEventType.ContentChanged, { reset: true });\n if (this.lastQuery) {\n window.clearTimeout(this.lastQuery);\n this.fetching = false;\n }\n\n if (this.query.trim().length > 0 || this.recipients.length > 0) {\n this.fetching = true;\n this.lastQuery = window.setTimeout(() => {\n this.fetchSummary();\n }, QUEIT_MILLIS);\n }\n }\n }\n\n public fetchSummary(): any {\n if (this.endpoint) {\n const group_uuids = this.recipients\n .filter((value: OmniOption) => value.type === 'group')\n .map((value: OmniOption) => value.id);\n\n const contact_uuids = this.recipients\n .filter((value: OmniOption) => value.type === 'contact')\n .map((value: OmniOption) => value.id);\n\n postJSON(this.endpoint, {\n include: this.advanced\n ? { query: this.query }\n : { contact_uuids, group_uuids },\n\n exclude: this.exclusions,\n }).then((response: WebResponse) => {\n this.fetching = false;\n if (response.status === 200) {\n this.summary = response.json as SummaryResponse;\n if (!this.advanced) {\n this.query = this.summary.query;\n }\n this.setValue({\n advanced: this.advanced,\n query: this.query,\n exclusions: this.exclusions,\n recipients: this.recipients,\n });\n\n if (this.summary.error) {\n this.errors = [this.summary.error];\n } else {\n this.errors = [];\n }\n this.requestUpdate('errors');\n this.fireCustomEvent(CustomEventType.ContentChanged, this.summary);\n } else {\n this.summary = response.json as SummaryResponse;\n if (this.summary.error) {\n this.errors = [this.summary.error];\n }\n this.requestUpdate('errors');\n this.fireCustomEvent(CustomEventType.ContentChanged, this.summary);\n }\n });\n }\n }\n\n private handleAdvancedToggle(evt: MouseEvent) {\n stopEvent(evt);\n this.recipients = [];\n this.exclusions = {};\n if (this.advanced) {\n this.query = '';\n this.value = null;\n }\n this.advanced = !this.advanced;\n\n this.setValue({\n advanced: this.advanced,\n query: this.query,\n exclusions: this.exclusions,\n recipients: this.recipients,\n });\n }\n\n private handleQueryChange(evt: KeyboardEvent) {\n const input = evt.target as TextInput;\n this.query = input.inputElement.value;\n }\n\n private handleRecipientsChanged(evt: any) {\n if (this.refreshKey !== '0' || this.initialized) {\n this.refresh();\n } else {\n this.initialized = true;\n }\n }\n\n private handleExclusionChanged(evt: any) {\n if (evt.target.tagName === 'TEMBA-CHECKBOX') {\n const ex = JSON.stringify(this.exclusions);\n const checkbox = evt.target as Checkbox;\n let value = checkbox.checked as any;\n\n if (!value) {\n delete this.exclusions[checkbox.name];\n } else {\n if (checkbox.name === 'not_seen_since_days') {\n value = 90;\n }\n\n this.exclusions[checkbox.name] = value;\n }\n\n if (ex !== JSON.stringify(this.exclusions)) {\n this.refresh();\n }\n }\n }\n\n public render(): TemplateResult {\n let summary: TemplateResult;\n if (this.summary) {\n if (!this.summary.error) {\n const count = this.summary.total || 0;\n\n summary = html`\n
    \n Found\n \n ${count.toLocaleString()}\n \n contact${count !== 1 ? 's' : ''}\n
    \n \n
    \n
    \n ${this.advanced\n ? html` \n Start Over`\n : html` \n Edit Query`}\n
    \n
    \n \n `;\n }\n }\n\n if (\n this.summary &&\n this.summary.blockers &&\n this.summary.blockers.length > 0\n ) {\n return html`${this.summary.blockers.map(\n error =>\n html`${unsafeHTML(error)}`\n )}`;\n }\n\n return html`\n ${this.advanced\n ? html`
    \n \n \n
    `\n : html`\n \n\n ${this.not_seen_since_days\n ? html``\n : null}\n ${this.in_a_flow\n ? html``\n : null}\n ${this.started_previously\n ? html``\n : null}`}\n\n \n \n
    ${summary}
    \n \n\n ${this.summary && this.summary.warnings\n ? this.summary.warnings.map(\n warning =>\n html`${unsafeHTML(warning)}`\n )\n : ``}\n `;\n }\n}\n","import { LitElement, TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { Icon, SVG_FINGERPRINT } from '.';\nimport { getClasses } from '../utils';\n\nexport class VectorIcon extends LitElement {\n @property({ type: String })\n name: string;\n\n @property({ type: String })\n prefix: string;\n\n // same as name but without implicit coloring\n @property({ type: String })\n id: string;\n\n @property({ type: Number })\n size = 1;\n\n @property({ type: Boolean })\n spin: boolean;\n\n @property({ type: Boolean })\n clickable: boolean;\n\n @property({ type: Boolean })\n circled: boolean;\n\n @property({ type: String })\n animateChange: string;\n\n @property({ type: String })\n animateClick: string;\n\n @property({ type: Number })\n animationDuration = 200;\n\n @property({ type: String })\n src = '';\n\n @property({ type: Number, attribute: false })\n steps = 2;\n\n @property({ type: Number, attribute: false })\n animationStep: number;\n\n @property({ type: String })\n easing = 'cubic-bezier(0.68, -0.55, 0.265, 1.55)';\n\n static get styles() {\n return css`\n :host {\n display: flex-inline;\n align-items: center;\n align-self: center;\n }\n\n .sheet {\n color: var(--icon-color);\n transform: scale(1);\n transition: fill 100ms ease-in-out,\n background 200ms cubic-bezier(0.68, -0.55, 0.265, 1.55),\n padding 200ms cubic-bezier(0.68, -0.55, 0.265, 1.55),\n margin 200ms cubic-bezier(0.68, -0.55, 0.265, 1.55);\n }\n\n .sheet.spin {\n transform: rotate(0deg);\n }\n\n .sheet.spin-1 {\n transform: rotate(180deg);\n }\n\n .sheet.spin-2 {\n transform: rotate(360deg);\n }\n\n .sheet.spin-3 {\n transform: rotate(0deg);\n transition-duration: 0ms !important;\n }\n\n .sheet.pulse {\n transform: scale(1);\n }\n\n .sheet.pulse-1 {\n transform: scale(1.2);\n }\n\n .clickable:hover {\n cursor: pointer;\n fill: var(--color-link-primary) !important;\n background: rgb(255, 255, 255);\n }\n\n .circled {\n background: var(--icon-color-circle);\n padding: 0.15em;\n margin: -0.15em;\n box-shadow: var(--shadow);\n }\n\n .wrapper {\n display: flex;\n flex-direction: column;\n border-radius: 999px;\n transition: background 200ms linear,\n transform 300ms cubic-bezier(0.68, -0.55, 0.265, 1.55),\n padding 150ms linear, margin 150ms linear;\n }\n\n .wrapper.clickable {\n transform: scale(1);\n }\n\n .wrapper.clickable:hover {\n --icon-circle-size: 0.35em;\n --icon-background: var(--icon-color-circle-hover);\n }\n\n .wrapper.clickable {\n padding: var(--icon-circle-size);\n margin: calc(-1 * var(--icon-circle-size));\n background: var(--icon-background);\n }\n\n .spin-forever {\n animation-name: spin;\n animation-duration: 2000ms;\n animation-iteration-count: infinite;\n animation-timing-function: linear;\n }\n\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n `;\n }\n\n constructor() {\n super();\n }\n\n private lastName: string;\n\n public firstUpdated(changes: Map) {\n super.firstUpdated(changes);\n if (changes.has('animateChange')) {\n // set our default duration if we need one\n if (!changes.has('animationDuration')) {\n this.animationDuration = this.steps * this.animationDuration;\n }\n\n if (this.animateChange === 'spin') {\n this.steps = 3;\n this.animationDuration = 400;\n this.easing = 'linear';\n }\n }\n }\n\n public handleClicked() {\n if (this.animateClick) {\n this.animationStep = 1;\n }\n }\n\n public updated(changes: Map) {\n super.updated(changes);\n\n if (changes.has('animationStep')) {\n // if we are halfway through, change the icon\n if (this.lastName && this.animationStep >= this.steps / 2) {\n this.lastName = null;\n this.requestUpdate();\n }\n\n setTimeout(() => {\n if (this.animationStep > 0 && this.animationStep < this.steps) {\n this.animationStep++;\n } else {\n this.animationStep = 0;\n }\n }, this.animationDuration / this.steps);\n }\n\n if (changes.has('name') && this.animateChange) {\n this.lastName = changes.get('name');\n\n // our name changed, lets animate it\n if (this.lastName && this.animateChange) {\n this.animationStep = 1;\n }\n }\n }\n\n public render(): TemplateResult {\n if (!this.name) {\n return null;\n }\n\n // let icon name mappings take precedence\n let name = this.lastName || this.name;\n\n // special case our channel icon fallback\n if (name.startsWith('channel_') && !Icon[name]) {\n name = Icon.channel_ex;\n } else {\n name = Icon[name.replace('icon.', '')] || name;\n }\n\n // referencing icons by id is explicit\n if (!name) {\n name = this.id;\n }\n\n return html`\n \n 0,\n [this.animateClick]: !!this.animateClick,\n [this.animateClick + '-' + this.animationStep]:\n this.animationStep > 0,\n })}\"\n >\n \n \n \n `;\n }\n}\n","import { TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { RapidElement } from '../RapidElement';\nimport { Select } from '../select/Select';\nimport { Icon } from '../vectoricon';\n\nenum OmniType {\n Group = 'group',\n Contact = 'contact',\n}\n\nexport interface OmniOption {\n id: string;\n name: string;\n type: OmniType;\n urn?: string;\n count?: number;\n contact?: string;\n scheme?: string;\n}\n\nconst postNameStyle = {\n color: 'var(--color-text-dark)',\n padding: '0px 6px',\n fontSize: '12px',\n};\n\nexport class Omnibox extends RapidElement {\n static get styles() {\n return css`\n temba-select:focus {\n outline: none;\n box-shadow: none;\n }\n\n :host {\n }\n `;\n }\n\n @property()\n endpoint: string;\n\n @property()\n name: string;\n\n @property({ type: Boolean })\n groups = false;\n\n @property({ type: Boolean })\n contacts = false;\n\n @property({ type: Array })\n value: OmniOption[] = [];\n\n @property({ type: Array })\n errors: string[];\n\n @property()\n placeholder = 'Select recipients';\n\n @property({ type: Boolean })\n disabled = false;\n\n @property({ type: String, attribute: 'help_text' })\n helpText: string;\n\n @property({ type: Boolean, attribute: 'help_always' })\n helpAlways: boolean;\n\n @property({ type: Boolean, attribute: 'widget_only' })\n widgetOnly: boolean;\n\n @property({ type: Boolean, attribute: 'hide_label' })\n hideLabel: boolean;\n\n @property({ type: String })\n label: string;\n\n @property({ type: String, attribute: 'info_text' })\n infoText = '';\n\n /** An option in the drop down */\n private renderOption(option: OmniOption): TemplateResult {\n return html`\n
    \n
    ${this.getIcon(option)}
    \n
    ${option.name}
    \n \n ${this.getPostName(option)}\n
    \n \n `;\n }\n\n private getPostName(option: OmniOption): TemplateResult {\n const style = { ...postNameStyle };\n\n if (option.urn && option.type === OmniType.Contact) {\n if (option.urn !== option.name) {\n return html`
    ${option.urn}
    `;\n }\n }\n\n if (option.type === OmniType.Group) {\n return html`\n
    ${option.count.toLocaleString()}
    \n `;\n }\n\n return null;\n }\n\n /** Selection in the multi-select select box */\n private renderSelection(option: OmniOption): TemplateResult {\n return html`\n \n
    \n ${this.getIcon(option)}\n
    \n \n ${option.name}\n \n \n ${this.getPostName(option)}\n \n \n `;\n }\n\n private getIcon(option: OmniOption): TemplateResult {\n if (option.type === OmniType.Group) {\n return html``;\n }\n\n if (option.type === OmniType.Contact) {\n return html``;\n }\n }\n\n private getEndpoint() {\n const endpoint = this.endpoint;\n let types = '&types=';\n if (this.groups) {\n types += 'g';\n }\n\n if (this.contacts) {\n types += 'c';\n }\n\n return endpoint + types;\n }\n\n public getValues(): any[] {\n const select = this.shadowRoot.querySelector('temba-select') as Select;\n return select.values;\n }\n\n public isMatch() {\n return true;\n }\n\n public render(): TemplateResult {\n return html`\n
    \n \n `;\n }\n}\n","export const getMiddle = (a: DOMRect, b: DOMRect) => {\n return a.top + a.height / 2 - b.height / 2;\n};\n\nexport const getCenter = (a: DOMRect, b: DOMRect) => {\n return a.left + a.width / 2 - b.width / 2;\n};\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { RapidElement } from '../RapidElement';\nimport { getClasses } from '../utils';\nimport { getCenter, getMiddle } from './helpers';\n\nexport class Tip extends RapidElement {\n static get styles() {\n return css`\n .tip {\n transition: opacity 200ms ease-in-out;\n margin: 0px;\n position: fixed;\n opacity: 0;\n background: #fff;\n padding: 4px 8px;\n pointer-events: none;\n border-radius: var(--curvature-widget);\n box-shadow: 0 1px 10px 10px rgba(0, 0, 0, 0.035),\n 0 1px 3px 0px rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);\n font-size: 14px;\n z-index: 10000;\n color: #333;\n }\n\n .tip.hide-on-change {\n transition: none;\n }\n\n .show {\n opacity: 1;\n }\n\n .slot {\n display: flex;\n flex-direction: column;\n }\n\n .arrow {\n position: absolute;\n color: #fff;\n font-size: 10px;\n line-height: 0px;\n }\n\n .◀ {\n text-shadow: -1px 2px 2px rgba(0, 0, 0, 0.1);\n }\n\n .▶ {\n text-shadow: 1px 2px 2px rgba(0, 0, 0, 0.1);\n }\n\n .▼ {\n text-shadow: 0px 3px 3px rgba(0, 0, 0, 0.1);\n }\n\n .▲ {\n text-shadow: 0px -1px 1px rgba(0, 0, 0, 0.1);\n }\n `;\n }\n\n @property({ type: String })\n text: string;\n\n @property({ type: Boolean })\n visible = false;\n\n @property({ type: String })\n position = 'auto';\n\n @property({ type: Boolean })\n hideOnChange: boolean;\n\n @property({ type: Number, attribute: false })\n top: number;\n\n @property({ type: Number, attribute: false })\n left: number;\n\n @property({ type: Number, attribute: false })\n width: number;\n\n @property({ type: Boolean, attribute: false })\n poppedTop: boolean;\n\n arrow: string;\n arrowTop: number;\n arrowLeft: number;\n arrowDirection: string;\n\n lastEnter = 0;\n failSafe = 0;\n\n public updated(changed: Map) {\n if ((changed.has('visible') || changed.has('text')) && this.visible) {\n this.calculatePosition();\n }\n\n if (changed.has('text') && this.hideOnChange) {\n this.visible = false;\n }\n }\n\n private calculatePosition() {\n if (this.visible) {\n const tipBounds = this.getDiv('.tip').getBoundingClientRect();\n const anchorBounds = this.getDiv('.slot').getBoundingClientRect();\n\n // TODO: pick a direction automatically\n let tipSide = this.position;\n if (tipSide === 'auto') {\n tipSide = 'left';\n }\n\n this.arrowLeft = 0;\n this.arrowTop = 0;\n\n if (tipSide === 'left') {\n this.left = anchorBounds.left - tipBounds.width - 16;\n this.top = getMiddle(anchorBounds, tipBounds);\n\n // position our arrow\n this.arrowTop = tipBounds.height / 2;\n this.arrowLeft = tipBounds.width - 1;\n this.arrow = '▶';\n } else if (tipSide === 'right') {\n this.left = anchorBounds.right + 12;\n this.top = getMiddle(anchorBounds, tipBounds);\n\n this.arrowTop = tipBounds.height / 2;\n this.arrowLeft = -8;\n this.arrow = '◀';\n } else if (tipSide === 'top') {\n this.top = anchorBounds.top - tipBounds.height - 12;\n this.left = getCenter(anchorBounds, tipBounds);\n\n this.arrowTop = tipBounds.height + 2;\n this.arrowLeft = tipBounds.width / 2 - 4;\n this.arrow = '▼';\n } else if (tipSide === 'bottom') {\n this.top = anchorBounds.bottom + 10;\n this.left = getCenter(anchorBounds, tipBounds);\n\n this.arrowTop = -2;\n this.arrowLeft = tipBounds.width / 2 - 3;\n this.arrow = '▲';\n }\n }\n }\n\n private handleMouseEnter() {\n this.lastEnter = window.setTimeout(() => {\n this.visible = true;\n this.failSafe = window.setTimeout(() => {\n this.visible = false;\n }, 2000);\n }, 600);\n }\n\n private handleMouseLeave() {\n window.clearTimeout(this.lastEnter);\n window.clearTimeout(this.failSafe);\n this.visible = false;\n }\n\n public render(): TemplateResult {\n const tipStyle: any = {\n top: this.top ? `${this.top}px` : '0px',\n left: this.left ? `${this.left}px` : '0px',\n };\n\n const arrowStyle: any = {\n top: this.arrowTop ? `${this.arrowTop}px` : '0px',\n left: this.arrowLeft ? `${this.arrowLeft}px` : '0px',\n };\n\n if (this.width) {\n tipStyle.width = `${this.width}px`;\n }\n\n const classes = getClasses({\n tip: true,\n show: this.visible,\n top: this.poppedTop,\n 'hide-on-change': this.hideOnChange,\n });\n\n return html`\n \n \n
    \n
    \n ${this.text}\n
    \n ${this.arrow}\n
    \n
    \n `;\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { debounce, fetchResults, getClasses, renderAvatar } from '../utils';\nimport { Icon } from '../vectoricon';\nimport { Dropdown } from '../dropdown/Dropdown';\nimport { NotificationList } from './NotificationList';\nimport { ResizeElement } from '../ResizeElement';\nexport interface MenuItem {\n id?: string;\n vanity_id?: string;\n name?: string;\n verbose_name?: string;\n count?: number;\n icon?: string;\n collapsed_icon?: string;\n endpoint?: string;\n loading?: boolean;\n bottom?: boolean;\n level?: number;\n href?: string;\n show_header?: boolean;\n items?: MenuItem[];\n inline?: boolean;\n type?: string;\n on_submit?: string;\n bubble?: string;\n popup?: boolean;\n avatar?: string;\n trigger?: boolean;\n event?: string;\n mobile?: boolean;\n}\n\ninterface MenuItemState {\n collapsed?: string;\n}\n\nconst findItem = (\n items: MenuItem[],\n id: string\n): { item: MenuItem; index: number } => {\n const search = items || [];\n\n const index = search.findIndex((item: MenuItem) => {\n return item.id == id || item.vanity_id == id;\n });\n\n if (index > -1) {\n const item = search[index];\n return { item, index };\n }\n\n return { item: null, index: -1 };\n};\n\nexport class TembaMenu extends ResizeElement {\n static get styles() {\n return css`\n :host {\n width: 100%;\n display: block;\n --color-widget-bg-focused: transparent;\n --options-block-shadow: none;\n }\n\n .bubble {\n width: 0.6em;\n height: 0.6em;\n right: 0em;\n bottom: 0em;\n border-radius: 99em;\n border: 0.12em solid rgba(0, 0, 0, 0.1);\n position: absolute;\n }\n\n .bubble.count {\n position: relative;\n width: inherit;\n height: inherit;\n right: inherit;\n bottom: inherit;\n color: #fff;\n line-height: 1em;\n padding: 0.12em;\n min-width: 1em;\n text-align: center;\n }\n\n .section {\n font-size: 1.5em;\n margin-bottom: 0.2em;\n color: var(--color-text-dark);\n }\n\n .collapse-toggle {\n width: 0.5em;\n cursor: pointer;\n display: block;\n margin-right: 5px;\n margin-top: 3px;\n margin-bottom: 3px;\n }\n\n .collapse-toggle:hover {\n background: rgb(100, 100, 100, 0.05);\n }\n\n .item {\n cursor: pointer;\n user-select: none;\n -webkit-user-select: none;\n display: flex;\n --icon-color: var(--color-text-dark);\n }\n\n .item.selected,\n .item.pressed {\n background: var(--color-selection);\n color: var(--color-primary-dark);\n --icon-color: var(--color-primary-dark);\n }\n\n .root {\n display: flex;\n flex-direction: row;\n height: 100%;\n }\n\n .level {\n display: flex;\n flex-direction: column;\n }\n\n .level.hidden {\n display: none;\n }\n\n .popup {\n --icon-color: rgba(255, 255, 255, 0.7);\n }\n\n .level-0 > .item,\n .level-0 > temba-dropdown > div[slot='toggle'] > .avatar {\n padding: 0px;\n --icon-color: rgba(255, 255, 255, 0.7);\n flex-direction: column;\n border: 0px solid green;\n width: 100%;\n display: flex;\n align-items: center;\n }\n\n .level-0 > temba-dropdown .icon-wrapper {\n padding: 0.2em 0.4em 0.2em 0.4em;\n }\n\n .level-0 > .item.selected::before,\n .level-0 > .item.selected::after {\n content: ' ';\n height: var(--curvature);\n background: var(--color-primary-dark);\n display: block;\n width: 100%;\n }\n\n .level-0 > .item.selected::before {\n border-bottom-right-radius: var(--curvature);\n }\n\n .level-0 .item > temba-tip {\n padding: 0.5em 0em;\n }\n\n .level-0 > .item.selected::after {\n border-top-right-radius: var(--curvature);\n }\n\n .level-0 {\n padding-top: var(--menu-padding) !important;\n }\n\n .level-0 > .empty {\n background: var(--color-primary-dark);\n align-self: stretch;\n flex-grow: 1;\n }\n\n .level-0 > .bottom {\n height: 1em;\n background: var(--color-primary-dark);\n }\n\n .level-0 > temba-dropdown.open > div[slot='toggle'] > .avatar {\n background: transparent !important;\n }\n\n .level-0 {\n background: var(--color-primary-dark);\n }\n\n temba-dropdown {\n }\n\n temba-dropdown > div[slot='dropdown'] .avatar > .details {\n margin-left: 0.75em;\n }\n\n temba-dropdown > div[slot='dropdown'] .bubble.count {\n margin-right: 0.75em;\n }\n\n .level-0 > .item > .details,\n .level-0 > temba-dropdown > div[slot='toggle'] .details {\n display: none !important;\n }\n\n .avatar {\n align-items: center;\n }\n\n temba-dropdown > div[slot='dropdown'] {\n }\n\n temba-dropdown > div[slot='dropdown'] .avatar .avatar-circle,\n temba-dropdown > div[slot='dropdown'] .avatar .bubble {\n font-size: 0.7em;\n }\n\n .level-0.expanded {\n background: inherit;\n }\n\n .level-0 > .item.selected {\n background: white;\n --icon-color: var(--color-primary-dark);\n }\n\n .level {\n padding: var(--menu-padding);\n }\n\n .level-0 {\n padding: 0px;\n }\n\n .top {\n display: flex;\n align-items: center;\n flex-direction: column;\n }\n\n .item {\n padding: 0.2em 0.75em;\n margin-top: 0.1em;\n border-radius: var(--curvature);\n display: flex;\n min-width: 12em;\n position: relative;\n }\n\n .item > temba-icon {\n margin-right: 0.5em;\n }\n\n .item > .details > .name {\n flex-grow: 1;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n width: 0;\n }\n\n .level-0 .item {\n margin-top: 0em;\n border-radius: 0px;\n min-width: inherit;\n max-width: inherit;\n }\n\n .popup:hover {\n --icon-color: #fff;\n }\n\n .level-0 > .item > temba-icon {\n margin-right: 0px;\n }\n\n .level-0 > .item > .name {\n min-width: 0px;\n }\n\n .count {\n align-self: center;\n margin-left: 1em;\n font-size: 0.8em;\n font-weight: 400;\n }\n\n .level-0 > .item-top {\n background: var(--color-primary-dark);\n min-height: var(--curvature);\n }\n\n .level-0 > .item-bottom {\n background: var(--color-primary-dark);\n min-height: var(--curvature);\n }\n\n .level-0 > .item-bottom.selected {\n border-top-right-radius: var(--curvature);\n }\n\n .level-0 > .item-top.selected {\n border-bottom-right-radius: var(--curvature);\n }\n\n .level-0 > .item:hover {\n background: rgba(255, 255, 255, 0.15);\n --icon-color: #fff;\n }\n\n .level-0 > .item.selected:hover {\n background: white;\n --icon-color: var(--color-primary-dark);\n cursor: default;\n }\n\n .item.inline {\n border: 0px solid transparent;\n }\n\n .level-1,\n .level-2 {\n border-right: 1px solid rgba(0 0 0 / 8%);\n box-shadow: rgb(0 0 0 / 6%) 4px 0px 6px 1px;\n }\n\n .level-1 {\n transition: opacity 100ms linear, margin 200ms linear;\n overflow-y: scroll;\n }\n\n .mobile.root {\n height: 100svh;\n }\n\n .mobile.root.fully-collapsed {\n height: initial;\n }\n\n .root.fully-collapsed.mobile .level.level-0 {\n padding-right: 0.5em;\n }\n\n .root.fully-collapsed.mobile .level.level-0 {\n flex-direction: row;\n }\n\n .root.fully-collapsed.mobile .level.level-0 > .item {\n display: none;\n }\n\n .root.fully-collapsed.mobile .level.level-0 > .empty {\n display: block;\n width: 100%;\n min-width: inherit;\n max-width: inherit;\n }\n\n .root .level.level-0 > .show-mobile {\n display: none;\n }\n\n .root.mobile .level.level-0 > .show-mobile {\n display: flex;\n }\n\n .root.fully-collapsed.mobile .level.level-0 > .show-mobile {\n display: contents !important;\n }\n\n .root.fully-collapsed.mobile .level.level-0 .expand-icon {\n max-height: 100%;\n padding: 1em;\n }\n\n .mobile.fully-collapsed.root {\n flex-direction: column;\n }\n\n .mobile.fully-collapsed.root .level-0 {\n padding-top: 0px !important;\n }\n\n .mobile.fully-collapsed .level-1 {\n display: none;\n }\n\n .mobile .level-1 {\n flex-grow: 1;\n }\n\n .mobile .level-1 .item {\n max-width: inherit;\n min-width: inherit;\n }\n\n .mobile .level-1 .section {\n max-width: inherit;\n min-width: inherit;\n }\n\n .mobile.fully-collapsed .item {\n }\n\n .mobile .expand-icon {\n transition: none;\n transform: rotate(-90deg);\n align-self: center;\n }\n\n .mobile.fully-collapsed .level-0 .empty {\n flex-grow: 1;\n }\n\n .mobile.fully-collapsed .top-spacer {\n flex-grow: 0;\n }\n\n .mobile.fully-collapsed #dd-workspace {\n display: none;\n }\n\n .mobile.fully-collapsed .expand-icon {\n transform: none;\n }\n\n .level-2 {\n background: #fbfbfb;\n overflow-y: auto;\n }\n\n .level-2 .item .details {\n overflow: hidden;\n }\n\n .level-2 .item {\n min-width: 12em;\n max-width: 12em;\n }\n\n .level-1 .item {\n overflow: hidden;\n max-width: 12em;\n min-width: 12em;\n min-height: 1.5em;\n max-height: 1.5em;\n transition: min-width var(--transition-speed) !important;\n }\n\n .collapsed .item {\n overflow: hidden;\n min-width: 0;\n margin: 0;\n }\n\n .item .details {\n opacity: 1;\n min-height: 1.5em;\n max-height: 1.5em;\n align-items: center;\n }\n\n .collapsed .item {\n margin-bottom: 0.5em;\n }\n\n .collapsed .item .details {\n overflow: hidden;\n max-height: 0em;\n max-width: 0em;\n }\n\n .collapsed .item .details {\n max-height: 0em;\n }\n\n .collapsed .item temba-icon {\n margin-right: 0;\n }\n\n .section {\n max-width: 12em;\n }\n\n .collapsed .section {\n opacity: 0;\n max-width: 0em;\n max-height: 0.6em;\n }\n\n .collapsed.level-1 {\n overflow: hidden;\n padding: 0.5em;\n --icon-color: #999;\n }\n\n .collapsed .item .right {\n flex-grow: 1;\n }\n\n .collapse-icon {\n display: none;\n }\n\n .collapsed .collapse-icon {\n --icon-color: #ccc;\n display: block;\n }\n\n .collapsed .item.iconless {\n max-height: 0em;\n padding: 0em;\n min-height: 0em;\n margin-bottom: 0em;\n }\n\n .divider {\n height: 1px;\n background: #f3f3f3;\n margin: 0.5em 0.75em;\n min-height: 1px;\n }\n\n .space {\n margin: 0.5em;\n }\n\n .collapsed .divider {\n height: 0;\n margin: 0;\n padding: 0;\n min-height: 0px;\n }\n\n .sub-section {\n font-size: 0.9rem;\n color: #888;\n margin-top: 1rem;\n margin-left: 0.3rem;\n }\n\n .fully-collapsed .level-1 {\n margin-left: -208px;\n pointer-events: none;\n border: none;\n overflow: hidden;\n }\n\n .fully-collapsed .level-1 > * {\n opacity: 0;\n }\n\n .fully-collapsed .level-1 .item,\n .fully-collapsed .level-1 .divider {\n opacity: 0;\n }\n\n .fully-collapsed .level-2,\n .fully-collapsed .level-3 {\n display: none;\n }\n\n temba-button {\n margin-top: 0.2em;\n margin-bottom: 0.2em;\n margin-left: 0.75em;\n margin-right: 0.75em;\n }\n\n .expand-icon {\n transform: rotate(180deg);\n --icon-color: rgba(255, 255, 255, 0.5);\n cursor: pointer;\n max-height: 0px;\n overflow: hidden;\n opacity: 0;\n transition: all 400ms ease-in-out 400ms;\n }\n\n .expand-icon:hover {\n --icon-color: #fff;\n }\n\n .fully-collapsed .expand-icon {\n padding-top: 0.5em;\n max-height: 2em;\n opacity: 1;\n }\n\n .section-header {\n display: flex;\n align-items: center;\n }\n\n .section-header .section {\n flex-grow: 1;\n }\n\n .section-header temba-icon {\n --icon-color: #ddd;\n cursor: pointer;\n padding-bottom: 0.5em;\n padding-right: 0.5em;\n }\n\n .section-header temba-icon:hover {\n --icon-color: var(--color-link-primary);\n }\n\n a {\n text-decoration: none;\n color: var(--color-text-dark);\n }\n\n slot[name='header'] {\n display: none;\n }\n\n slot[name='header'].show-header {\n display: block;\n }\n\n .icon-wrapper {\n position: relative;\n padding: 0.2em 0.4em 0.2em 0em;\n }\n\n .level-0 .icon-wrapper {\n padding: 0.4em 0.9em;\n }\n `;\n }\n\n @property({ type: Boolean })\n wraps = false;\n\n @property({ type: Boolean })\n wait: boolean;\n\n @property({ type: String })\n endpoint: string;\n\n @property({ type: String })\n expanding: string;\n\n @property({ type: String })\n value: string;\n\n // submenu to constrain to\n @property({ type: String })\n submenu: string;\n\n @property({ type: Boolean })\n collapsed: boolean;\n\n @property({ type: Object })\n pressedItem: MenuItem;\n\n // http promise to monitor for completeness\n public httpComplete: Promise;\n\n root: MenuItem;\n selection: string[] = [];\n state: { [id: string]: MenuItemState } = {};\n\n constructor() {\n super();\n this.doRefresh = this.doRefresh.bind(this);\n\n // scroll any lists to the top\n this.addEventListener('blur', () => {\n this.shadowRoot\n .querySelectorAll('temba-list, temba-notification-list')\n .forEach((ele: NotificationList) => {\n ele.scrollToTop();\n });\n });\n }\n\n public setBubble(id: string, color: string) {\n const found = findItem(this.root.items, id);\n if (found && found.item) {\n found.item.bubble = color;\n this.requestUpdate('root');\n return true;\n }\n return false;\n }\n\n private getMenuItemState(id: string): MenuItemState {\n let itemState = {};\n if (id) {\n itemState = this.state[id];\n if (!itemState) {\n itemState = {};\n this.state[id] = itemState;\n }\n }\n return itemState;\n }\n\n public updated(changes: Map) {\n if (changes.has('endpoint')) {\n this.root = {\n level: -1,\n endpoint: this.endpoint,\n };\n\n if (!this.wait) {\n this.loadItems(this.root);\n } else {\n this.fireCustomEvent(CustomEventType.Ready);\n }\n }\n\n if (changes.has('root')) {\n if (this.value) {\n this.setFocusedItem(this.value);\n this.value = null;\n }\n }\n }\n\n public reset() {\n this.loadItems(this.root);\n }\n\n public async doRefresh() {\n const path = [...this.selection];\n let item = this.root;\n\n while (path.length > 0) {\n this.loadItems(item);\n // we need to wait until the load is complete before doing the replace\n await this.httpComplete;\n const id = path.shift();\n item = (item.items || []).find(_item => _item.id == id);\n }\n\n this.loadItems(item);\n\n // refresh any embedded lists\n this.shadowRoot\n .querySelectorAll('temba-notification-list')\n .forEach((ele: NotificationList) => {\n ele.refresh();\n });\n }\n\n public refresh = debounce(this.doRefresh, 200);\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n private loadItems(item: MenuItem, event: MouseEvent = null) {\n if (item && item.endpoint) {\n item.loading = true;\n this.httpComplete = fetchResults(item.endpoint).then(\n (items: MenuItem[]) => {\n items.forEach(newItem => {\n if (!newItem.items) {\n const prevItem = (item.items || []).find(\n prev => prev.id == newItem.id\n );\n if (prevItem && prevItem.items) {\n newItem.items = prevItem.items;\n }\n }\n });\n\n // update our item level\n items.forEach(subItem => {\n subItem.level = item.level + 1;\n // if we came with preset items, set the level for them accordingly\n if (subItem.items) {\n subItem.items.forEach(inlineItem => {\n inlineItem.level = item.level + 2;\n });\n }\n });\n\n item.items = items;\n item.loading = false;\n\n if (this.submenu && this.selection.length == 0) {\n const sub = this.getMenuItemForSelection([this.submenu]);\n this.handleItemClicked(event, sub);\n }\n\n if (!this.wait) {\n this.fireCustomEvent(CustomEventType.Ready);\n this.wait = true;\n }\n\n this.requestUpdate('root');\n this.scrollSelectedIntoView();\n }\n );\n }\n }\n\n private handleItemClicked(\n event: MouseEvent,\n menuItem: MenuItem,\n parent: MenuItem = null\n ) {\n if (parent && parent.popup) {\n const dropdown = this.shadowRoot.querySelector(\n 'temba-dropdown'\n ) as Dropdown;\n if (dropdown) {\n dropdown.blur();\n }\n\n if (event) {\n this.fireCustomEvent(CustomEventType.ButtonClicked, {\n item: menuItem,\n selection: this.getSelection(),\n parent,\n });\n }\n\n return;\n }\n\n if (menuItem.popup) {\n if (event) {\n this.fireCustomEvent(CustomEventType.ButtonClicked, {\n item: menuItem,\n selection: this.getSelection(),\n parent,\n });\n }\n return;\n }\n\n if (event) {\n event.preventDefault();\n event.stopPropagation();\n if (event.metaKey && menuItem.href) {\n window.open(menuItem.href, '_blank');\n return;\n }\n }\n\n if (parent && parent.inline) {\n this.handleItemClicked(null, parent);\n }\n\n if (this.collapsed && !this.isMobile()) {\n this.collapsed = false;\n }\n\n if (this.isMobile()) {\n this.collapsed = true;\n }\n\n if (menuItem.trigger || menuItem.event) {\n this.fireCustomEvent(CustomEventType.ButtonClicked, {\n item: menuItem,\n selection: this.getSelection(),\n parent,\n });\n return;\n }\n\n // update our selection\n if (menuItem.level >= this.selection.length) {\n this.selection.push(menuItem.vanity_id || menuItem.id);\n } else {\n this.selection.splice(\n menuItem.level,\n this.selection.length - menuItem.level,\n menuItem.vanity_id || menuItem.id\n );\n }\n\n if (menuItem.endpoint) {\n this.loadItems(menuItem, event);\n\n // make sure change events fire for events with hrefs\n if (!menuItem.href) {\n return;\n }\n } else {\n this.requestUpdate();\n }\n\n if (menuItem.href) {\n this.dispatchEvent(new Event('change'));\n }\n\n this.fireCustomEvent(CustomEventType.ButtonClicked, {\n item: menuItem,\n selection: this.getSelection(),\n parent,\n });\n }\n\n public scrollSelectedIntoView() {\n // makes sure we are scrolled into view\n window.setTimeout(() => {\n const eles = this.shadowRoot.querySelectorAll('.selected');\n eles.forEach(ele => {\n ele.scrollIntoView({ block: 'end', behavior: 'smooth' });\n });\n }, 0);\n }\n\n public clickItem(id: string): boolean {\n const path = [...this.selection];\n path.splice(path.length - 1, 1, id);\n const item = this.getMenuItemForSelection(path);\n\n if (item) {\n this.handleItemClicked(null, item);\n this.scrollSelectedIntoView();\n return true;\n }\n return false;\n }\n\n public getMenuItem(): MenuItem {\n return this.getMenuItemForSelection([...this.selection]);\n }\n\n public getMenuItemForSelection(selection: string[]) {\n const path = [...selection];\n let items = this.root.items;\n let item = null;\n while (path.length > 0) {\n const step = path.splice(0, 1)[0];\n if (items) {\n item = findItem(items, step).item;\n if (item) {\n items = item.items;\n } else {\n break;\n }\n } else {\n break;\n }\n }\n\n return item;\n }\n\n public getSelection() {\n return this.selection;\n }\n\n public handleExpand() {\n this.collapsed = false;\n }\n\n public handleCollapse() {\n this.collapsed = true;\n }\n\n public async setFocusedItem(path: string) {\n const focusedPath = path.split('/').filter(step => !!step);\n if (!this.root) {\n return;\n }\n\n // if we don't match at the first level, we are a noop\n if (focusedPath.length > 0) {\n const rootItem = findItem(this.root.items, focusedPath[0]).item;\n if (!rootItem) {\n return;\n }\n }\n\n const newPath = [];\n let level = this.root;\n while (focusedPath.length > 0) {\n const nextId = focusedPath.shift();\n if (nextId) {\n if (!level.items) {\n this.loadItems(level);\n await this.httpComplete;\n }\n\n level = findItem(level.items, nextId).item;\n if (!level) {\n focusedPath.splice(0, focusedPath.length);\n } else {\n newPath.push(nextId);\n }\n }\n }\n\n this.selection = newPath;\n this.refresh();\n this.requestUpdate('root');\n }\n\n private isSelected(menuItem: MenuItem) {\n if (menuItem.level < this.selection.length) {\n const selected =\n this.selection[menuItem.level] == (menuItem.vanity_id || menuItem.id);\n return selected;\n }\n return false;\n }\n\n private isExpanded(menuItem: MenuItem) {\n const expanded = !!this.selection.find(\n id => id === menuItem.vanity_id || menuItem.id\n );\n return expanded;\n }\n\n private renderMenuItem = (\n menuItem: MenuItem,\n parent: MenuItem = null\n ): TemplateResult => {\n if (menuItem.type === 'divider') {\n return html`
    `;\n }\n\n if (menuItem.type === 'temba-notification-list') {\n return html``;\n }\n\n if (menuItem.type === 'space') {\n return html`
    `;\n }\n\n if (menuItem.type === 'section' || menuItem.inline) {\n return html`
    ${menuItem.name}
    `;\n }\n\n if (menuItem.type === 'modax-button') {\n return html` {\n this.handleItemClicked(event, menuItem);\n }}\n />`;\n }\n\n const isSelected = this.isSelected(menuItem);\n const isChildSelected =\n isSelected && this.selection.length > menuItem.level + 1;\n\n let icon = menuItem.icon\n ? html`
    \n ${menuItem.bubble && !menuItem.count\n ? html`
    `\n : null}\n `\n : null;\n\n const collapsedIcon = menuItem.collapsed_icon\n ? html``\n : null;\n\n const itemClasses = getClasses({\n ['menu-' + menuItem.id]: true,\n 'child-selected': isChildSelected,\n selected: isSelected,\n item: !(menuItem.avatar && menuItem.level === 0),\n avatar: !!menuItem.avatar,\n popup: menuItem.popup,\n inline: menuItem.inline,\n expanding: this.expanding && this.expanding === menuItem.id,\n expanded: this.isExpanded(menuItem),\n iconless: !icon && !collapsedIcon && !menuItem.avatar,\n pressed: this.pressedItem && this.pressedItem.id == menuItem.id,\n 'show-mobile': menuItem.mobile,\n });\n\n if (menuItem.avatar) {\n icon = renderAvatar({\n name: menuItem.avatar,\n tip: false,\n scale: parent ? 0.9 : 1.2,\n });\n if (menuItem.bubble) {\n icon = html`${icon}${menuItem.bubble\n ? html``\n : null}`;\n }\n icon = html`
    ${icon}
    `;\n }\n\n const item = html`\n {\n event.preventDefault();\n this.pressedItem = null;\n this.handleItemClicked(event, menuItem, parent);\n }}\n @mousedown=${() => {\n if (menuItem.level > 0) {\n this.pressedItem = menuItem;\n }\n }}\n @mouseleave=${() => {\n this.pressedItem = null;\n }}\n >\n ${menuItem.level === 0\n ? menuItem.avatar\n ? icon\n : html`${icon}`\n : html`${icon}${collapsedIcon}`}\n\n
    \n \n ${menuItem.name}\n
    \n ${menuItem.level > 0\n ? menuItem.inline\n ? html``\n : html`${menuItem.count || menuItem.count == 0\n ? html`\n \n ${menuItem.count.toLocaleString()}\n \n `\n : html`
    `}`\n : null}\n \n
    \n \n `;\n\n if (menuItem.popup) {\n return html`\n \n
    ${item}
    \n
    \n
    \n ${(menuItem.items || []).map((child: MenuItem) => {\n child.level = menuItem.level + 1;\n return html`${this.renderMenuItem(child, menuItem)}`;\n })}\n
    \n
    \n \n `;\n }\n return item;\n };\n\n public render(): TemplateResult {\n if (!this.root || !this.root.items) {\n return null;\n }\n\n let items = this.root.items || [];\n const levels = [];\n\n const expandIcon = this.isMobile() ? Icon.menu : Icon.menu_collapse;\n\n levels.push(\n html`
    \n
    \n
    \n \n
    \n
    \n
    \n\n ${items\n .filter(item => !item.bottom)\n .map((item: MenuItem) => {\n return this.renderMenuItem(item);\n })}\n\n
    \n ${items\n .filter(item => !!item.bottom)\n .map((item: MenuItem) => {\n return this.renderMenuItem(item);\n })}\n
    \n
    `\n );\n\n this.selection.forEach((id, index) => {\n const selected = findItem(items, id).item;\n\n let collapsed = false;\n if (selected) {\n items = selected.items;\n const itemState = this.getMenuItemState(selected.id);\n // users set an explicit collapse state\n if (itemState.collapsed) {\n collapsed = itemState.collapsed === 'collapsed';\n }\n // otherwise pick a default collapse state\n else {\n if (this.selection.length > selected.level + 2) {\n collapsed = false;\n }\n }\n } else {\n items = null;\n }\n\n const collapseIcon = this.isMobile() ? Icon.close : Icon.menu_collapse;\n\n if (items && items.length > 0 && !selected.inline) {\n levels.push(\n html`\n ${!this.submenu\n ? html`\n \n
    \n
    ${selected.name}
    \n\n ${index == 0 && !this.collapsed\n ? html``\n : null}\n
    \n `\n : null}\n ${items.map((item: MenuItem) => {\n if (item.inline && item.items) {\n return html`${this.renderMenuItem(item)}\n
    \n ${(item.items || []).map((child: MenuItem) => {\n return this.renderMenuItem(child, item);\n })}\n
    `;\n }\n return this.renderMenuItem(item);\n })}\n `\n );\n }\n });\n\n const menu = html`\n ${levels}\n `;\n return html`${menu}`;\n }\n}\n","import { LitElement, TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\n\nexport class Anchor extends LitElement {\n static get styles() {\n return css`\n :host {\n color: var(--color-link-primary);\n display: inline-block;\n }\n\n slot:hover {\n cursor: pointer;\n text-decoration: underline;\n }\n `;\n }\n\n @property({ type: String })\n href: string;\n\n private handleClick(evt: MouseEvent) {\n // TODO: fire event instead to be handled upstream\n (window as any).goto(evt);\n }\n\n public render(): TemplateResult {\n return html``;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\nimport { getClasses } from '../utils';\nimport { ContactStoreElement } from '../contacts/ContactStoreElement';\n\nexport class Dropdown extends RapidElement {\n static get styles() {\n return css`\n .wrapper {\n position: relative;\n }\n\n .toggle {\n cursor: pointer;\n }\n\n .dropdown-wrapper {\n position: relative;\n overflow: auto;\n }\n\n .dropdown {\n position: absolute;\n opacity: 0;\n z-index: 2;\n pointer-events: none;\n padding: 0;\n border-radius: var(--curvature);\n background: #fff;\n transform: translateY(1em) scale(0.9);\n transition: all calc(0.8 * var(--transition-speed)) var(--bounce);\n user-select: none;\n margin-top: 0px;\n margin-left: 0px;\n box-shadow: var(--dropdown-shadow);\n }\n\n .dropdown:focus {\n outline: none;\n }\n\n .arrow {\n content: '';\n width: 0px;\n height: 0;\n top: -6px;\n z-index: 10;\n position: absolute;\n border-left: 6px solid transparent;\n border-right: 6px solid transparent;\n border-bottom: 6px solid white;\n }\n\n .open .dropdown {\n opacity: 1;\n pointer-events: auto;\n transform: translateY(0.5em) scale(1);\n }\n\n .mask {\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n opacity: 0;\n transition: opacity var(--transition-speed) ease-in-out;\n pointer-events: none;\n z-index: 1;\n }\n\n .mask.open {\n opacity: 1;\n pointer-events: auto;\n }\n\n .right {\n right: 0;\n }\n `;\n }\n\n @property({ type: Boolean })\n open = false;\n\n @property({ type: Boolean })\n top = false;\n\n @property({ type: Boolean })\n bottom = false;\n\n @property({ type: Boolean })\n left = false;\n\n @property({ type: Boolean })\n right = false;\n\n @property({ type: Number })\n arrowSize = 6;\n\n @property({ type: Number })\n arrowOffset = this.arrowSize * 2;\n\n @property({ type: Number })\n offsetX = 0;\n\n @property({ type: Number })\n offsetY = 0;\n\n @property({ type: Boolean })\n mask = false;\n\n constructor() {\n super();\n this.ensureOnScreen = this.ensureOnScreen.bind(this);\n }\n\n public firstUpdated(props: any) {\n super.firstUpdated(props);\n\n const arrow = this.shadowRoot.querySelector('.arrow') as HTMLDivElement;\n arrow.style.borderWidth = this.arrowSize + 'px';\n arrow.style.top = '-' + this.arrowSize + 'px';\n\n if (this.arrowOffset < 0) {\n arrow.style.right = Math.abs(this.arrowOffset) + 'px';\n } else {\n arrow.style.left = this.arrowOffset + 'px';\n }\n\n const dropdown = this.shadowRoot.querySelector(\n '.dropdown'\n ) as HTMLDivElement;\n\n dropdown.addEventListener('blur', () => {\n // we nest this to deal with clicking the toggle to close\n // as we don't want it to toggle an immediate open, probably\n // a better way to deal with this\n window.setTimeout(() => {\n this.open = false;\n // blur our host element too\n (this.shadowRoot.host as HTMLDivElement).blur();\n }, 200);\n });\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n const dropdown = this.shadowRoot.querySelector(\n '.dropdown'\n ) as HTMLDivElement;\n\n if (changedProperties.has('offsetY') || changedProperties.has('offsetX')) {\n dropdown.style.marginTop = this.offsetY + 'px';\n if (dropdown.offsetLeft + dropdown.clientWidth > window.outerWidth) {\n dropdown.style.marginLeft =\n '-' + (dropdown.clientWidth - this.clientWidth - this.offsetX) + 'px';\n } else {\n if (this.right) {\n dropdown.style.marginRight = this.offsetX + 'px';\n } else {\n dropdown.style.marginLeft = this.offsetX + 'px';\n }\n }\n }\n\n if (changedProperties.has('open')) {\n // check right away if we are on the screen, and then again moments after render\n window.setTimeout(this.ensureOnScreen, 0);\n window.setTimeout(this.ensureOnScreen, 100);\n }\n }\n\n public ensureOnScreen() {\n const dropdown = this.shadowRoot.querySelector(\n '.dropdown'\n ) as HTMLDivElement;\n\n if (dropdown) {\n // dropdown will go off the screen, let's push it up\n const toggle = this.querySelector('div[slot=\"toggle\"]');\n\n if (!toggle) {\n return;\n }\n\n if (dropdown.getBoundingClientRect().bottom > window.innerHeight - 100) {\n if (this.bottom) {\n dropdown.style.top = toggle.clientHeight + 'px';\n } else {\n dropdown.style.top = '';\n dropdown.style.bottom = toggle.clientHeight + 'px';\n }\n } else if (dropdown.getBoundingClientRect().top < 0) {\n if (this.bottom) {\n dropdown.style.top = toggle.clientHeight + 'px';\n } else {\n dropdown.style.top = toggle.clientHeight + 'px';\n dropdown.style.bottom = '';\n }\n }\n\n if (dropdown.getBoundingClientRect().right > window.innerWidth) {\n dropdown.style.left = '';\n dropdown.style.right = '0px';\n } else if (dropdown.getBoundingClientRect().left < 0) {\n dropdown.style.left = 0 + 'px';\n dropdown.style.right = '';\n }\n }\n }\n\n public handleToggleClicked(event: MouseEvent): void {\n event.preventDefault();\n event.stopPropagation();\n if (!this.open) {\n this.open = true;\n\n const dropdown = this.shadowRoot.querySelector(\n '.dropdown'\n ) as HTMLDivElement;\n dropdown.focus();\n }\n }\n\n private handleDropdownMouseDown(event: MouseEvent): void {\n // block mouse down when clicking inside dropdown so we don't lose focus yet\n event.preventDefault();\n event.stopPropagation();\n }\n\n public render(): TemplateResult {\n return html`\n ${this.mask\n ? html`
    `\n : null}\n\n
    \n \n \n
    \n
    \n \n
    \n
    \n
    \n `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { RapidElement } from '../RapidElement';\nimport { getClasses } from '../utils';\nimport { Tab } from './Tab';\n\nexport class TabPane extends RapidElement {\n static get styles() {\n return css`\n :host {\n display: flex;\n flex-direction: column;\n min-height: 0;\n flex-grow: 1;\n }\n\n .tabs {\n display: flex;\n align-items: stretch;\n }\n\n .tab {\n user-select: none;\n padding: 0.5em 0.7em;\n margin: 0em 0em;\n cursor: pointer;\n display: flex;\n font-size: 1.01em;\n align-items: center;\n border-radius: var(--curvature);\n border-bottom-right-radius: 0px;\n border-bottom-left-radius: 0px;\n border: 0px solid rgba(0, 0, 0, 0.45);\n color: var(--color-text-dark);\n --icon-color: var(--color-text-dark);\n white-space: nowrap;\n transition: all 100ms linear;\n }\n\n .focusedname .tab .name {\n transition: all 0s linear !important;\n }\n\n .focusedname .tab.selected .name {\n transition: all 200ms linear !important;\n }\n\n .tab.hidden {\n display: none;\n }\n\n .tab temba-icon {\n }\n\n .tab .name {\n margin-left: 0.4em;\n max-width: 80px;\n overflow: hidden;\n transition: max-width 500ms ease-in-out, margin 500ms ease-in-out;\n white-space: nowrap;\n text-overflow: ellipsis;\n }\n\n .tab .badge {\n margin-left: 0.4em;\n }\n\n @media (max-width: 900px) {\n .collapses .tab .name {\n max-width: 0px;\n margin: 0;\n }\n }\n\n @media (max-width: 600px) {\n .collapses .tab .badge {\n display: none;\n }\n }\n\n .focusedname .tab.selected {\n transform: none;\n }\n\n .focusedname .tab .name {\n max-width: 0px;\n margin: 0;\n transition: max-width 200ms linear, margin 200ms linear;\n }\n\n .focusedname .tab.selected .name {\n margin-left: 0.4em;\n max-width: 200px;\n }\n\n .tab {\n transform: scale(0.9) translate(0em, -0.05em);\n --icon-color: #aaa;\n color: #aaa;\n }\n\n .tab.selected {\n }\n\n .tab.selected,\n .tab.selected:hover {\n cursor: default;\n box-shadow: 0px -3px 3px 1px rgba(0, 0, 0, 0.02);\n background: var(--focused-tab-color, #fff);\n transform: scale(1) translateY(0em);\n --icon-color: #666;\n color: #666;\n }\n\n .bottom .tab.selected {\n }\n\n .tab:hover {\n --icon-color: #666;\n color: #666;\n background: rgba(0, 0, 0, 0.02);\n }\n\n .pane {\n display: flex;\n flex-direction: column;\n flex-grow: 1;\n background: var(--focused-tab-color, #fff);\n border-radius: var(--curvature);\n box-shadow: var(\n --tabs-shadow,\n rgba(0, 0, 0, 0.1) 0px 1px 3px 0px,\n rgba(0, 0, 0, 0.03) 0px 1px 2px 0px\n );\n min-height: 0;\n }\n\n .pane.first {\n border-top-left-radius: 0px;\n overflow: hidden;\n }\n\n .badge {\n }\n\n .count {\n border-radius: 99px;\n background: rgba(0, 0, 0, 0.05);\n color: rgba(0, 0, 0, 0.5);\n font-size: 0.6em;\n font-weight: 400;\n padding: 0.1em 0.4em;\n min-width: 1em;\n text-align: center;\n }\n\n .notify .count {\n background: var(--color-alert);\n color: #fff;\n }\n\n .bottom.tabs .tab {\n border-radius: 0em;\n }\n\n .bottom.pane {\n border-radius: 0em;\n }\n\n .bottom.pane.first {\n border-bottom-left-radius: 0px;\n }\n\n .bottom .tab.first {\n border-bottom-left-radius: var(--curvature);\n }\n\n .embedded.pane {\n box-shadow: none;\n margin: 0;\n }\n\n .embedded.tabs {\n margin: 0;\n }\n\n .embedded .tab {\n }\n\n .embedded.tabs .tab.selected {\n box-shadow: none !important;\n }\n\n .embedded.pane {\n // padding: 0.3em;\n }\n\n .check {\n margin-left: 0.4em;\n }\n `;\n }\n\n @property({ type: Boolean })\n embedded = false;\n\n @property({ type: Boolean })\n collapses = false;\n\n // are the tabs on the bottom of the pane?\n @property({ type: Boolean })\n bottom = false;\n\n // Only shows the name if the tab is focused\n @property({ type: Boolean })\n focusedName = false;\n\n @property({ type: Number })\n index = -1;\n\n @property({ type: String })\n refresh = '';\n\n private handleTabClick(event: MouseEvent): void {\n this.index = parseInt(\n (event.currentTarget as HTMLDivElement).dataset.index\n );\n event.preventDefault();\n event.stopPropagation();\n this.requestUpdate('index');\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n if (changedProperties.has('index')) {\n const tabs = this.getTabs();\n if (tabs.length > this.index) {\n for (let i = 0; i < tabs.length; i++) {\n const tab = tabs[i];\n tab.selected = i == this.index;\n if (tab.selected) {\n tab.style.display = 'flex';\n } else {\n tab.style.display = 'none';\n }\n }\n }\n this.fireEvent(CustomEventType.ContextChanged);\n }\n\n // if our current tab is hidden, select the first visible one\n if (this.index > -1) {\n const tabs = this.getTabs();\n if (this.getTab(this.index).hidden) {\n for (let i = 0; i < tabs.length; i++) {\n const tab = this.getTab(i);\n if (!tab.hidden) {\n this.index = i;\n return;\n }\n }\n }\n }\n }\n\n public getCurrentTab(): Tab {\n return this.getTabs()[this.index];\n }\n\n public getTab(index: number): Tab {\n return this.getTabs()[index];\n }\n\n public handleTabContentChanged() {\n this.requestUpdate();\n }\n\n public getTabs(): Tab[] {\n const tabs: Tab[] = [];\n for (const t of this.children) {\n if (t.tagName === 'TEMBA-TAB') {\n const tab = t as Tab;\n tabs.push(tab);\n }\n }\n return tabs;\n }\n\n public render(): TemplateResult {\n const tabs = this.getTabs();\n\n return html`\n ${this.bottom\n ? html`\n \n `\n : null}\n\n \n ${tabs.map(\n (tab, index) => html`\n \n ${tab.icon ? html`` : null}\n
    ${tab.name}
    \n ${tab.hasBadge()\n ? html`\n
    \n ${tab.count > 0\n ? html`
    \n ${tab.count.toLocaleString()}\n
    `\n : null}\n
    \n `\n : null}\n ${tab.checked\n ? html``\n : null}\n \n `\n )}\n\n
    \n
    \n \n
    \n \n ${!this.bottom\n ? html`\n \n `\n : null}\n `;\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\nimport { getClasses } from '../utils';\n\nexport class Tab extends RapidElement {\n static get styles() {\n return css`\n :host {\n display: flex;\n flex-direction: column;\n flex-grow: 1; \n min-height: 0;\n } \n \n slot {\n // display: none;\n \n\n slot.selected {\n // display: flex;\n // flex-direction: column;\n // flex-grow: 1;\n }\n `;\n }\n\n @property({ type: String })\n name: string;\n\n @property({ type: String })\n icon: string;\n\n @property({ type: String })\n selectionColor: string;\n\n @property({ type: String })\n selectionBackground: string;\n\n @property({ type: Boolean })\n selected = false;\n\n @property({ type: Boolean })\n notify = false;\n\n @property({ type: Boolean })\n hidden = false;\n\n @property({ type: Number })\n count = 0;\n\n @property({ type: Boolean })\n checked = false;\n\n public hasBadge() {\n return this.count > 0;\n }\n\n public render(): TemplateResult {\n return html` `;\n }\n}\n","import { LitElement, TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { getClasses } from '../utils';\nimport { styleMap } from 'lit-html/directives/style-map.js';\n\nexport default class Label extends LitElement {\n static get styles() {\n return css`\n :host {\n display: inline-block;\n }\n\n slot {\n white-space: nowrap;\n overflow-x: hidden;\n text-overflow: ellipsis;\n display: block;\n }\n\n .mask {\n padding: 3px 8px;\n border-radius: 12px;\n display: flex;\n }\n\n temba-icon {\n margin-right: 0.3em;\n padding-bottom: 0.1em;\n }\n\n .label.clickable .mask:hover {\n background: var(--color-background-hover, rgb(0, 0, 0, 0.05));\n }\n\n .label {\n font-size: 0.8em;\n font-weight: 400;\n border-radius: 12px;\n box-shadow: var(--widget-shadow, 0 0.04em 0.08em rgba(0, 0, 0, 0.15));\n background: var(--color-overlay-light);\n color: var(--color-overlay-light-text);\n --icon-color: var(--color-overlay-light-text);\n text-shadow: none;\n }\n\n .danger {\n background: tomato;\n color: #fff;\n --icon-color: #fff;\n }\n\n .primary {\n background: var(--color-primary-dark);\n color: var(--color-text-light);\n --icon-color: var(--color-text-light);\n }\n\n .secondary {\n background: var(--color-secondary-dark);\n color: var(--color-text-light);\n --icon-color: var(--color-text-light);\n }\n\n .tertiary {\n background: var(--color-tertiary);\n color: var(--color-text-light);\n --icon-color: var(--color-text-light);\n }\n\n .dark {\n background: var(--color-overlay-dark);\n text-shadow: none;\n }\n\n .clickable {\n cursor: pointer;\n }\n\n .shadow {\n box-shadow: 1px 1px 2px 1px rgba(0, 0, 0, 0.1);\n }\n `;\n }\n\n @property({ type: Boolean })\n clickable: boolean;\n\n @property({ type: Boolean })\n primary: boolean;\n\n @property({ type: Boolean })\n secondary: boolean;\n\n @property({ type: Boolean })\n tertiary: boolean;\n\n @property({ type: Boolean })\n danger: boolean;\n\n @property({ type: Boolean })\n dark: boolean;\n\n @property({ type: Boolean })\n shadow: boolean;\n\n @property({ type: String })\n icon: string;\n\n @property()\n backgroundColor: string;\n\n @property()\n textColor: string;\n\n public render(): TemplateResult {\n const labelStyle = {};\n\n if (this.backgroundColor) {\n labelStyle['background'] = this.backgroundColor;\n }\n\n if (this.textColor) {\n labelStyle['color'] = this.textColor;\n labelStyle['--icon-color'] = this.textColor;\n }\n\n return html`\n \n
    \n ${this.icon ? html`` : null}\n \n
    \n \n `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\n\nexport class ContactName extends RapidElement {\n @property({ type: String })\n name: string;\n\n @property({ type: String })\n urn: string;\n\n @property({ type: Number, attribute: 'icon-size' })\n size = 20;\n\n static get styles() {\n return css`\n :host {\n display: flex;\n align-items: center;\n }\n\n temba-urn {\n margin-right: 0.2em;\n }\n\n .name {\n font-size: 1.5rem;\n overflow: hidden;\n max-height: 2rem;\n line-height: 2rem;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: 1;\n text-overflow: ellipsis;\n display: -webkit-box;\n margin: auto;\n }\n `;\n }\n public render(): TemplateResult {\n const urn = this.urn\n ? html``\n : null;\n return html`\n ${urn}\n
    \n ${this.name ? this.name : this.urn ? this.urn.split(':')[1] : ''}\n
    \n \n `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\n\nexport class ContactUrn extends RapidElement {\n @property({ type: String })\n urn: string;\n\n @property({ type: String })\n scheme: string;\n\n @property({ type: Number })\n size = 20;\n\n static get styles() {\n return css`\n :host {\n display: flex;\n align-items: center;\n }\n .urn {\n box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.04) inset;\n padding: 3px;\n border: 1px solid #ddd;\n border-radius: 18rem;\n background: #eee;\n margin-right: 0.2em;\n }\n\n .small {\n padding: 0px;\n border: 0px;\n box-shadow: none;\n margin-right: 0.5em;\n }\n `;\n }\n\n public render(): TemplateResult {\n const scheme = this.scheme || this.urn.split(':')[0];\n return html`\n \n `;\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { getClasses, postJSON } from '../utils';\nimport { ContactFieldEditor } from './ContactFieldEditor';\nimport { ContactStoreElement } from './ContactStoreElement';\nimport { Checkbox } from '../checkbox/Checkbox';\n\nconst MIN_FOR_FILTER = 10;\n\nexport class ContactFields extends ContactStoreElement {\n static get styles() {\n return css`\n .field {\n display: flex;\n margin: 0.3em 0.3em;\n box-shadow: 0 0 0.2em rgba(0, 0, 0, 0.15);\n border-radius: 0px;\n align-items: center;\n overflow: hidden;\n }\n\n .show-all .unset,\n .featured {\n display: block !important;\n }\n\n .unset {\n display: none;\n }\n\n .field:hover {\n box-shadow: 1px 1px 6px 2px rgba(0, 0, 0, 0.05),\n 0px 0px 0px 2px var(--color-link-primary);\n cursor: pointer;\n }\n\n .label {\n padding: 0.25em 1em;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 0px;\n color: #777;\n font-size: 0.9em;\n font-weight: 400;\n box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.1) inset;\n }\n\n .value {\n --icon-color: #ddd;\n max-width: 150px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n padding: 0.25em 1em;\n border-top-right-radius: 0px;\n border-bottom-right-radius: 0px;\n font-size: 0.9em;\n }\n\n .toggle {\n display: flex;\n background: #fff;\n align-items: center;\n margin-bottom: 0.5em;\n }\n\n .disabled .toggle {\n display: none;\n }\n `;\n }\n\n @property({ type: Boolean })\n system: boolean;\n\n @property({ type: Boolean })\n dirty: boolean;\n\n @property({ type: Boolean })\n showAll: boolean;\n\n @property({ type: String })\n timezone: string;\n\n @property({ type: String })\n role: string;\n\n @property({ type: Boolean })\n disabled = false;\n\n connectedCallback(): void {\n super.connectedCallback();\n this.handleFieldChanged = this.handleFieldChanged.bind(this);\n }\n\n private isAgent(): boolean {\n return this.role === 'T';\n }\n\n protected updated(\n changes: PropertyValueMap | Map\n ): void {\n super.updated(changes);\n if (changes.has('data')) {\n if (Object.keys(this.data.fields).length <= MIN_FOR_FILTER) {\n this.showAll = true;\n }\n }\n }\n\n public handleFieldChanged(evt: InputEvent) {\n const field = evt.currentTarget as ContactFieldEditor;\n const value = field.value;\n postJSON('/api/v2/contacts.json?uuid=' + this.data.uuid, {\n fields: { [field.key]: value },\n })\n .then((response: any) => {\n field.handleResponse(response);\n\n // returns a single contact with latest updates\n this.setContact(response.json);\n })\n .catch(error => {\n field.handleResponse(error);\n });\n }\n\n public handleToggle(evt: Event) {\n const checkbox = evt.currentTarget as Checkbox;\n this.showAll = checkbox.checked;\n }\n\n public render(): TemplateResult {\n if (this.data) {\n const fieldsToShow = Object.entries(this.data.fields).sort(\n (a: [string, string], b: [string, string]) => {\n const [ak] = a;\n const [bk] = b;\n const fieldA = this.store.getContactField(ak);\n const fieldB = this.store.getContactField(bk);\n\n if (fieldA.type === 'ward') {\n return 1;\n }\n\n if (fieldB.type === 'ward') {\n return -1;\n }\n\n if (\n fieldA.type === 'district' &&\n fieldB.type !== 'ward' &&\n fieldB.type !== 'district'\n ) {\n return 1;\n }\n\n if (\n fieldB.type === 'district' &&\n fieldA.type !== 'ward' &&\n fieldA.type !== 'district'\n ) {\n return -1;\n }\n\n if (\n fieldA.type === 'state' &&\n fieldB.type !== 'ward' &&\n fieldB.type !== 'district' &&\n fieldB.type !== 'state'\n ) {\n return 1;\n }\n\n if (\n fieldB.type === 'state' &&\n fieldA.type !== 'ward' &&\n fieldA.type !== 'district' &&\n fieldA.type !== 'state'\n ) {\n return -1;\n }\n\n if (fieldA.featured && !fieldB.featured) {\n return -1;\n }\n\n if (fieldB.featured && !fieldA.featured) {\n return 1;\n }\n\n const priority = fieldB.priority - fieldA.priority;\n if (priority !== 0) {\n return priority;\n }\n\n return ak.localeCompare(bk);\n }\n );\n\n if (fieldsToShow.length == 0) {\n return html``;\n }\n\n const fields = fieldsToShow.map((entry: [string, string]) => {\n const [k, v] = entry;\n const field = this.store.getContactField(k);\n return html``;\n });\n\n return html`\n
    \n
    ${fields}
    \n ${Object.keys(this.data.fields).length >= MIN_FOR_FILTER\n ? html`
    \n
    \n
    \n \n
    \n
    `\n : null}\n
    \n `;\n }\n\n return super.render();\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { FormElement } from '../FormElement';\nimport { CustomEventType } from '../interfaces';\nimport { RapidElement } from '../RapidElement';\nimport { InputType, TextInput } from '../textinput/TextInput';\nimport { Icon } from '../vectoricon';\nimport { getClasses, WebResponse } from '../utils';\n\nenum Status {\n Success = 'success',\n Failure = 'failure',\n Saving = 'saving',\n Ready = 'ready',\n}\n\nexport class ContactFieldEditor extends RapidElement {\n @property({ type: String })\n key: string;\n\n @property({ type: String })\n value: string;\n\n @property({ type: String })\n name: string;\n\n @property({ type: String })\n type: string;\n\n @property({ type: String })\n timezone: string;\n\n @property({ type: String })\n icon = navigator.clipboard ? Icon.copy : '';\n\n @property({ type: String })\n iconClass = '';\n\n @property({ type: String })\n status: Status = Status.Ready;\n\n @property({ type: Boolean })\n disabled = false;\n\n @property({ type: Boolean })\n dirty = false;\n\n static get styles() {\n return css`\n :host {\n --transition-speed: 0ms;\n }\n\n .wrapper {\n --temba-textinput-padding: 1.4em 0.8em 0.4em 0.8em;\n --disabled-opacity: 1;\n position: relative;\n --color-widget-bg: transparent;\n --color-widget-bg-focused: #fff;\n --widget-box-shadow: none;\n padding-bottom: 0.6em;\n border-bottom: 1px solid #ececec;\n }\n\n .wrapper.disabled {\n --color-widget-border: transparent;\n }\n\n .wrapper.mutable:hover {\n }\n\n .wrapper.mutable {\n --color-widget-border: rgb(235, 235, 235);\n --color-widget-bg: transparent;\n --input-cursor: pointer;\n\n border-bottom: none;\n margin-bottom: 0.5em;\n padding-bottom: 0em;\n }\n\n .mutable.success {\n --color-widget-border: rgba(var(--success-rgb), 0.6);\n }\n\n .mutable.failure {\n --color-widget-border: rgba(var(--error-rgb), 0.3) !important;\n }\n\n .mutable .dirty {\n --color-widget-border: rgb(235, 235, 235);\n }\n\n .prefix {\n border-top-left-radius: var(--curvature-widget);\n border-bottom-left-radius: var(--curvature-widget);\n cursor: pointer !important;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n display: flex;\n padding: 0em 0.5em;\n position: absolute;\n margin-top: 0.2em;\n pointer-events: none;\n }\n\n .wrapper {\n margin-bottom: 0.5em;\n }\n\n .prefix .name {\n padding: 0em 0.4em;\n color: rgba(100, 100, 100, 0.7);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n font-size: 0.8em;\n }\n\n .postfix {\n display: flex;\n align-items: stretch;\n margin-left: 1em;\n }\n\n .popper {\n background: rgba(0, 0, 0, 0.03);\n border-top-right-radius: var(--curvature-widget);\n border-bottom-right-radius: var(--curvature-widget);\n --icon-color: #888;\n display: flex;\n cursor: default;\n transition: all var(--transition-speed) ease-in-out;\n align-items: stretch;\n margin: -1px;\n }\n\n temba-icon[name='calendar'] {\n --icon-color: rgba(0, 0, 0, 0.2);\n }\n\n temba-icon:hover {\n --icon-color: rgba(0, 0, 0, 0.5);\n }\n\n temba-icon {\n cursor: pointer;\n --icon-color: rgba(0, 0, 0, 0.3);\n }\n\n temba-textinput:focus .popper,\n temba-textinput:hover .popper {\n display: flex;\n }\n\n .disabled temba-textinput .postfix {\n display: none;\n padding: none;\n }\n\n .unset temba-textinput .popper .copy,\n .unset temba-textinput .popper .search {\n display: none;\n }\n\n .unset temba-textinput:focus .popper .copy,\n .unset temba-textinput:hover .popper .copy,\n .unset temba-textinput:focus .popper .save,\n .unset temba-textinput:hover .popper .save {\n display: none;\n }\n\n .popper temba-icon {\n padding: 0.5em 0em;\n padding-right: 1em;\n }\n\n .popper:first-child {\n padding: 0.5em 0em;\n padding-right: 0.5em;\n padding-left: 1em;\n }\n\n .popper:last-child {\n padding-right: 0em;\n }\n\n .copy.clicked temba-icon {\n transform: scale(1.2);\n }\n\n temba-icon {\n transition: all 200ms ease-in-out;\n }\n\n temba-datepicker {\n position: relative;\n }\n\n .save-state {\n display: flex;\n align-items: center;\n }\n\n .save-button {\n padding-right: 1em;\n }\n\n .dirty .copy,\n .dirty .search {\n display: none;\n }\n\n .saving .copy,\n .saving .search {\n display: none;\n }\n\n .success .copy,\n .success .search {\n display: none;\n }\n\n .failure .copy,\n .failure .search {\n display: none;\n }\n\n .popper.success {\n background: rgb(var(--success-rgb));\n }\n\n .popper.failure {\n background: rgb(var(--error-rgb));\n }\n\n .popper.success temba-icon,\n .popper.failure temba-icon {\n --icon-color: #fff !important;\n }\n\n .popper.dirty {\n background: rgba(0, 0, 0, 0.03);\n }\n\n temba-datepicker .popper {\n border-radius: 0px;\n }\n\n temba-datepicker .popper:first-child {\n padding: 0;\n }\n\n .dirty temba-datepicker .popper:first-child {\n padding-left: 1em;\n }\n\n .success temba-datepicker .popper:first-child {\n padding-left: 1em;\n }\n\n .failure temba-datepicker .popper:first-child {\n padding-left: 1em;\n }\n\n .saving temba-datepicker .popper:first-child {\n padding-left: 1em;\n }\n\n temba-datepicker .postfix {\n margin-left: 0;\n }\n\n .saving temba-datepicker,\n .saving temba-textinput {\n pointer-events: none !important;\n cursor: default !important;\n opacity: 0.7;\n }\n `;\n }\n\n connectedCallback(): void {\n super.connectedCallback();\n this.handleInput = this.handleInput.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n public handleIconClick(evt: MouseEvent) {\n const ele = evt.target as HTMLDivElement;\n const icon = ele.getAttribute('icon-action');\n const input = this.shadowRoot.querySelector('temba-textinput') as TextInput;\n\n if (icon === 'copy') {\n if (navigator.clipboard) {\n this.iconClass = 'clicked';\n navigator.clipboard.writeText(input.getDisplayValue()).then(() => {\n window.setTimeout(() => {\n this.iconClass = '';\n }, 300);\n });\n }\n }\n\n if (icon === 'search') {\n this.fireCustomEvent(CustomEventType.ButtonClicked, {\n key: this.key,\n value: this.value,\n });\n }\n\n evt.preventDefault();\n evt.stopPropagation();\n }\n\n public handleResponse(response: WebResponse) {\n if (response.status === 200) {\n this.value = response.json.fields[this.key];\n // this.status = Status.Success;\n // on success lets go back to ready state for now\n this.status = Status.Ready;\n this.dirty = false;\n } else {\n this.status = Status.Failure;\n this.dirty = false;\n }\n }\n\n public handleSubmit() {\n const input = this.shadowRoot.querySelector(\n 'temba-textinput, temba-datepicker'\n ) as FormElement;\n\n if (input.value !== this.value) {\n this.dirty = true;\n this.status = Status.Saving;\n this.value = input.value;\n this.fireEvent('change');\n }\n }\n\n public handleChange(evt: Event) {\n evt.preventDefault();\n evt.stopPropagation();\n }\n\n public handleDateChange(evt: Event) {\n evt.preventDefault();\n evt.stopPropagation();\n this.dirty = true;\n }\n\n public handleInput(evt: KeyboardEvent) {\n const input = evt.currentTarget as TextInput;\n if (evt.key === 'Enter') {\n input.blur();\n this.handleSubmit();\n } else {\n if (input.value !== this.value) {\n this.dirty = true;\n }\n }\n }\n\n private getInputType(type: string): string {\n if (type === 'numeric') {\n return InputType.Number;\n }\n return InputType.Text;\n }\n\n public render(): TemplateResult {\n const state = html`
    \n ${this.dirty\n ? html``\n : html` ${this.status === Status.Saving\n ? html``\n : null}\n ${this.status === Status.Success && !this.dirty\n ? html``\n : null}\n ${this.status === Status.Failure\n ? html``\n : null}`}\n
    `;\n\n return html`\n \n ${this.type === 'datetime'\n ? html`\n \n
    \n
    ${this.name}
    \n
    \n
    \n \n ${state}\n
    \n \n \n `\n : html`\n \n
    \n
    ${this.name}
    \n
    \n\n
    \n \n ${state}\n\n \n \n
    \n \n \n `}\n \n `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { Group } from '../interfaces';\nimport { debounce, getClasses } from '../utils';\nimport { Icon } from '../vectoricon';\nimport { ContactStoreElement } from './ContactStoreElement';\n\nconst STATUS = {\n stopped: { name: 'Stopped' },\n blocked: { name: 'Blocked' },\n archived: { name: 'Archived' },\n};\n\nexport class ContactBadges extends ContactStoreElement {\n static get styles() {\n return css`\n .wrapper {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n temba-label {\n margin: 0.3em;\n }\n\n .expanded .badges {\n max-height: inherit;\n }\n\n .expanded .show-button {\n opacity: 1;\n margin-bottom: 0em;\n margin-top: -0.5em;\n }\n\n .expanded .show-line {\n width: 98%;\n opacity: 1;\n }\n\n .badges {\n display: flex;\n overflow: hidden;\n flex-wrap: wrap;\n max-height: 2.2em;\n align-self: flex-start;\n }\n\n .show-button {\n transition: all var(--transition-speed) ease-in-out\n var(--transition-speed);\n opacity: 0;\n display: flex;\n padding: 0em 1em;\n margin-top: -0.8em;\n cursor: pointer;\n --icon-color-circle: #fff;\n margin-bottom: -1.5em;\n }\n\n .show-line {\n height: 1px;\n width: 100%;\n background: rgba(0, 0, 0, 0.05);\n margin-top: 1em;\n width: 0px;\n transition: width calc(var(--transition-speed) * 2) linear\n var(--transition-speed);\n }\n\n .has-more .show-line {\n width: 98%;\n }\n\n .has-more .show-button {\n opacity: 1;\n margin-bottom: 0em;\n margin-top: -0.5em;\n }\n\n .show-button temba-icon {\n border-radius: 9999px;\n }\n `;\n }\n\n @property({ type: Boolean })\n hasMore = false;\n\n @property({ type: Boolean })\n expanded = false;\n\n private handleResized() {\n if (this.shadowRoot) {\n const badges = this.shadowRoot.querySelector('.badges');\n if (badges) {\n this.hasMore = badges.scrollHeight > badges.clientHeight;\n }\n }\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n if (changedProperties.has('data')) {\n if (!changedProperties.get('data')) {\n const badges = this.shadowRoot.querySelector('.badges');\n new ResizeObserver(\n debounce(this.handleResized.bind(this), 200)\n ).observe(badges);\n }\n }\n }\n\n public render(): TemplateResult {\n if (this.data) {\n const status = STATUS[this.data.status];\n return html`\n \n
    \n ${status && this.data.status !== 'active'\n ? html`\n \n ${status.name}\n \n `\n : null}\n ${this.data.flow\n ? html`\n \n ${this.data.flow.name}\n \n `\n : null}\n ${this.data.language\n ? html`\n \n ${this.store.getLanguageName(this.data.language)}\n \n `\n : null}\n ${this.data.groups.map((group: Group) => {\n return html`\n \n ${group.name}\n \n `;\n })}\n
    \n
    \n\n
    \n {\n this.expanded = !this.expanded;\n }}\n circled\n name=${!this.expanded ? Icon.down : Icon.up}\n animateChange=\"spin\"\n >\n
    \n \n `;\n } else {\n return null;\n }\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport {\n CustomEventType,\n ScheduledEvent,\n ScheduledEventType,\n} from '../interfaces';\nimport { StoreElement } from '../store/StoreElement';\nimport { Icon } from '../vectoricon';\n\nconst ICONS = {\n [ScheduledEventType.CampaignEvent]: Icon.campaign,\n [ScheduledEventType.ScheduledBroadcast]: Icon.message,\n [ScheduledEventType.ScheduledTrigger]: Icon.trigger,\n};\n\nexport class ContactPending extends StoreElement {\n @property({ type: String })\n contact: string;\n\n @property({ type: Object, attribute: false })\n data: ScheduledEvent[];\n\n @property({ type: String })\n lang_weekly = 'Weekly';\n\n @property({ type: String })\n lang_daily = 'Daily';\n\n @property({ type: String })\n lang_once = 'Once';\n\n REPEAT_PERIOD = {\n O: this.lang_once,\n D: this.lang_daily,\n W: this.lang_weekly,\n };\n\n static get styles() {\n return css`\n :host {\n }\n\n a,\n .linked {\n color: var(--color-link-primary);\n cursor: pointer;\n }\n\n a:hover,\n .linked:hover {\n text-decoration: underline;\n color: var(--color-link-primary-hover);\n }\n\n .type {\n background: rgba(0, 0, 0, 0.02);\n padding: 1em;\n display: flex;\n align-self: stretch;\n --icon-color: rgba(50, 50, 50, 0.25);\n border-top-left-radius: var(--curvature);\n border-bottom-left-radius: var(--curvature);\n }\n\n .details {\n display: flex;\n flex-direction: column;\n padding: 0.5em 1em;\n flex-grow: 1;\n }\n\n .campaign {\n display: flex;\n color: var(--text-color);\n --icon-color: var(--text-color);\n align-self: center;\n white-space: nowrap;\n }\n\n .message {\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n padding: 0.1em;\n }\n\n .event {\n margin-bottom: 0.5em;\n border-radius: var(--curvature);\n display: flex;\n flex-direction: row;\n align-items: center;\n box-shadow: 0 0 8px 1px rgba(0, 0, 0, 0.055),\n 0 0 0px 1px rgba(0, 0, 0, 0.02);\n }\n\n .event:hover {\n cursor: pointer;\n box-shadow: 0 0 8px 1px rgba(0, 0, 0, 0.055),\n 0 0 0px 2px var(--color-link-primary);\n }\n\n .time {\n white-space: nowrap;\n background: rgba(0, 0, 0, 0.02);\n border-top-right-radius: var(--curvature);\n border-bottom-right-radius: var(--curvature);\n display: flex;\n align-self: stretch;\n padding: 0 1em;\n min-width: 5em;\n }\n\n .duration {\n align-self: center;\n flex-grow: 1;\n text-align: center;\n }\n\n .flow {\n display: inline-block;\n }\n\n temba-tip {\n cursor: default;\n }\n\n .scheduled-by {\n font-size: 0.85em;\n display: flex;\n color: var(--text-color);\n --icon-color: var(--text-color);\n }\n\n .scheduled-by temba-icon {\n margin-right: 0.25em;\n }\n\n .scheduled-by .name {\n flex-grow: 1;\n }\n `;\n }\n\n constructor() {\n super();\n this.handleEventClicked = this.handleEventClicked.bind(this);\n }\n\n protected updated(\n changes: PropertyValueMap | Map\n ): void {\n super.updated(changes);\n if (changes.has('contact')) {\n if (this.contact) {\n this.url = `/contact/scheduled/${this.contact}/`;\n } else {\n this.url = null;\n }\n }\n }\n\n public handleEventClicked(event: ScheduledEvent) {\n this.fireCustomEvent(CustomEventType.Selection, event);\n }\n\n public renderEvent(scheduledEvent: ScheduledEvent) {\n return html`\n this.handleEventClicked(scheduledEvent)}\"\n >\n
    \n \n
    \n\n
    \n
    \n ${scheduledEvent.flow\n ? html` Start ${scheduledEvent.flow.name}`\n : null}\n ${scheduledEvent.message\n ? html`
    ${scheduledEvent.message}
    `\n : null}\n
    \n\n
    \n ${scheduledEvent.campaign\n ? html`
    \n \n
    ${scheduledEvent.campaign.name}
    \n
    `\n : html`\n ${scheduledEvent.type === ScheduledEventType.ScheduledTrigger\n ? html``\n : null}\n
    \n ${this.REPEAT_PERIOD[scheduledEvent.repeat_period]}\n
    \n `}\n
    \n
    \n\n
    \n
    \n \n ${this.store.getShortDurationFromIso(scheduledEvent.scheduled)}\n \n
    \n
    \n \n `;\n }\n\n public render(): TemplateResult {\n if (this.data) {\n if (this.data.length > 0) {\n return html`\n ${this.data.map(event => {\n return this.renderEvent(event);\n })}\n `;\n } else {\n return html``;\n }\n }\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType, Ticket, TicketStatus, User } from '../interfaces';\nimport { StoreElement } from '../store/StoreElement';\nimport { getClasses, postJSON, stopEvent } from '../utils';\nimport { Icon } from '../vectoricon';\n\nconst dropdownUserScale = 0.7;\nconst inlineUserScale = 0.8;\n\nexport class ContactTickets extends StoreElement {\n @property({ type: String })\n agent: string;\n\n @property({ type: String })\n contact: string;\n\n @property({ type: String })\n ticket: string;\n\n @property({ type: Boolean })\n clickable = false;\n\n @property({ type: Boolean })\n expandable = false;\n\n @property({ type: Boolean })\n expanded = false;\n\n @property({ type: Object, attribute: false })\n data: Ticket[];\n\n static get styles() {\n return css`\n :host {\n }\n\n :hover {\n }\n\n .ticket.expandable:hover,\n .ticket.clickable:hover {\n cursor: pointer;\n box-shadow: 0 0 8px 1px rgba(0, 0, 0, 0.055),\n 0 0 0px 2px var(--color-link-primary);\n }\n\n .header {\n display: flex;\n flex-direction: row;\n flex-grow: 1;\n }\n\n .tickets {\n display: flex;\n flex-direction: column;\n padding: 0.3em 0.8em;\n }\n\n .count {\n margin-left: 0.5em;\n }\n\n .ticket {\n background: #fff;\n display: flex;\n flex-direction: column;\n margin-bottom: 0.5em;\n border-radius: var(--curvature);\n display: flex;\n flex-direction: column;\n align-items: stretch;\n box-shadow: 0 0 8px 1px rgba(0, 0, 0, 0.055),\n 0 0 0px 1px rgba(0, 0, 0, 0.02);\n transition: all 200ms ease-in-out;\n }\n\n .ticket .topic {\n overflow: hidden;\n text-overflow: ellipsis;\n margin: 0.5em 0.75em 0.5em 0.75em;\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: 1;\n flex-grow: 2;\n }\n\n .ticket .body {\n max-height: 0px;\n overflow-y: auto;\n -webkit-line-clamp: none;\n white-space: normal;\n width: initial;\n padding: 0.5em 0.75em 0em 0.75em;\n max-height: 40vh;\n display: none;\n margin-bottom: 0.5em;\n border-top: 1px solid #e6e6e6;\n }\n\n .ticket.expanded .body {\n display: block;\n }\n\n .status {\n --icon-color: #999;\n }\n\n .ticket.closed {\n background: #f9f9f9;\n color: #888;\n }\n\n .resolve {\n color: var(--color-primary-dark);\n }\n\n .dropdown {\n color: rgb(45, 45, 45);\n z-index: 50;\n width: 18em;\n }\n\n .option-group {\n padding: 0.4em;\n border-bottom: 1px solid #f3f3f3;\n }\n\n .option-group temba-user {\n flex-grow: 1;\n }\n\n .assigned .user {\n flex-grow: 1;\n }\n\n .assigned {\n display: flex;\n align-items: center;\n }\n\n .assigned temba-button {\n margin-right: 0.75em;\n }\n\n .assigned .user:hover {\n cursor: default;\n background: none;\n }\n\n .options {\n max-height: 40vh;\n overflow-y: auto;\n border-bottom: none;\n }\n\n .user {\n display: flex;\n align-items: center;\n border-radius: var(--curvature);\n cursor: pointer;\n }\n\n .user:hover {\n background: var(--color-selection);\n }\n\n .user .name {\n display: -webkit-box;\n -webkit-line-clamp: 1;\n -webkit-box-orient: vertical;\n overflow: hidden;\n flex-grow: 1;\n }\n\n .user temba-button {\n margin-left: 0.5em;\n }\n\n .current-user {\n font-weight: 400;\n }\n\n .details {\n display: flex;\n align-items: center;\n flex-shrink: 1;\n margin-right: 0.5em;\n }\n\n .details .date {\n padding: 0em 0.5em;\n }\n\n .details .toggle {\n padding-right: 0.5em;\n }\n `;\n }\n\n prepareData(data: any): any {\n if (data && data.length) {\n data.sort((a: Ticket, b: Ticket) => {\n if (a.status == TicketStatus.Open && b.status == TicketStatus.Closed) {\n return -1;\n }\n\n if (b.status == TicketStatus.Open && a.status == TicketStatus.Closed) {\n return 1;\n }\n\n if (\n a.status == TicketStatus.Closed &&\n b.status == TicketStatus.Closed\n ) {\n return (\n new Date(b.closed_on).getTime() - new Date(a.closed_on).getTime()\n );\n }\n\n return (\n new Date(b.opened_on).getTime() - new Date(a.opened_on).getTime()\n );\n });\n }\n return data;\n }\n\n protected updated(\n changes: PropertyValueMap | Map\n ): void {\n super.updated(changes);\n if (changes.has('contact') || changes.has('ticket')) {\n if (this.contact) {\n this.url = `/api/v2/tickets.json?contact=${this.contact}${\n this.ticket ? '&ticket=' + this.ticket : ''\n }`;\n } else {\n this.url = null;\n }\n }\n }\n\n private handleClose(uuid: string) {\n postJSON(`/api/v2/ticket_actions.json`, {\n tickets: [uuid],\n action: 'close',\n })\n .then(() => {\n this.refresh();\n })\n .catch((response: any) => {\n console.error(response);\n });\n }\n\n private handleReopen(uuid: string) {\n postJSON(`/api/v2/ticket_actions.json`, {\n tickets: [uuid],\n action: 'reopen',\n })\n .then(() => {\n this.refresh();\n })\n .catch((response: any) => {\n console.error(response);\n });\n }\n\n public handleTicketAssignment(uuid: string, email: string) {\n // if its already assigned to use, it's a noop\n const ticket = this.data.find(ticket => ticket.uuid === uuid);\n if (ticket.assignee && ticket.assignee.email === email) {\n return;\n }\n this.blur();\n\n postJSON(`/api/v2/ticket_actions.json`, {\n tickets: [uuid],\n action: 'assign',\n assignee: email,\n })\n .then(() => {\n this.refresh();\n })\n .catch((response: any) => {\n console.error(response);\n });\n return true;\n }\n\n public renderTicket(ticket: Ticket) {\n const date = ticket.opened_on;\n const users = this.store.getAssignableUsers();\n const agent = users.find(user => user.email === this.agent);\n return html`\n {\n if (this.clickable) {\n this.fireCustomEvent(CustomEventType.ButtonClicked, { ticket });\n } else if (this.expandable) {\n this.expanded = !this.expanded;\n }\n }}\n class=\"ticket ${ticket.status} ${getClasses({\n clickable: this.clickable,\n expandable: this.expandable,\n expanded: this.expanded,\n })}\"\n >\n
    \n
    ${ticket.topic.name}
    \n\n
    \n
    \n \n
    \n\n ${ticket.status === TicketStatus.Closed\n ? html`
    \n {\n event.preventDefault();\n event.stopPropagation();\n this.handleReopen(ticket.uuid);\n }}\n >\n
    `\n : html`\n
    \n \n
    \n ${ticket.assignee\n ? html`\n \n `\n : html`\n \n `}\n
    \n\n {\n stopEvent(event);\n }}\n >\n ${ticket.assignee\n ? html`\n \n \n {\n stopEvent(event);\n this.handleTicketAssignment(\n ticket.uuid,\n null\n );\n }}\n >\n
    \n `\n : null}\n ${agent &&\n (!ticket.assignee ||\n agent.email !== ticket.assignee.email)\n ? html`\n {\n stopEvent(event);\n this.handleTicketAssignment(\n ticket.uuid,\n agent.email\n );\n }}\n >\n \n
    \n `\n : null}\n\n
    \n ${this.store.getAssignableUsers().map(user => {\n if (\n ticket.assignee &&\n user.email === ticket.assignee.email\n ) {\n return null;\n }\n\n if (user.email === this.agent) {\n return null;\n }\n return html` {\n stopEvent(event);\n this.handleTicketAssignment(\n ticket.uuid,\n user.email\n );\n }}\n >\n \n
    `;\n })}\n
    \n \n \n \n \n {\n event.preventDefault();\n event.stopPropagation();\n this.handleClose(ticket.uuid);\n }}\n ?clickable=${open}\n />\n
    \n `}\n \n \n
    ${ticket.body}
    \n \n `;\n }\n\n public render(): TemplateResult {\n if (this.data && this.data.length > 0) {\n const tickets = this.data.map(ticket => {\n return this.renderTicket(ticket);\n });\n return html`${tickets}`;\n }\n\n return html``;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { property } from 'lit/decorators.js';\nimport { FormElement } from '../FormElement';\nimport { getClasses } from '../utils';\n\nexport class TembaSlider extends FormElement {\n static get styles() {\n return css`\n :host {\n display: block;\n }\n\n .track {\n height: 2px;\n border-top: 0.5em solid #fff;\n border-bottom: 0.5em solid #fff;\n background: #ddd;\n flex-grow: 1;\n }\n\n .circle {\n margin-bottom: -1.05em;\n margin-left: -0.5em;\n width: 0.75em;\n height: 0.75em;\n border: 2px solid #999;\n border-radius: 999px;\n position: relative;\n background: #fff;\n box-shadow: 0 0 0 4px rgb(255, 255, 255);\n transition: transform 200ms ease-in-out;\n }\n\n .grabbed .track {\n cursor: pointer;\n }\n\n :hover .circle {\n border-color: #777;\n cursor: pointer;\n }\n\n .grabbed .circle {\n border-color: var(--color-primary-dark);\n background: #fff;\n }\n\n .grabbed .circle {\n transform: scale(1.2);\n }\n\n .wrapper {\n display: flex;\n align-items: center;\n }\n\n .pre,\n .post {\n font-size: 0.9em;\n color: #999;\n padding: 0em 1em;\n }\n `;\n }\n\n @property({ type: Boolean })\n range = false;\n\n @property({ type: Number })\n min = 0;\n\n @property({ type: Number })\n max = 100;\n\n circleX = 0;\n grabbed = false;\n\n public firstUpdated(changes: Map) {\n super.firstUpdated(changes);\n this.handleMouseMove = this.handleMouseMove.bind(this);\n this.handleMouseUp = this.handleMouseUp.bind(this);\n }\n\n public updated(changedProperties: Map): void {\n if (changedProperties.has('value')) {\n this.updateCircle();\n }\n }\n\n public updateValue(evt: MouseEvent) {\n const track = this.shadowRoot.querySelector('.track') as HTMLDivElement;\n const left = evt.pageX - track.offsetLeft;\n const pct = left / track.offsetWidth;\n\n const range = this.max - this.min;\n const pctAsValue = range * pct + this.min;\n this.value =\n '' + Math.max(this.min, Math.min(Math.round(pctAsValue), this.max));\n }\n\n public handleMouseMove(evt: MouseEvent) {\n if (this.grabbed) {\n this.updateValue(evt);\n }\n }\n\n public handleTrackDown(evt: MouseEvent) {\n this.grabbed = true;\n document.addEventListener('mousemove', this.handleMouseMove);\n document.addEventListener('mouseup', this.handleMouseUp);\n document.querySelector('html').classList.add('dragging');\n this.updateValue(evt);\n this.requestUpdate();\n }\n\n public handleMouseUp(evt: MouseEvent) {\n this.grabbed = false;\n this.updateValue(evt);\n this.requestUpdate();\n\n document.removeEventListener('mousemove', this.handleMouseMove);\n document.removeEventListener('mouseup', this.handleMouseUp);\n document.querySelector('html').classList.remove('dragging');\n }\n\n public updateCircle() {\n const track = this.shadowRoot.querySelector('.track') as HTMLDivElement;\n const pre = this.shadowRoot.querySelector('.pre') as HTMLDivElement;\n const range = this.max - this.min;\n let cValue = parseInt(this.value);\n if (!cValue || cValue < this.min) {\n cValue = this.min;\n } else if (cValue > this.max) {\n cValue = this.max;\n }\n this.value = '' + cValue;\n const pct = (cValue - this.min) / range;\n const pctAsPixels = track.offsetWidth * pct;\n\n this.circleX = pctAsPixels + (pre ? pre.offsetWidth : 0);\n this.requestUpdate();\n }\n\n public render(): TemplateResult {\n return html`
    \n
    \n
    \n ${this.range ? html`
    ${this.min}
    ` : null}\n
    \n ${this.range ? html`
    ${this.max}
    ` : null}\n
    \n `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { Checkbox } from '../checkbox/Checkbox';\nimport { Select } from '../select/Select';\nimport { capitalize } from '../utils';\nimport { Icon } from '../vectoricon';\nimport { TembaList } from './TembaList';\n\nconst FLOW_COLOR = 'rgb(223, 65, 159)';\n\nexport class RunList extends TembaList {\n @property({ type: String })\n flow: string;\n\n @property({ type: Object, attribute: false })\n results: any[];\n\n @property({ type: Boolean })\n responses = true;\n\n @property({ type: Object })\n resultPreview: any;\n\n @property({ type: Object })\n selectedRun: any;\n\n private resultKeys = {};\n\n static get styles() {\n return css`\n :host {\n overflow-y: auto !important;\n }\n\n @media only screen and (max-height: 768px) {\n temba-options {\n max-height: 20vh;\n }\n }\n\n temba-options {\n display: block;\n width: 100%;\n flex-grow: 1;\n }\n `;\n }\n\n public firstUpdated(changedProperties: Map) {\n super.firstUpdated(changedProperties);\n }\n\n public updated(changedProperties: Map): void {\n super.updated(changedProperties);\n if (changedProperties.has('responses') || changedProperties.has('flow')) {\n if (this.flow) {\n this.endpoint = `/api/v2/runs.json?flow=${this.flow}${\n this.responses ? '&responded=1' : ''\n }`;\n }\n }\n\n if (changedProperties.has('resultPreview')) {\n this.createRenderOption();\n }\n\n if (changedProperties.has('results')) {\n if (this.results) {\n const select = this.shadowRoot.querySelector('temba-select') as Select;\n select.setOptions(this.results);\n this.resultKeys = this.results.reduce(\n (current, result) => ({ ...current, [result.key]: result }),\n {}\n );\n }\n }\n }\n\n public renderResultPreview(run: any) {\n if (this.resultPreview) {\n const runResult = run.values[this.resultPreview.key];\n if (runResult) {\n if (this.resultPreview.categories.length > 1) {\n if (runResult.category) {\n return runResult.category;\n }\n } else {\n return runResult.value;\n }\n }\n }\n return null;\n }\n\n public removeRun(id: number) {\n this.items = this.items.filter(run => run.id !== id);\n this.cursorIndex = Math.min(this.cursorIndex, this.items.length);\n this.requestUpdate('cursorIndex');\n }\n\n public getIcon(run: any): TemplateResult {\n let icon = null;\n if (run.exit_type == 'completed') {\n icon = html``;\n } else if (run.exit_type == 'interrupted') {\n icon = html``;\n } else if (run.exit_type == 'expired') {\n icon = html``;\n } else if (!run.exit_type) {\n if (run.responded) {\n icon = html``;\n } else {\n icon = html``;\n }\n }\n return icon;\n }\n\n public createRenderOption() {\n this.renderOption = (run: any): TemplateResult => {\n let statusStyle = '';\n\n if (!run.exited_on) {\n statusStyle = 'font-weight:400;';\n }\n\n if (!run.responded) {\n statusStyle += '';\n }\n\n return html`\n
    \n \n \n
    \n\n \n ${this.renderResultPreview(run)}\n \n\n
    \n \n
    \n ${this.getIcon(run)}\n \n `;\n };\n }\n\n public getRefreshEndpoint() {\n if (this.items.length > 0) {\n const modifiedOn = this.items[0].modified_on;\n return this.endpoint + '&after=' + modifiedOn;\n }\n return this.endpoint;\n }\n\n public toggleResponded() {\n this.responses = (\n this.shadowRoot.querySelector('#responded') as Checkbox\n ).checked;\n }\n\n public handleColumnChanged(event: any) {\n if (event.target.values.length > 0) {\n this.resultPreview = event.target.values[0];\n } else {\n this.resultPreview = null;\n }\n }\n\n public handleSelected(selected: any) {\n this.selectedRun = selected;\n }\n\n public getListStyle(): string {\n return '';\n }\n\n public renderHeader(): TemplateResult {\n return html`\n
    \n
    \n ${this.results\n ? html`\n \n `\n : null}\n
    \n
    \n \n
    \n
    \n \n Last Updated\n \n `;\n }\n\n public renderFooter(): TemplateResult {\n if (!this.selectedRun || !this.resultKeys) {\n return null;\n }\n\n const resultKeys = Object.keys(this.selectedRun.values);\n\n return html` \n
    \n \n
    \n \n \n ${this.selectedRun.exit_type\n ? html`\n
    \n ${this.getIcon(this.selectedRun)}\n
    \n ${capitalize(this.selectedRun.exit_type)} \n
    \n \n
    \n `\n : html`${this.getIcon(this.selectedRun)}\n
    \n
    Started 
    \n \n
    `}\n
    \n
    \n
    \n
    \n
    \n ${new Date(this.selectedRun.created_on).toLocaleString()}\n
    \n \n Started\n
    \n \n \n \n\n ${resultKeys.length > 0\n ? html`\n
    \n \n
    \n
    \n\n \n \n \n \n \n \n\n ${Object.keys(this.selectedRun.values).map((key: string) => {\n const result = this.selectedRun.values[key];\n const meta = this.resultKeys[key];\n\n // if our result is no longer represented in the flow, skip it\n if (meta) {\n return html`\n \n \n \n `;\n }\n return null;\n })}\n
    ResultCategoryValue
    ${result.name}\n ${meta.categories.length > 1 ? result.category : '--'}\n ${result.value}
    \n \n `\n : null}\n \n `;\n }\n\n constructor() {\n super();\n this.reverseRefresh = false;\n this.valueKey = 'uuid';\n this.hideShadow = true;\n this.createRenderOption();\n }\n}\n","import { html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { FlowDetails } from '../interfaces';\nimport { StoreElement } from '../store/StoreElement';\n\nexport class FlowStoreElement extends StoreElement {\n @property({ type: String })\n flow: string;\n\n @property({ type: Object, attribute: false })\n data: FlowDetails;\n\n @property({ type: String })\n endpoint = '/api/v2/flows.json?uuid=';\n\n prepareData(data: any) {\n if (data && data.length > 0) {\n data = data[0];\n }\n return data;\n }\n\n protected updated(\n changes: PropertyValueMap | Map\n ): void {\n super.updated(changes);\n if (changes.has('flow')) {\n if (this.flow) {\n this.url = `${this.endpoint}${this.flow}`;\n } else {\n this.url = null;\n }\n }\n }\n\n public render(): TemplateResult {\n if (!this.data) {\n return;\n }\n return html`
    `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { ContactStoreElement } from './ContactStoreElement';\n\nexport class ContactNameFetch extends ContactStoreElement {\n @property({ type: Number, attribute: 'icon-size' })\n size = 20;\n\n static get styles() {\n return css`\n :host {\n display: flex;\n }\n\n temba-urn {\n margin-right: 0.2em;\n margin-top: 2px;\n }\n `;\n }\n\n public render(): TemplateResult {\n if (this.data) {\n return html` 0 ? this.data.urns[0] : null}\n >\n `;\n }\n return super.render();\n }\n}\n","import { TemplateResult, html, css, PropertyValueMap } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { FormElement } from '../FormElement';\nimport { getClasses } from '../utils';\nimport { DateTime } from 'luxon';\n\nexport default class DatePicker extends FormElement {\n static get styles() {\n return css`\n :host {\n display: block;\n }\n\n input {\n width: inherit;\n }\n\n .container {\n border-radius: var(--curvature);\n border: 1px solid var(--color-widget-border);\n display: flex;\n cursor: pointer;\n box-shadow: var(--widget-box-shadow);\n flex-wrap: wrap;\n overflow: hidden;\n }\n\n .input-wrapper {\n padding: var(--temba-textinput-padding);\n flex-grow: 1;\n }\n\n .tz {\n margin-left: 0.5em;\n font-size: 0.8em;\n flex-direction: column;\n align-self: stretch;\n color: #888;\n display: flex;\n align-items: flex-start;\n flex-direction: column;\n padding: 0em 1em;\n font-weight: 400;\n cursor: pointer;\n margin: auto 0;\n }\n\n .tz .label {\n font-size: 0.8em;\n color: #aaa;\n white-space: nowrap;\n text-overflow: ellipsis;\n }\n\n .tz .zone {\n white-space: nowrap;\n text-overflow: ellipsis;\n }\n\n .tz-wrapper {\n background: #efefef;\n display: flex;\n flex-direction: row;\n align-items: center;\n padding: 0.4em 0em;\n }\n\n .container:focus-within {\n border-color: var(--color-focus);\n background: var(--color-widget-bg-focused);\n box-shadow: var(--widget-box-shadow-focused);\n }\n\n input {\n color: var(--color-widget-text);\n border: 0px;\n font-family: var(--font-family);\n font-weight: 300;\n outline: none;\n width: 100%;\n font-size: 13px;\n padding: 0px;\n margin: 0px;\n line-height: 1em;\n }\n\n input.unset {\n color: #ddd;\n }\n\n input.unset:focus {\n color: var(--color-widget-text);\n }\n\n input:focus {\n outline: none;\n }\n\n .disabled ::-webkit-calendar-picker-indicator {\n display: none;\n }\n\n .disabled .tz-wrapper {\n border-radius: var(--curvature);\n }\n\n ::-webkit-calendar-picker-indicator {\n background-image: url('data:image/svg+xml;utf8,');\n cursor: pointer;\n margin: 0;\n padding: 0;\n }\n\n ::-webkit-calendar-picker-indicator:hover {\n background-image: url('data:image/svg+xml;utf8,');\n cursor: pointer;\n margin: 0;\n padding: 0;\n }\n `;\n }\n\n @property({ type: String })\n timezone = '';\n\n @property({ type: String })\n timezoneFriendly = '';\n\n @property({ type: Object })\n datetime = null;\n\n @property({ type: Boolean })\n time = false;\n\n /** we just return the value since it should be a string */\n public serializeValue(value: any): string {\n return value;\n }\n\n public constructor() {\n super();\n }\n\n protected firstUpdated(\n changed: PropertyValueMap | Map\n ): void {\n if (changed.has('value')) {\n // default to the local browser zone\n if (this.time) {\n this.timezone =\n this.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;\n this.timezoneFriendly = this.timezone\n .replace('_', ' ')\n .replace('/', ', ');\n\n if (this.value) {\n // we fire a change event on blur\n let datetime = DateTime.fromSQL(this.value).setZone(this.timezone);\n // if we can't read it as a sql stamp, try iso\n if (datetime.invalid) {\n datetime = DateTime.fromISO(this.value).setZone(this.timezone);\n }\n this.datetime = datetime;\n this.value = this.datetime.toUTC().toISO();\n }\n } else {\n this.datetime = DateTime.fromSQL(this.value);\n this.value = this.datetime.toISODate();\n }\n }\n }\n\n public updated(changed: Map): void {\n super.updated(changed);\n if (changed.has('timezone') && this.time) {\n this.timezone =\n this.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;\n this.timezoneFriendly = this.timezone\n .replace('_', ' ')\n .replace('/', ', ');\n this.requestUpdate('value');\n }\n }\n\n public handleChange(event) {\n event.preventDefault();\n event.stopPropagation();\n if (this.time) {\n this.datetime = DateTime.fromISO(event.target.value, {\n zone: this.timezone,\n });\n this.value = this.datetime.toUTC().toISO();\n } else {\n this.value = event.target.value;\n }\n this.fireEvent('change');\n }\n\n public handleClicked() {\n this.shadowRoot.querySelector('input').focus();\n }\n\n public render(): TemplateResult {\n const classes = getClasses({ unset: !this.value });\n\n let dateWidgetValue = null;\n if (this.time && this.datetime && !this.datetime.invalid) {\n dateWidgetValue = this.datetime.toFormat(\"yyyy-LL-dd'T'HH:mm\");\n } else if (!this.time) {\n dateWidgetValue = this.value;\n }\n\n return html`\n \n
    \n \n
    \n \n
    \n ${this.time\n ? html`\n
    \n
    \n
    Time Zone
    \n
    ${this.timezoneFriendly}
    \n
    \n
    \n `\n : null}\n \n
    \n \n `;\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { ContactField, CustomEventType } from '../interfaces';\n\nimport { SortableList } from '../list/SortableList';\nimport { StoreElement } from '../store/StoreElement';\nimport { TextInput } from '../textinput/TextInput';\nimport { postJSON } from '../utils';\n\nconst TYPE_NAMES = {\n text: 'Text',\n numeric: 'Number',\n number: 'Number',\n datetime: 'Date & Time',\n state: 'State',\n ward: 'Ward',\n district: 'District',\n};\n\nconst matches = (field: ContactField, query: string): boolean => {\n if (!query) {\n return true;\n }\n const search = (\n field.label +\n field.key +\n TYPE_NAMES[field.value_type]\n ).toLowerCase();\n if (search.toLowerCase().indexOf(query) > -1) {\n return true;\n }\n return false;\n};\n\nexport class FieldManager extends StoreElement {\n static get styles() {\n return css`\n :host {\n display: flex;\n flex-grow: 1;\n flex-direction: column;\n min-height: 0px;\n }\n\n .featured,\n .other-fields {\n background: #fff;\n border-radius: var(--curvature);\n box-shadow: var(--shadow);\n margin-bottom: 1em;\n display: flex;\n flex-direction: column;\n }\n\n .featured {\n max-height: 40%;\n }\n\n .other-fields {\n flex-grow: 2;\n min-height: 0px;\n margin-bottom: 0px;\n }\n\n temba-textinput {\n margin-bottom: 1em;\n }\n\n .scroll-box {\n overflow-y: auto;\n flex-grow: 1;\n flex-direction: column;\n display: flex;\n }\n\n .header temba-icon {\n margin-right: 0.5em;\n }\n\n .label {\n flex-grow: 1;\n }\n\n .header {\n padding: 0.5em 1em;\n display: flex;\n align-items: flex-start;\n border-bottom: 1px solid var(--color-widget-border);\n }\n\n .featured-field {\n user-select: none;\n }\n\n temba-sortable-list {\n padding: 0.5em 0em;\n width: 100%;\n overflow-y: auto;\n }\n\n .scroll-box {\n padding: 0.5em 0em;\n }\n\n temba-icon[name='usages']:hover {\n --icon-color: var(--color-link-primary);\n }\n\n .field:hover temba-icon[name='delete_small'] {\n opacity: 1 !important;\n cursor: pointer !important;\n pointer-events: all !important;\n }\n\n temba-icon[name='delete_small']:hover {\n --icon-color: var(--color-link-primary);\n }\n\n .field {\n border: 1px solid transparent;\n margin: 0 0.5em;\n border-radius: var(--curvature);\n }\n\n .featured temba-sortable-list .field:hover {\n cursor: move;\n border-color: #e6e6e6;\n background: #fcfcfc;\n }\n `;\n }\n\n @property({ type: String, attribute: 'priority-endpoint' })\n priorityEndpoint: string;\n\n @property({ type: Object, attribute: false })\n featuredFields: ContactField[];\n\n @property({ type: Object, attribute: false })\n otherFieldKeys: string[] = [];\n\n @property({ type: String })\n draggingId: string;\n\n @property({ type: String })\n query = '';\n\n protected firstUpdated(\n _changedProperties: PropertyValueMap | Map\n ): void {\n super.firstUpdated(_changedProperties);\n this.url = this.store.fieldsEndpoint;\n }\n\n private filterFields() {\n const filteredKeys = this.store.getFieldKeys().filter(key => {\n const field = this.store.getContactField(key);\n if (field.featured) {\n return false;\n }\n return matches(field, this.query);\n });\n\n // sort by the label instead of the key\n filteredKeys.sort((a, b) => {\n return this.store\n .getContactField(a)\n .label.localeCompare(this.store.getContactField(b).label);\n });\n\n const featured: ContactField[] = [];\n this.store.getFeaturedFields().forEach(field => {\n if (matches(field, this.query)) {\n featured.push(field);\n }\n });\n\n this.otherFieldKeys = filteredKeys;\n this.featuredFields = featured;\n }\n\n protected updated(\n properties: PropertyValueMap | Map\n ): void {\n super.update(properties);\n if (properties.has('data')) {\n this.filterFields();\n } else if (properties.has('query')) {\n this.filterFields();\n }\n }\n\n private handleSaveOrder(event) {\n const list = event.currentTarget as SortableList;\n postJSON(\n this.priorityEndpoint,\n list\n .getIds()\n .reverse()\n .reduce((map, key, idx) => {\n map[key] = idx;\n return map;\n }, {})\n ).then(() => {\n this.store.refreshFields();\n });\n }\n\n private handleOrderChanged(event) {\n const swapsies = event.detail;\n const temp = this.featuredFields[swapsies.fromIdx];\n this.featuredFields[swapsies.fromIdx] = this.featuredFields[swapsies.toIdx];\n this.featuredFields[swapsies.toIdx] = temp;\n this.requestUpdate('featuredFields');\n }\n\n private handleDragStart(event) {\n this.draggingId = event.detail.id;\n }\n\n private handleDragStop() {\n this.draggingId = null;\n }\n\n private handleFieldAction(event: MouseEvent) {\n const ele = event.target as HTMLDivElement;\n const key = ele.dataset.key;\n const action = ele.dataset.action;\n this.fireCustomEvent(CustomEventType.Selection, { key, action });\n }\n\n private handleSearch(event) {\n this.query = (event.target.value || '').trim();\n }\n\n private hasUsages(field: ContactField): boolean {\n return (\n field.usages.campaign_events + field.usages.flows + field.usages.groups >\n 0\n );\n }\n\n private renderField(field: ContactField) {\n return html`\n \n \n \n ${field.label}\n \n ${this.hasUsages(field)\n ? html`\n \n `\n : null}\n
    \n \n \n @fields.${field.key}\n \n
    ${TYPE_NAMES[field.value_type]}
    \n \n \n `;\n }\n\n public render(): TemplateResult {\n if (!this.featuredFields) {\n return null;\n }\n\n return html`\n \n\n ${this.featuredFields.length > 0\n ? html`\n
    \n
    \n \n
    Featured
    \n
    \n ${this.query\n ? html`\n
    \n ${this.featuredFields.map(field =>\n this.renderField(field)\n )}\n
    \n `\n : html`\n \n ${this.featuredFields.map(field =>\n this.renderField(field)\n )}\n \n `}\n
    \n `\n : null}\n\n
    \n
    \n \n
    Everything Else
    \n
    \n
    \n ${this.otherFieldKeys.map(field =>\n this.renderField(this.store.getContactField(field))\n )}\n
    \n
    \n `;\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { RapidElement } from '../RapidElement';\n\n/**\n * A simple list that can be sorted by dragging\n */\n\n// how far we have to drag before it starts\nconst DRAG_THRESHOLD = 5;\nexport class SortableList extends RapidElement {\n static get styles() {\n return css`\n :host {\n margin: auto;\n }\n\n .container {\n user-select: none;\n }\n\n .dragging {\n background: var(--color-selection);\n }\n\n .sortable {\n transition: all 300ms ease-in-out;\n display: flex;\n padding: 0.4em 0;\n }\n\n .sortable:hover temba-icon {\n opacity: 1;\n cursor: move;\n }\n\n .ghost {\n position: absolute;\n opacity: 0.5;\n transition: none;\n }\n\n .slot {\n flex-grow: 1;\n }\n\n slot > * {\n user-select: none;\n }\n\n temba-icon {\n opacity: 0.1;\n padding: 0.2em 0.5em;\n transition: all 300ms ease-in-out;\n }\n `;\n }\n\n @property({ type: String })\n draggingId: string;\n\n ghostElement: HTMLDivElement = null;\n downEle: HTMLDivElement = null;\n xOffset = 0;\n yOffset = 0;\n yDown = 0;\n\n draggingIdx = -1;\n draggingEle = null;\n\n public constructor() {\n super();\n this.handleMouseMove = this.handleMouseMove.bind(this);\n this.handleMouseUp = this.handleMouseUp.bind(this);\n this.handleMouseDown = this.handleMouseDown.bind(this);\n }\n\n protected firstUpdated(\n _changedProperties: PropertyValueMap | Map\n ): void {\n super.firstUpdated(_changedProperties);\n }\n\n public getIds() {\n return this.shadowRoot\n .querySelector('slot')\n .assignedElements()\n .map(ele => ele.id);\n }\n\n private getRowIndex(id: string): number {\n return this.shadowRoot\n .querySelector('slot')\n .assignedElements()\n .findIndex(ele => ele.id === id);\n }\n\n private getOverlappingElement(mouseY: number): HTMLDivElement {\n const ghostRect = this.ghostElement.getBoundingClientRect();\n\n const ele = this.shadowRoot\n .querySelector('slot')\n .assignedElements()\n .find(otherEle => {\n const rect = otherEle.getBoundingClientRect();\n\n // don't return ourselves\n if (otherEle.id === this.ghostElement.id) {\n return false;\n }\n\n if (mouseY > this.yDown) {\n // moving down\n return ghostRect.top < rect.bottom && ghostRect.bottom > rect.bottom;\n } else {\n // moving up\n return rect.top < ghostRect.bottom && rect.bottom > ghostRect.bottom;\n }\n });\n return ele as HTMLDivElement;\n }\n\n private handleMouseDown(event: MouseEvent) {\n let ele = event.target as HTMLDivElement;\n ele = ele.closest('.sortable');\n if (ele) {\n this.downEle = ele;\n this.draggingId = ele.id;\n this.draggingIdx = this.getRowIndex(ele.id);\n this.draggingEle = ele;\n\n this.xOffset = event.clientX - ele.offsetLeft;\n this.yOffset = event.clientY - ele.offsetTop;\n this.yDown = event.clientY;\n\n document.addEventListener('mousemove', this.handleMouseMove);\n document.addEventListener('mouseup', this.handleMouseUp);\n }\n }\n\n private handleMouseMove(event: MouseEvent) {\n const scrollTop = this.shadowRoot\n .querySelector('slot')\n .assignedElements()[0].parentElement.scrollTop;\n\n if (\n !this.ghostElement &&\n this.downEle &&\n Math.abs(event.clientY - this.yDown) > DRAG_THRESHOLD\n ) {\n this.fireCustomEvent(CustomEventType.DragStart, {\n id: this.downEle.id,\n });\n\n this.ghostElement = this.downEle.cloneNode(true) as HTMLDivElement;\n this.ghostElement.classList.add('ghost');\n\n const computedStyle = getComputedStyle(this.downEle);\n\n this.ghostElement.style.width =\n this.downEle.clientWidth -\n parseFloat(computedStyle.paddingLeft) -\n parseFloat(computedStyle.paddingRight) +\n 'px';\n const container = this.shadowRoot.querySelector('.container');\n\n container.appendChild(this.ghostElement);\n\n this.downEle = null;\n }\n\n if (this.ghostElement) {\n this.ghostElement.style.left = event.clientX - this.xOffset + 'px';\n this.ghostElement.style.top =\n event.clientY - this.yOffset - scrollTop + 'px';\n\n const other = this.getOverlappingElement(event.clientY);\n if (other) {\n const otherIdx = this.getRowIndex(other.id);\n const dragId = this.ghostElement.id;\n const otherId = other.id;\n\n this.fireCustomEvent(CustomEventType.OrderChanged, {\n from: dragId,\n to: otherId,\n fromIdx: this.draggingIdx,\n toIdx: otherIdx,\n });\n\n // TODO: Dont do swapping, just send the full order?\n this.draggingIdx = otherIdx;\n this.draggingId = otherId;\n }\n }\n }\n\n private handleMouseUp() {\n if (this.draggingId) {\n this.fireCustomEvent(CustomEventType.DragStop, {\n id: this.draggingId,\n });\n\n this.draggingId = null;\n this.downEle = null;\n\n if (this.ghostElement) {\n this.ghostElement.remove();\n this.ghostElement = null;\n }\n }\n document.removeEventListener('mousemove', this.handleMouseMove);\n document.removeEventListener('mouseup', this.handleMouseUp);\n this.dispatchEvent(new Event('change'));\n }\n\n public render(): TemplateResult {\n return html`\n
    \n \n
    \n `;\n }\n}\n","import { TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\n\nimport { RapidElement } from '../RapidElement';\nimport { getUrl, WebResponse } from '../utils';\n\nconst HEADERS = {\n 'Temba-Content-Menu': '1',\n 'Temba-Spa': '1',\n};\nexport interface ContentMenuItem {\n type: string;\n as_button: boolean;\n label: string;\n url: string;\n disabled: boolean;\n modal_id: string;\n on_submit: string;\n primary: boolean;\n title: string;\n on_click: null;\n link_class: string;\n}\n\nexport enum ContentMenuItemType {\n LINK = 'link',\n JS = 'js',\n URL_POST = 'url_post',\n MODAX = 'modax',\n DIVIDER = 'divider',\n}\n\nexport class ContentMenu extends RapidElement {\n static get styles() {\n return css`\n .container {\n --button-y: 0.4em;\n --button-x: 1em;\n display: flex;\n }\n\n .button_item,\n .primary_button_item {\n margin-left: 1rem;\n }\n\n .toggle {\n --icon-color: rgb(102, 102, 102);\n padding: 0.5rem;\n margin-left: 0.5rem;\n }\n\n .toggle:hover {\n background: rgba(0, 0, 0, 0.05);\n border-radius: var(--curvature);\n --icon-color: rgb(136, 136, 136);\n }\n\n .dropdown {\n padding: 1rem 1.5rem;\n color: rgb(45, 45, 45);\n z-index: 50;\n min-width: 200px;\n }\n\n .divider {\n border-bottom: 1px solid rgb(237, 237, 237);\n margin: 1rem -1.5em;\n }\n\n .item {\n white-space: nowrap;\n margin: 0.2em 0em;\n font-size: 1.1rem;\n cursor: pointer;\n font-weight: 400;\n }\n\n .item:hover {\n color: var(--color-link-primary);\n }\n `;\n }\n\n @property({ type: String })\n endpoint: string;\n\n @property({ type: Number })\n legacy: number;\n\n @property({ type: Array, attribute: false })\n buttons: ContentMenuItem[] = [];\n\n @property({ type: Array, attribute: false })\n items: ContentMenuItem[] = [];\n\n private fetchContentMenu() {\n const url = this.endpoint;\n if (url) {\n const legacy = this.legacy;\n const headers = HEADERS;\n if (legacy) {\n delete headers['Temba-Spa'];\n }\n\n //ok, fetch the content menu\n getUrl(url, null, headers)\n .then((response: WebResponse) => {\n const json = response.json;\n const contentMenu = json.items as ContentMenuItem[];\n\n //populate (or initialize) the buttons and items\n if (contentMenu) {\n this.buttons = contentMenu.filter(item => item.as_button);\n this.items = contentMenu.filter(item => !item.as_button);\n } else {\n this.buttons = [];\n this.items = [];\n }\n\n //fire custom loaded event type when we're finished\n this.fireCustomEvent(CustomEventType.Loaded, {\n buttons: this.buttons,\n items: this.items,\n });\n })\n .catch((error: any) => {\n console.error(error);\n });\n }\n }\n\n public refresh() {\n this.fetchContentMenu();\n }\n\n protected updated(changes: Map) {\n super.updated(changes);\n\n if (changes.has('endpoint') || changes.has('legacy')) {\n this.fetchContentMenu();\n }\n }\n\n private handleItemClicked(item: ContentMenuItem, event: MouseEvent) {\n this.fireCustomEvent(CustomEventType.Selection, { item, event });\n }\n\n public render(): TemplateResult {\n return html`\n
    \n ${this.buttons.map(button => {\n return html` this.handleItemClicked(button, event)}\n >\n ${button.label}\n `;\n })}\n ${this.items && this.items.length > 0\n ? html`\n
    \n \n
    \n
    \n ${this.items.map(item => {\n if (item.type === ContentMenuItemType.DIVIDER) {\n return html`
    `;\n } else {\n return html` this.handleItemClicked(item, event)}\n >\n ${item.label}\n
    `;\n }\n })}\n
    \n `\n : null}\n \n `;\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\nimport { Store } from '../store/Store';\nimport { DateTime } from 'luxon';\n\nexport const Display = {\n date: DateTime.DATE_SHORT,\n datetime: DateTime.DATETIME_SHORT,\n time: DateTime.TIME_SIMPLE,\n timedate: 'timedate',\n duration: 'duration',\n relative: 'relative',\n day: 'LLL d',\n};\n\nexport class TembaDate extends RapidElement {\n static get styles() {\n return css`\n .date {\n display: inline;\n }\n `;\n }\n\n @property({ type: String })\n value: string;\n\n @property({ type: String })\n display = 'date';\n\n @property({ type: Object, attribute: false })\n datetime: DateTime;\n\n store: Store;\n\n protected firstUpdated(\n changedProperties: PropertyValueMap | Map\n ): void {\n super.firstUpdated(changedProperties);\n this.store = document.querySelector('temba-store');\n }\n\n protected updated(\n changedProperties: PropertyValueMap | Map\n ): void {\n super.updated(changedProperties);\n if (changedProperties.has('value')) {\n this.datetime = DateTime.fromISO(this.value);\n }\n }\n\n public connectedCallback(): void {\n super.connectedCallback();\n }\n\n public render(): TemplateResult {\n if (this.datetime && this.store) {\n this.datetime.setLocale(this.store.getLocale());\n\n let formatted = '';\n if (this.display === Display.timedate) {\n const hours = Math.abs(\n this.datetime.diffNow().milliseconds / 1000 / 60 / 60\n );\n if (hours < 24) {\n formatted = this.datetime.toLocaleString(Display.time);\n } else if (hours < 24 * 365) {\n formatted = this.datetime.toFormat(Display.day);\n } else {\n formatted = this.datetime.toLocaleString(Display.date);\n }\n } else if (this.display === Display.relative) {\n const minutes = Math.abs(\n this.datetime.diffNow().milliseconds / 1000 / 60\n );\n if (minutes < 1) {\n return html`just now`;\n }\n\n formatted = this.store.getShortDuration(this.datetime);\n } else if (this.display === Display.duration) {\n const minutes = Math.abs(\n this.datetime.diffNow().milliseconds / 1000 / 60\n );\n if (minutes < 1) {\n return html`just now`;\n }\n formatted = this.store.getShortDuration(this.datetime);\n } else if (this.display === Display.day) {\n formatted = this.datetime.toLocaleString(Display.day);\n } else {\n formatted = this.datetime.toLocaleString(Display[this.display]);\n }\n\n return html`${formatted}`;\n }\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property, customElement } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\nimport { getUrl } from '../utils';\nimport { unsafeHTML } from 'lit-html/directives/unsafe-html.js';\n\n@customElement('temba-remote')\nexport default class Remote extends RapidElement {\n @property({ type: String })\n endpoint: string;\n\n @property({ attribute: false })\n body: any = html``;\n\n static get styles() {\n return css``;\n }\n\n public updated(changes: Map) {\n super.updated(changes);\n\n if (changes.has('endpoint')) {\n getUrl(this.endpoint).then(response => {\n this.body = unsafeHTML(response.body);\n });\n }\n }\n\n public render(): TemplateResult {\n return html`${this.body}`;\n }\n}\n","/* eslint-disable @typescript-eslint/no-this-alias */\nimport { LitElement, TemplateResult, html, css, PropertyValueMap } from 'lit';\nimport { property } from 'lit/decorators.js';\n\ninterface Message {\n text: string;\n type: string;\n identifier?: string;\n origin?: string;\n timestamp: number;\n}\n\nenum ChatStatus {\n DISCONNECTED = 'disconnected',\n CONNECTING = 'connecting',\n CONNECTED = 'connected',\n}\n\n// how long of a window to show time between batches\nconst BATCH_TIME_WINDOW = 30 * 60 * 1000;\n\nconst TIME_FORMAT = { hour: 'numeric', minute: '2-digit' } as any;\nconst DAY_FORMAT = {\n weekday: undefined,\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n} as any;\nconst VERBOSE_FORMAT = {\n weekday: undefined,\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n hour: 'numeric',\n minute: '2-digit',\n} as any;\n\nexport class WebChat extends LitElement {\n static get styles() {\n return css`\n :host {\n display: flex-inline;\n align-items: center;\n align-self: center;\n --curvature: 0.6em;\n --color-primary: hsla(208, 70%, 55%, 1);\n font-family: 'Roboto', 'Helvetica Neue', sans-serif;\n }\n\n .block {\n margin-bottom: 1em;\n }\n\n .time {\n text-align: center;\n font-size: 0.8em;\n color: #999;\n margin-top: 2em;\n border-top: 1px solid #f8f8f8;\n padding: 1em;\n margin-left: 4em;\n margin-right: 4em;\n }\n\n .first .time {\n margin-top: 0;\n border-top: none;\n padding-top: 0;\n }\n\n .row {\n display: flex;\n flex-direction: row;\n align-items: flex-start;\n }\n\n .input-panel {\n padding: 1em;\n background: #fff;\n }\n\n .avatar {\n margin-top: 0.6em;\n margin-right: 0.6em;\n flex-shrink: 0;\n width: 2em;\n height: 2em;\n overflow: hidden;\n border-radius: 100%;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 3px 7px 0px,\n rgba(0, 0, 0, 0.2) 0px 1px 2px 0px,\n inset 0 0 0 0.15em rgba(0, 0, 0, 0.1);\n }\n\n .toggle {\n flex-shrink: 0;\n width: 4em;\n height: 4em;\n overflow: hidden;\n border-radius: 100%;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 1em 0.7em,\n rgba(0, 0, 0, 0.2) 0px 1px 2px 0px,\n inset 0 0 0 0.25em rgba(0, 0, 0, 0.1);\n cursor: pointer;\n transition: box-shadow 0.2s ease-out;\n position: absolute;\n bottom: 1em;\n right: 1em;\n }\n\n .toggle:hover {\n box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 1em 0.7em,\n rgba(0, 0, 0, 0.4) 0px 1px 2px 0px,\n inset 0 0 0 0.25em rgba(0, 0, 0, 0.2);\n }\n\n .incoming .row {\n flex-direction: row-reverse;\n margin-left: 1em;\n }\n\n .bubble {\n padding: 1em;\n padding-bottom: 0.5em;\n background: #fafafa;\n border-radius: var(--curvature);\n }\n\n .bubble .name {\n font-size: 0.9em;\n font-weight: 400;\n margin-bottom: 0.5em;\n }\n\n .outgoing .bubble {\n border-top-left-radius: 0;\n }\n\n .incoming .bubble {\n background: var(--color-primary);\n color: white;\n border-top-right-radius: 0;\n }\n\n .message {\n margin-bottom: 0.5em;\n }\n\n .chat {\n max-width: 50vw;\n width: 28rem;\n border-radius: var(--curvature);\n overflow: hidden;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 3px 7px 0px,\n rgba(0, 0, 0, 0.2) 0px 1px 2px 0px, rgba(0, 0, 0, 0.1) 5em 5em 5em 5em;\n position: absolute;\n bottom: 2em;\n right: 1em;\n transition: all 0.2s ease-out;\n transform: scale(0.9);\n pointer-events: none;\n opacity: 0;\n }\n\n .chat.open {\n bottom: 6em;\n opacity: 1;\n transform: scale(1);\n pointer-events: initial;\n }\n\n .messages {\n background: #fff;\n }\n\n .scroll {\n height: 40rem;\n max-height: 60vh;\n overflow: auto;\n -webkit-overflow-scrolling: touch;\n overflow-scrolling: touch;\n padding: 1em 1em 0 1em;\n }\n\n .messages:before {\n content: '';\n background: /* Shadow TOP */ radial-gradient(\n farthest-side at 50% 0,\n rgba(0, 0, 0, 0.2),\n rgba(0, 0, 0, 0)\n )\n center top;\n height: 10px;\n display: block;\n position: absolute;\n max-width: 50vw;\n width: 28rem;\n transition: opacity 0.1s ease-out;\n }\n\n .messages:after {\n content: '';\n background: /* Shadow BOTTOM */ radial-gradient(\n farthest-side at 50% 100%,\n rgba(0, 0, 0, 0.2),\n rgba(0, 0, 0, 0)\n )\n center bottom;\n height: 10px;\n display: block;\n position: absolute;\n margin-top: -10px;\n max-width: 50vw;\n width: 28rem;\n margin-right: 5em;\n transition: opacity 0.1s ease-out;\n }\n\n .scroll-at-top .messages:before {\n opacity: 0;\n }\n\n .scroll-at-bottom .messages:after {\n opacity: 0;\n }\n\n .input {\n border: none;\n flex-grow: 1;\n }\n\n .input:focus {\n outline: none;\n }\n\n input::placeholder {\n opacity: 0.3;\n }\n\n .input.inactive {\n // pointer-events: none;\n // opacity: 0.3;\n }\n\n .active {\n }\n\n .send-icon {\n color: #eee;\n pointer-events: none;\n transform: rotate(-45deg);\n transition: transform 0.2s ease-out;\n }\n\n .pending .send-icon {\n color: var(--color-primary);\n pointer-events: initial;\n transform: rotate(0deg);\n }\n\n .notice {\n padding: 1em;\n background: #f8f8f8;\n color: #666;\n text-align: center;\n cursor: pointer;\n }\n\n .connecting .notice {\n display: flex;\n justify-content: center;\n }\n\n .connecting .notice temba-icon {\n margin-left: 0.5em;\n }\n\n .reconnect {\n color: var(--color-primary);\n text-decoration: underline;\n font-size: 0.9em;\n }\n\n .input:disabled {\n background: transparent !important;\n }\n `;\n }\n\n @property({ type: String })\n channel: string;\n\n @property({ type: String })\n urn: string;\n\n @property({ type: Array })\n messages: Message[][] = [];\n\n // is our socket connection established\n @property({ type: String })\n status: ChatStatus = ChatStatus.DISCONNECTED;\n\n // is the chat widget open\n @property({ type: Boolean })\n open = false;\n\n @property({ type: Boolean })\n hasPendingText = false;\n\n @property({ type: Boolean, attribute: false })\n hideTopScroll = true;\n\n @property({ type: Boolean, attribute: false })\n hideBottomScroll = true;\n\n @property({ type: String })\n host: string;\n\n private sock: WebSocket;\n\n public constructor() {\n super();\n }\n\n private handleReconnect() {\n this.openSocket();\n }\n\n private openSocket(): void {\n if (this.status !== ChatStatus.DISCONNECTED) {\n return;\n }\n\n this.status = ChatStatus.CONNECTING;\n const webChat = this;\n let url = `ws://localhost:8070/start/${this.channel}/`;\n if (this.urn) {\n url = `${url}?chat_id=${this.urn}`;\n }\n this.sock = new WebSocket(url);\n this.sock.onclose = function (event) {\n webChat.status = ChatStatus.DISCONNECTED;\n };\n this.sock.onmessage = function (event) {\n webChat.status = ChatStatus.CONNECTED;\n const msg = JSON.parse(event.data) as Message;\n if (msg.type === 'chat_started') {\n if (webChat.urn !== msg.identifier) {\n webChat.messages = [];\n }\n webChat.urn = msg.identifier;\n webChat.requestUpdate('messages');\n } else if (msg.type === 'chat_resumed') {\n webChat.urn = msg.identifier;\n } else if (msg.type === 'msg_out') {\n msg['timestamp'] = new Date().getTime();\n webChat.addMessage(msg);\n webChat.requestUpdate('messages');\n }\n };\n }\n\n private restoreFromLocal(): void {\n const data = JSON.parse(localStorage.getItem('temba-chat') || '{}');\n const urn = 'urn' in data ? data['urn'] : null;\n if (urn && !this.urn) {\n this.urn = urn;\n const messages = 'messages' in data ? data['messages'] : [];\n this.messages.push(...messages);\n }\n }\n\n private writeToLocal(): void {\n console.log('Writing to localStorage..');\n if (this.urn) {\n const data = { urn: this.urn, messages: this.messages, version: 1 };\n localStorage.setItem('temba-chat', JSON.stringify(data));\n }\n }\n\n public firstUpdated(\n changed: PropertyValueMap | Map\n ): void {\n super.firstUpdated(changed);\n }\n\n private focusInput() {\n const input = this.shadowRoot.querySelector('.input') as any;\n if (input) {\n input.focus();\n }\n }\n\n public updated(\n changed: PropertyValueMap | Map\n ): void {\n super.updated(changed);\n\n if (this.open && changed.has('open') && changed.get('open') !== undefined) {\n const scroll = this.shadowRoot.querySelector('.scroll');\n const hasScroll = scroll.scrollHeight > scroll.clientHeight;\n this.hideBottomScroll = true;\n this.hideTopScroll = !hasScroll;\n this.scrollToBottom();\n\n if (this.status === ChatStatus.DISCONNECTED) {\n this.openSocket();\n }\n }\n\n if (changed.has('status')) {\n if (this.status === ChatStatus.CONNECTED) {\n this.focusInput();\n }\n }\n\n if (changed.has('channel')) {\n this.restoreFromLocal();\n }\n\n if (changed.has('messages')) {\n console.log('messages changed', this.messages);\n this.writeToLocal();\n console.log(this.messages);\n this.scrollToBottom();\n }\n }\n\n private addMessage(msg: Message) {\n let lastGroup =\n this.messages.length > 0 ? this.messages[this.messages.length - 1] : [];\n const isSame = lastGroup.length === 0 || lastGroup[0].origin === msg.origin;\n if (!isSame) {\n lastGroup = [];\n }\n if (lastGroup.length === 0) {\n this.messages.push(lastGroup);\n }\n lastGroup.push(msg);\n }\n\n public openChat(): void {\n this.open = true;\n }\n\n public handleKeyUp(event: any) {\n if (this.hasPendingText && event.key === 'Enter') {\n this.sendPendingMessage();\n }\n\n this.hasPendingText = event.target.value.length > 0;\n }\n\n private sendPendingMessage() {\n if (this.status === ChatStatus.CONNECTED) {\n const input = this.shadowRoot.querySelector('.input') as any;\n const text = input.value;\n input.value = '';\n\n const msg = {\n type: 'msg_in',\n text: text,\n timestamp: new Date().getTime(),\n };\n\n this.addMessage(msg);\n this.sock.send(JSON.stringify(msg));\n this.requestUpdate('messages');\n this.hasPendingText = input.value.length > 0;\n }\n }\n\n private scrollToBottom() {\n const scroll = this.shadowRoot.querySelector('.scroll');\n if (scroll) {\n scroll.scrollTop = scroll.scrollHeight;\n this.hideBottomScroll = true;\n }\n }\n\n private renderMessageGroup(\n messages: Message[],\n idx: number,\n groups: Message[][]\n ): TemplateResult {\n let lastBatchTime = null;\n if (idx > 0) {\n const lastGroup = groups[idx - 1];\n if (lastGroup && lastGroup.length > 0) {\n lastBatchTime = lastGroup[lastGroup.length - 1].timestamp;\n }\n }\n\n const newBatchTime = messages[0].timestamp;\n const showTime = newBatchTime - lastBatchTime > BATCH_TIME_WINDOW;\n\n let timeDisplay = null;\n if (showTime) {\n let lastTime = null;\n const newTime = new Date(newBatchTime);\n if (lastBatchTime) {\n lastTime = new Date(lastBatchTime);\n }\n const showDay = !lastTime || newTime.getDate() !== lastTime.getDate();\n if (showDay) {\n timeDisplay = html`
    \n ${newTime.toLocaleDateString(undefined, DAY_FORMAT)}\n
    `;\n } else {\n timeDisplay = html`
    \n ${newTime.toLocaleTimeString(undefined, TIME_FORMAT)}\n
    `;\n }\n }\n\n const blockTime = new Date(messages[messages.length - 1].timestamp);\n const incoming = !messages[0].origin;\n\n return html` \n ${timeDisplay}\n
    \n ${!incoming\n ? html`\n
    \n `\n : null}\n\n
    \n ${!incoming ? html`
    Henry McHelper
    ` : null}\n ${messages.map(msg => html`
    ${msg.text}
    `)}\n
    \n \n `;\n }\n\n private handleScroll(event: any) {\n this.hideBottomScroll =\n Math.round(event.target.scrollTop + event.target.clientHeight) >=\n event.target.scrollHeight;\n this.hideTopScroll = event.target.scrollTop === 0;\n }\n\n private handleClickInputPanel(event: any) {\n const input = this.shadowRoot.querySelector('.input') as any;\n input.focus();\n }\n\n private toggleChat() {\n this.open = !this.open;\n }\n\n public render(): TemplateResult {\n return html`\n \n
    \n
    \n ${this.messages\n ? this.messages.map(\n (msgGroup, idx, groups) =>\n html`${this.renderMessageGroup(msgGroup, idx, groups)}`\n )\n : null}\n
    \n
    \n\n ${this.status === ChatStatus.DISCONNECTED\n ? html`
    \n
    This chat is not currently connected.
    \n
    \n Click here to reconnect\n
    \n
    \n
    `\n : null}\n ${this.status === ChatStatus.CONNECTING\n ? html`
    \n
    Connecting
    \n \n
    `\n : null}\n ${this.status === ChatStatus.CONNECTED\n ? html` \n \n \n `\n : null}\n \n\n
    \n
    \n \n `;\n }\n}\n","import { TemplateResult, html, css } from 'lit';\nimport { FormElement } from '../FormElement';\nimport { property } from 'lit/decorators.js';\nimport { Icon } from '../vectoricon';\nimport { Attachment, CustomEventType, Language } from '../interfaces';\nimport {\n formatFileSize,\n getClasses,\n postFormData,\n truncate,\n DEFAULT_MEDIA_ENDPOINT,\n WebResponse,\n isImageAttachment,\n} from '../utils';\nimport { Completion } from '../completion/Completion';\nimport { Select } from '../select/Select';\nimport { TabPane } from '../tabpane/TabPane';\nimport { EventHandler } from '../RapidElement';\n\nexport class Compose extends FormElement {\n static get styles() {\n return css`\n .container {\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n position: relative;\n\n border-radius: var(--curvature-widget);\n background: var(--color-widget-bg);\n border: var(--compose-border, 1px solid var(--color-widget-border));\n transition: all ease-in-out var(--transition-speed);\n box-shadow: var(--compose-shadow, var(--widget-box-shadow));\n caret-color: var(--input-caret);\n }\n\n .drop-mask {\n opacity: 0;\n pointer-events: none;\n position: absolute;\n height: 100%;\n width: 100%;\n bottom: 0;\n right: 0;\n background: rgba(210, 243, 184, 0.8);\n border-radius: var(--curvature-widget);\n transition: opacity ease-in-out var(--transition-speed);\n display: flex;\n align-items: center;\n text-align: center;\n }\n\n .highlight .drop-mask {\n opacity: 1;\n }\n\n .drop-mask > div {\n margin: auto;\n border-radius: var(--curvature-widget);\n font-weight: 400;\n color: rgba(0, 0, 0, 0.5);\n }\n\n .items {\n }\n\n .chatbox {\n --color-widget-border: none;\n --curvature-widget: var(\n --compose-curvature,\n var(--curvature) var(--curvature) 0px 0px\n );\n --textarea-min-height: var(--textarea-min-height, 4em);\n --widget-box-shadow: none;\n padding: var(--compose-padding, 0px);\n }\n\n .attachments {\n }\n .attachments-list {\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n padding: 0.2em;\n }\n .attachment-item {\n padding: 0.4em;\n }\n .attachment-item.error {\n background: #fff;\n color: rgba(250, 0, 0, 0.75);\n padding: 0.2em;\n margin: 0.3em 0.5em;\n border-radius: var(--curvature);\n display: block;\n }\n\n .remove-item {\n position: absolute;\n --icon-color: #ccc;\n background: #fff;\n border-radius: 99%;\n transform: scale(0);\n transition: transform 200ms linear;\n }\n\n .attachment-item:hover .remove-item {\n transform: scale(1);\n }\n\n .remove-item:hover {\n --icon-color: #333;\n cursor: pointer;\n }\n\n .remove-item.error:hover {\n background: rgba(250, 0, 0, 0.1);\n }\n\n .remove-item.error {\n background: rgba(250, 0, 0, 0.05);\n color: rgba(250, 0, 0, 0.75);\n }\n .attachment-name {\n align-self: center;\n font-size: 12px;\n padding: 2px 8px;\n }\n\n .actions {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 0em;\n background: #f9f9f9;\n border-bottom-left-radius: var(--curvature);\n border-bottom-right-radius: var(--curvature);\n border-top: solid 1px var(--color-widget-border);\n }\n\n #upload-input {\n display: none;\n }\n .upload-label {\n display: flex;\n align-items: center;\n }\n .upload-icon {\n color: rgb(102, 102, 102);\n }\n .actions-right {\n display: flex;\n align-items: center;\n }\n temba-charcount {\n margin-right: 5px;\n overflow: hidden;\n --temba-charcount-counts-margin-top: 0px;\n --temba-charcount-summary-margin-top: 0px;\n --temba-charcount-summary-position: fixed;\n --temba-charcount-summary-right: 105px;\n --temba-charcount-summary-bottom: 105px;\n }\n temba-button {\n --button-y: 1px;\n --button-x: 12px;\n }\n .send-error {\n color: rgba(250, 0, 0, 0.75);\n font-size: var(--help-text-size);\n }\n\n .language {\n margin-bottom: 0.6em;\n display: block;\n }\n\n .top-right {\n align-items: center;\n display: flex;\n }\n\n #send-button {\n margin: 0.3em;\n }\n\n temba-tabs {\n --focused-tab-color: #f4f4f4;\n }\n\n .quick-replies {\n margin: 0.8em;\n }\n\n .add-attachment {\n padding: 1em;\n background: #eee;\n border-radius: var(--curvature);\n color: #aaa;\n margin: 0.5em;\n }\n\n .add-attachment:hover {\n background: #e9e9e9;\n cursor: pointer;\n }\n\n temba-loading {\n margin: auto 1em;\n }\n\n .optins {\n padding: 1em;\n }\n `;\n }\n\n @property({ type: Number })\n index = 1;\n\n @property({ type: Number })\n maxAttachments = 3;\n\n @property({ type: Number })\n maxLength = 640;\n\n @property({ type: Boolean })\n completion: boolean;\n\n @property({ type: Boolean })\n chatbox: boolean;\n\n @property({ type: Boolean })\n attachments: boolean;\n\n @property({ type: Boolean })\n quickReplies: boolean;\n\n @property({ type: Boolean })\n optIns: boolean;\n\n @property({ type: Boolean })\n counter: boolean;\n\n @property({ type: Boolean })\n pendingDrop: boolean;\n\n @property({ type: Boolean })\n button: boolean;\n\n @property({ type: String })\n currentText = '';\n\n @property({ type: String })\n initialText = '';\n\n @property({ type: String })\n accept = ''; //e.g. \".xls,.xlsx\"\n\n @property({ type: String, attribute: false })\n endpoint = DEFAULT_MEDIA_ENDPOINT;\n\n @property({ type: Boolean, attribute: false })\n uploading: boolean;\n\n @property({ type: Array })\n languages: Language[] = [];\n\n @property({ type: Array })\n currentAttachments: Attachment[] = [];\n\n @property({ type: Array })\n currentQuickReplies: { name: string; value: string }[] = [];\n\n @property({ type: Array })\n currentOptin: { name: string; uuid: string }[] = [];\n\n @property({ type: String })\n optinEndpoint = '/api/v2/optins.json';\n\n @property({ type: Array, attribute: false })\n failedAttachments: Attachment[] = [];\n\n @property({ type: String })\n buttonName = 'Send';\n\n @property({ type: Boolean, attribute: false })\n buttonDisabled = true;\n\n @property({ type: String, attribute: false })\n buttonError = '';\n\n @property({ type: Boolean, attribute: 'widget_only' })\n widgetOnly: boolean;\n\n @property({ type: Array })\n errors: string[];\n\n @property({ type: Object })\n langValues: {\n [lang: string]: {\n text: string;\n attachments: Attachment[];\n quick_replies: string[];\n optin?: { name: string; uuid: string };\n };\n } = {};\n\n @property({ type: String })\n currentLanguage = 'und';\n\n public constructor() {\n super();\n }\n\n private isBaseLanguage(): boolean {\n return (\n this.currentLanguage == 'und' ||\n this.currentLanguage == this.languages[0].iso\n );\n }\n\n private handleTabChanged() {\n const tabs = this.shadowRoot.querySelector('temba-tabs') as TabPane;\n const tab = tabs.getCurrentTab();\n if (tab) {\n // check we are going for the first attachment\n if (tab.icon == 'attachment') {\n if (this.currentAttachments.length == 0) {\n this.handleUploadFileIconClicked();\n }\n }\n }\n }\n\n public getEventHandlers(): EventHandler[] {\n return [\n { event: CustomEventType.ContextChanged, method: this.handleTabChanged },\n ];\n }\n\n public firstUpdated(changes: Map): void {\n super.firstUpdated(changes);\n\n if (changes.has('languages') && this.languages.length > 0) {\n this.currentLanguage = this.languages[0].iso;\n }\n\n if (changes.has('value')) {\n this.langValues = this.getDeserializedValue() || {};\n }\n this.setFocusOnChatbox();\n }\n\n public updated(changes: Map): void {\n super.updated(changes);\n\n if (changes.has('currentLanguage') && this.langValues) {\n let langValue = {\n text: '',\n attachments: [],\n quick_replies: [],\n };\n\n if (this.currentLanguage in this.langValues) {\n langValue = this.langValues[this.currentLanguage];\n }\n\n this.currentText = langValue.text;\n this.initialText = langValue.text;\n this.currentAttachments = langValue.attachments;\n this.currentQuickReplies = (langValue.quick_replies || []).map(value => {\n return { name: value, value };\n });\n this.currentOptin = langValue['optin'] ? [langValue['optin']] : [];\n this.setFocusOnChatbox();\n\n // TODO: this feels like it shouldn't be needed\n const chatbox = this.shadowRoot.querySelector('.chatbox') as any;\n if (chatbox) {\n chatbox.value = this.initialText;\n }\n this.resetTabs();\n this.requestUpdate('currentAttachments');\n }\n\n if (\n (this.langValues &&\n (changes.has('currentText') ||\n changes.has('currentAttachments') ||\n changes.has('currentQuickReplies'))) ||\n changes.has('currentOptin')\n ) {\n this.toggleButton();\n\n const trimmed = this.currentText ? this.currentText.trim() : '';\n if (\n trimmed ||\n this.currentAttachments.length > 0 ||\n this.currentQuickReplies.length > 0\n ) {\n this.langValues[this.currentLanguage] = {\n text: trimmed,\n attachments: this.currentAttachments,\n quick_replies: this.currentQuickReplies.map(option => option.value),\n optin: this.currentOptin.length > 0 ? this.currentOptin[0] : null,\n };\n } else {\n delete this.langValues[this.currentLanguage];\n }\n this.fireCustomEvent(CustomEventType.ContentChanged, this.langValues);\n this.requestUpdate('langValues');\n this.setValue(this.langValues);\n }\n }\n\n private setFocusOnChatbox(): void {\n if (this.chatbox) {\n const completion = this.shadowRoot.querySelector(\n '.chatbox'\n ) as Completion;\n if (completion) {\n window.setTimeout(() => {\n completion.focus();\n // this.resetTabs();\n }, 0);\n }\n }\n }\n\n public reset(): void {\n (this.shadowRoot.querySelector('.chatbox') as HTMLInputElement).value = '';\n this.initialText = '';\n this.currentText = '';\n this.currentQuickReplies = [];\n this.currentAttachments = [];\n this.failedAttachments = [];\n this.buttonError = '';\n }\n\n private handleQuickReplyChange(event: InputEvent) {\n this.requestUpdate('currentQuickReplies');\n }\n\n private handleOptInChange(event: InputEvent) {\n this.currentOptin = (event.target as any).values;\n this.requestUpdate('optIn');\n }\n\n private handleChatboxChange(evt: Event) {\n const chatbox = evt.target as HTMLInputElement;\n this.currentText = chatbox.value;\n }\n\n private handleDragEnter(evt: DragEvent): void {\n this.highlight(evt);\n }\n\n private handleDragOver(evt: DragEvent): void {\n this.highlight(evt);\n }\n\n private handleDragLeave(evt: DragEvent): void {\n this.unhighlight(evt);\n }\n\n private handleDrop(evt: DragEvent): void {\n if (this.canAcceptAttachments()) {\n this.unhighlight(evt);\n const dt = evt.dataTransfer;\n if (dt) {\n const files = dt.files;\n this.uploadFiles(files);\n }\n }\n }\n\n private preventDefaults(evt: Event): void {\n evt.preventDefault();\n evt.stopPropagation();\n }\n\n private highlight(evt: DragEvent): void {\n if (this.canAcceptAttachments()) {\n this.pendingDrop = true;\n this.preventDefaults(evt);\n }\n }\n\n private unhighlight(evt: DragEvent): void {\n if (this.canAcceptAttachments()) {\n this.pendingDrop = false;\n this.preventDefaults(evt);\n }\n }\n\n private handleUploadFileIconClicked(): void {\n this.dispatchEvent(new Event('change'));\n }\n\n private handleUploadFileInputChanged(evt: Event): void {\n const target = evt.target as HTMLInputElement;\n const files = target.files;\n this.uploadFiles(files);\n }\n\n public canAcceptAttachments() {\n return (\n this.attachments && this.currentAttachments.length < this.maxAttachments\n );\n }\n\n public uploadFiles(files: FileList): void {\n let filesToUpload = [];\n if (this.currentAttachments && this.currentAttachments.length > 0) {\n //remove duplicate files that have already been uploaded\n filesToUpload = [...files].filter(file => {\n const index = this.currentAttachments.findIndex(\n value => value.filename === file.name && value.size === file.size\n );\n if (index === -1) {\n return file;\n }\n });\n } else {\n filesToUpload = [...files];\n }\n filesToUpload.map(fileToUpload => {\n this.uploadFile(fileToUpload);\n });\n }\n\n private uploadFile(file: File): void {\n this.uploading = true;\n\n const url = this.endpoint;\n const payload = new FormData();\n payload.append('file', file);\n postFormData(url, payload)\n .then((response: WebResponse) => {\n if (this.currentAttachments.length >= this.maxAttachments) {\n this.addFailedAttachment(file, 'Too many attachments');\n } else {\n const attachment = response.json as Attachment;\n if (attachment) {\n this.addCurrentAttachment(attachment);\n }\n }\n })\n .catch((error: WebResponse) => {\n let uploadError = '';\n if (error.status === 400) {\n uploadError = error.json.file[0];\n } else {\n uploadError = 'Server failure';\n }\n console.error(uploadError);\n this.addFailedAttachment(file, uploadError);\n })\n .finally(() => {\n this.uploading = false;\n });\n }\n\n private addCurrentAttachment(attachmentToAdd: any) {\n this.currentAttachments.push(attachmentToAdd);\n this.requestUpdate('currentAttachments');\n }\n private removeCurrentAttachment(attachmentToRemove: any) {\n this.currentAttachments = this.currentAttachments.filter(\n currentAttachment => currentAttachment !== attachmentToRemove\n );\n this.requestUpdate('currentAttachments');\n }\n\n private addFailedAttachment(file: File, error: string) {\n const failedAttachment = {\n uuid: Math.random().toString(36).slice(2, 6),\n content_type: file.type,\n filename: file.name,\n url: file.name,\n size: file.size,\n error: error,\n } as Attachment;\n this.failedAttachments.push(failedAttachment);\n this.requestUpdate('failedAttachments');\n }\n private removeFailedAttachment(attachmentToRemove: any) {\n this.failedAttachments = this.failedAttachments.filter(\n (failedAttachment: any) => failedAttachment !== attachmentToRemove\n );\n this.requestUpdate('failedAttachments');\n }\n\n private handleRemoveFileClicked(evt: Event): void {\n const target = evt.target as HTMLDivElement;\n\n const currentAttachmentToRemove = this.currentAttachments.find(\n ({ uuid }) => uuid === target.id\n );\n if (currentAttachmentToRemove) {\n this.removeCurrentAttachment(currentAttachmentToRemove);\n }\n\n const failedAttachmentToRemove = this.failedAttachments.find(\n ({ uuid }) => uuid === target.id\n );\n if (failedAttachmentToRemove) {\n this.removeFailedAttachment(failedAttachmentToRemove);\n }\n }\n\n public toggleButton() {\n if (this.button) {\n this.buttonError = '';\n const chatboxEmpty = this.currentText.trim().length === 0;\n const attachmentsEmpty = this.currentAttachments.length === 0;\n if (this.chatbox && this.attachments) {\n this.buttonDisabled = chatboxEmpty && attachmentsEmpty;\n } else if (this.chatbox) {\n this.buttonDisabled = chatboxEmpty;\n } else if (this.attachments) {\n this.buttonDisabled = attachmentsEmpty;\n } else {\n this.buttonDisabled = true;\n }\n }\n }\n\n private handleSendClick(evt: Event) {\n evt.stopPropagation();\n this.handleSend();\n }\n\n private handleSendEnter(evt: KeyboardEvent) {\n if (this.button) {\n if (evt.key === 'Enter' && !evt.shiftKey) {\n if (this.completion) {\n const chat = evt.target as Completion;\n if (!chat.hasVisibleOptions()) {\n this.handleSend();\n this.preventDefaults(evt);\n }\n } else {\n this.handleSend();\n this.preventDefaults(evt);\n }\n }\n }\n }\n\n private handleSend() {\n if (!this.buttonDisabled) {\n this.buttonDisabled = true;\n const name = this.buttonName;\n this.fireCustomEvent(CustomEventType.ButtonClicked, { name });\n }\n }\n\n private handleLanguageChange(evt: Event) {\n const select = evt.target as Select;\n this.currentLanguage = select.values[0].iso;\n }\n\n public resetTabs() {\n (this.shadowRoot.querySelector('temba-tabs') as TabPane).index = -1;\n }\n\n public render(): TemplateResult {\n return html`\n \n ${this.languages.length > 1\n ? html`\n `\n : null}\n\n \n
    Upload Attachment
    \n\n ${this.chatbox ? html`${this.getChatbox()}` : null}\n\n
    ${this.getActions()}
    \n \n \n `;\n }\n\n private getChatbox(): TemplateResult {\n if (this.completion) {\n return html`\n `;\n } else {\n return html`\n `;\n }\n }\n\n private getAttachments(): TemplateResult {\n return html`\n ${this.attachments\n ? html`
    \n ${this.currentAttachments.map(validAttachment => {\n return html`
    \n \n ${isImageAttachment(validAttachment)\n ? html``\n : html``}\n
    `;\n })}\n ${this.getUploader()}\n
    \n ${this.failedAttachments.map(invalidAttachment => {\n return html`
    \n \n \n
    \n
    \n ${truncate(invalidAttachment.filename, 25)}\n (${formatFileSize(0, 0)}) - Attachment failed\n
    \n `;\n })}`\n : null}\n `;\n }\n\n private getActions(): TemplateResult {\n const showOptins = this.optIns && this.isBaseLanguage();\n return html`\n \n ${this.attachments\n ? html`\n
    ${this.getAttachments()}
    \n `\n : null}\n ${this.quickReplies\n ? html`\n \n `\n : null}\n 0}\n >\n \n \n\n
    \n ${this.buttonError\n ? html`
    ${this.buttonError}
    `\n : null}\n ${this.counter ? this.getCounter() : null}\n ${this.button ? this.getButton() : null}\n
    \n \n `;\n }\n\n private getUploader(): TemplateResult {\n if (this.uploading) {\n return html``;\n } else {\n return this.currentAttachments.length < this.maxAttachments\n ? html`\n \n \n \n \n `\n : null;\n }\n }\n\n private getCounter(): TemplateResult {\n return html``;\n }\n\n private getButton(): TemplateResult {\n return html` `;\n }\n}\n","import { css, html, PropertyValueMap } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\nimport { getClasses } from '../utils';\nimport { styleMap } from 'lit-html/directives/style-map.js';\n\n/**\n * This component relies on a bit of sleight of hand magic\n * to achieve it's effect. As such, it requires the use of\n * computed animation times and window.setTimeout().\n */\nexport class Lightbox extends RapidElement {\n static get styles() {\n return css`\n :host {\n position: absolute;\n }\n\n .mask {\n display: flex;\n opacity: 0;\n background: rgba(0, 0, 0, 0.5);\n position: absolute;\n height: 100svh;\n width: 100svw;\n pointer-events: none;\n }\n\n .zoom .mask {\n opacity: 1;\n pointer-events: auto;\n }\n\n .matte {\n position: absolute;\n transform: translate(400, 400) scale(3, 3);\n border-radius: 2%;\n overflow: hidden;\n box-shadow: 0 0 12px 3px rgba(0, 0, 0, 0.15);\n }\n `;\n }\n\n @property({ type: Number })\n animationTime = 300;\n\n @property({ type: Boolean })\n show = false;\n\n @property({ type: Boolean })\n zoom = false;\n\n @property({ type: Number })\n zoomPct = 0.9;\n\n private ele: HTMLElement;\n private left: number;\n private top: number;\n private height: number;\n private width: number;\n private scale = 1;\n private xTrans = '0px';\n private yTrans = '0px';\n\n protected updated(\n changed: PropertyValueMap | Map\n ): void {\n if (changed.has('show') && this.show) {\n window.setTimeout(() => {\n this.zoom = true;\n }, 0);\n }\n\n if (changed.has('zoom') && !this.zoom && this.show) {\n window.setTimeout(() => {\n this.show = false;\n }, this.animationTime);\n }\n }\n\n public showElement(ele: HTMLElement) {\n // size our matte according to the ele's boundaries\n const bounds = ele.getBoundingClientRect();\n this.ele = ele.cloneNode() as HTMLElement;\n this.left = bounds.left;\n this.top = bounds.top;\n this.width = bounds.width;\n this.height = bounds.height;\n\n this.xTrans = '0px';\n this.yTrans = '0px';\n this.scale = 1;\n\n let desiredWidth = this.width;\n let desiredHeight = this.height;\n let desiredScale = this.scale;\n\n const maxHeight = window.innerHeight * this.zoomPct;\n const maxWidth = window.innerWidth * this.zoomPct;\n\n // if the width fits, constrain by height\n if (this.width * (maxHeight / this.height) < maxWidth) {\n desiredHeight = window.innerHeight * this.zoomPct;\n desiredScale = desiredHeight / this.height;\n desiredWidth = this.width * desiredScale;\n } else {\n desiredWidth = window.innerWidth * this.zoomPct;\n desiredScale = desiredWidth / this.width;\n desiredHeight = this.height * desiredScale;\n }\n\n const xGrowth = (desiredWidth - this.width) / 2;\n const xDest = (window.innerWidth - desiredWidth) / 2;\n this.xTrans = xDest - this.left + xGrowth + 'px';\n\n const yGrowth = (desiredHeight - this.height) / 2;\n const yDest = (window.innerHeight - desiredHeight) / 2;\n this.yTrans = yDest - this.top + yGrowth + 'px';\n\n this.scale = desiredScale;\n this.show = true;\n }\n\n public handleClick() {\n this.zoom = false;\n }\n\n public render() {\n const styles = {\n transition: `transform ${this.animationTime}ms ease, box-shadow ${this.animationTime}ms ease`,\n };\n\n if (this.show) {\n styles['left'] = this.left + 'px';\n styles['top'] = this.top + 'px';\n styles['width'] = this.width + 'px';\n styles['height'] = this.height + 'px';\n }\n\n if (this.zoom) {\n styles[\n 'transform'\n ] = `translate(${this.xTrans}, ${this.yTrans}) scale(${this.scale}, ${this.scale})`;\n }\n\n return html`\n \n \n
    \n ${this.show ? this.ele : null}\n
    \n \n `;\n }\n}\n","import { html, css, PropertyValueMap } from 'lit';\nimport { FormElement } from '../FormElement';\nimport { property } from 'lit/decorators.js';\nimport { getClasses, hslToHex } from '../utils';\nimport { TextInput } from '../textinput/TextInput';\n\nexport class ColorPicker extends FormElement {\n @property({ type: Boolean })\n expanded = false;\n\n @property({ type: String })\n previewColor = '#ffffff';\n\n @property({ type: String })\n labelColor = '#ffffffee';\n\n @property({ type: Boolean })\n selecting = false;\n\n @property({ type: Number }) hue: number;\n @property({ type: Number }) saturation = 100;\n @property({ type: Number }) lightness = 50;\n @property({ type: String }) hex = '';\n\n static get styles() {\n return css`\n :host {\n color: var(--color-text);\n display: inline-block;\n --curvature: 0.55em;\n width: 100%;\n\n --temba-textinput-padding: 0.4em;\n }\n\n temba-textinput {\n margin-left: 0.3em;\n width: 5em;\n }\n\n temba-field {\n display: block;\n width: 100%;\n }\n\n .wrapper {\n border: 1px solid var(--color-widget-border);\n padding: calc(var(--curvature) / 2);\n border-radius: calc(var(--curvature) * 1.5);\n transition: all calc(var(--transition-speed) * 2) var(--bounce);\n\n display: flex;\n flex-grow: 0;\n }\n\n .picker-wrapper {\n display: flex;\n flex-direction: row;\n align-items: stretch;\n transition: all calc(var(--transition-speed) * 2) var(--bounce);\n flex-grow: 0;\n }\n\n .preview {\n width: initial;\n border-radius: var(--curvature);\n padding: 0.2em 0.5em;\n font-weight: 400;\n border: 2px solid rgba(0, 0, 0, 0.1);\n white-space: nowrap;\n cursor: pointer;\n transition: transform calc(var(--transition-speed) * 0.5) var(--bounce);\n }\n\n .preview.selecting {\n transform: scale(1.05);\n }\n\n .wrapper.expanded {\n flex-grow: 1 !important;\n }\n\n .wrapper.expanded .picker-wrapper {\n flex-grow: 1 !important;\n }\n\n .wrapper.expanded .preview {\n pointer-events: none;\n }\n\n .wrapper.expanded .color-picker {\n margin-left: calc(var(--curvature) / 2);\n }\n\n .wrapper.expanded temba-textinput {\n display: block;\n }\n\n .color-picker {\n border-radius: var(--curvature);\n cursor: pointer;\n transition: all calc(var(--transition-speed) * 2) var(--bounce);\n flex-grow: 1;\n position: relative;\n width: 100%;\n height: 100%;\n background-image: linear-gradient(\n to bottom,\n rgba(0, 0, 0, 0) 60%,\n rgba(0, 0, 0, 0.5) 90%,\n rgba(0, 0, 0, 1)\n ),\n linear-gradient(\n to top,\n rgba(255, 255, 255, 0) 60%,\n rgba(255, 255, 255, 0.8) 90%,\n rgba(255, 255, 255, 1)\n ),\n linear-gradient(\n to right,\n hsla(0, 100%, 50%, 1),\n hsla(60, 100%, 50%, 1),\n hsla(120, 100%, 50%, 1),\n hsla(180, 100%, 50%, 1),\n hsla(240, 100%, 50%, 1),\n hsla(300, 100%, 50%, 1),\n hsla(360, 100%, 50%, 1)\n );\n mix-blend-mode: multiply;\n }\n\n .color-picker:focus {\n outline: none;\n }\n `;\n }\n\n protected firstUpdated(\n _changedProperties: PropertyValueMap | Map\n ): void {\n super.firstUpdated(_changedProperties);\n }\n\n public updated(changed: Map): void {\n super.updated(changed);\n\n if (changed.has('value')) {\n this.previewColor = this.value || '#9c9c9c';\n this.hex = this.value;\n }\n\n if (changed.has('selecting')) {\n if (this.selecting) {\n window.setTimeout(() => {\n this.selecting = false;\n }, 100);\n }\n }\n\n if (changed.has('previewLabel') && this.hue) {\n this.hex = hslToHex(this.hue, this.saturation, this.lightness);\n }\n }\n\n private handleBlur(event: FocusEvent) {\n if (this.expanded) {\n this.expanded = false;\n }\n }\n\n private handleMouseOut(event: MouseEvent) {\n this.previewColor = this.value;\n this.hex = this.value;\n }\n\n private handleMouseMove(event: MouseEvent) {\n if (this.expanded) {\n const rect = (event.target as HTMLElement).getBoundingClientRect();\n const x = event.clientX - rect.left;\n const y = event.clientY - rect.top;\n this.hue = (x / rect.width) * 360;\n this.lightness = 100 - (y / rect.height) * 100;\n this.previewColor = `hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, 1)`;\n this.hex = hslToHex(this.hue, this.saturation, this.lightness);\n }\n }\n\n private handlePreviewClick(event: MouseEvent) {\n this.expanded = !this.expanded;\n this.selecting = true;\n (this.shadowRoot.querySelector('.color-picker') as HTMLDivElement).focus();\n }\n\n private handleColorClick(event: MouseEvent) {\n if (this.expanded) {\n const rect = (event.target as HTMLElement).getBoundingClientRect();\n const x = event.clientX - rect.left;\n const y = event.clientY - rect.top;\n this.hue = (x / rect.width) * 360;\n this.lightness = 100 - (y / rect.height) * 100;\n this.previewColor = `hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, 1)`;\n this.value = this.hex;\n this.selecting = true;\n this.expanded = false;\n }\n\n if (!this.expanded) {\n //\n }\n }\n\n private handleHexInput(event: InputEvent) {\n const hex = (event.target as TextInput).value;\n if (hex.startsWith('#')) {\n this.previewColor = hex;\n this.value = hex;\n }\n }\n\n public serializeValue(value: any): string {\n return value;\n }\n\n public render() {\n return html`\n \n
    \n
    \n
    \n \n ${this.label}\n
    \n
    \n
    \n \n \n \n \n `;\n }\n}\n","import { PropertyValueMap, css, html } from 'lit';\nimport { getClasses } from '../utils';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { ResizeElement } from '../ResizeElement';\n\nexport class Resizer extends ResizeElement {\n static styles = css`\n :host {\n display: block;\n position: relative;\n width: var(--box-width, 200px);\n --resizer-handle-size: 15px;\n }\n\n .resizer {\n position: absolute;\n right: calc(var(--resizer-handle-size) * -1);\n height: 100%;\n cursor: col-resize;\n padding: 0 calc(var(--resizer-handle-size) / 2);\n z-index: 1;\n }\n\n .resizer-handle {\n position: relative;\n width: 4px;\n background: rgba(0, 0, 0, 0);\n height: 100%;\n }\n\n .resizer:hover .resizer-handle {\n background: rgba(0, 0, 0, 0.05);\n width: 3px;\n margin-right: -1px;\n }\n\n .resizing .resizer-handle {\n background: rgba(0, 0, 0, 0.1) !important;\n width: 3px;\n margin-right: -1px;\n }\n\n slot {\n margin-right: var(--resizer-handle-size);\n background: red;\n }\n `;\n\n initialX: number;\n boxWidth: number;\n\n @property({ type: Number })\n minWidth = 200;\n\n @property({ type: Number })\n maxWidth = 2000;\n\n @property({ type: Boolean })\n resizing = false;\n\n @property({ type: Number })\n currentWidth: number;\n\n constructor() {\n super();\n this.startResize = this.startResize.bind(this);\n this.resize = this.resize.bind(this);\n this.stopResize = this.stopResize.bind(this);\n }\n\n protected updated(\n _changedProperties: PropertyValueMap | Map\n ): void {\n super.updated(_changedProperties);\n if (_changedProperties.has('currentWidth')) {\n this.style.setProperty('--box-width', `${this.currentWidth}px`);\n }\n }\n\n public setWidth(width: number) {\n const newWidth = Math.min(Math.max(width, this.minWidth), this.maxWidth);\n this.currentWidth = newWidth;\n }\n\n startResize(e: MouseEvent) {\n this.initialX = e.x;\n this.boxWidth = this.offsetWidth;\n document.body.style.userSelect = 'none';\n this.resizing = true;\n window.addEventListener('mousemove', this.resize);\n window.addEventListener('mouseup', this.stopResize);\n this.requestUpdate();\n }\n\n resize(event: MouseEvent) {\n const dx = event.x - this.initialX;\n this.setWidth(this.boxWidth + dx);\n }\n\n stopResize() {\n document.body.style.userSelect = 'initial';\n window.removeEventListener('mousemove', this.resize);\n window.removeEventListener('mouseup', this.stopResize);\n this.requestUpdate();\n this.resizing = false;\n\n this.fireCustomEvent(CustomEventType.Resized, { width: this.currentWidth });\n }\n\n render() {\n return html`\n \n
    \n \n \n `;\n }\n}\n","import { css, html } from 'lit';\nimport { RapidElement } from '../RapidElement';\nimport { property } from 'lit/decorators.js';\nimport { getClasses } from '../utils';\nimport { Lightbox } from '../lightbox/Lightbox';\nimport { styleMap } from 'lit-html/directives/style-map.js';\n\nexport class Thumbnail extends RapidElement {\n static get styles() {\n return css`\n :host {\n display: inline-block;\n }\n\n .zooming.wrapper {\n padding: 0 !important;\n border-radius: 0;\n }\n\n .zooming .thumb {\n border-radius: 0;\n }\n\n .wrapper {\n padding: var(--thumb-padding, 0.4em);\n background: #fff;\n border-radius: var(--curvature);\n box-shadow: var(--widget-box-shadow);\n }\n\n .thumb {\n }\n `;\n }\n\n @property({ type: String })\n url: string;\n\n @property({ type: String })\n label: string;\n\n @property({ type: Boolean })\n zoom = true;\n\n @property({ type: Boolean })\n zooming = false;\n\n public handleClick(evt: MouseEvent) {\n window.setTimeout(() => {\n const lightbox = document.querySelector('temba-lightbox') as Lightbox;\n lightbox.showElement(this);\n }, 0);\n }\n\n public render() {\n if (this.zooming) {\n return html`\n \n \n ${this.label}\n \n \n `;\n } else {\n return html`\n
    \n\n
    \n ${this.label}\n
    \n
    \n `;\n }\n }\n}\n","import { css } from 'lit';\n\nexport const CroppieCSS = css`\n .croppie-container {\n width: 100%;\n height: 100%;\n }\n\n .croppie-container .cr-image {\n z-index: -1;\n position: absolute;\n top: 0;\n left: 0;\n transform-origin: 0 0;\n max-height: none;\n max-width: none;\n }\n\n .croppie-container .cr-boundary {\n position: relative;\n overflow: hidden;\n margin: 0 auto;\n z-index: 1;\n width: 100%;\n height: 100%;\n }\n\n .croppie-container .cr-viewport,\n .croppie-container .cr-resizer {\n position: absolute;\n border: 2px solid #fff;\n margin: auto;\n top: 0;\n bottom: 0;\n right: 0;\n left: 0;\n box-shadow: 0 0 2000px 2000px rgba(0, 0, 0, 0.5);\n z-index: 0;\n }\n\n .croppie-container .cr-resizer {\n z-index: 2;\n box-shadow: none;\n pointer-events: none;\n }\n\n .croppie-container .cr-resizer-vertical,\n .croppie-container .cr-resizer-horisontal {\n position: absolute;\n pointer-events: all;\n }\n\n .croppie-container .cr-resizer-vertical::after,\n .croppie-container .cr-resizer-horisontal::after {\n display: block;\n position: absolute;\n box-sizing: border-box;\n border: 1px solid black;\n background: #fff;\n width: 10px;\n height: 10px;\n content: '';\n }\n\n .croppie-container .cr-resizer-vertical {\n bottom: -5px;\n cursor: row-resize;\n width: 100%;\n height: 10px;\n }\n\n .croppie-container .cr-resizer-vertical::after {\n left: 50%;\n margin-left: -5px;\n }\n\n .croppie-container .cr-resizer-horisontal {\n right: -5px;\n cursor: col-resize;\n width: 10px;\n height: 100%;\n }\n\n .croppie-container .cr-resizer-horisontal::after {\n top: 50%;\n margin-top: -5px;\n }\n\n .croppie-container .cr-original-image {\n display: none;\n }\n\n .croppie-container .cr-vp-circle {\n border-radius: 50%;\n }\n\n .croppie-container .cr-overlay {\n z-index: 1;\n position: absolute;\n cursor: move;\n touch-action: none;\n }\n\n .croppie-container .cr-slider-wrap {\n width: 75%;\n margin: 15px auto;\n text-align: center;\n }\n\n .croppie-result {\n position: relative;\n overflow: hidden;\n }\n\n .croppie-result img {\n position: absolute;\n }\n\n .croppie-container .cr-image,\n .croppie-container .cr-overlay,\n .croppie-container .cr-viewport {\n -webkit-transform: translateZ(0);\n -moz-transform: translateZ(0);\n -ms-transform: translateZ(0);\n transform: translateZ(0);\n }\n\n /*************************************/\n /***** STYLING RANGE INPUT ***********/\n /*************************************/\n /*http://brennaobrien.com/blog/2014/05/style-input-type-range-in-every-browser.html */\n /*************************************/\n\n .cr-slider {\n -webkit-appearance: none;\n /*removes default webkit styles*/\n /*border: 1px solid white; */ /*fix for FF unable to apply focus style bug */\n width: 300px;\n /*required for proper track sizing in FF*/\n max-width: 100%;\n padding-top: 8px;\n padding-bottom: 8px;\n background-color: transparent;\n }\n\n .cr-slider::-webkit-slider-runnable-track {\n width: 100%;\n height: 3px;\n background: rgba(0, 0, 0, 0.5);\n border: 0;\n border-radius: 3px;\n }\n\n .cr-slider::-webkit-slider-thumb {\n -webkit-appearance: none;\n border: none;\n height: 16px;\n width: 16px;\n border-radius: 50%;\n background: #ddd;\n margin-top: -6px;\n }\n\n .cr-slider:focus {\n outline: none;\n }\n /*\n.cr-slider:focus::-webkit-slider-runnable-track {\nbackground: #ccc;\n}\n*/\n\n .cr-slider::-moz-range-track {\n width: 100%;\n height: 3px;\n background: rgba(0, 0, 0, 0.5);\n border: 0;\n border-radius: 3px;\n }\n\n .cr-slider::-moz-range-thumb {\n border: none;\n height: 16px;\n width: 16px;\n border-radius: 50%;\n background: #ddd;\n margin-top: -6px;\n }\n\n /*hide the outline behind the border*/\n .cr-slider:-moz-focusring {\n outline: 1px solid white;\n outline-offset: -1px;\n }\n\n .cr-slider::-ms-track {\n width: 100%;\n height: 5px;\n background: transparent;\n /*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */\n border-color: transparent; /*leave room for the larger thumb to overflow with a transparent border */\n border-width: 6px 0;\n color: transparent; /*remove default tick marks*/\n }\n .cr-slider::-ms-fill-lower {\n background: rgba(0, 0, 0, 0.5);\n border-radius: 10px;\n }\n .cr-slider::-ms-fill-upper {\n background: rgba(0, 0, 0, 0.5);\n border-radius: 10px;\n }\n .cr-slider::-ms-thumb {\n border: none;\n height: 16px;\n width: 16px;\n border-radius: 50%;\n background: #ddd;\n margin-top: 1px;\n }\n .cr-slider:focus::-ms-fill-lower {\n background: rgba(0, 0, 0, 0.5);\n }\n .cr-slider:focus::-ms-fill-upper {\n background: rgba(0, 0, 0, 0.5);\n }\n /*******************************************/\n\n /***********************************/\n /* Rotation Tools */\n /***********************************/\n .cr-rotate-controls {\n position: absolute;\n bottom: 5px;\n left: 5px;\n z-index: 1;\n }\n .cr-rotate-controls button {\n border: 0;\n background: none;\n }\n .cr-rotate-controls i:before {\n display: inline-block;\n font-style: normal;\n font-weight: 900;\n font-size: 22px;\n }\n .cr-rotate-l i:before {\n content: '↺';\n }\n .cr-rotate-r i:before {\n content: '↻';\n }\n`;\n","/* eslint-disable @typescript-eslint/no-this-alias */\nimport { html, css, PropertyValueMap } from 'lit';\nimport { CroppieCSS } from './CroppieCSS';\nimport { property } from 'lit/decorators.js';\nimport { Icon } from '../vectoricon';\nimport { FormElement } from '../FormElement';\n\nexport class ImagePicker extends FormElement {\n static styles = css`\n ${CroppieCSS}\n\n .croppie {\n max-width: 400px;\n border: 0px solid #ccc;\n border-radius: 0.5em;\n overflow: hidden;\n background: #fff;\n margin-top: -20%;\n box-shadow: 0 0 15px 5px rgba(0, 0, 0, 0.1);\n }\n\n .croppie .controls {\n display: flex;\n align-items: center;\n flex-direction: row;\n justify-content: center;\n position: absolute;\n z-index: 1;\n width: 400px;\n margin-top: -42px;\n }\n\n .toggle {\n height: 110px;\n width: 110px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .circle .toggle {\n border-radius: 50%;\n }\n\n .toggle.set {\n box-shadow: rgba(0, 0, 0, 0.1) 0px 3px 7px 0px,\n rgba(0, 0, 0, 0.2) 0px 1px 2px 0px, inset 0 0 0 5px rgba(0, 0, 0, 0.1);\n }\n\n .toggle.set:hover {\n box-shadow: rgba(0, 0, 0, 0.1) 0px 3px 7px 0px,\n rgba(0, 0, 0, 0.2) 0px 1px 2px 0px, inset 0 0 0 5px rgba(0, 0, 0, 0.2);\n }\n\n .toggle temba-icon {\n color: rgba(0, 0, 0, 0.2);\n padding: 5px;\n }\n\n toggle:hover temba-icon {\n color: rgba(0, 0, 0, 0.8);\n }\n\n .toggle.set temba-icon {\n border-radius: 50%;\n margin-right: -90%;\n margin-bottom: -50%;\n background: rgba(240, 240, 240, 1);\n box-shadow: rgba(0, 0, 0, 0.2) 0px 1px 2px 0px;\n }\n\n .toggle.set:hover temba-icon {\n background: #fff;\n color: var(--color-primary-dark);\n }\n\n .circle .toggle.set temba-icon {\n margin-right: -70%;\n margin-bottom: -70%;\n }\n\n .hidden {\n display: none;\n }\n\n .controls temba-icon {\n margin: 0em 0.75em;\n background: rgba(255, 255, 255, 0.8);\n border-radius: 50%;\n padding: 6px;\n transition: all 0.1s ease-in-out;\n }\n\n .controls {\n pointer-events: none;\n display: flex;\n }\n\n .controls temba-icon {\n pointer-events: all;\n }\n\n .controls temba-icon.close {\n color: rgba(0, 0, 0, 0.2);\n background: rgba(255, 255, 255, 0.2);\n }\n\n .controls temba-icon.submit {\n color: rgba(0, 0, 0, 0.2);\n box-shadow: inset 0 0 0 2px rgba(0, 0, 0, 0.1);\n }\n\n .controls temba-icon:hover {\n color: white;\n cursor: pointer;\n background: var(--color-primary-dark);\n }\n `;\n\n @property({ type: String })\n tempImage: string;\n\n @property({ type: String })\n url: string;\n\n @property({ type: String })\n shape = 'square';\n\n @property({ type: Boolean, attribute: false })\n showCroppie = false;\n\n uploadReader = new FileReader();\n croppie: any;\n\n protected firstUpdated(\n changed: PropertyValueMap | Map\n ): void {\n super.firstUpdated(changed);\n const picker = this;\n\n this.uploadReader.onload = function () {\n picker.launchCroppie(picker.uploadReader.result as any);\n };\n }\n\n public updated(changed: Map): void {\n super.updated(changed);\n if (changed.has('url')) {\n this.setAttribute('url', this.url);\n }\n }\n\n private closeCroppie() {\n this.showCroppie = false;\n const wrapper = this.shadowRoot.querySelector('.croppie .embed');\n if (wrapper.firstChild) {\n wrapper.removeChild(wrapper.firstChild);\n }\n }\n\n private launchCroppie(url: string) {\n const wrapper = this.shadowRoot.querySelector('.croppie .embed');\n if (wrapper.firstChild) {\n wrapper.removeChild(wrapper.firstChild);\n }\n this.showCroppie = true;\n const ele = document.createElement('div');\n wrapper.appendChild(ele);\n\n const Croppie = (window as any).Croppie;\n this.croppie = new Croppie(ele, {\n enableExif: true,\n viewport: {\n width: 300,\n height: 300,\n type: this.shape,\n },\n boundary: {\n width: 400,\n height: 400,\n },\n });\n\n this.croppie.bind({ url });\n }\n\n private saveResult() {\n const picker = this;\n this.croppie\n .result({\n type: 'blob',\n size: 'viewport',\n format: 'webp',\n quality: 1,\n circle: false,\n })\n .then(function (resp: any) {\n const blob = resp;\n picker.url = URL.createObjectURL(blob);\n\n // const blob = dataURItoBlob(resp);\n const fd = new FormData();\n fd.append(picker.name, blob, 'filename.webp');\n\n picker.value = fd;\n picker.closeCroppie();\n });\n }\n\n private handleToggleClicked() {\n const fileInput = this.shadowRoot.querySelector('#file');\n (fileInput as any).click();\n }\n\n private handleFileChanged(e: Event) {\n const input = e.target as any;\n if (input.files.length > 0) {\n this.uploadReader.readAsDataURL(input.files[0]);\n }\n input.value = '';\n }\n\n protected render() {\n return html`\n
    \n \n \n
    \n \n
    \n \n \n
    \n
    \n
    \n \n
    \n \n
    \n \n \n
    \n `;\n }\n}\n","import { LitElement, css, html } from 'lit';\nimport { property } from 'lit/decorators.js';\n\nexport class Mask extends LitElement {\n static styles = css`\n .mask {\n position: fixed;\n top: 0;\n left: 0;\n z-index: 100;\n width: 100vw;\n height: 100vh;\n background: rgba(0, 0, 0, 0.6);\n display: none;\n align-items: center;\n justify-content: center;\n }\n\n .show {\n display: flex;\n }\n `;\n\n @property({ type: Boolean })\n show = false;\n\n render() {\n return html`
    \n \n
    `;\n }\n}\n","import { PropertyValueMap, TemplateResult, css, html } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { User } from '../interfaces';\nimport { StoreMonitorElement } from '../store/StoreMonitorElement';\nimport { colorHash, extractInitials } from '../utils';\n\nexport class TembaUser extends StoreMonitorElement {\n public static styles = css`\n :host {\n display: flex;\n }\n\n .wrapper {\n display: flex;\n flex-direction: row;\n align-items: center;\n flex-grow: 1;\n }\n\n .name {\n flex-grow: 1;\n display: -webkit-box;\n -webkit-line-clamp: 1;\n -webkit-box-orient: vertical;\n overflow: hidden;\n }\n `;\n\n @property({ type: String })\n email: string;\n\n @property({ type: Number })\n scale: number;\n\n @property({ type: Boolean })\n name: string;\n\n @property({ type: Object, attribute: false })\n user: User;\n\n @property({ type: String, attribute: false })\n background: string;\n\n @property({ type: String, attribute: false })\n initials: string;\n\n @property({ type: String, attribute: false })\n fullName: string;\n\n public updated(\n changed: PropertyValueMap | Map\n ): void {\n super.updated(changed);\n if (changed.has('email')) {\n this.user = this.store.getUser(this.email);\n if (this.user) {\n this.fullName = [this.user.first_name, this.user.last_name].join(' ');\n if (this.user.avatar) {\n this.background = `url('${this.user.avatar}') center / contain no-repeat`;\n this.initials = '';\n } else {\n this.background = colorHash.hex(this.fullName);\n this.initials = extractInitials(this.fullName);\n }\n }\n }\n }\n\n public render(): TemplateResult {\n if (!this.user) {\n return null;\n }\n\n return html`
    \n \n ${this.initials\n ? html` \n
    ${this.initials}
    \n
    `\n : null}\n
    \n ${this.name\n ? html`\n ${this.fullName}\n `\n : null}\n `;\n }\n}\n","import { property } from 'lit/decorators.js';\nimport { FormElement } from '../FormElement';\nimport { TemplateResult, html, css, PropertyValueMap } from 'lit';\nimport { CustomEventType } from '../interfaces';\n\ninterface Component {\n name: string;\n type: string;\n content: string;\n params: { type: string }[];\n}\n\ninterface Translation {\n locale: string;\n status: string;\n channel: { uuid: string; name: string };\n components: Component[];\n}\n\ninterface Template {\n created_on: string;\n modified_on: string;\n name: string;\n translations: Translation[];\n uuid: string;\n}\n\nexport class TemplateEditor extends FormElement {\n static get styles() {\n return css`\n .component {\n background: #fff;\n border: 1px solid var(--color-widget-border);\n border-radius: var(--curvature);\n padding: 1em;\n margin-top: 1em;\n }\n .picker {\n margin-bottom: 0.5em;\n display: block;\n }\n .param {\n display: flex;\n margin-bottom: 0.5em;\n align-items: center;\n }\n label {\n margin-right: 0.5em;\n }\n\n .content span {\n margin-right: 0.25em;\n }\n\n .error-message {\n padding-left: 0.5em;\n }\n\n .variable {\n display: inline-block;\n margin: 0.25em 0em;\n margin-right: 0.25em;\n }\n\n .button-wrapper {\n margin-top: 1em;\n background: #f9f9f9;\n border-radius: var(--curvature);\n padding: 0.5em;\n display: flex;\n flex-direction: column;\n }\n\n .button-header {\n font-weight: normal;\n margin-left: 0.25em;\n margin-bottom: -0.5em;\n font-size: 0.9em;\n color: #777;\n }\n\n .buttons {\n display: flex;\n align-items: center;\n flex-wrap: wrap;\n }\n\n .button {\n background: #fff;\n padding: 0.3em 1em;\n border: 1px solid #e6e6e6;\n border-radius: var(--curvature);\n min-height: 23px;\n display: flex;\n flex-direction: row;\n align-items: center;\n margin-right: 0.5em;\n margin-top: 0.5em;\n align-items: center;\n }\n\n .button .display {\n margin-right: 0.5em;\n background: #f9f9f9;\n padding: 0.25em 1em;\n border-radius: var(--curvature);\n }\n\n temba-textinput,\n temba-completion {\n --temba-textinput-padding: 5px 5px;\n --temba-textinput-font-size: 0.9em;\n line-height: initial;\n }\n\n .template {\n background: #fff;\n border-radius: var(--curvature);\n border: 1px solid var(--color-widget-border);\n padding: 1em;\n line-height: 2.2em;\n }\n `;\n }\n\n @property({ type: String })\n url: string;\n\n // initial template uuid\n @property({ type: String })\n template: string;\n\n @property({ type: Object })\n selectedTemplate: Template;\n\n @property({ type: String })\n lang = 'eng-US';\n\n // component key to array of strings for variables\n @property({ type: Object })\n params: { [key: string]: string[] };\n\n @property({ type: Object, attribute: false })\n translation: Translation;\n\n @property({ type: Boolean })\n translating: boolean;\n\n public firstUpdated(\n changes: PropertyValueMap | Map\n ): void {\n super.firstUpdated(changes);\n }\n\n public updated(changedProperties: Map): void {\n super.updated(changedProperties);\n }\n\n private handleTemplateChanged(event: CustomEvent) {\n this.selectedTemplate = (event.target as any).values[0] as Template;\n const [lang, loc] = this.lang.split('-');\n\n const newParams = {};\n if (this.selectedTemplate) {\n this.selectedTemplate.translations.forEach(translation => {\n if (\n translation.locale === this.lang ||\n (!loc && translation.locale.split('-')[0] === lang)\n ) {\n this.translation = translation;\n for (const comp of translation.components) {\n const compParams = comp.params || [];\n if (compParams.length > 0) {\n // create an array for the length of params\n newParams[comp.name] = new Array(compParams.length).fill('');\n }\n }\n\n // if we are looking at the same template copy our params on top\n if (this.template === this.selectedTemplate.uuid) {\n for (const key of Object.keys(this.params || {})) {\n if (newParams[key]) {\n for (let i = 0; i < this.params[key].length; i++) {\n newParams[key][i] = this.params[key][i];\n }\n }\n }\n }\n }\n });\n } else {\n this.translation = null;\n }\n\n this.params = newParams;\n this.fireCustomEvent(CustomEventType.ContextChanged, {\n template: this.selectedTemplate,\n translation: this.translation,\n params: this.params,\n });\n }\n\n private handleVariableChanged(event: CustomEvent) {\n const target = event.target as HTMLInputElement;\n const index = parseInt(target.getAttribute('index'));\n this.params[target.name][index - 1] = target.value;\n this.fireCustomEvent(CustomEventType.ContentChanged, {\n template: this.selectedTemplate,\n translation: this.translation,\n params: this.params,\n });\n }\n\n private renderVariables(component: Component) {\n const parts = component.content.split(/{{(\\d+)}}/g);\n if (parts.length > 0) {\n const variables = parts.map((part, index) => {\n const paramIndex = Math.round(index / 2);\n if (index % 2 === 0) {\n return html`${part}`;\n }\n return html``;\n });\n return html`
    ${variables}
    `;\n }\n }\n\n public renderComponents(components: Component[]): TemplateResult {\n const nonButtons = components\n .filter(comp => !comp.type.startsWith('button/'))\n .map(\n component =>\n html`
    \n ${this.renderVariables(component)}\n
    `\n );\n const buttonComponents = components.filter(comp =>\n comp.type.startsWith('button/')\n );\n const buttons =\n buttonComponents.length > 0 ? this.renderButtons(buttonComponents) : null;\n return html`
    ${nonButtons}
    \n
    \n ${buttons}\n
    \n
    `;\n }\n\n public renderButtons(components): TemplateResult {\n const buttons = components.map(component => {\n if (component.display) {\n return html`\n
    \n
    ${component.display}
    \n ${this.renderVariables(component)}\n
    \n `;\n } else {\n return html`\n
    ${this.renderVariables(component)}
    \n `;\n }\n });\n return html`
    \n
    Template Buttons
    \n
    ${buttons}
    \n
    `;\n }\n\n public render(): TemplateResult {\n let content = null;\n if (this.translation) {\n content = this.renderComponents(this.translation.components);\n } else {\n content = html`
    \n No approved translation was found for current language.\n
    `;\n }\n\n return html`\n
    \n template.status !== 'approved'}\n placeholder=\"Select a template\"\n @temba-content-changed=${this.swallowEvent}\n @change=${this.handleTemplateChanged}\n >\n \n\n ${this.template ? html`
    ${content}
    ` : null}\n
    \n `;\n }\n}\n","import { Checkbox } from './src/checkbox/Checkbox';\nimport { TextInput } from './src/textinput/TextInput';\nimport { Store } from './src/store/Store';\nimport { Select } from './src/select/Select';\nimport { Completion } from './src/completion/Completion';\nimport { Modax } from './src/dialog/Modax';\nimport { Dialog } from './src/dialog/Dialog';\nimport { Button } from './src/button/Button';\nimport { FormField } from './src/formfield/FormField';\nimport { Loading } from './src/loading/Loading';\nimport { CharCount } from './src/charcount/CharCount';\nimport { Options } from './src/options/Options';\nimport { ContactChat } from './src/contacts/ContactChat';\nimport { ContactHistory } from './src/contacts/ContactHistory';\nimport { TicketList } from './src/list/TicketList';\nimport { ContactDetails } from './src/contacts/ContactDetails';\nimport { TembaList } from './src/list/TembaList';\nimport { ContactSearch } from './src/contactsearch/ContactSearch';\nimport { VectorIcon } from './src/vectoricon/VectorIcon';\nimport { Alert } from './src/alert/Alert';\nimport { Omnibox } from './src/omnibox/Omnibox';\nimport { Tip } from './src/tip/Tip';\nimport { TembaMenu } from './src/list/TembaMenu';\nimport { Anchor } from './src/anchor/Anchor';\nimport { Dropdown } from './src/dropdown/Dropdown';\nimport { TabPane } from './src/tabpane/TabPane';\nimport { Tab } from './src/tabpane/Tab';\nimport Label from './src/label/Label';\nimport { ContactName } from './src/contacts/ContactName';\nimport { ContactUrn } from './src/contacts/ContactUrn';\nimport { ContactFields } from './src/contacts/ContactFields';\nimport { ContactFieldEditor } from './src/contacts/ContactFieldEditor';\n\nimport { ContactBadges } from './src/contacts/ContactBadges';\nimport { ContactPending } from './src/contacts/ContactPending';\nimport { ContactTickets } from './src/contacts/ContactTickets';\nimport { TembaSlider } from './src/slider/TembaSlider';\nimport { RunList } from './src/list/RunList';\nimport { FlowStoreElement } from './src/flow/FlowStoreElement';\nimport { ContactNameFetch } from './src/contacts/ContactNameFetch';\nimport DatePicker from './src/datepicker/DatePicker';\nimport { FieldManager } from './src/fields/FieldManager';\nimport { SortableList } from './src/list/SortableList';\nimport { ContentMenu } from './src/list/ContentMenu';\nimport { TembaDate } from './src/date/TembaDate';\nimport Remote from './src/remote/Remote';\nimport { Compose } from './src/compose/Compose';\nimport { Lightbox } from './src/lightbox/Lightbox';\nimport { ColorPicker } from './src/colorpicker/ColorPicker';\nimport { Resizer } from './src/resizer/Resizer';\nimport { Thumbnail } from './src/thumbnail/Thumbnail';\nimport { NotificationList } from './src/list/NotificationList';\nimport { WebChat } from './src/webchat/WebChat';\nimport { ImagePicker } from './src/imagepicker/ImagePicker';\nimport { Mask } from './src/mask/Mask';\nimport { TembaUser } from './src/user/TembaUser';\nimport { TemplateEditor } from './src/templates/TemplateEditor';\n\nexport function addCustomElement(name: string, comp: any) {\n if (!window.customElements.get(name)) {\n window.customElements.define(name, comp);\n }\n}\n\naddCustomElement('temba-anchor', Anchor);\naddCustomElement('temba-alert', Alert);\naddCustomElement('temba-store', Store);\naddCustomElement('temba-textinput', TextInput);\naddCustomElement('temba-datepicker', DatePicker);\naddCustomElement('temba-date', TembaDate);\naddCustomElement('temba-completion', Completion);\naddCustomElement('temba-checkbox', Checkbox);\naddCustomElement('temba-select', Select);\naddCustomElement('temba-options', Options);\naddCustomElement('temba-loading', Loading);\naddCustomElement('temba-lightbox', Lightbox);\naddCustomElement('temba-button', Button);\naddCustomElement('temba-omnibox', Omnibox);\naddCustomElement('temba-tip', Tip);\naddCustomElement('temba-contact-name', ContactName);\naddCustomElement('temba-contact-name-fetch', ContactNameFetch);\naddCustomElement('temba-contact-field', ContactFieldEditor);\naddCustomElement('temba-contact-fields', ContactFields);\naddCustomElement('temba-field-manager', FieldManager);\naddCustomElement('temba-urn', ContactUrn);\naddCustomElement('temba-content-menu', ContentMenu);\n\naddCustomElement('temba-field', FormField);\naddCustomElement('temba-dialog', Dialog);\naddCustomElement('temba-modax', Modax);\naddCustomElement('temba-charcount', CharCount);\naddCustomElement('temba-contact-history', ContactHistory);\naddCustomElement('temba-contact-chat', ContactChat);\naddCustomElement('temba-contact-details', ContactDetails);\naddCustomElement('temba-ticket-list', TicketList);\naddCustomElement('temba-notification-list', NotificationList);\naddCustomElement('temba-list', TembaList);\naddCustomElement('temba-sortable-list', SortableList);\naddCustomElement('temba-run-list', RunList);\naddCustomElement('temba-flow-details', FlowStoreElement);\naddCustomElement('temba-label', Label);\naddCustomElement('temba-menu', TembaMenu);\naddCustomElement('temba-remote', Remote);\naddCustomElement('temba-contact-search', ContactSearch);\naddCustomElement('temba-icon', VectorIcon);\naddCustomElement('temba-dropdown', Dropdown);\naddCustomElement('temba-tabs', TabPane);\naddCustomElement('temba-tab', Tab);\naddCustomElement('temba-contact-badges', ContactBadges);\naddCustomElement('temba-contact-pending', ContactPending);\naddCustomElement('temba-contact-tickets', ContactTickets);\naddCustomElement('temba-slider', TembaSlider);\naddCustomElement('temba-content-menu', ContentMenu);\naddCustomElement('temba-compose', Compose);\naddCustomElement('temba-color-picker', ColorPicker);\naddCustomElement('temba-resizer', Resizer);\naddCustomElement('temba-thumbnail', Thumbnail);\naddCustomElement('temba-webchat', WebChat);\naddCustomElement('temba-image-picker', ImagePicker);\naddCustomElement('temba-mask', Mask);\naddCustomElement('temba-user', TembaUser);\naddCustomElement('temba-template-editor', TemplateEditor);\n","import { css, html, TemplateResult } from 'lit';\nimport { TembaList } from './TembaList';\nimport { StyleInfo } from 'lit-html/directives/style-map.js';\nimport { Options } from '../options/Options';\nimport { Icon } from '../vectoricon';\n\ninterface Notification {\n created_on: string;\n type: string;\n target_url: string;\n is_seen: boolean;\n export?: {\n type: string;\n };\n import?: {\n type: string;\n num_records: number;\n };\n incident?: {\n type: string;\n started_on: string;\n ended_on?: string;\n };\n}\n\nexport class NotificationList extends TembaList {\n reverseRefresh = false;\n internalFocusDisabled = true;\n static get styles() {\n return css`\n :host {\n --option-hover-bg: #f9f9f9;\n }\n\n .header {\n padding: 0.25em 1em;\n background: #f9f9f9;\n border-top-left-radius: var(--curvature);\n border-top-right-radius: var(--curvature);\n display: flex;\n color: #999;\n border-bottom: 1px solid #f3f3f3;\n }\n\n .header temba-icon {\n margin-right: 0.35em;\n }\n\n .footer {\n background: #f9f9f9;\n }\n\n .title {\n font-weight: normal;\n }\n `;\n }\n\n constructor() {\n super();\n this.valueKey = 'target_url';\n this.renderOption = (notification: Notification): TemplateResult => {\n let icon = null;\n let body = null;\n const color = '#333';\n\n if (notification.type === 'incident:started') {\n if (notification.incident.type === 'org:flagged') {\n icon = Icon.incidents;\n body =\n 'Your workspace was flagged, please contact support for assistance.';\n } else if (notification.incident.type === 'org:suspended') {\n icon = Icon.incidents;\n body =\n 'Your workspace was suspended, please contact support for assistance.';\n } else if (notification.incident.type === 'channel:disconnected') {\n icon = Icon.channel;\n body = 'Your android channel is not connected';\n } else if (notification.incident.type === 'channel:templates_failed') {\n icon = Icon.channel;\n body = 'Your WhatsApp channel templates failed syncing';\n } else if (notification.incident.type === 'webhooks:unhealthy') {\n icon = Icon.webhook;\n body = 'Your webhook calls are not working properly.';\n }\n } else if (notification.type === 'import:finished') {\n if (notification.import.type === 'contact') {\n icon = Icon.contact_import;\n body = `Imported ${notification.import.num_records.toLocaleString()} contacts`;\n }\n } else if (notification.type === 'export:finished') {\n if (notification.export.type === 'contact') {\n icon = Icon.contact_export;\n body = 'Exported contacts';\n } else if (notification.export.type === 'message') {\n icon = Icon.message_export;\n body = 'Exported messages';\n } else if (notification.export.type === 'results') {\n icon = Icon.results_export;\n body = 'Exported flow results';\n } else if (notification.export.type === 'ticket') {\n icon = Icon.tickets_export;\n body = 'Exported tickets';\n }\n } else if (notification.type === 'tickets:activity') {\n icon = Icon.tickets;\n body = 'New ticket activity';\n } else if (notification.type === 'tickets:opened') {\n icon = Icon.tickets;\n body = 'New unassigned ticket';\n }\n return html`\n ${icon\n ? html`
    \n \n
    `\n : null}\n
    \n
    ${body}
    \n \n
    \n `;\n };\n }\n\n public renderHeader(): TemplateResult {\n return html`
    \n \n
    Notifications
    \n
    `;\n }\n\n protected handleSelection(event: CustomEvent) {\n super.handleSelected(event);\n }\n\n public scrollToTop(): void {\n // scroll back to the top\n window.setTimeout(() => {\n const options = this.shadowRoot.querySelector('temba-options') as Options;\n options.scrollToTop();\n }, 1000);\n }\n}\n","import { css, html, LitElement, TemplateResult } from 'lit';\nimport { FeatureProperties } from '../interfaces';\nimport { getUrl, postJSON, WebResponse } from '../utils';\nimport { TextInput } from '../textinput/TextInput';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { FormElement } from '../FormElement';\nimport { Icon } from '../vectoricon';\n\nimport { property } from 'lit/decorators.js';\nimport { Select } from '../select/Select';\n\nexport class AliasEditor extends LitElement {\n static get styles() {\n return css`\n :host {\n line-height: normal;\n }\n\n temba-textinput {\n height: 150px;\n }\n\n #left-column {\n display: inline-block;\n margin-left: 10px;\n width: 300px;\n z-index: 100;\n }\n\n .search {\n margin-bottom: 10px;\n }\n\n .feature {\n padding: 4px 14px;\n font-size: 16px;\n }\n\n .level-0 {\n margin-left: 0px;\n }\n\n .level-1 {\n margin-left: 5px;\n font-size: 95%;\n }\n\n .level-2 {\n margin-left: 10px;\n font-size: 90%;\n }\n\n .level-3 {\n margin-left: 15px;\n font-size: 85%;\n }\n\n .feature-name {\n display: inline-block;\n }\n\n .clickable {\n text-decoration: none;\n cursor: pointer;\n color: var(--color-link-primary);\n }\n\n .clickable.secondary {\n color: var(--color-link-secondary);\n }\n\n .clickable:hover {\n text-decoration: underline;\n color: var(--color-link-primary-hover);\n }\n\n .feature:hover .showonhover {\n visibility: visible;\n }\n\n .showonhover {\n visibility: hidden;\n }\n\n .aliases {\n color: #bbb;\n font-size: 80%;\n display: inline;\n margin-left: 5px;\n }\n\n temba-label {\n margin-right: 3px;\n margin-bottom: 3px;\n vertical-align: top;\n }\n\n .selected {\n display: flex;\n flex-direction: column;\n padding: 15px;\n padding-bottom: 40px;\n }\n\n .selected .name {\n font-size: 18px;\n padding: 5px;\n }\n\n .selected .help {\n padding: 5px 2px;\n font-size: 11px;\n color: var(--color-secondary-light);\n }\n\n #right-column {\n vertical-align: top;\n margin-left: 20px;\n display: inline-block;\n }\n\n leaflet-map {\n height: 600px;\n width: 800px;\n border: 0px solid #999;\n border-radius: var(--curvature);\n }\n\n .edit {\n display: inline-block;\n margin-right: 0px;\n }\n `;\n }\n\n @property({ type: Array, attribute: false })\n path: FeatureProperties[] = [];\n\n @property()\n endpoint: string;\n\n @property()\n osmId: string;\n\n @property({ type: Object })\n hovered: FeatureProperties;\n\n @property({ type: Object })\n editFeature: FeatureProperties;\n\n @property({ type: String, attribute: false })\n editFeatureAliases: string;\n\n public constructor() {\n super();\n }\n\n public updated(changedProperties: Map) {\n if (changedProperties.has('osmId')) {\n // going up the tree doesn't require a fetch\n const newPath = [];\n for (const feature of this.path) {\n newPath.push(feature);\n if (feature.osm_id === this.osmId) {\n this.path = [...newPath];\n this.hideAliasDialog();\n return;\n }\n }\n\n this.fetchFeature();\n }\n }\n\n private fetchFeature() {\n getUrl(this.getEndpoint() + 'boundaries/' + this.osmId + '/').then(\n (response: WebResponse) => {\n this.path = response.json as FeatureProperties[];\n this.hideAliasDialog();\n }\n );\n }\n\n private handleMapClicked(feature: FeatureProperties): void {\n this.hovered = null;\n if (!feature || feature.osm_id !== this.osmId) {\n this.osmId = feature.osm_id;\n }\n }\n\n private handlePlaceClicked(feature: FeatureProperties) {\n this.osmId = feature.osm_id;\n }\n\n private handleSearchSelection(evt: CustomEvent) {\n const selection = evt.detail.selected as FeatureProperties;\n this.showAliasDialog(selection);\n const select = this.shadowRoot.querySelector('temba-select') as Select;\n select.clear();\n }\n\n private isMatch(option: any, query: string) {\n return `${option.name} ${option.aliases}`.toLowerCase().indexOf(query) > -1;\n }\n\n private renderFeature(\n feature: FeatureProperties,\n remainingPath: FeatureProperties[]\n ): TemplateResult {\n const selectedFeature = this.path[this.path.length - 1];\n const clickable =\n (feature.has_children || feature.level === 0) &&\n feature !== selectedFeature;\n const renderedFeature = html`\n
    \n {\n if (feature.level > 0) {\n this.hovered = feature;\n }\n }}\n @mouseout=${() => {\n this.hovered = null;\n }}\n class=\"level-${feature.level}\"\n >\n {\n if (clickable) {\n this.handlePlaceClicked(feature);\n }\n }}\n >\n ${feature.name}\n
    \n\n
    \n ${feature.aliases.split('\\n').map((alias: string) =>\n alias.trim().length > 0\n ? html`\n {\n this.showAliasDialog(feature);\n }}\n light\n clickable\n >${alias}\n `\n : null\n )}\n ${feature.level > 0\n ? html`\n {\n this.showAliasDialog(feature);\n evt.preventDefault();\n evt.stopPropagation();\n }}\n >\n \n
    \n `\n : ''}\n \n \n \n `;\n\n const renderedChildren = (feature.children || []).map(\n (child: FeatureProperties) => {\n if (\n remainingPath.length > 0 &&\n remainingPath[0].osm_id === child.osm_id\n ) {\n return this.renderFeature(remainingPath[0], remainingPath.slice(1));\n }\n\n if (\n remainingPath.length === 0 ||\n remainingPath[0].children.length === 0\n ) {\n return this.renderFeature(child, remainingPath);\n }\n\n return null;\n }\n );\n\n return html` ${renderedFeature} ${renderedChildren} `;\n }\n\n public showAliasDialog(feature: FeatureProperties) {\n this.editFeatureAliases = feature.aliases;\n this.editFeature = feature;\n const aliasDialog = this.shadowRoot.getElementById('alias-dialog');\n if (aliasDialog) {\n aliasDialog.setAttribute('open', '');\n }\n }\n\n public hideAliasDialog() {\n const aliasDialog = this.shadowRoot.getElementById('alias-dialog');\n this.editFeature = null;\n this.editFeatureAliases = null;\n if (aliasDialog) {\n aliasDialog.removeAttribute('open');\n }\n\n this.requestUpdate();\n }\n\n private getEndpoint(): string {\n return this.endpoint + (!this.endpoint.endsWith('/') ? '/' : '');\n }\n\n private handleDialogClick(evt: CustomEvent) {\n const button = evt.detail.button;\n if (button.name === 'Save') {\n const textarea = this.shadowRoot.getElementById(\n this.editFeature.osm_id\n ) as TextInput;\n const aliases = textarea.inputElement.value;\n const payload = { osm_id: this.editFeature.osm_id, aliases };\n postJSON(\n this.getEndpoint() + 'boundaries/' + this.editFeature.osm_id + '/',\n payload\n ).then(() => {\n this.fetchFeature();\n });\n }\n\n if (button.name === 'Cancel') {\n this.hideAliasDialog();\n }\n }\n\n private getOptions(response: WebResponse) {\n return response.json.filter((option: any) => option.level > 0);\n }\n\n private getOptionsComplete(newestOptions: FeatureProperties[]) {\n return newestOptions.length === 0;\n }\n\n private renderOptionDetail(option: FeatureProperties): TemplateResult {\n const labelStyles = {\n marginTop: '3px',\n marginRight: '3px',\n };\n\n const aliasList = option.aliases.split('\\n');\n const aliases = aliasList.map((alias: string) =>\n alias.trim().length > 0\n ? html`\n ${alias}\n `\n : null\n );\n return html`\n
    ${option.path.replace(/>/gi, '‣')}
    \n
    ${aliases}
    \n `;\n }\n\n public render(): TemplateResult {\n if (this.path.length === 0) {\n return html``;\n }\n\n // if we are a leaf, have our map show the level above\n const selectedFeature = this.path[this.path.length - 1];\n const mapFeature =\n selectedFeature.children.length === 0\n ? this.path[this.path.length - 2]\n : selectedFeature;\n\n const editFeatureId = this.editFeature ? this.editFeature.osm_id : null;\n const editFeatureName = this.editFeature ? this.editFeature.name : null;\n\n return html`\n
    \n
    \n \n
    \n
    \n ${this.renderFeature(this.path[0], this.path.slice(1))}\n
    \n
    \n\n
    \n \n \n
    \n\n \n
    \n \n
    \n \n `;\n }\n}\n","/* @preserve\n * Leaflet 1.5.1+build.2e3e0ff, a JS library for interactive maps. http://leafletjs.com\n * (c) 2010-2018 Vladimir Agafonkin, (c) 2010-2011 CloudMade\n */\n\n(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n\ttypeof define === 'function' && define.amd ? define(['exports'], factory) :\n\t(factory((global.L = {})));\n}(this, (function (exports) { 'use strict';\n\nvar version = \"1.5.1+build.2e3e0ffb\";\n\n/*\r\n * @namespace Util\r\n *\r\n * Various utility functions, used by Leaflet internally.\r\n */\r\n\r\nvar freeze = Object.freeze;\r\nObject.freeze = function (obj) { return obj; };\r\n\r\n// @function extend(dest: Object, src?: Object): Object\r\n// Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.\r\nfunction extend(dest) {\r\n\tvar i, j, len, src;\r\n\r\n\tfor (j = 1, len = arguments.length; j < len; j++) {\r\n\t\tsrc = arguments[j];\r\n\t\tfor (i in src) {\r\n\t\t\tdest[i] = src[i];\r\n\t\t}\r\n\t}\r\n\treturn dest;\r\n}\r\n\r\n// @function create(proto: Object, properties?: Object): Object\r\n// Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)\r\nvar create = Object.create || (function () {\r\n\tfunction F() {}\r\n\treturn function (proto) {\r\n\t\tF.prototype = proto;\r\n\t\treturn new F();\r\n\t};\r\n})();\r\n\r\n// @function bind(fn: Function, …): Function\r\n// Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).\r\n// Has a `L.bind()` shortcut.\r\nfunction bind(fn, obj) {\r\n\tvar slice = Array.prototype.slice;\r\n\r\n\tif (fn.bind) {\r\n\t\treturn fn.bind.apply(fn, slice.call(arguments, 1));\r\n\t}\r\n\r\n\tvar args = slice.call(arguments, 2);\r\n\r\n\treturn function () {\r\n\t\treturn fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);\r\n\t};\r\n}\r\n\r\n// @property lastId: Number\r\n// Last unique ID used by [`stamp()`](#util-stamp)\r\nvar lastId = 0;\r\n\r\n// @function stamp(obj: Object): Number\r\n// Returns the unique ID of an object, assigning it one if it doesn't have it.\r\nfunction stamp(obj) {\r\n\t/*eslint-disable */\r\n\tobj._leaflet_id = obj._leaflet_id || ++lastId;\r\n\treturn obj._leaflet_id;\r\n\t/* eslint-enable */\r\n}\r\n\r\n// @function throttle(fn: Function, time: Number, context: Object): Function\r\n// Returns a function which executes function `fn` with the given scope `context`\r\n// (so that the `this` keyword refers to `context` inside `fn`'s code). The function\r\n// `fn` will be called no more than one time per given amount of `time`. The arguments\r\n// received by the bound function will be any arguments passed when binding the\r\n// function, followed by any arguments passed when invoking the bound function.\r\n// Has an `L.throttle` shortcut.\r\nfunction throttle(fn, time, context) {\r\n\tvar lock, args, wrapperFn, later;\r\n\r\n\tlater = function () {\r\n\t\t// reset lock and call if queued\r\n\t\tlock = false;\r\n\t\tif (args) {\r\n\t\t\twrapperFn.apply(context, args);\r\n\t\t\targs = false;\r\n\t\t}\r\n\t};\r\n\r\n\twrapperFn = function () {\r\n\t\tif (lock) {\r\n\t\t\t// called too soon, queue to call later\r\n\t\t\targs = arguments;\r\n\r\n\t\t} else {\r\n\t\t\t// call and lock until later\r\n\t\t\tfn.apply(context, arguments);\r\n\t\t\tsetTimeout(later, time);\r\n\t\t\tlock = true;\r\n\t\t}\r\n\t};\r\n\r\n\treturn wrapperFn;\r\n}\r\n\r\n// @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number\r\n// Returns the number `num` modulo `range` in such a way so it lies within\r\n// `range[0]` and `range[1]`. The returned value will be always smaller than\r\n// `range[1]` unless `includeMax` is set to `true`.\r\nfunction wrapNum(x, range, includeMax) {\r\n\tvar max = range[1],\r\n\t min = range[0],\r\n\t d = max - min;\r\n\treturn x === max && includeMax ? x : ((x - min) % d + d) % d + min;\r\n}\r\n\r\n// @function falseFn(): Function\r\n// Returns a function which always returns `false`.\r\nfunction falseFn() { return false; }\r\n\r\n// @function formatNum(num: Number, digits?: Number): Number\r\n// Returns the number `num` rounded to `digits` decimals, or to 6 decimals by default.\r\nfunction formatNum(num, digits) {\r\n\tdigits = (digits === undefined ? 6 : digits);\r\n\treturn +(Math.round(num + ('e+' + digits)) + ('e-' + digits));\r\n}\r\n\r\n// @function trim(str: String): String\r\n// Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)\r\nfunction trim(str) {\r\n\treturn str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '');\r\n}\r\n\r\n// @function splitWords(str: String): String[]\r\n// Trims and splits the string on whitespace and returns the array of parts.\r\nfunction splitWords(str) {\r\n\treturn trim(str).split(/\\s+/);\r\n}\r\n\r\n// @function setOptions(obj: Object, options: Object): Object\r\n// Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.\r\nfunction setOptions(obj, options) {\r\n\tif (!obj.hasOwnProperty('options')) {\r\n\t\tobj.options = obj.options ? create(obj.options) : {};\r\n\t}\r\n\tfor (var i in options) {\r\n\t\tobj.options[i] = options[i];\r\n\t}\r\n\treturn obj.options;\r\n}\r\n\r\n// @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String\r\n// Converts an object into a parameter URL string, e.g. `{a: \"foo\", b: \"bar\"}`\r\n// translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will\r\n// be appended at the end. If `uppercase` is `true`, the parameter names will\r\n// be uppercased (e.g. `'?A=foo&B=bar'`)\r\nfunction getParamString(obj, existingUrl, uppercase) {\r\n\tvar params = [];\r\n\tfor (var i in obj) {\r\n\t\tparams.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));\r\n\t}\r\n\treturn ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');\r\n}\r\n\r\nvar templateRe = /\\{ *([\\w_-]+) *\\}/g;\r\n\r\n// @function template(str: String, data: Object): String\r\n// Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`\r\n// and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string\r\n// `('Hello foo, bar')`. You can also specify functions instead of strings for\r\n// data values — they will be evaluated passing `data` as an argument.\r\nfunction template(str, data) {\r\n\treturn str.replace(templateRe, function (str, key) {\r\n\t\tvar value = data[key];\r\n\r\n\t\tif (value === undefined) {\r\n\t\t\tthrow new Error('No value provided for variable ' + str);\r\n\r\n\t\t} else if (typeof value === 'function') {\r\n\t\t\tvalue = value(data);\r\n\t\t}\r\n\t\treturn value;\r\n\t});\r\n}\r\n\r\n// @function isArray(obj): Boolean\r\n// Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)\r\nvar isArray = Array.isArray || function (obj) {\r\n\treturn (Object.prototype.toString.call(obj) === '[object Array]');\r\n};\r\n\r\n// @function indexOf(array: Array, el: Object): Number\r\n// Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)\r\nfunction indexOf(array, el) {\r\n\tfor (var i = 0; i < array.length; i++) {\r\n\t\tif (array[i] === el) { return i; }\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\n// @property emptyImageUrl: String\r\n// Data URI string containing a base64-encoded empty GIF image.\r\n// Used as a hack to free memory from unused images on WebKit-powered\r\n// mobile devices (by setting image `src` to this string).\r\nvar emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';\r\n\r\n// inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/\r\n\r\nfunction getPrefixed(name) {\r\n\treturn window['webkit' + name] || window['moz' + name] || window['ms' + name];\r\n}\r\n\r\nvar lastTime = 0;\r\n\r\n// fallback for IE 7-8\r\nfunction timeoutDefer(fn) {\r\n\tvar time = +new Date(),\r\n\t timeToCall = Math.max(0, 16 - (time - lastTime));\r\n\r\n\tlastTime = time + timeToCall;\r\n\treturn window.setTimeout(fn, timeToCall);\r\n}\r\n\r\nvar requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;\r\nvar cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||\r\n\t\tgetPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };\r\n\r\n// @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number\r\n// Schedules `fn` to be executed when the browser repaints. `fn` is bound to\r\n// `context` if given. When `immediate` is set, `fn` is called immediately if\r\n// the browser doesn't have native support for\r\n// [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),\r\n// otherwise it's delayed. Returns a request ID that can be used to cancel the request.\r\nfunction requestAnimFrame(fn, context, immediate) {\r\n\tif (immediate && requestFn === timeoutDefer) {\r\n\t\tfn.call(context);\r\n\t} else {\r\n\t\treturn requestFn.call(window, bind(fn, context));\r\n\t}\r\n}\r\n\r\n// @function cancelAnimFrame(id: Number): undefined\r\n// Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).\r\nfunction cancelAnimFrame(id) {\r\n\tif (id) {\r\n\t\tcancelFn.call(window, id);\r\n\t}\r\n}\r\n\n\nvar Util = (Object.freeze || Object)({\n\tfreeze: freeze,\n\textend: extend,\n\tcreate: create,\n\tbind: bind,\n\tlastId: lastId,\n\tstamp: stamp,\n\tthrottle: throttle,\n\twrapNum: wrapNum,\n\tfalseFn: falseFn,\n\tformatNum: formatNum,\n\ttrim: trim,\n\tsplitWords: splitWords,\n\tsetOptions: setOptions,\n\tgetParamString: getParamString,\n\ttemplate: template,\n\tisArray: isArray,\n\tindexOf: indexOf,\n\temptyImageUrl: emptyImageUrl,\n\trequestFn: requestFn,\n\tcancelFn: cancelFn,\n\trequestAnimFrame: requestAnimFrame,\n\tcancelAnimFrame: cancelAnimFrame\n});\n\n// @class Class\r\n// @aka L.Class\r\n\r\n// @section\r\n// @uninheritable\r\n\r\n// Thanks to John Resig and Dean Edwards for inspiration!\r\n\r\nfunction Class() {}\r\n\r\nClass.extend = function (props) {\r\n\r\n\t// @function extend(props: Object): Function\r\n\t// [Extends the current class](#class-inheritance) given the properties to be included.\r\n\t// Returns a Javascript function that is a class constructor (to be called with `new`).\r\n\tvar NewClass = function () {\r\n\r\n\t\t// call the constructor\r\n\t\tif (this.initialize) {\r\n\t\t\tthis.initialize.apply(this, arguments);\r\n\t\t}\r\n\r\n\t\t// call all constructor hooks\r\n\t\tthis.callInitHooks();\r\n\t};\r\n\r\n\tvar parentProto = NewClass.__super__ = this.prototype;\r\n\r\n\tvar proto = create(parentProto);\r\n\tproto.constructor = NewClass;\r\n\r\n\tNewClass.prototype = proto;\r\n\r\n\t// inherit parent's statics\r\n\tfor (var i in this) {\r\n\t\tif (this.hasOwnProperty(i) && i !== 'prototype' && i !== '__super__') {\r\n\t\t\tNewClass[i] = this[i];\r\n\t\t}\r\n\t}\r\n\r\n\t// mix static properties into the class\r\n\tif (props.statics) {\r\n\t\textend(NewClass, props.statics);\r\n\t\tdelete props.statics;\r\n\t}\r\n\r\n\t// mix includes into the prototype\r\n\tif (props.includes) {\r\n\t\tcheckDeprecatedMixinEvents(props.includes);\r\n\t\textend.apply(null, [proto].concat(props.includes));\r\n\t\tdelete props.includes;\r\n\t}\r\n\r\n\t// merge options\r\n\tif (proto.options) {\r\n\t\tprops.options = extend(create(proto.options), props.options);\r\n\t}\r\n\r\n\t// mix given properties into the prototype\r\n\textend(proto, props);\r\n\r\n\tproto._initHooks = [];\r\n\r\n\t// add method for calling all hooks\r\n\tproto.callInitHooks = function () {\r\n\r\n\t\tif (this._initHooksCalled) { return; }\r\n\r\n\t\tif (parentProto.callInitHooks) {\r\n\t\t\tparentProto.callInitHooks.call(this);\r\n\t\t}\r\n\r\n\t\tthis._initHooksCalled = true;\r\n\r\n\t\tfor (var i = 0, len = proto._initHooks.length; i < len; i++) {\r\n\t\t\tproto._initHooks[i].call(this);\r\n\t\t}\r\n\t};\r\n\r\n\treturn NewClass;\r\n};\r\n\r\n\r\n// @function include(properties: Object): this\r\n// [Includes a mixin](#class-includes) into the current class.\r\nClass.include = function (props) {\r\n\textend(this.prototype, props);\r\n\treturn this;\r\n};\r\n\r\n// @function mergeOptions(options: Object): this\r\n// [Merges `options`](#class-options) into the defaults of the class.\r\nClass.mergeOptions = function (options) {\r\n\textend(this.prototype.options, options);\r\n\treturn this;\r\n};\r\n\r\n// @function addInitHook(fn: Function): this\r\n// Adds a [constructor hook](#class-constructor-hooks) to the class.\r\nClass.addInitHook = function (fn) { // (Function) || (String, args...)\r\n\tvar args = Array.prototype.slice.call(arguments, 1);\r\n\r\n\tvar init = typeof fn === 'function' ? fn : function () {\r\n\t\tthis[fn].apply(this, args);\r\n\t};\r\n\r\n\tthis.prototype._initHooks = this.prototype._initHooks || [];\r\n\tthis.prototype._initHooks.push(init);\r\n\treturn this;\r\n};\r\n\r\nfunction checkDeprecatedMixinEvents(includes) {\r\n\tif (typeof L === 'undefined' || !L || !L.Mixin) { return; }\r\n\r\n\tincludes = isArray(includes) ? includes : [includes];\r\n\r\n\tfor (var i = 0; i < includes.length; i++) {\r\n\t\tif (includes[i] === L.Mixin.Events) {\r\n\t\t\tconsole.warn('Deprecated include of L.Mixin.Events: ' +\r\n\t\t\t\t'this property will be removed in future releases, ' +\r\n\t\t\t\t'please inherit from L.Evented instead.', new Error().stack);\r\n\t\t}\r\n\t}\r\n}\n\n/*\r\n * @class Evented\r\n * @aka L.Evented\r\n * @inherits Class\r\n *\r\n * A set of methods shared between event-powered classes (like `Map` and `Marker`). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire `'click'` event).\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * map.on('click', function(e) {\r\n * \talert(e.latlng);\r\n * } );\r\n * ```\r\n *\r\n * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:\r\n *\r\n * ```js\r\n * function onClick(e) { ... }\r\n *\r\n * map.on('click', onClick);\r\n * map.off('click', onClick);\r\n * ```\r\n */\r\n\r\nvar Events = {\r\n\t/* @method on(type: String, fn: Function, context?: Object): this\r\n\t * Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`).\r\n\t *\r\n\t * @alternative\r\n\t * @method on(eventMap: Object): this\r\n\t * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`\r\n\t */\r\n\ton: function (types, fn, context) {\r\n\r\n\t\t// types can be a map of types/handlers\r\n\t\tif (typeof types === 'object') {\r\n\t\t\tfor (var type in types) {\r\n\t\t\t\t// we don't process space-separated events here for performance;\r\n\t\t\t\t// it's a hot path since Layer uses the on(obj) syntax\r\n\t\t\t\tthis._on(type, types[type], fn);\r\n\t\t\t}\r\n\r\n\t\t} else {\r\n\t\t\t// types can be a string of space-separated words\r\n\t\t\ttypes = splitWords(types);\r\n\r\n\t\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\t\tthis._on(types[i], fn, context);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t/* @method off(type: String, fn?: Function, context?: Object): this\r\n\t * Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener.\r\n\t *\r\n\t * @alternative\r\n\t * @method off(eventMap: Object): this\r\n\t * Removes a set of type/listener pairs.\r\n\t *\r\n\t * @alternative\r\n\t * @method off: this\r\n\t * Removes all listeners to all events on the object. This includes implicitly attached events.\r\n\t */\r\n\toff: function (types, fn, context) {\r\n\r\n\t\tif (!types) {\r\n\t\t\t// clear all listeners if called without arguments\r\n\t\t\tdelete this._events;\r\n\r\n\t\t} else if (typeof types === 'object') {\r\n\t\t\tfor (var type in types) {\r\n\t\t\t\tthis._off(type, types[type], fn);\r\n\t\t\t}\r\n\r\n\t\t} else {\r\n\t\t\ttypes = splitWords(types);\r\n\r\n\t\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\t\tthis._off(types[i], fn, context);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// attach listener (without syntactic sugar now)\r\n\t_on: function (type, fn, context) {\r\n\t\tthis._events = this._events || {};\r\n\r\n\t\t/* get/init listeners for type */\r\n\t\tvar typeListeners = this._events[type];\r\n\t\tif (!typeListeners) {\r\n\t\t\ttypeListeners = [];\r\n\t\t\tthis._events[type] = typeListeners;\r\n\t\t}\r\n\r\n\t\tif (context === this) {\r\n\t\t\t// Less memory footprint.\r\n\t\t\tcontext = undefined;\r\n\t\t}\r\n\t\tvar newListener = {fn: fn, ctx: context},\r\n\t\t listeners = typeListeners;\r\n\r\n\t\t// check if fn already there\r\n\t\tfor (var i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\tif (listeners[i].fn === fn && listeners[i].ctx === context) {\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tlisteners.push(newListener);\r\n\t},\r\n\r\n\t_off: function (type, fn, context) {\r\n\t\tvar listeners,\r\n\t\t i,\r\n\t\t len;\r\n\r\n\t\tif (!this._events) { return; }\r\n\r\n\t\tlisteners = this._events[type];\r\n\r\n\t\tif (!listeners) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (!fn) {\r\n\t\t\t// Set all removed listeners to noop so they are not called if remove happens in fire\r\n\t\t\tfor (i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\t\tlisteners[i].fn = falseFn;\r\n\t\t\t}\r\n\t\t\t// clear all listeners for a type if function isn't specified\r\n\t\t\tdelete this._events[type];\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (context === this) {\r\n\t\t\tcontext = undefined;\r\n\t\t}\r\n\r\n\t\tif (listeners) {\r\n\r\n\t\t\t// find fn and remove it\r\n\t\t\tfor (i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\t\tvar l = listeners[i];\r\n\t\t\t\tif (l.ctx !== context) { continue; }\r\n\t\t\t\tif (l.fn === fn) {\r\n\r\n\t\t\t\t\t// set the removed listener to noop so that's not called if remove happens in fire\r\n\t\t\t\t\tl.fn = falseFn;\r\n\r\n\t\t\t\t\tif (this._firingCount) {\r\n\t\t\t\t\t\t/* copy array in case events are being fired */\r\n\t\t\t\t\t\tthis._events[type] = listeners = listeners.slice();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tlisteners.splice(i, 1);\r\n\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t// @method fire(type: String, data?: Object, propagate?: Boolean): this\r\n\t// Fires an event of the specified type. You can optionally provide an data\r\n\t// object — the first argument of the listener function will contain its\r\n\t// properties. The event can optionally be propagated to event parents.\r\n\tfire: function (type, data, propagate) {\r\n\t\tif (!this.listens(type, propagate)) { return this; }\r\n\r\n\t\tvar event = extend({}, data, {\r\n\t\t\ttype: type,\r\n\t\t\ttarget: this,\r\n\t\t\tsourceTarget: data && data.sourceTarget || this\r\n\t\t});\r\n\r\n\t\tif (this._events) {\r\n\t\t\tvar listeners = this._events[type];\r\n\r\n\t\t\tif (listeners) {\r\n\t\t\t\tthis._firingCount = (this._firingCount + 1) || 1;\r\n\t\t\t\tfor (var i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\t\t\tvar l = listeners[i];\r\n\t\t\t\t\tl.fn.call(l.ctx || this, event);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tthis._firingCount--;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (propagate) {\r\n\t\t\t// propagate the event to parents (set with addEventParent)\r\n\t\t\tthis._propagateEvent(event);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method listens(type: String): Boolean\r\n\t// Returns `true` if a particular event type has any listeners attached to it.\r\n\tlistens: function (type, propagate) {\r\n\t\tvar listeners = this._events && this._events[type];\r\n\t\tif (listeners && listeners.length) { return true; }\r\n\r\n\t\tif (propagate) {\r\n\t\t\t// also check parents for listeners if event propagates\r\n\t\t\tfor (var id in this._eventParents) {\r\n\t\t\t\tif (this._eventParents[id].listens(type, propagate)) { return true; }\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t},\r\n\r\n\t// @method once(…): this\r\n\t// Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.\r\n\tonce: function (types, fn, context) {\r\n\r\n\t\tif (typeof types === 'object') {\r\n\t\t\tfor (var type in types) {\r\n\t\t\t\tthis.once(type, types[type], fn);\r\n\t\t\t}\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tvar handler = bind(function () {\r\n\t\t\tthis\r\n\t\t\t .off(types, fn, context)\r\n\t\t\t .off(types, handler, context);\r\n\t\t}, this);\r\n\r\n\t\t// add a listener that's executed once and removed after that\r\n\t\treturn this\r\n\t\t .on(types, fn, context)\r\n\t\t .on(types, handler, context);\r\n\t},\r\n\r\n\t// @method addEventParent(obj: Evented): this\r\n\t// Adds an event parent - an `Evented` that will receive propagated events\r\n\taddEventParent: function (obj) {\r\n\t\tthis._eventParents = this._eventParents || {};\r\n\t\tthis._eventParents[stamp(obj)] = obj;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeEventParent(obj: Evented): this\r\n\t// Removes an event parent, so it will stop receiving propagated events\r\n\tremoveEventParent: function (obj) {\r\n\t\tif (this._eventParents) {\r\n\t\t\tdelete this._eventParents[stamp(obj)];\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_propagateEvent: function (e) {\r\n\t\tfor (var id in this._eventParents) {\r\n\t\t\tthis._eventParents[id].fire(e.type, extend({\r\n\t\t\t\tlayer: e.target,\r\n\t\t\t\tpropagatedFrom: e.target\r\n\t\t\t}, e), true);\r\n\t\t}\r\n\t}\r\n};\r\n\r\n// aliases; we should ditch those eventually\r\n\r\n// @method addEventListener(…): this\r\n// Alias to [`on(…)`](#evented-on)\r\nEvents.addEventListener = Events.on;\r\n\r\n// @method removeEventListener(…): this\r\n// Alias to [`off(…)`](#evented-off)\r\n\r\n// @method clearAllEventListeners(…): this\r\n// Alias to [`off()`](#evented-off)\r\nEvents.removeEventListener = Events.clearAllEventListeners = Events.off;\r\n\r\n// @method addOneTimeEventListener(…): this\r\n// Alias to [`once(…)`](#evented-once)\r\nEvents.addOneTimeEventListener = Events.once;\r\n\r\n// @method fireEvent(…): this\r\n// Alias to [`fire(…)`](#evented-fire)\r\nEvents.fireEvent = Events.fire;\r\n\r\n// @method hasEventListeners(…): Boolean\r\n// Alias to [`listens(…)`](#evented-listens)\r\nEvents.hasEventListeners = Events.listens;\r\n\r\nvar Evented = Class.extend(Events);\n\n/*\r\n * @class Point\r\n * @aka L.Point\r\n *\r\n * Represents a point with `x` and `y` coordinates in pixels.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var point = L.point(200, 300);\r\n * ```\r\n *\r\n * All Leaflet methods and options that accept `Point` objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent:\r\n *\r\n * ```js\r\n * map.panBy([200, 300]);\r\n * map.panBy(L.point(200, 300));\r\n * ```\r\n *\r\n * Note that `Point` does not inherit from Leafet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nfunction Point(x, y, round) {\r\n\t// @property x: Number; The `x` coordinate of the point\r\n\tthis.x = (round ? Math.round(x) : x);\r\n\t// @property y: Number; The `y` coordinate of the point\r\n\tthis.y = (round ? Math.round(y) : y);\r\n}\r\n\r\nvar trunc = Math.trunc || function (v) {\r\n\treturn v > 0 ? Math.floor(v) : Math.ceil(v);\r\n};\r\n\r\nPoint.prototype = {\r\n\r\n\t// @method clone(): Point\r\n\t// Returns a copy of the current point.\r\n\tclone: function () {\r\n\t\treturn new Point(this.x, this.y);\r\n\t},\r\n\r\n\t// @method add(otherPoint: Point): Point\r\n\t// Returns the result of addition of the current and the given points.\r\n\tadd: function (point) {\r\n\t\t// non-destructive, returns a new point\r\n\t\treturn this.clone()._add(toPoint(point));\r\n\t},\r\n\r\n\t_add: function (point) {\r\n\t\t// destructive, used directly for performance in situations where it's safe to modify existing point\r\n\t\tthis.x += point.x;\r\n\t\tthis.y += point.y;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method subtract(otherPoint: Point): Point\r\n\t// Returns the result of subtraction of the given point from the current.\r\n\tsubtract: function (point) {\r\n\t\treturn this.clone()._subtract(toPoint(point));\r\n\t},\r\n\r\n\t_subtract: function (point) {\r\n\t\tthis.x -= point.x;\r\n\t\tthis.y -= point.y;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method divideBy(num: Number): Point\r\n\t// Returns the result of division of the current point by the given number.\r\n\tdivideBy: function (num) {\r\n\t\treturn this.clone()._divideBy(num);\r\n\t},\r\n\r\n\t_divideBy: function (num) {\r\n\t\tthis.x /= num;\r\n\t\tthis.y /= num;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method multiplyBy(num: Number): Point\r\n\t// Returns the result of multiplication of the current point by the given number.\r\n\tmultiplyBy: function (num) {\r\n\t\treturn this.clone()._multiplyBy(num);\r\n\t},\r\n\r\n\t_multiplyBy: function (num) {\r\n\t\tthis.x *= num;\r\n\t\tthis.y *= num;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method scaleBy(scale: Point): Point\r\n\t// Multiply each coordinate of the current point by each coordinate of\r\n\t// `scale`. In linear algebra terms, multiply the point by the\r\n\t// [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)\r\n\t// defined by `scale`.\r\n\tscaleBy: function (point) {\r\n\t\treturn new Point(this.x * point.x, this.y * point.y);\r\n\t},\r\n\r\n\t// @method unscaleBy(scale: Point): Point\r\n\t// Inverse of `scaleBy`. Divide each coordinate of the current point by\r\n\t// each coordinate of `scale`.\r\n\tunscaleBy: function (point) {\r\n\t\treturn new Point(this.x / point.x, this.y / point.y);\r\n\t},\r\n\r\n\t// @method round(): Point\r\n\t// Returns a copy of the current point with rounded coordinates.\r\n\tround: function () {\r\n\t\treturn this.clone()._round();\r\n\t},\r\n\r\n\t_round: function () {\r\n\t\tthis.x = Math.round(this.x);\r\n\t\tthis.y = Math.round(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method floor(): Point\r\n\t// Returns a copy of the current point with floored coordinates (rounded down).\r\n\tfloor: function () {\r\n\t\treturn this.clone()._floor();\r\n\t},\r\n\r\n\t_floor: function () {\r\n\t\tthis.x = Math.floor(this.x);\r\n\t\tthis.y = Math.floor(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method ceil(): Point\r\n\t// Returns a copy of the current point with ceiled coordinates (rounded up).\r\n\tceil: function () {\r\n\t\treturn this.clone()._ceil();\r\n\t},\r\n\r\n\t_ceil: function () {\r\n\t\tthis.x = Math.ceil(this.x);\r\n\t\tthis.y = Math.ceil(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method trunc(): Point\r\n\t// Returns a copy of the current point with truncated coordinates (rounded towards zero).\r\n\ttrunc: function () {\r\n\t\treturn this.clone()._trunc();\r\n\t},\r\n\r\n\t_trunc: function () {\r\n\t\tthis.x = trunc(this.x);\r\n\t\tthis.y = trunc(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method distanceTo(otherPoint: Point): Number\r\n\t// Returns the cartesian distance between the current and the given points.\r\n\tdistanceTo: function (point) {\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\tvar x = point.x - this.x,\r\n\t\t y = point.y - this.y;\r\n\r\n\t\treturn Math.sqrt(x * x + y * y);\r\n\t},\r\n\r\n\t// @method equals(otherPoint: Point): Boolean\r\n\t// Returns `true` if the given point has the same coordinates.\r\n\tequals: function (point) {\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\treturn point.x === this.x &&\r\n\t\t point.y === this.y;\r\n\t},\r\n\r\n\t// @method contains(otherPoint: Point): Boolean\r\n\t// Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).\r\n\tcontains: function (point) {\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\treturn Math.abs(point.x) <= Math.abs(this.x) &&\r\n\t\t Math.abs(point.y) <= Math.abs(this.y);\r\n\t},\r\n\r\n\t// @method toString(): String\r\n\t// Returns a string representation of the point for debugging purposes.\r\n\ttoString: function () {\r\n\t\treturn 'Point(' +\r\n\t\t formatNum(this.x) + ', ' +\r\n\t\t formatNum(this.y) + ')';\r\n\t}\r\n};\r\n\r\n// @factory L.point(x: Number, y: Number, round?: Boolean)\r\n// Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.\r\n\r\n// @alternative\r\n// @factory L.point(coords: Number[])\r\n// Expects an array of the form `[x, y]` instead.\r\n\r\n// @alternative\r\n// @factory L.point(coords: Object)\r\n// Expects a plain object of the form `{x: Number, y: Number}` instead.\r\nfunction toPoint(x, y, round) {\r\n\tif (x instanceof Point) {\r\n\t\treturn x;\r\n\t}\r\n\tif (isArray(x)) {\r\n\t\treturn new Point(x[0], x[1]);\r\n\t}\r\n\tif (x === undefined || x === null) {\r\n\t\treturn x;\r\n\t}\r\n\tif (typeof x === 'object' && 'x' in x && 'y' in x) {\r\n\t\treturn new Point(x.x, x.y);\r\n\t}\r\n\treturn new Point(x, y, round);\r\n}\n\n/*\r\n * @class Bounds\r\n * @aka L.Bounds\r\n *\r\n * Represents a rectangular area in pixel coordinates.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var p1 = L.point(10, 10),\r\n * p2 = L.point(40, 60),\r\n * bounds = L.bounds(p1, p2);\r\n * ```\r\n *\r\n * All Leaflet methods that accept `Bounds` objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:\r\n *\r\n * ```js\r\n * otherBounds.intersects([[10, 10], [40, 60]]);\r\n * ```\r\n *\r\n * Note that `Bounds` does not inherit from Leafet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nfunction Bounds(a, b) {\r\n\tif (!a) { return; }\r\n\r\n\tvar points = b ? [a, b] : a;\r\n\r\n\tfor (var i = 0, len = points.length; i < len; i++) {\r\n\t\tthis.extend(points[i]);\r\n\t}\r\n}\r\n\r\nBounds.prototype = {\r\n\t// @method extend(point: Point): this\r\n\t// Extends the bounds to contain the given point.\r\n\textend: function (point) { // (Point)\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\t// @property min: Point\r\n\t\t// The top left corner of the rectangle.\r\n\t\t// @property max: Point\r\n\t\t// The bottom right corner of the rectangle.\r\n\t\tif (!this.min && !this.max) {\r\n\t\t\tthis.min = point.clone();\r\n\t\t\tthis.max = point.clone();\r\n\t\t} else {\r\n\t\t\tthis.min.x = Math.min(point.x, this.min.x);\r\n\t\t\tthis.max.x = Math.max(point.x, this.max.x);\r\n\t\t\tthis.min.y = Math.min(point.y, this.min.y);\r\n\t\t\tthis.max.y = Math.max(point.y, this.max.y);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getCenter(round?: Boolean): Point\r\n\t// Returns the center point of the bounds.\r\n\tgetCenter: function (round) {\r\n\t\treturn new Point(\r\n\t\t (this.min.x + this.max.x) / 2,\r\n\t\t (this.min.y + this.max.y) / 2, round);\r\n\t},\r\n\r\n\t// @method getBottomLeft(): Point\r\n\t// Returns the bottom-left point of the bounds.\r\n\tgetBottomLeft: function () {\r\n\t\treturn new Point(this.min.x, this.max.y);\r\n\t},\r\n\r\n\t// @method getTopRight(): Point\r\n\t// Returns the top-right point of the bounds.\r\n\tgetTopRight: function () { // -> Point\r\n\t\treturn new Point(this.max.x, this.min.y);\r\n\t},\r\n\r\n\t// @method getTopLeft(): Point\r\n\t// Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).\r\n\tgetTopLeft: function () {\r\n\t\treturn this.min; // left, top\r\n\t},\r\n\r\n\t// @method getBottomRight(): Point\r\n\t// Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).\r\n\tgetBottomRight: function () {\r\n\t\treturn this.max; // right, bottom\r\n\t},\r\n\r\n\t// @method getSize(): Point\r\n\t// Returns the size of the given bounds\r\n\tgetSize: function () {\r\n\t\treturn this.max.subtract(this.min);\r\n\t},\r\n\r\n\t// @method contains(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle contains the given one.\r\n\t// @alternative\r\n\t// @method contains(point: Point): Boolean\r\n\t// Returns `true` if the rectangle contains the given point.\r\n\tcontains: function (obj) {\r\n\t\tvar min, max;\r\n\r\n\t\tif (typeof obj[0] === 'number' || obj instanceof Point) {\r\n\t\t\tobj = toPoint(obj);\r\n\t\t} else {\r\n\t\t\tobj = toBounds(obj);\r\n\t\t}\r\n\r\n\t\tif (obj instanceof Bounds) {\r\n\t\t\tmin = obj.min;\r\n\t\t\tmax = obj.max;\r\n\t\t} else {\r\n\t\t\tmin = max = obj;\r\n\t\t}\r\n\r\n\t\treturn (min.x >= this.min.x) &&\r\n\t\t (max.x <= this.max.x) &&\r\n\t\t (min.y >= this.min.y) &&\r\n\t\t (max.y <= this.max.y);\r\n\t},\r\n\r\n\t// @method intersects(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle intersects the given bounds. Two bounds\r\n\t// intersect if they have at least one point in common.\r\n\tintersects: function (bounds) { // (Bounds) -> Boolean\r\n\t\tbounds = toBounds(bounds);\r\n\r\n\t\tvar min = this.min,\r\n\t\t max = this.max,\r\n\t\t min2 = bounds.min,\r\n\t\t max2 = bounds.max,\r\n\t\t xIntersects = (max2.x >= min.x) && (min2.x <= max.x),\r\n\t\t yIntersects = (max2.y >= min.y) && (min2.y <= max.y);\r\n\r\n\t\treturn xIntersects && yIntersects;\r\n\t},\r\n\r\n\t// @method overlaps(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle overlaps the given bounds. Two bounds\r\n\t// overlap if their intersection is an area.\r\n\toverlaps: function (bounds) { // (Bounds) -> Boolean\r\n\t\tbounds = toBounds(bounds);\r\n\r\n\t\tvar min = this.min,\r\n\t\t max = this.max,\r\n\t\t min2 = bounds.min,\r\n\t\t max2 = bounds.max,\r\n\t\t xOverlaps = (max2.x > min.x) && (min2.x < max.x),\r\n\t\t yOverlaps = (max2.y > min.y) && (min2.y < max.y);\r\n\r\n\t\treturn xOverlaps && yOverlaps;\r\n\t},\r\n\r\n\tisValid: function () {\r\n\t\treturn !!(this.min && this.max);\r\n\t}\r\n};\r\n\r\n\r\n// @factory L.bounds(corner1: Point, corner2: Point)\r\n// Creates a Bounds object from two corners coordinate pairs.\r\n// @alternative\r\n// @factory L.bounds(points: Point[])\r\n// Creates a Bounds object from the given array of points.\r\nfunction toBounds(a, b) {\r\n\tif (!a || a instanceof Bounds) {\r\n\t\treturn a;\r\n\t}\r\n\treturn new Bounds(a, b);\r\n}\n\n/*\r\n * @class LatLngBounds\r\n * @aka L.LatLngBounds\r\n *\r\n * Represents a rectangular geographical area on a map.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var corner1 = L.latLng(40.712, -74.227),\r\n * corner2 = L.latLng(40.774, -74.125),\r\n * bounds = L.latLngBounds(corner1, corner2);\r\n * ```\r\n *\r\n * All Leaflet methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:\r\n *\r\n * ```js\r\n * map.fitBounds([\r\n * \t[40.712, -74.227],\r\n * \t[40.774, -74.125]\r\n * ]);\r\n * ```\r\n *\r\n * Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners _outside_ the [-180, 180] degrees longitude range.\r\n *\r\n * Note that `LatLngBounds` does not inherit from Leafet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nfunction LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])\r\n\tif (!corner1) { return; }\r\n\r\n\tvar latlngs = corner2 ? [corner1, corner2] : corner1;\r\n\r\n\tfor (var i = 0, len = latlngs.length; i < len; i++) {\r\n\t\tthis.extend(latlngs[i]);\r\n\t}\r\n}\r\n\r\nLatLngBounds.prototype = {\r\n\r\n\t// @method extend(latlng: LatLng): this\r\n\t// Extend the bounds to contain the given point\r\n\r\n\t// @alternative\r\n\t// @method extend(otherBounds: LatLngBounds): this\r\n\t// Extend the bounds to contain the given bounds\r\n\textend: function (obj) {\r\n\t\tvar sw = this._southWest,\r\n\t\t ne = this._northEast,\r\n\t\t sw2, ne2;\r\n\r\n\t\tif (obj instanceof LatLng) {\r\n\t\t\tsw2 = obj;\r\n\t\t\tne2 = obj;\r\n\r\n\t\t} else if (obj instanceof LatLngBounds) {\r\n\t\t\tsw2 = obj._southWest;\r\n\t\t\tne2 = obj._northEast;\r\n\r\n\t\t\tif (!sw2 || !ne2) { return this; }\r\n\r\n\t\t} else {\r\n\t\t\treturn obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;\r\n\t\t}\r\n\r\n\t\tif (!sw && !ne) {\r\n\t\t\tthis._southWest = new LatLng(sw2.lat, sw2.lng);\r\n\t\t\tthis._northEast = new LatLng(ne2.lat, ne2.lng);\r\n\t\t} else {\r\n\t\t\tsw.lat = Math.min(sw2.lat, sw.lat);\r\n\t\t\tsw.lng = Math.min(sw2.lng, sw.lng);\r\n\t\t\tne.lat = Math.max(ne2.lat, ne.lat);\r\n\t\t\tne.lng = Math.max(ne2.lng, ne.lng);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method pad(bufferRatio: Number): LatLngBounds\r\n\t// Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.\r\n\t// For example, a ratio of 0.5 extends the bounds by 50% in each direction.\r\n\t// Negative values will retract the bounds.\r\n\tpad: function (bufferRatio) {\r\n\t\tvar sw = this._southWest,\r\n\t\t ne = this._northEast,\r\n\t\t heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,\r\n\t\t widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;\r\n\r\n\t\treturn new LatLngBounds(\r\n\t\t new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),\r\n\t\t new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));\r\n\t},\r\n\r\n\t// @method getCenter(): LatLng\r\n\t// Returns the center point of the bounds.\r\n\tgetCenter: function () {\r\n\t\treturn new LatLng(\r\n\t\t (this._southWest.lat + this._northEast.lat) / 2,\r\n\t\t (this._southWest.lng + this._northEast.lng) / 2);\r\n\t},\r\n\r\n\t// @method getSouthWest(): LatLng\r\n\t// Returns the south-west point of the bounds.\r\n\tgetSouthWest: function () {\r\n\t\treturn this._southWest;\r\n\t},\r\n\r\n\t// @method getNorthEast(): LatLng\r\n\t// Returns the north-east point of the bounds.\r\n\tgetNorthEast: function () {\r\n\t\treturn this._northEast;\r\n\t},\r\n\r\n\t// @method getNorthWest(): LatLng\r\n\t// Returns the north-west point of the bounds.\r\n\tgetNorthWest: function () {\r\n\t\treturn new LatLng(this.getNorth(), this.getWest());\r\n\t},\r\n\r\n\t// @method getSouthEast(): LatLng\r\n\t// Returns the south-east point of the bounds.\r\n\tgetSouthEast: function () {\r\n\t\treturn new LatLng(this.getSouth(), this.getEast());\r\n\t},\r\n\r\n\t// @method getWest(): Number\r\n\t// Returns the west longitude of the bounds\r\n\tgetWest: function () {\r\n\t\treturn this._southWest.lng;\r\n\t},\r\n\r\n\t// @method getSouth(): Number\r\n\t// Returns the south latitude of the bounds\r\n\tgetSouth: function () {\r\n\t\treturn this._southWest.lat;\r\n\t},\r\n\r\n\t// @method getEast(): Number\r\n\t// Returns the east longitude of the bounds\r\n\tgetEast: function () {\r\n\t\treturn this._northEast.lng;\r\n\t},\r\n\r\n\t// @method getNorth(): Number\r\n\t// Returns the north latitude of the bounds\r\n\tgetNorth: function () {\r\n\t\treturn this._northEast.lat;\r\n\t},\r\n\r\n\t// @method contains(otherBounds: LatLngBounds): Boolean\r\n\t// Returns `true` if the rectangle contains the given one.\r\n\r\n\t// @alternative\r\n\t// @method contains (latlng: LatLng): Boolean\r\n\t// Returns `true` if the rectangle contains the given point.\r\n\tcontains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean\r\n\t\tif (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {\r\n\t\t\tobj = toLatLng(obj);\r\n\t\t} else {\r\n\t\t\tobj = toLatLngBounds(obj);\r\n\t\t}\r\n\r\n\t\tvar sw = this._southWest,\r\n\t\t ne = this._northEast,\r\n\t\t sw2, ne2;\r\n\r\n\t\tif (obj instanceof LatLngBounds) {\r\n\t\t\tsw2 = obj.getSouthWest();\r\n\t\t\tne2 = obj.getNorthEast();\r\n\t\t} else {\r\n\t\t\tsw2 = ne2 = obj;\r\n\t\t}\r\n\r\n\t\treturn (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&\r\n\t\t (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);\r\n\t},\r\n\r\n\t// @method intersects(otherBounds: LatLngBounds): Boolean\r\n\t// Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.\r\n\tintersects: function (bounds) {\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tvar sw = this._southWest,\r\n\t\t ne = this._northEast,\r\n\t\t sw2 = bounds.getSouthWest(),\r\n\t\t ne2 = bounds.getNorthEast(),\r\n\r\n\t\t latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),\r\n\t\t lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);\r\n\r\n\t\treturn latIntersects && lngIntersects;\r\n\t},\r\n\r\n\t// @method overlaps(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.\r\n\toverlaps: function (bounds) {\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tvar sw = this._southWest,\r\n\t\t ne = this._northEast,\r\n\t\t sw2 = bounds.getSouthWest(),\r\n\t\t ne2 = bounds.getNorthEast(),\r\n\r\n\t\t latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),\r\n\t\t lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);\r\n\r\n\t\treturn latOverlaps && lngOverlaps;\r\n\t},\r\n\r\n\t// @method toBBoxString(): String\r\n\t// Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data.\r\n\ttoBBoxString: function () {\r\n\t\treturn [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');\r\n\t},\r\n\r\n\t// @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean\r\n\t// Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number.\r\n\tequals: function (bounds, maxMargin) {\r\n\t\tif (!bounds) { return false; }\r\n\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\treturn this._southWest.equals(bounds.getSouthWest(), maxMargin) &&\r\n\t\t this._northEast.equals(bounds.getNorthEast(), maxMargin);\r\n\t},\r\n\r\n\t// @method isValid(): Boolean\r\n\t// Returns `true` if the bounds are properly initialized.\r\n\tisValid: function () {\r\n\t\treturn !!(this._southWest && this._northEast);\r\n\t}\r\n};\r\n\r\n// TODO International date line?\r\n\r\n// @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)\r\n// Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.\r\n\r\n// @alternative\r\n// @factory L.latLngBounds(latlngs: LatLng[])\r\n// Creates a `LatLngBounds` object defined by the geographical points it contains. Very useful for zooming the map to fit a particular set of locations with [`fitBounds`](#map-fitbounds).\r\nfunction toLatLngBounds(a, b) {\r\n\tif (a instanceof LatLngBounds) {\r\n\t\treturn a;\r\n\t}\r\n\treturn new LatLngBounds(a, b);\r\n}\n\n/* @class LatLng\r\n * @aka L.LatLng\r\n *\r\n * Represents a geographical point with a certain latitude and longitude.\r\n *\r\n * @example\r\n *\r\n * ```\r\n * var latlng = L.latLng(50.5, 30.5);\r\n * ```\r\n *\r\n * All Leaflet methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent:\r\n *\r\n * ```\r\n * map.panTo([50, 30]);\r\n * map.panTo({lon: 30, lat: 50});\r\n * map.panTo({lat: 50, lng: 30});\r\n * map.panTo(L.latLng(50, 30));\r\n * ```\r\n *\r\n * Note that `LatLng` does not inherit from Leaflet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nfunction LatLng(lat, lng, alt) {\r\n\tif (isNaN(lat) || isNaN(lng)) {\r\n\t\tthrow new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');\r\n\t}\r\n\r\n\t// @property lat: Number\r\n\t// Latitude in degrees\r\n\tthis.lat = +lat;\r\n\r\n\t// @property lng: Number\r\n\t// Longitude in degrees\r\n\tthis.lng = +lng;\r\n\r\n\t// @property alt: Number\r\n\t// Altitude in meters (optional)\r\n\tif (alt !== undefined) {\r\n\t\tthis.alt = +alt;\r\n\t}\r\n}\r\n\r\nLatLng.prototype = {\r\n\t// @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean\r\n\t// Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number.\r\n\tequals: function (obj, maxMargin) {\r\n\t\tif (!obj) { return false; }\r\n\r\n\t\tobj = toLatLng(obj);\r\n\r\n\t\tvar margin = Math.max(\r\n\t\t Math.abs(this.lat - obj.lat),\r\n\t\t Math.abs(this.lng - obj.lng));\r\n\r\n\t\treturn margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);\r\n\t},\r\n\r\n\t// @method toString(): String\r\n\t// Returns a string representation of the point (for debugging purposes).\r\n\ttoString: function (precision) {\r\n\t\treturn 'LatLng(' +\r\n\t\t formatNum(this.lat, precision) + ', ' +\r\n\t\t formatNum(this.lng, precision) + ')';\r\n\t},\r\n\r\n\t// @method distanceTo(otherLatLng: LatLng): Number\r\n\t// Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines).\r\n\tdistanceTo: function (other) {\r\n\t\treturn Earth.distance(this, toLatLng(other));\r\n\t},\r\n\r\n\t// @method wrap(): LatLng\r\n\t// Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.\r\n\twrap: function () {\r\n\t\treturn Earth.wrapLatLng(this);\r\n\t},\r\n\r\n\t// @method toBounds(sizeInMeters: Number): LatLngBounds\r\n\t// Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.\r\n\ttoBounds: function (sizeInMeters) {\r\n\t\tvar latAccuracy = 180 * sizeInMeters / 40075017,\r\n\t\t lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);\r\n\r\n\t\treturn toLatLngBounds(\r\n\t\t [this.lat - latAccuracy, this.lng - lngAccuracy],\r\n\t\t [this.lat + latAccuracy, this.lng + lngAccuracy]);\r\n\t},\r\n\r\n\tclone: function () {\r\n\t\treturn new LatLng(this.lat, this.lng, this.alt);\r\n\t}\r\n};\r\n\r\n\r\n\r\n// @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng\r\n// Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).\r\n\r\n// @alternative\r\n// @factory L.latLng(coords: Array): LatLng\r\n// Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.\r\n\r\n// @alternative\r\n// @factory L.latLng(coords: Object): LatLng\r\n// Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.\r\n\r\nfunction toLatLng(a, b, c) {\r\n\tif (a instanceof LatLng) {\r\n\t\treturn a;\r\n\t}\r\n\tif (isArray(a) && typeof a[0] !== 'object') {\r\n\t\tif (a.length === 3) {\r\n\t\t\treturn new LatLng(a[0], a[1], a[2]);\r\n\t\t}\r\n\t\tif (a.length === 2) {\r\n\t\t\treturn new LatLng(a[0], a[1]);\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\tif (a === undefined || a === null) {\r\n\t\treturn a;\r\n\t}\r\n\tif (typeof a === 'object' && 'lat' in a) {\r\n\t\treturn new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);\r\n\t}\r\n\tif (b === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\treturn new LatLng(a, b, c);\r\n}\n\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.Base\r\n * Object that defines coordinate reference systems for projecting\r\n * geographical points into pixel (screen) coordinates and back (and to\r\n * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See\r\n * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).\r\n *\r\n * Leaflet defines the most usual CRSs by default. If you want to use a\r\n * CRS not defined by default, take a look at the\r\n * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.\r\n *\r\n * Note that the CRS instances do not inherit from Leafet's `Class` object,\r\n * and can't be instantiated. Also, new classes can't inherit from them,\r\n * and methods can't be added to them with the `include` function.\r\n */\r\n\r\nvar CRS = {\r\n\t// @method latLngToPoint(latlng: LatLng, zoom: Number): Point\r\n\t// Projects geographical coordinates into pixel coordinates for a given zoom.\r\n\tlatLngToPoint: function (latlng, zoom) {\r\n\t\tvar projectedPoint = this.projection.project(latlng),\r\n\t\t scale = this.scale(zoom);\r\n\r\n\t\treturn this.transformation._transform(projectedPoint, scale);\r\n\t},\r\n\r\n\t// @method pointToLatLng(point: Point, zoom: Number): LatLng\r\n\t// The inverse of `latLngToPoint`. Projects pixel coordinates on a given\r\n\t// zoom into geographical coordinates.\r\n\tpointToLatLng: function (point, zoom) {\r\n\t\tvar scale = this.scale(zoom),\r\n\t\t untransformedPoint = this.transformation.untransform(point, scale);\r\n\r\n\t\treturn this.projection.unproject(untransformedPoint);\r\n\t},\r\n\r\n\t// @method project(latlng: LatLng): Point\r\n\t// Projects geographical coordinates into coordinates in units accepted for\r\n\t// this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).\r\n\tproject: function (latlng) {\r\n\t\treturn this.projection.project(latlng);\r\n\t},\r\n\r\n\t// @method unproject(point: Point): LatLng\r\n\t// Given a projected coordinate returns the corresponding LatLng.\r\n\t// The inverse of `project`.\r\n\tunproject: function (point) {\r\n\t\treturn this.projection.unproject(point);\r\n\t},\r\n\r\n\t// @method scale(zoom: Number): Number\r\n\t// Returns the scale used when transforming projected coordinates into\r\n\t// pixel coordinates for a particular zoom. For example, it returns\r\n\t// `256 * 2^zoom` for Mercator-based CRS.\r\n\tscale: function (zoom) {\r\n\t\treturn 256 * Math.pow(2, zoom);\r\n\t},\r\n\r\n\t// @method zoom(scale: Number): Number\r\n\t// Inverse of `scale()`, returns the zoom level corresponding to a scale\r\n\t// factor of `scale`.\r\n\tzoom: function (scale) {\r\n\t\treturn Math.log(scale / 256) / Math.LN2;\r\n\t},\r\n\r\n\t// @method getProjectedBounds(zoom: Number): Bounds\r\n\t// Returns the projection's bounds scaled and transformed for the provided `zoom`.\r\n\tgetProjectedBounds: function (zoom) {\r\n\t\tif (this.infinite) { return null; }\r\n\r\n\t\tvar b = this.projection.bounds,\r\n\t\t s = this.scale(zoom),\r\n\t\t min = this.transformation.transform(b.min, s),\r\n\t\t max = this.transformation.transform(b.max, s);\r\n\r\n\t\treturn new Bounds(min, max);\r\n\t},\r\n\r\n\t// @method distance(latlng1: LatLng, latlng2: LatLng): Number\r\n\t// Returns the distance between two geographical coordinates.\r\n\r\n\t// @property code: String\r\n\t// Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)\r\n\t//\r\n\t// @property wrapLng: Number[]\r\n\t// An array of two numbers defining whether the longitude (horizontal) coordinate\r\n\t// axis wraps around a given range and how. Defaults to `[-180, 180]` in most\r\n\t// geographical CRSs. If `undefined`, the longitude axis does not wrap around.\r\n\t//\r\n\t// @property wrapLat: Number[]\r\n\t// Like `wrapLng`, but for the latitude (vertical) axis.\r\n\r\n\t// wrapLng: [min, max],\r\n\t// wrapLat: [min, max],\r\n\r\n\t// @property infinite: Boolean\r\n\t// If true, the coordinate space will be unbounded (infinite in both axes)\r\n\tinfinite: false,\r\n\r\n\t// @method wrapLatLng(latlng: LatLng): LatLng\r\n\t// Returns a `LatLng` where lat and lng has been wrapped according to the\r\n\t// CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.\r\n\twrapLatLng: function (latlng) {\r\n\t\tvar lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,\r\n\t\t lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,\r\n\t\t alt = latlng.alt;\r\n\r\n\t\treturn new LatLng(lat, lng, alt);\r\n\t},\r\n\r\n\t// @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds\r\n\t// Returns a `LatLngBounds` with the same size as the given one, ensuring\r\n\t// that its center is within the CRS's bounds.\r\n\t// Only accepts actual `L.LatLngBounds` instances, not arrays.\r\n\twrapLatLngBounds: function (bounds) {\r\n\t\tvar center = bounds.getCenter(),\r\n\t\t newCenter = this.wrapLatLng(center),\r\n\t\t latShift = center.lat - newCenter.lat,\r\n\t\t lngShift = center.lng - newCenter.lng;\r\n\r\n\t\tif (latShift === 0 && lngShift === 0) {\r\n\t\t\treturn bounds;\r\n\t\t}\r\n\r\n\t\tvar sw = bounds.getSouthWest(),\r\n\t\t ne = bounds.getNorthEast(),\r\n\t\t newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),\r\n\t\t newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);\r\n\r\n\t\treturn new LatLngBounds(newSw, newNe);\r\n\t}\r\n};\n\n/*\n * @namespace CRS\n * @crs L.CRS.Earth\n *\n * Serves as the base for CRS that are global such that they cover the earth.\n * Can only be used as the base for other CRS and cannot be used directly,\n * since it does not have a `code`, `projection` or `transformation`. `distance()` returns\n * meters.\n */\n\nvar Earth = extend({}, CRS, {\n\twrapLng: [-180, 180],\n\n\t// Mean Earth Radius, as recommended for use by\n\t// the International Union of Geodesy and Geophysics,\n\t// see http://rosettacode.org/wiki/Haversine_formula\n\tR: 6371000,\n\n\t// distance between two geographical points using spherical law of cosines approximation\n\tdistance: function (latlng1, latlng2) {\n\t\tvar rad = Math.PI / 180,\n\t\t lat1 = latlng1.lat * rad,\n\t\t lat2 = latlng2.lat * rad,\n\t\t sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),\n\t\t sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),\n\t\t a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,\n\t\t c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\t\treturn this.R * c;\n\t}\n});\n\n/*\r\n * @namespace Projection\r\n * @projection L.Projection.SphericalMercator\r\n *\r\n * Spherical Mercator projection — the most common projection for online maps,\r\n * used by almost all free and commercial tile providers. Assumes that Earth is\r\n * a sphere. Used by the `EPSG:3857` CRS.\r\n */\r\n\r\nvar earthRadius = 6378137;\r\n\r\nvar SphericalMercator = {\r\n\r\n\tR: earthRadius,\r\n\tMAX_LATITUDE: 85.0511287798,\r\n\r\n\tproject: function (latlng) {\r\n\t\tvar d = Math.PI / 180,\r\n\t\t max = this.MAX_LATITUDE,\r\n\t\t lat = Math.max(Math.min(max, latlng.lat), -max),\r\n\t\t sin = Math.sin(lat * d);\r\n\r\n\t\treturn new Point(\r\n\t\t\tthis.R * latlng.lng * d,\r\n\t\t\tthis.R * Math.log((1 + sin) / (1 - sin)) / 2);\r\n\t},\r\n\r\n\tunproject: function (point) {\r\n\t\tvar d = 180 / Math.PI;\r\n\r\n\t\treturn new LatLng(\r\n\t\t\t(2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,\r\n\t\t\tpoint.x * d / this.R);\r\n\t},\r\n\r\n\tbounds: (function () {\r\n\t\tvar d = earthRadius * Math.PI;\r\n\t\treturn new Bounds([-d, -d], [d, d]);\r\n\t})()\r\n};\n\n/*\r\n * @class Transformation\r\n * @aka L.Transformation\r\n *\r\n * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`\r\n * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing\r\n * the reverse. Used by Leaflet in its projections code.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var transformation = L.transformation(2, 5, -1, 10),\r\n * \tp = L.point(1, 2),\r\n * \tp2 = transformation.transform(p), // L.point(7, 8)\r\n * \tp3 = transformation.untransform(p2); // L.point(1, 2)\r\n * ```\r\n */\r\n\r\n\r\n// factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)\r\n// Creates a `Transformation` object with the given coefficients.\r\nfunction Transformation(a, b, c, d) {\r\n\tif (isArray(a)) {\r\n\t\t// use array properties\r\n\t\tthis._a = a[0];\r\n\t\tthis._b = a[1];\r\n\t\tthis._c = a[2];\r\n\t\tthis._d = a[3];\r\n\t\treturn;\r\n\t}\r\n\tthis._a = a;\r\n\tthis._b = b;\r\n\tthis._c = c;\r\n\tthis._d = d;\r\n}\r\n\r\nTransformation.prototype = {\r\n\t// @method transform(point: Point, scale?: Number): Point\r\n\t// Returns a transformed point, optionally multiplied by the given scale.\r\n\t// Only accepts actual `L.Point` instances, not arrays.\r\n\ttransform: function (point, scale) { // (Point, Number) -> Point\r\n\t\treturn this._transform(point.clone(), scale);\r\n\t},\r\n\r\n\t// destructive transform (faster)\r\n\t_transform: function (point, scale) {\r\n\t\tscale = scale || 1;\r\n\t\tpoint.x = scale * (this._a * point.x + this._b);\r\n\t\tpoint.y = scale * (this._c * point.y + this._d);\r\n\t\treturn point;\r\n\t},\r\n\r\n\t// @method untransform(point: Point, scale?: Number): Point\r\n\t// Returns the reverse transformation of the given point, optionally divided\r\n\t// by the given scale. Only accepts actual `L.Point` instances, not arrays.\r\n\tuntransform: function (point, scale) {\r\n\t\tscale = scale || 1;\r\n\t\treturn new Point(\r\n\t\t (point.x / scale - this._b) / this._a,\r\n\t\t (point.y / scale - this._d) / this._c);\r\n\t}\r\n};\r\n\r\n// factory L.transformation(a: Number, b: Number, c: Number, d: Number)\r\n\r\n// @factory L.transformation(a: Number, b: Number, c: Number, d: Number)\r\n// Instantiates a Transformation object with the given coefficients.\r\n\r\n// @alternative\r\n// @factory L.transformation(coefficients: Array): Transformation\r\n// Expects an coefficients array of the form\r\n// `[a: Number, b: Number, c: Number, d: Number]`.\r\n\r\nfunction toTransformation(a, b, c, d) {\r\n\treturn new Transformation(a, b, c, d);\r\n}\n\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.EPSG3857\r\n *\r\n * The most common CRS for online maps, used by almost all free and commercial\r\n * tile providers. Uses Spherical Mercator projection. Set in by default in\r\n * Map's `crs` option.\r\n */\r\n\r\nvar EPSG3857 = extend({}, Earth, {\r\n\tcode: 'EPSG:3857',\r\n\tprojection: SphericalMercator,\r\n\r\n\ttransformation: (function () {\r\n\t\tvar scale = 0.5 / (Math.PI * SphericalMercator.R);\r\n\t\treturn toTransformation(scale, 0.5, -scale, 0.5);\r\n\t}())\r\n});\r\n\r\nvar EPSG900913 = extend({}, EPSG3857, {\r\n\tcode: 'EPSG:900913'\r\n});\n\n// @namespace SVG; @section\n// There are several static functions which can be called without instantiating L.SVG:\n\n// @function create(name: String): SVGElement\n// Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),\n// corresponding to the class name passed. For example, using 'line' will return\n// an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).\nfunction svgCreate(name) {\n\treturn document.createElementNS('http://www.w3.org/2000/svg', name);\n}\n\n// @function pointsToPath(rings: Point[], closed: Boolean): String\n// Generates a SVG path string for multiple rings, with each ring turning\n// into \"M..L..L..\" instructions\nfunction pointsToPath(rings, closed) {\n\tvar str = '',\n\ti, j, len, len2, points, p;\n\n\tfor (i = 0, len = rings.length; i < len; i++) {\n\t\tpoints = rings[i];\n\n\t\tfor (j = 0, len2 = points.length; j < len2; j++) {\n\t\t\tp = points[j];\n\t\t\tstr += (j ? 'L' : 'M') + p.x + ' ' + p.y;\n\t\t}\n\n\t\t// closes the ring for polygons; \"x\" is VML syntax\n\t\tstr += closed ? (svg ? 'z' : 'x') : '';\n\t}\n\n\t// SVG complains about empty path strings\n\treturn str || 'M0 0';\n}\n\n/*\r\n * @namespace Browser\r\n * @aka L.Browser\r\n *\r\n * A namespace with static properties for browser/feature detection used by Leaflet internally.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * if (L.Browser.ielt9) {\r\n * alert('Upgrade your browser, dude!');\r\n * }\r\n * ```\r\n */\r\n\r\nvar style$1 = document.documentElement.style;\r\n\r\n// @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).\r\nvar ie = 'ActiveXObject' in window;\r\n\r\n// @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.\r\nvar ielt9 = ie && !document.addEventListener;\r\n\r\n// @property edge: Boolean; `true` for the Edge web browser.\r\nvar edge = 'msLaunchUri' in navigator && !('documentMode' in document);\r\n\r\n// @property webkit: Boolean;\r\n// `true` for webkit-based browsers like Chrome and Safari (including mobile versions).\r\nvar webkit = userAgentContains('webkit');\r\n\r\n// @property android: Boolean\r\n// `true` for any browser running on an Android platform.\r\nvar android = userAgentContains('android');\r\n\r\n// @property android23: Boolean; `true` for browsers running on Android 2 or Android 3.\r\nvar android23 = userAgentContains('android 2') || userAgentContains('android 3');\r\n\r\n/* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */\r\nvar webkitVer = parseInt(/WebKit\\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit\r\n// @property androidStock: Boolean; `true` for the Android stock browser (i.e. not Chrome)\r\nvar androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);\r\n\r\n// @property opera: Boolean; `true` for the Opera browser\r\nvar opera = !!window.opera;\r\n\r\n// @property chrome: Boolean; `true` for the Chrome browser.\r\nvar chrome = userAgentContains('chrome');\r\n\r\n// @property gecko: Boolean; `true` for gecko-based browsers like Firefox.\r\nvar gecko = userAgentContains('gecko') && !webkit && !opera && !ie;\r\n\r\n// @property safari: Boolean; `true` for the Safari browser.\r\nvar safari = !chrome && userAgentContains('safari');\r\n\r\nvar phantom = userAgentContains('phantom');\r\n\r\n// @property opera12: Boolean\r\n// `true` for the Opera browser supporting CSS transforms (version 12 or later).\r\nvar opera12 = 'OTransition' in style$1;\r\n\r\n// @property win: Boolean; `true` when the browser is running in a Windows platform\r\nvar win = navigator.platform.indexOf('Win') === 0;\r\n\r\n// @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.\r\nvar ie3d = ie && ('transition' in style$1);\r\n\r\n// @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.\r\nvar webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;\r\n\r\n// @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.\r\nvar gecko3d = 'MozPerspective' in style$1;\r\n\r\n// @property any3d: Boolean\r\n// `true` for all browsers supporting CSS transforms.\r\nvar any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;\r\n\r\n// @property mobile: Boolean; `true` for all browsers running in a mobile device.\r\nvar mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');\r\n\r\n// @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.\r\nvar mobileWebkit = mobile && webkit;\r\n\r\n// @property mobileWebkit3d: Boolean\r\n// `true` for all webkit-based browsers in a mobile device supporting CSS transforms.\r\nvar mobileWebkit3d = mobile && webkit3d;\r\n\r\n// @property msPointer: Boolean\r\n// `true` for browsers implementing the Microsoft touch events model (notably IE10).\r\nvar msPointer = !window.PointerEvent && window.MSPointerEvent;\r\n\r\n// @property pointer: Boolean\r\n// `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).\r\nvar pointer = !!(window.PointerEvent || msPointer);\r\n\r\n// @property touch: Boolean\r\n// `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).\r\n// This does not necessarily mean that the browser is running in a computer with\r\n// a touchscreen, it only means that the browser is capable of understanding\r\n// touch events.\r\nvar touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||\r\n\t\t(window.DocumentTouch && document instanceof window.DocumentTouch));\r\n\r\n// @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.\r\nvar mobileOpera = mobile && opera;\r\n\r\n// @property mobileGecko: Boolean\r\n// `true` for gecko-based browsers running in a mobile device.\r\nvar mobileGecko = mobile && gecko;\r\n\r\n// @property retina: Boolean\r\n// `true` for browsers on a high-resolution \"retina\" screen or on any screen when browser's display zoom is more than 100%.\r\nvar retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;\r\n\r\n\r\n// @property canvas: Boolean\r\n// `true` when the browser supports [``](https://developer.mozilla.org/docs/Web/API/Canvas_API).\r\nvar canvas = (function () {\r\n\treturn !!document.createElement('canvas').getContext;\r\n}());\r\n\r\n// @property svg: Boolean\r\n// `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).\r\nvar svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);\r\n\r\n// @property vml: Boolean\r\n// `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).\r\nvar vml = !svg && (function () {\r\n\ttry {\r\n\t\tvar div = document.createElement('div');\r\n\t\tdiv.innerHTML = '';\r\n\r\n\t\tvar shape = div.firstChild;\r\n\t\tshape.style.behavior = 'url(#default#VML)';\r\n\r\n\t\treturn shape && (typeof shape.adj === 'object');\r\n\r\n\t} catch (e) {\r\n\t\treturn false;\r\n\t}\r\n}());\r\n\r\n\r\nfunction userAgentContains(str) {\r\n\treturn navigator.userAgent.toLowerCase().indexOf(str) >= 0;\r\n}\r\n\n\nvar Browser = (Object.freeze || Object)({\n\tie: ie,\n\tielt9: ielt9,\n\tedge: edge,\n\twebkit: webkit,\n\tandroid: android,\n\tandroid23: android23,\n\tandroidStock: androidStock,\n\topera: opera,\n\tchrome: chrome,\n\tgecko: gecko,\n\tsafari: safari,\n\tphantom: phantom,\n\topera12: opera12,\n\twin: win,\n\tie3d: ie3d,\n\twebkit3d: webkit3d,\n\tgecko3d: gecko3d,\n\tany3d: any3d,\n\tmobile: mobile,\n\tmobileWebkit: mobileWebkit,\n\tmobileWebkit3d: mobileWebkit3d,\n\tmsPointer: msPointer,\n\tpointer: pointer,\n\ttouch: touch,\n\tmobileOpera: mobileOpera,\n\tmobileGecko: mobileGecko,\n\tretina: retina,\n\tcanvas: canvas,\n\tsvg: svg,\n\tvml: vml\n});\n\n/*\n * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.\n */\n\n\nvar POINTER_DOWN = msPointer ? 'MSPointerDown' : 'pointerdown';\nvar POINTER_MOVE = msPointer ? 'MSPointerMove' : 'pointermove';\nvar POINTER_UP = msPointer ? 'MSPointerUp' : 'pointerup';\nvar POINTER_CANCEL = msPointer ? 'MSPointerCancel' : 'pointercancel';\nvar TAG_WHITE_LIST = ['INPUT', 'SELECT', 'OPTION'];\n\nvar _pointers = {};\nvar _pointerDocListener = false;\n\n// DomEvent.DoubleTap needs to know about this\nvar _pointersCount = 0;\n\n// Provides a touch events wrapper for (ms)pointer events.\n// ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890\n\nfunction addPointerListener(obj, type, handler, id) {\n\tif (type === 'touchstart') {\n\t\t_addPointerStart(obj, handler, id);\n\n\t} else if (type === 'touchmove') {\n\t\t_addPointerMove(obj, handler, id);\n\n\t} else if (type === 'touchend') {\n\t\t_addPointerEnd(obj, handler, id);\n\t}\n\n\treturn this;\n}\n\nfunction removePointerListener(obj, type, id) {\n\tvar handler = obj['_leaflet_' + type + id];\n\n\tif (type === 'touchstart') {\n\t\tobj.removeEventListener(POINTER_DOWN, handler, false);\n\n\t} else if (type === 'touchmove') {\n\t\tobj.removeEventListener(POINTER_MOVE, handler, false);\n\n\t} else if (type === 'touchend') {\n\t\tobj.removeEventListener(POINTER_UP, handler, false);\n\t\tobj.removeEventListener(POINTER_CANCEL, handler, false);\n\t}\n\n\treturn this;\n}\n\nfunction _addPointerStart(obj, handler, id) {\n\tvar onDown = bind(function (e) {\n\t\tif (e.pointerType !== 'mouse' && e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {\n\t\t\t// In IE11, some touch events needs to fire for form controls, or\n\t\t\t// the controls will stop working. We keep a whitelist of tag names that\n\t\t\t// need these events. For other target tags, we prevent default on the event.\n\t\t\tif (TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {\n\t\t\t\tpreventDefault(e);\n\t\t\t} else {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t_handlePointer(e, handler);\n\t});\n\n\tobj['_leaflet_touchstart' + id] = onDown;\n\tobj.addEventListener(POINTER_DOWN, onDown, false);\n\n\t// need to keep track of what pointers and how many are active to provide e.touches emulation\n\tif (!_pointerDocListener) {\n\t\t// we listen documentElement as any drags that end by moving the touch off the screen get fired there\n\t\tdocument.documentElement.addEventListener(POINTER_DOWN, _globalPointerDown, true);\n\t\tdocument.documentElement.addEventListener(POINTER_MOVE, _globalPointerMove, true);\n\t\tdocument.documentElement.addEventListener(POINTER_UP, _globalPointerUp, true);\n\t\tdocument.documentElement.addEventListener(POINTER_CANCEL, _globalPointerUp, true);\n\n\t\t_pointerDocListener = true;\n\t}\n}\n\nfunction _globalPointerDown(e) {\n\t_pointers[e.pointerId] = e;\n\t_pointersCount++;\n}\n\nfunction _globalPointerMove(e) {\n\tif (_pointers[e.pointerId]) {\n\t\t_pointers[e.pointerId] = e;\n\t}\n}\n\nfunction _globalPointerUp(e) {\n\tdelete _pointers[e.pointerId];\n\t_pointersCount--;\n}\n\nfunction _handlePointer(e, handler) {\n\te.touches = [];\n\tfor (var i in _pointers) {\n\t\te.touches.push(_pointers[i]);\n\t}\n\te.changedTouches = [e];\n\n\thandler(e);\n}\n\nfunction _addPointerMove(obj, handler, id) {\n\tvar onMove = function (e) {\n\t\t// don't fire touch moves when mouse isn't down\n\t\tif ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }\n\n\t\t_handlePointer(e, handler);\n\t};\n\n\tobj['_leaflet_touchmove' + id] = onMove;\n\tobj.addEventListener(POINTER_MOVE, onMove, false);\n}\n\nfunction _addPointerEnd(obj, handler, id) {\n\tvar onUp = function (e) {\n\t\t_handlePointer(e, handler);\n\t};\n\n\tobj['_leaflet_touchend' + id] = onUp;\n\tobj.addEventListener(POINTER_UP, onUp, false);\n\tobj.addEventListener(POINTER_CANCEL, onUp, false);\n}\n\n/*\r\n * Extends the event handling code with double tap support for mobile browsers.\r\n */\r\n\r\nvar _touchstart = msPointer ? 'MSPointerDown' : pointer ? 'pointerdown' : 'touchstart';\r\nvar _touchend = msPointer ? 'MSPointerUp' : pointer ? 'pointerup' : 'touchend';\r\nvar _pre = '_leaflet_';\r\n\r\n// inspired by Zepto touch code by Thomas Fuchs\r\nfunction addDoubleTapListener(obj, handler, id) {\r\n\tvar last, touch$$1,\r\n\t doubleTap = false,\r\n\t delay = 250;\r\n\r\n\tfunction onTouchStart(e) {\r\n\t\tvar count;\r\n\r\n\t\tif (pointer) {\r\n\t\t\tif ((!edge) || e.pointerType === 'mouse') { return; }\r\n\t\t\tcount = _pointersCount;\r\n\t\t} else {\r\n\t\t\tcount = e.touches.length;\r\n\t\t}\r\n\r\n\t\tif (count > 1) { return; }\r\n\r\n\t\tvar now = Date.now(),\r\n\t\t delta = now - (last || now);\r\n\r\n\t\ttouch$$1 = e.touches ? e.touches[0] : e;\r\n\t\tdoubleTap = (delta > 0 && delta <= delay);\r\n\t\tlast = now;\r\n\t}\r\n\r\n\tfunction onTouchEnd(e) {\r\n\t\tif (doubleTap && !touch$$1.cancelBubble) {\r\n\t\t\tif (pointer) {\r\n\t\t\t\tif ((!edge) || e.pointerType === 'mouse') { return; }\r\n\t\t\t\t// work around .type being readonly with MSPointer* events\r\n\t\t\t\tvar newTouch = {},\r\n\t\t\t\t prop, i;\r\n\r\n\t\t\t\tfor (i in touch$$1) {\r\n\t\t\t\t\tprop = touch$$1[i];\r\n\t\t\t\t\tnewTouch[i] = prop && prop.bind ? prop.bind(touch$$1) : prop;\r\n\t\t\t\t}\r\n\t\t\t\ttouch$$1 = newTouch;\r\n\t\t\t}\r\n\t\t\ttouch$$1.type = 'dblclick';\r\n\t\t\ttouch$$1.button = 0;\r\n\t\t\thandler(touch$$1);\r\n\t\t\tlast = null;\r\n\t\t}\r\n\t}\r\n\r\n\tobj[_pre + _touchstart + id] = onTouchStart;\r\n\tobj[_pre + _touchend + id] = onTouchEnd;\r\n\tobj[_pre + 'dblclick' + id] = handler;\r\n\r\n\tobj.addEventListener(_touchstart, onTouchStart, false);\r\n\tobj.addEventListener(_touchend, onTouchEnd, false);\r\n\r\n\t// On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),\r\n\t// the browser doesn't fire touchend/pointerup events but does fire\r\n\t// native dblclicks. See #4127.\r\n\t// Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.\r\n\tobj.addEventListener('dblclick', handler, false);\r\n\r\n\treturn this;\r\n}\r\n\r\nfunction removeDoubleTapListener(obj, id) {\r\n\tvar touchstart = obj[_pre + _touchstart + id],\r\n\t touchend = obj[_pre + _touchend + id],\r\n\t dblclick = obj[_pre + 'dblclick' + id];\r\n\r\n\tobj.removeEventListener(_touchstart, touchstart, false);\r\n\tobj.removeEventListener(_touchend, touchend, false);\r\n\tif (!edge) {\r\n\t\tobj.removeEventListener('dblclick', dblclick, false);\r\n\t}\r\n\r\n\treturn this;\r\n}\n\n/*\r\n * @namespace DomUtil\r\n *\r\n * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)\r\n * tree, used by Leaflet internally.\r\n *\r\n * Most functions expecting or returning a `HTMLElement` also work for\r\n * SVG elements. The only difference is that classes refer to CSS classes\r\n * in HTML and SVG classes in SVG.\r\n */\r\n\r\n\r\n// @property TRANSFORM: String\r\n// Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).\r\nvar TRANSFORM = testProp(\r\n\t['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);\r\n\r\n// webkitTransition comes first because some browser versions that drop vendor prefix don't do\r\n// the same for the transitionend event, in particular the Android 4.1 stock browser\r\n\r\n// @property TRANSITION: String\r\n// Vendor-prefixed transition style name.\r\nvar TRANSITION = testProp(\r\n\t['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);\r\n\r\n// @property TRANSITION_END: String\r\n// Vendor-prefixed transitionend event name.\r\nvar TRANSITION_END =\r\n\tTRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';\r\n\r\n\r\n// @function get(id: String|HTMLElement): HTMLElement\r\n// Returns an element given its DOM id, or returns the element itself\r\n// if it was passed directly.\r\nfunction get(id) {\r\n\treturn typeof id === 'string' ? document.getElementById(id) : id;\r\n}\r\n\r\n// @function getStyle(el: HTMLElement, styleAttrib: String): String\r\n// Returns the value for a certain style attribute on an element,\r\n// including computed values or values set through CSS.\r\nfunction getStyle(el, style) {\r\n\tvar value = el.style[style] || (el.currentStyle && el.currentStyle[style]);\r\n\r\n\tif ((!value || value === 'auto') && document.defaultView) {\r\n\t\tvar css = document.defaultView.getComputedStyle(el, null);\r\n\t\tvalue = css ? css[style] : null;\r\n\t}\r\n\treturn value === 'auto' ? null : value;\r\n}\r\n\r\n// @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement\r\n// Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.\r\nfunction create$1(tagName, className, container) {\r\n\tvar el = document.createElement(tagName);\r\n\tel.className = className || '';\r\n\r\n\tif (container) {\r\n\t\tcontainer.appendChild(el);\r\n\t}\r\n\treturn el;\r\n}\r\n\r\n// @function remove(el: HTMLElement)\r\n// Removes `el` from its parent element\r\nfunction remove(el) {\r\n\tvar parent = el.parentNode;\r\n\tif (parent) {\r\n\t\tparent.removeChild(el);\r\n\t}\r\n}\r\n\r\n// @function empty(el: HTMLElement)\r\n// Removes all of `el`'s children elements from `el`\r\nfunction empty(el) {\r\n\twhile (el.firstChild) {\r\n\t\tel.removeChild(el.firstChild);\r\n\t}\r\n}\r\n\r\n// @function toFront(el: HTMLElement)\r\n// Makes `el` the last child of its parent, so it renders in front of the other children.\r\nfunction toFront(el) {\r\n\tvar parent = el.parentNode;\r\n\tif (parent && parent.lastChild !== el) {\r\n\t\tparent.appendChild(el);\r\n\t}\r\n}\r\n\r\n// @function toBack(el: HTMLElement)\r\n// Makes `el` the first child of its parent, so it renders behind the other children.\r\nfunction toBack(el) {\r\n\tvar parent = el.parentNode;\r\n\tif (parent && parent.firstChild !== el) {\r\n\t\tparent.insertBefore(el, parent.firstChild);\r\n\t}\r\n}\r\n\r\n// @function hasClass(el: HTMLElement, name: String): Boolean\r\n// Returns `true` if the element's class attribute contains `name`.\r\nfunction hasClass(el, name) {\r\n\tif (el.classList !== undefined) {\r\n\t\treturn el.classList.contains(name);\r\n\t}\r\n\tvar className = getClass(el);\r\n\treturn className.length > 0 && new RegExp('(^|\\\\s)' + name + '(\\\\s|$)').test(className);\r\n}\r\n\r\n// @function addClass(el: HTMLElement, name: String)\r\n// Adds `name` to the element's class attribute.\r\nfunction addClass(el, name) {\r\n\tif (el.classList !== undefined) {\r\n\t\tvar classes = splitWords(name);\r\n\t\tfor (var i = 0, len = classes.length; i < len; i++) {\r\n\t\t\tel.classList.add(classes[i]);\r\n\t\t}\r\n\t} else if (!hasClass(el, name)) {\r\n\t\tvar className = getClass(el);\r\n\t\tsetClass(el, (className ? className + ' ' : '') + name);\r\n\t}\r\n}\r\n\r\n// @function removeClass(el: HTMLElement, name: String)\r\n// Removes `name` from the element's class attribute.\r\nfunction removeClass(el, name) {\r\n\tif (el.classList !== undefined) {\r\n\t\tel.classList.remove(name);\r\n\t} else {\r\n\t\tsetClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));\r\n\t}\r\n}\r\n\r\n// @function setClass(el: HTMLElement, name: String)\r\n// Sets the element's class.\r\nfunction setClass(el, name) {\r\n\tif (el.className.baseVal === undefined) {\r\n\t\tel.className = name;\r\n\t} else {\r\n\t\t// in case of SVG element\r\n\t\tel.className.baseVal = name;\r\n\t}\r\n}\r\n\r\n// @function getClass(el: HTMLElement): String\r\n// Returns the element's class.\r\nfunction getClass(el) {\r\n\t// Check if the element is an SVGElementInstance and use the correspondingElement instead\r\n\t// (Required for linked SVG elements in IE11.)\r\n\tif (el.correspondingElement) {\r\n\t\tel = el.correspondingElement;\r\n\t}\r\n\treturn el.className.baseVal === undefined ? el.className : el.className.baseVal;\r\n}\r\n\r\n// @function setOpacity(el: HTMLElement, opacity: Number)\r\n// Set the opacity of an element (including old IE support).\r\n// `opacity` must be a number from `0` to `1`.\r\nfunction setOpacity(el, value) {\r\n\tif ('opacity' in el.style) {\r\n\t\tel.style.opacity = value;\r\n\t} else if ('filter' in el.style) {\r\n\t\t_setOpacityIE(el, value);\r\n\t}\r\n}\r\n\r\nfunction _setOpacityIE(el, value) {\r\n\tvar filter = false,\r\n\t filterName = 'DXImageTransform.Microsoft.Alpha';\r\n\r\n\t// filters collection throws an error if we try to retrieve a filter that doesn't exist\r\n\ttry {\r\n\t\tfilter = el.filters.item(filterName);\r\n\t} catch (e) {\r\n\t\t// don't set opacity to 1 if we haven't already set an opacity,\r\n\t\t// it isn't needed and breaks transparent pngs.\r\n\t\tif (value === 1) { return; }\r\n\t}\r\n\r\n\tvalue = Math.round(value * 100);\r\n\r\n\tif (filter) {\r\n\t\tfilter.Enabled = (value !== 100);\r\n\t\tfilter.Opacity = value;\r\n\t} else {\r\n\t\tel.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';\r\n\t}\r\n}\r\n\r\n// @function testProp(props: String[]): String|false\r\n// Goes through the array of style names and returns the first name\r\n// that is a valid style name for an element. If no such name is found,\r\n// it returns false. Useful for vendor-prefixed styles like `transform`.\r\nfunction testProp(props) {\r\n\tvar style = document.documentElement.style;\r\n\r\n\tfor (var i = 0; i < props.length; i++) {\r\n\t\tif (props[i] in style) {\r\n\t\t\treturn props[i];\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n// @function setTransform(el: HTMLElement, offset: Point, scale?: Number)\r\n// Resets the 3D CSS transform of `el` so it is translated by `offset` pixels\r\n// and optionally scaled by `scale`. Does not have an effect if the\r\n// browser doesn't support 3D CSS transforms.\r\nfunction setTransform(el, offset, scale) {\r\n\tvar pos = offset || new Point(0, 0);\r\n\r\n\tel.style[TRANSFORM] =\r\n\t\t(ie3d ?\r\n\t\t\t'translate(' + pos.x + 'px,' + pos.y + 'px)' :\r\n\t\t\t'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +\r\n\t\t(scale ? ' scale(' + scale + ')' : '');\r\n}\r\n\r\n// @function setPosition(el: HTMLElement, position: Point)\r\n// Sets the position of `el` to coordinates specified by `position`,\r\n// using CSS translate or top/left positioning depending on the browser\r\n// (used by Leaflet internally to position its layers).\r\nfunction setPosition(el, point) {\r\n\r\n\t/*eslint-disable */\r\n\tel._leaflet_pos = point;\r\n\t/* eslint-enable */\r\n\r\n\tif (any3d) {\r\n\t\tsetTransform(el, point);\r\n\t} else {\r\n\t\tel.style.left = point.x + 'px';\r\n\t\tel.style.top = point.y + 'px';\r\n\t}\r\n}\r\n\r\n// @function getPosition(el: HTMLElement): Point\r\n// Returns the coordinates of an element previously positioned with setPosition.\r\nfunction getPosition(el) {\r\n\t// this method is only used for elements previously positioned using setPosition,\r\n\t// so it's safe to cache the position for performance\r\n\r\n\treturn el._leaflet_pos || new Point(0, 0);\r\n}\r\n\r\n// @function disableTextSelection()\r\n// Prevents the user from generating `selectstart` DOM events, usually generated\r\n// when the user drags the mouse through a page with text. Used internally\r\n// by Leaflet to override the behaviour of any click-and-drag interaction on\r\n// the map. Affects drag interactions on the whole document.\r\n\r\n// @function enableTextSelection()\r\n// Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).\r\nvar disableTextSelection;\r\nvar enableTextSelection;\r\nvar _userSelect;\r\nif ('onselectstart' in document) {\r\n\tdisableTextSelection = function () {\r\n\t\ton(window, 'selectstart', preventDefault);\r\n\t};\r\n\tenableTextSelection = function () {\r\n\t\toff(window, 'selectstart', preventDefault);\r\n\t};\r\n} else {\r\n\tvar userSelectProperty = testProp(\r\n\t\t['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);\r\n\r\n\tdisableTextSelection = function () {\r\n\t\tif (userSelectProperty) {\r\n\t\t\tvar style = document.documentElement.style;\r\n\t\t\t_userSelect = style[userSelectProperty];\r\n\t\t\tstyle[userSelectProperty] = 'none';\r\n\t\t}\r\n\t};\r\n\tenableTextSelection = function () {\r\n\t\tif (userSelectProperty) {\r\n\t\t\tdocument.documentElement.style[userSelectProperty] = _userSelect;\r\n\t\t\t_userSelect = undefined;\r\n\t\t}\r\n\t};\r\n}\r\n\r\n// @function disableImageDrag()\r\n// As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but\r\n// for `dragstart` DOM events, usually generated when the user drags an image.\r\nfunction disableImageDrag() {\r\n\ton(window, 'dragstart', preventDefault);\r\n}\r\n\r\n// @function enableImageDrag()\r\n// Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).\r\nfunction enableImageDrag() {\r\n\toff(window, 'dragstart', preventDefault);\r\n}\r\n\r\nvar _outlineElement;\nvar _outlineStyle;\r\n// @function preventOutline(el: HTMLElement)\r\n// Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)\r\n// of the element `el` invisible. Used internally by Leaflet to prevent\r\n// focusable elements from displaying an outline when the user performs a\r\n// drag interaction on them.\r\nfunction preventOutline(element) {\r\n\twhile (element.tabIndex === -1) {\r\n\t\telement = element.parentNode;\r\n\t}\r\n\tif (!element.style) { return; }\r\n\trestoreOutline();\r\n\t_outlineElement = element;\r\n\t_outlineStyle = element.style.outline;\r\n\telement.style.outline = 'none';\r\n\ton(window, 'keydown', restoreOutline);\r\n}\r\n\r\n// @function restoreOutline()\r\n// Cancels the effects of a previous [`L.DomUtil.preventOutline`]().\r\nfunction restoreOutline() {\r\n\tif (!_outlineElement) { return; }\r\n\t_outlineElement.style.outline = _outlineStyle;\r\n\t_outlineElement = undefined;\r\n\t_outlineStyle = undefined;\r\n\toff(window, 'keydown', restoreOutline);\r\n}\r\n\r\n// @function getSizedParentNode(el: HTMLElement): HTMLElement\r\n// Finds the closest parent node which size (width and height) is not null.\r\nfunction getSizedParentNode(element) {\r\n\tdo {\r\n\t\telement = element.parentNode;\r\n\t} while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);\r\n\treturn element;\r\n}\r\n\r\n// @function getScale(el: HTMLElement): Object\r\n// Computes the CSS scale currently applied on the element.\r\n// Returns an object with `x` and `y` members as horizontal and vertical scales respectively,\r\n// and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).\r\nfunction getScale(element) {\r\n\tvar rect = element.getBoundingClientRect(); // Read-only in old browsers.\r\n\r\n\treturn {\r\n\t\tx: rect.width / element.offsetWidth || 1,\r\n\t\ty: rect.height / element.offsetHeight || 1,\r\n\t\tboundingClientRect: rect\r\n\t};\r\n}\r\n\n\nvar DomUtil = (Object.freeze || Object)({\n\tTRANSFORM: TRANSFORM,\n\tTRANSITION: TRANSITION,\n\tTRANSITION_END: TRANSITION_END,\n\tget: get,\n\tgetStyle: getStyle,\n\tcreate: create$1,\n\tremove: remove,\n\tempty: empty,\n\ttoFront: toFront,\n\ttoBack: toBack,\n\thasClass: hasClass,\n\taddClass: addClass,\n\tremoveClass: removeClass,\n\tsetClass: setClass,\n\tgetClass: getClass,\n\tsetOpacity: setOpacity,\n\ttestProp: testProp,\n\tsetTransform: setTransform,\n\tsetPosition: setPosition,\n\tgetPosition: getPosition,\n\tdisableTextSelection: disableTextSelection,\n\tenableTextSelection: enableTextSelection,\n\tdisableImageDrag: disableImageDrag,\n\tenableImageDrag: enableImageDrag,\n\tpreventOutline: preventOutline,\n\trestoreOutline: restoreOutline,\n\tgetSizedParentNode: getSizedParentNode,\n\tgetScale: getScale\n});\n\n/*\r\n * @namespace DomEvent\r\n * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.\r\n */\r\n\r\n// Inspired by John Resig, Dean Edwards and YUI addEvent implementations.\r\n\r\n// @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this\r\n// Adds a listener function (`fn`) to a particular DOM event type of the\r\n// element `el`. You can optionally specify the context of the listener\r\n// (object the `this` keyword will point to). You can also pass several\r\n// space-separated types (e.g. `'click dblclick'`).\r\n\r\n// @alternative\r\n// @function on(el: HTMLElement, eventMap: Object, context?: Object): this\r\n// Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`\r\nfunction on(obj, types, fn, context) {\r\n\r\n\tif (typeof types === 'object') {\r\n\t\tfor (var type in types) {\r\n\t\t\taddOne(obj, type, types[type], fn);\r\n\t\t}\r\n\t} else {\r\n\t\ttypes = splitWords(types);\r\n\r\n\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\taddOne(obj, types[i], fn, context);\r\n\t\t}\r\n\t}\r\n\r\n\treturn this;\r\n}\r\n\r\nvar eventsKey = '_leaflet_events';\r\n\r\n// @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this\r\n// Removes a previously added listener function.\r\n// Note that if you passed a custom context to on, you must pass the same\r\n// context to `off` in order to remove the listener.\r\n\r\n// @alternative\r\n// @function off(el: HTMLElement, eventMap: Object, context?: Object): this\r\n// Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`\r\nfunction off(obj, types, fn, context) {\r\n\r\n\tif (typeof types === 'object') {\r\n\t\tfor (var type in types) {\r\n\t\t\tremoveOne(obj, type, types[type], fn);\r\n\t\t}\r\n\t} else if (types) {\r\n\t\ttypes = splitWords(types);\r\n\r\n\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\tremoveOne(obj, types[i], fn, context);\r\n\t\t}\r\n\t} else {\r\n\t\tfor (var j in obj[eventsKey]) {\r\n\t\t\tremoveOne(obj, j, obj[eventsKey][j]);\r\n\t\t}\r\n\t\tdelete obj[eventsKey];\r\n\t}\r\n\r\n\treturn this;\r\n}\r\n\r\nfunction addOne(obj, type, fn, context) {\r\n\tvar id = type + stamp(fn) + (context ? '_' + stamp(context) : '');\r\n\r\n\tif (obj[eventsKey] && obj[eventsKey][id]) { return this; }\r\n\r\n\tvar handler = function (e) {\r\n\t\treturn fn.call(context || obj, e || window.event);\r\n\t};\r\n\r\n\tvar originalHandler = handler;\r\n\r\n\tif (pointer && type.indexOf('touch') === 0) {\r\n\t\t// Needs DomEvent.Pointer.js\r\n\t\taddPointerListener(obj, type, handler, id);\r\n\r\n\t} else if (touch && (type === 'dblclick') && addDoubleTapListener &&\r\n\t !(pointer && chrome)) {\r\n\t\t// Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener\r\n\t\t// See #5180\r\n\t\taddDoubleTapListener(obj, handler, id);\r\n\r\n\t} else if ('addEventListener' in obj) {\r\n\r\n\t\tif (type === 'mousewheel') {\r\n\t\t\tobj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);\r\n\r\n\t\t} else if ((type === 'mouseenter') || (type === 'mouseleave')) {\r\n\t\t\thandler = function (e) {\r\n\t\t\t\te = e || window.event;\r\n\t\t\t\tif (isExternalTarget(obj, e)) {\r\n\t\t\t\t\toriginalHandler(e);\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\tobj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);\r\n\r\n\t\t} else {\r\n\t\t\tif (type === 'click' && android) {\r\n\t\t\t\thandler = function (e) {\r\n\t\t\t\t\tfilterClick(e, originalHandler);\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t\tobj.addEventListener(type, handler, false);\r\n\t\t}\r\n\r\n\t} else if ('attachEvent' in obj) {\r\n\t\tobj.attachEvent('on' + type, handler);\r\n\t}\r\n\r\n\tobj[eventsKey] = obj[eventsKey] || {};\r\n\tobj[eventsKey][id] = handler;\r\n}\r\n\r\nfunction removeOne(obj, type, fn, context) {\r\n\r\n\tvar id = type + stamp(fn) + (context ? '_' + stamp(context) : ''),\r\n\t handler = obj[eventsKey] && obj[eventsKey][id];\r\n\r\n\tif (!handler) { return this; }\r\n\r\n\tif (pointer && type.indexOf('touch') === 0) {\r\n\t\tremovePointerListener(obj, type, id);\r\n\r\n\t} else if (touch && (type === 'dblclick') && removeDoubleTapListener &&\r\n\t !(pointer && chrome)) {\r\n\t\tremoveDoubleTapListener(obj, id);\r\n\r\n\t} else if ('removeEventListener' in obj) {\r\n\r\n\t\tif (type === 'mousewheel') {\r\n\t\t\tobj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);\r\n\r\n\t\t} else {\r\n\t\t\tobj.removeEventListener(\r\n\t\t\t\ttype === 'mouseenter' ? 'mouseover' :\r\n\t\t\t\ttype === 'mouseleave' ? 'mouseout' : type, handler, false);\r\n\t\t}\r\n\r\n\t} else if ('detachEvent' in obj) {\r\n\t\tobj.detachEvent('on' + type, handler);\r\n\t}\r\n\r\n\tobj[eventsKey][id] = null;\r\n}\r\n\r\n// @function stopPropagation(ev: DOMEvent): this\r\n// Stop the given event from propagation to parent elements. Used inside the listener functions:\r\n// ```js\r\n// L.DomEvent.on(div, 'click', function (ev) {\r\n// \tL.DomEvent.stopPropagation(ev);\r\n// });\r\n// ```\r\nfunction stopPropagation(e) {\r\n\r\n\tif (e.stopPropagation) {\r\n\t\te.stopPropagation();\r\n\t} else if (e.originalEvent) { // In case of Leaflet event.\r\n\t\te.originalEvent._stopped = true;\r\n\t} else {\r\n\t\te.cancelBubble = true;\r\n\t}\r\n\tskipped(e);\r\n\r\n\treturn this;\r\n}\r\n\r\n// @function disableScrollPropagation(el: HTMLElement): this\r\n// Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).\r\nfunction disableScrollPropagation(el) {\r\n\taddOne(el, 'mousewheel', stopPropagation);\r\n\treturn this;\r\n}\r\n\r\n// @function disableClickPropagation(el: HTMLElement): this\r\n// Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,\r\n// `'mousedown'` and `'touchstart'` events (plus browser variants).\r\nfunction disableClickPropagation(el) {\r\n\ton(el, 'mousedown touchstart dblclick', stopPropagation);\r\n\taddOne(el, 'click', fakeStop);\r\n\treturn this;\r\n}\r\n\r\n// @function preventDefault(ev: DOMEvent): this\r\n// Prevents the default action of the DOM Event `ev` from happening (such as\r\n// following a link in the href of the a element, or doing a POST request\r\n// with page reload when a `
    ` is submitted).\r\n// Use it inside listener functions.\r\nfunction preventDefault(e) {\r\n\tif (e.preventDefault) {\r\n\t\te.preventDefault();\r\n\t} else {\r\n\t\te.returnValue = false;\r\n\t}\r\n\treturn this;\r\n}\r\n\r\n// @function stop(ev: DOMEvent): this\r\n// Does `stopPropagation` and `preventDefault` at the same time.\r\nfunction stop(e) {\r\n\tpreventDefault(e);\r\n\tstopPropagation(e);\r\n\treturn this;\r\n}\r\n\r\n// @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point\r\n// Gets normalized mouse position from a DOM event relative to the\r\n// `container` (border excluded) or to the whole page if not specified.\r\nfunction getMousePosition(e, container) {\r\n\tif (!container) {\r\n\t\treturn new Point(e.clientX, e.clientY);\r\n\t}\r\n\r\n\tvar scale = getScale(container),\r\n\t offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y)\r\n\r\n\treturn new Point(\r\n\t\t// offset.left/top values are in page scale (like clientX/Y),\r\n\t\t// whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).\r\n\t\t(e.clientX - offset.left) / scale.x - container.clientLeft,\r\n\t\t(e.clientY - offset.top) / scale.y - container.clientTop\r\n\t);\r\n}\r\n\r\n// Chrome on Win scrolls double the pixels as in other platforms (see #4538),\r\n// and Firefox scrolls device pixels, not CSS pixels\r\nvar wheelPxFactor =\r\n\t(win && chrome) ? 2 * window.devicePixelRatio :\r\n\tgecko ? window.devicePixelRatio : 1;\r\n\r\n// @function getWheelDelta(ev: DOMEvent): Number\r\n// Gets normalized wheel delta from a mousewheel DOM event, in vertical\r\n// pixels scrolled (negative if scrolling down).\r\n// Events from pointing devices without precise scrolling are mapped to\r\n// a best guess of 60 pixels.\r\nfunction getWheelDelta(e) {\r\n\treturn (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta\r\n\t (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels\r\n\t (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines\r\n\t (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages\r\n\t (e.deltaX || e.deltaZ) ? 0 :\t// Skip horizontal/depth wheel events\r\n\t e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels\r\n\t (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines\r\n\t e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages\r\n\t 0;\r\n}\r\n\r\nvar skipEvents = {};\r\n\r\nfunction fakeStop(e) {\r\n\t// fakes stopPropagation by setting a special event flag, checked/reset with skipped(e)\r\n\tskipEvents[e.type] = true;\r\n}\r\n\r\nfunction skipped(e) {\r\n\tvar events = skipEvents[e.type];\r\n\t// reset when checking, as it's only used in map container and propagates outside of the map\r\n\tskipEvents[e.type] = false;\r\n\treturn events;\r\n}\r\n\r\n// check if element really left/entered the event target (for mouseenter/mouseleave)\r\nfunction isExternalTarget(el, e) {\r\n\r\n\tvar related = e.relatedTarget;\r\n\r\n\tif (!related) { return true; }\r\n\r\n\ttry {\r\n\t\twhile (related && (related !== el)) {\r\n\t\t\trelated = related.parentNode;\r\n\t\t}\r\n\t} catch (err) {\r\n\t\treturn false;\r\n\t}\r\n\treturn (related !== el);\r\n}\r\n\r\nvar lastClick;\r\n\r\n// this is a horrible workaround for a bug in Android where a single touch triggers two click events\r\nfunction filterClick(e, handler) {\r\n\tvar timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),\r\n\t elapsed = lastClick && (timeStamp - lastClick);\r\n\r\n\t// are they closer together than 500ms yet more than 100ms?\r\n\t// Android typically triggers them ~300ms apart while multiple listeners\r\n\t// on the same event should be triggered far faster;\r\n\t// or check if click is simulated on the element, and if it is, reject any non-simulated events\r\n\r\n\tif ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {\r\n\t\tstop(e);\r\n\t\treturn;\r\n\t}\r\n\tlastClick = timeStamp;\r\n\r\n\thandler(e);\r\n}\r\n\r\n\r\n\n\nvar DomEvent = (Object.freeze || Object)({\n\ton: on,\n\toff: off,\n\tstopPropagation: stopPropagation,\n\tdisableScrollPropagation: disableScrollPropagation,\n\tdisableClickPropagation: disableClickPropagation,\n\tpreventDefault: preventDefault,\n\tstop: stop,\n\tgetMousePosition: getMousePosition,\n\tgetWheelDelta: getWheelDelta,\n\tfakeStop: fakeStop,\n\tskipped: skipped,\n\tisExternalTarget: isExternalTarget,\n\taddListener: on,\n\tremoveListener: off\n});\n\n/*\n * @class PosAnimation\n * @aka L.PosAnimation\n * @inherits Evented\n * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.\n *\n * @example\n * ```js\n * var fx = new L.PosAnimation();\n * fx.run(el, [300, 500], 0.5);\n * ```\n *\n * @constructor L.PosAnimation()\n * Creates a `PosAnimation` object.\n *\n */\n\nvar PosAnimation = Evented.extend({\n\n\t// @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)\n\t// Run an animation of a given element to a new position, optionally setting\n\t// duration in seconds (`0.25` by default) and easing linearity factor (3rd\n\t// argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),\n\t// `0.5` by default).\n\trun: function (el, newPos, duration, easeLinearity) {\n\t\tthis.stop();\n\n\t\tthis._el = el;\n\t\tthis._inProgress = true;\n\t\tthis._duration = duration || 0.25;\n\t\tthis._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);\n\n\t\tthis._startPos = getPosition(el);\n\t\tthis._offset = newPos.subtract(this._startPos);\n\t\tthis._startTime = +new Date();\n\n\t\t// @event start: Event\n\t\t// Fired when the animation starts\n\t\tthis.fire('start');\n\n\t\tthis._animate();\n\t},\n\n\t// @method stop()\n\t// Stops the animation (if currently running).\n\tstop: function () {\n\t\tif (!this._inProgress) { return; }\n\n\t\tthis._step(true);\n\t\tthis._complete();\n\t},\n\n\t_animate: function () {\n\t\t// animation loop\n\t\tthis._animId = requestAnimFrame(this._animate, this);\n\t\tthis._step();\n\t},\n\n\t_step: function (round) {\n\t\tvar elapsed = (+new Date()) - this._startTime,\n\t\t duration = this._duration * 1000;\n\n\t\tif (elapsed < duration) {\n\t\t\tthis._runFrame(this._easeOut(elapsed / duration), round);\n\t\t} else {\n\t\t\tthis._runFrame(1);\n\t\t\tthis._complete();\n\t\t}\n\t},\n\n\t_runFrame: function (progress, round) {\n\t\tvar pos = this._startPos.add(this._offset.multiplyBy(progress));\n\t\tif (round) {\n\t\t\tpos._round();\n\t\t}\n\t\tsetPosition(this._el, pos);\n\n\t\t// @event step: Event\n\t\t// Fired continuously during the animation.\n\t\tthis.fire('step');\n\t},\n\n\t_complete: function () {\n\t\tcancelAnimFrame(this._animId);\n\n\t\tthis._inProgress = false;\n\t\t// @event end: Event\n\t\t// Fired when the animation ends.\n\t\tthis.fire('end');\n\t},\n\n\t_easeOut: function (t) {\n\t\treturn 1 - Math.pow(1 - t, this._easeOutPower);\n\t}\n});\n\n/*\r\n * @class Map\r\n * @aka L.Map\r\n * @inherits Evented\r\n *\r\n * The central class of the API — it is used to create a map on a page and manipulate it.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * // initialize the map on the \"map\" div with a given center and zoom\r\n * var map = L.map('map', {\r\n * \tcenter: [51.505, -0.09],\r\n * \tzoom: 13\r\n * });\r\n * ```\r\n *\r\n */\r\n\r\nvar Map = Evented.extend({\r\n\r\n\toptions: {\r\n\t\t// @section Map State Options\r\n\t\t// @option crs: CRS = L.CRS.EPSG3857\r\n\t\t// The [Coordinate Reference System](#crs) to use. Don't change this if you're not\r\n\t\t// sure what it means.\r\n\t\tcrs: EPSG3857,\r\n\r\n\t\t// @option center: LatLng = undefined\r\n\t\t// Initial geographic center of the map\r\n\t\tcenter: undefined,\r\n\r\n\t\t// @option zoom: Number = undefined\r\n\t\t// Initial map zoom level\r\n\t\tzoom: undefined,\r\n\r\n\t\t// @option minZoom: Number = *\r\n\t\t// Minimum zoom level of the map.\r\n\t\t// If not specified and at least one `GridLayer` or `TileLayer` is in the map,\r\n\t\t// the lowest of their `minZoom` options will be used instead.\r\n\t\tminZoom: undefined,\r\n\r\n\t\t// @option maxZoom: Number = *\r\n\t\t// Maximum zoom level of the map.\r\n\t\t// If not specified and at least one `GridLayer` or `TileLayer` is in the map,\r\n\t\t// the highest of their `maxZoom` options will be used instead.\r\n\t\tmaxZoom: undefined,\r\n\r\n\t\t// @option layers: Layer[] = []\r\n\t\t// Array of layers that will be added to the map initially\r\n\t\tlayers: [],\r\n\r\n\t\t// @option maxBounds: LatLngBounds = null\r\n\t\t// When this option is set, the map restricts the view to the given\r\n\t\t// geographical bounds, bouncing the user back if the user tries to pan\r\n\t\t// outside the view. To set the restriction dynamically, use\r\n\t\t// [`setMaxBounds`](#map-setmaxbounds) method.\r\n\t\tmaxBounds: undefined,\r\n\r\n\t\t// @option renderer: Renderer = *\r\n\t\t// The default method for drawing vector layers on the map. `L.SVG`\r\n\t\t// or `L.Canvas` by default depending on browser support.\r\n\t\trenderer: undefined,\r\n\r\n\r\n\t\t// @section Animation Options\r\n\t\t// @option zoomAnimation: Boolean = true\r\n\t\t// Whether the map zoom animation is enabled. By default it's enabled\r\n\t\t// in all browsers that support CSS3 Transitions except Android.\r\n\t\tzoomAnimation: true,\r\n\r\n\t\t// @option zoomAnimationThreshold: Number = 4\r\n\t\t// Won't animate zoom if the zoom difference exceeds this value.\r\n\t\tzoomAnimationThreshold: 4,\r\n\r\n\t\t// @option fadeAnimation: Boolean = true\r\n\t\t// Whether the tile fade animation is enabled. By default it's enabled\r\n\t\t// in all browsers that support CSS3 Transitions except Android.\r\n\t\tfadeAnimation: true,\r\n\r\n\t\t// @option markerZoomAnimation: Boolean = true\r\n\t\t// Whether markers animate their zoom with the zoom animation, if disabled\r\n\t\t// they will disappear for the length of the animation. By default it's\r\n\t\t// enabled in all browsers that support CSS3 Transitions except Android.\r\n\t\tmarkerZoomAnimation: true,\r\n\r\n\t\t// @option transform3DLimit: Number = 2^23\r\n\t\t// Defines the maximum size of a CSS translation transform. The default\r\n\t\t// value should not be changed unless a web browser positions layers in\r\n\t\t// the wrong place after doing a large `panBy`.\r\n\t\ttransform3DLimit: 8388608, // Precision limit of a 32-bit float\r\n\r\n\t\t// @section Interaction Options\r\n\t\t// @option zoomSnap: Number = 1\r\n\t\t// Forces the map's zoom level to always be a multiple of this, particularly\r\n\t\t// right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.\r\n\t\t// By default, the zoom level snaps to the nearest integer; lower values\r\n\t\t// (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`\r\n\t\t// means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.\r\n\t\tzoomSnap: 1,\r\n\r\n\t\t// @option zoomDelta: Number = 1\r\n\t\t// Controls how much the map's zoom level will change after a\r\n\t\t// [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`\r\n\t\t// or `-` on the keyboard, or using the [zoom controls](#control-zoom).\r\n\t\t// Values smaller than `1` (e.g. `0.5`) allow for greater granularity.\r\n\t\tzoomDelta: 1,\r\n\r\n\t\t// @option trackResize: Boolean = true\r\n\t\t// Whether the map automatically handles browser window resize to update itself.\r\n\t\ttrackResize: true\r\n\t},\r\n\r\n\tinitialize: function (id, options) { // (HTMLElement or String, Object)\r\n\t\toptions = setOptions(this, options);\r\n\r\n\t\t// Make sure to assign internal flags at the beginning,\r\n\t\t// to avoid inconsistent state in some edge cases.\r\n\t\tthis._handlers = [];\r\n\t\tthis._layers = {};\r\n\t\tthis._zoomBoundLayers = {};\r\n\t\tthis._sizeChanged = true;\r\n\r\n\t\tthis._initContainer(id);\r\n\t\tthis._initLayout();\r\n\r\n\t\t// hack for https://github.com/Leaflet/Leaflet/issues/1980\r\n\t\tthis._onResize = bind(this._onResize, this);\r\n\r\n\t\tthis._initEvents();\r\n\r\n\t\tif (options.maxBounds) {\r\n\t\t\tthis.setMaxBounds(options.maxBounds);\r\n\t\t}\r\n\r\n\t\tif (options.zoom !== undefined) {\r\n\t\t\tthis._zoom = this._limitZoom(options.zoom);\r\n\t\t}\r\n\r\n\t\tif (options.center && options.zoom !== undefined) {\r\n\t\t\tthis.setView(toLatLng(options.center), options.zoom, {reset: true});\r\n\t\t}\r\n\r\n\t\tthis.callInitHooks();\r\n\r\n\t\t// don't animate on browsers without hardware-accelerated transitions or old Android/Opera\r\n\t\tthis._zoomAnimated = TRANSITION && any3d && !mobileOpera &&\r\n\t\t\t\tthis.options.zoomAnimation;\r\n\r\n\t\t// zoom transitions run with the same duration for all layers, so if one of transitionend events\r\n\t\t// happens after starting zoom animation (propagating to the map pane), we know that it ended globally\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tthis._createAnimProxy();\r\n\t\t\ton(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);\r\n\t\t}\r\n\r\n\t\tthis._addLayers(this.options.layers);\r\n\t},\r\n\r\n\r\n\t// @section Methods for modifying map state\r\n\r\n\t// @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this\r\n\t// Sets the view of the map (geographical center and zoom) with the given\r\n\t// animation options.\r\n\tsetView: function (center, zoom, options) {\r\n\r\n\t\tzoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);\r\n\t\tcenter = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);\r\n\t\toptions = options || {};\r\n\r\n\t\tthis._stop();\r\n\r\n\t\tif (this._loaded && !options.reset && options !== true) {\r\n\r\n\t\t\tif (options.animate !== undefined) {\r\n\t\t\t\toptions.zoom = extend({animate: options.animate}, options.zoom);\r\n\t\t\t\toptions.pan = extend({animate: options.animate, duration: options.duration}, options.pan);\r\n\t\t\t}\r\n\r\n\t\t\t// try animating pan or zoom\r\n\t\t\tvar moved = (this._zoom !== zoom) ?\r\n\t\t\t\tthis._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :\r\n\t\t\t\tthis._tryAnimatedPan(center, options.pan);\r\n\r\n\t\t\tif (moved) {\r\n\t\t\t\t// prevent resize handler call, the view will refresh after animation anyway\r\n\t\t\t\tclearTimeout(this._sizeTimer);\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// animation didn't start, just reset the map view\r\n\t\tthis._resetView(center, zoom);\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setZoom(zoom: Number, options?: Zoom/pan options): this\r\n\t// Sets the zoom of the map.\r\n\tsetZoom: function (zoom, options) {\r\n\t\tif (!this._loaded) {\r\n\t\t\tthis._zoom = zoom;\r\n\t\t\treturn this;\r\n\t\t}\r\n\t\treturn this.setView(this.getCenter(), zoom, {zoom: options});\r\n\t},\r\n\r\n\t// @method zoomIn(delta?: Number, options?: Zoom options): this\r\n\t// Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).\r\n\tzoomIn: function (delta, options) {\r\n\t\tdelta = delta || (any3d ? this.options.zoomDelta : 1);\r\n\t\treturn this.setZoom(this._zoom + delta, options);\r\n\t},\r\n\r\n\t// @method zoomOut(delta?: Number, options?: Zoom options): this\r\n\t// Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).\r\n\tzoomOut: function (delta, options) {\r\n\t\tdelta = delta || (any3d ? this.options.zoomDelta : 1);\r\n\t\treturn this.setZoom(this._zoom - delta, options);\r\n\t},\r\n\r\n\t// @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this\r\n\t// Zooms the map while keeping a specified geographical point on the map\r\n\t// stationary (e.g. used internally for scroll zoom and double-click zoom).\r\n\t// @alternative\r\n\t// @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this\r\n\t// Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.\r\n\tsetZoomAround: function (latlng, zoom, options) {\r\n\t\tvar scale = this.getZoomScale(zoom),\r\n\t\t viewHalf = this.getSize().divideBy(2),\r\n\t\t containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),\r\n\r\n\t\t centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),\r\n\t\t newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));\r\n\r\n\t\treturn this.setView(newCenter, zoom, {zoom: options});\r\n\t},\r\n\r\n\t_getBoundsCenterZoom: function (bounds, options) {\r\n\r\n\t\toptions = options || {};\r\n\t\tbounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);\r\n\r\n\t\tvar paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),\r\n\t\t paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),\r\n\r\n\t\t zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));\r\n\r\n\t\tzoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;\r\n\r\n\t\tif (zoom === Infinity) {\r\n\t\t\treturn {\r\n\t\t\t\tcenter: bounds.getCenter(),\r\n\t\t\t\tzoom: zoom\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tvar paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),\r\n\r\n\t\t swPoint = this.project(bounds.getSouthWest(), zoom),\r\n\t\t nePoint = this.project(bounds.getNorthEast(), zoom),\r\n\t\t center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);\r\n\r\n\t\treturn {\r\n\t\t\tcenter: center,\r\n\t\t\tzoom: zoom\r\n\t\t};\r\n\t},\r\n\r\n\t// @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this\r\n\t// Sets a map view that contains the given geographical bounds with the\r\n\t// maximum zoom level possible.\r\n\tfitBounds: function (bounds, options) {\r\n\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tif (!bounds.isValid()) {\r\n\t\t\tthrow new Error('Bounds are not valid.');\r\n\t\t}\r\n\r\n\t\tvar target = this._getBoundsCenterZoom(bounds, options);\r\n\t\treturn this.setView(target.center, target.zoom, options);\r\n\t},\r\n\r\n\t// @method fitWorld(options?: fitBounds options): this\r\n\t// Sets a map view that mostly contains the whole world with the maximum\r\n\t// zoom level possible.\r\n\tfitWorld: function (options) {\r\n\t\treturn this.fitBounds([[-90, -180], [90, 180]], options);\r\n\t},\r\n\r\n\t// @method panTo(latlng: LatLng, options?: Pan options): this\r\n\t// Pans the map to a given center.\r\n\tpanTo: function (center, options) { // (LatLng)\r\n\t\treturn this.setView(center, this._zoom, {pan: options});\r\n\t},\r\n\r\n\t// @method panBy(offset: Point, options?: Pan options): this\r\n\t// Pans the map by a given number of pixels (animated).\r\n\tpanBy: function (offset, options) {\r\n\t\toffset = toPoint(offset).round();\r\n\t\toptions = options || {};\r\n\r\n\t\tif (!offset.x && !offset.y) {\r\n\t\t\treturn this.fire('moveend');\r\n\t\t}\r\n\t\t// If we pan too far, Chrome gets issues with tiles\r\n\t\t// and makes them disappear or appear in the wrong place (slightly offset) #2602\r\n\t\tif (options.animate !== true && !this.getSize().contains(offset)) {\r\n\t\t\tthis._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tif (!this._panAnim) {\r\n\t\t\tthis._panAnim = new PosAnimation();\r\n\r\n\t\t\tthis._panAnim.on({\r\n\t\t\t\t'step': this._onPanTransitionStep,\r\n\t\t\t\t'end': this._onPanTransitionEnd\r\n\t\t\t}, this);\r\n\t\t}\r\n\r\n\t\t// don't fire movestart if animating inertia\r\n\t\tif (!options.noMoveStart) {\r\n\t\t\tthis.fire('movestart');\r\n\t\t}\r\n\r\n\t\t// animate pan unless animate: false specified\r\n\t\tif (options.animate !== false) {\r\n\t\t\taddClass(this._mapPane, 'leaflet-pan-anim');\r\n\r\n\t\t\tvar newPos = this._getMapPanePos().subtract(offset).round();\r\n\t\t\tthis._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);\r\n\t\t} else {\r\n\t\t\tthis._rawPanBy(offset);\r\n\t\t\tthis.fire('move').fire('moveend');\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this\r\n\t// Sets the view of the map (geographical center and zoom) performing a smooth\r\n\t// pan-zoom animation.\r\n\tflyTo: function (targetCenter, targetZoom, options) {\r\n\r\n\t\toptions = options || {};\r\n\t\tif (options.animate === false || !any3d) {\r\n\t\t\treturn this.setView(targetCenter, targetZoom, options);\r\n\t\t}\r\n\r\n\t\tthis._stop();\r\n\r\n\t\tvar from = this.project(this.getCenter()),\r\n\t\t to = this.project(targetCenter),\r\n\t\t size = this.getSize(),\r\n\t\t startZoom = this._zoom;\r\n\r\n\t\ttargetCenter = toLatLng(targetCenter);\r\n\t\ttargetZoom = targetZoom === undefined ? startZoom : targetZoom;\r\n\r\n\t\tvar w0 = Math.max(size.x, size.y),\r\n\t\t w1 = w0 * this.getZoomScale(startZoom, targetZoom),\r\n\t\t u1 = (to.distanceTo(from)) || 1,\r\n\t\t rho = 1.42,\r\n\t\t rho2 = rho * rho;\r\n\r\n\t\tfunction r(i) {\r\n\t\t\tvar s1 = i ? -1 : 1,\r\n\t\t\t s2 = i ? w1 : w0,\r\n\t\t\t t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,\r\n\t\t\t b1 = 2 * s2 * rho2 * u1,\r\n\t\t\t b = t1 / b1,\r\n\t\t\t sq = Math.sqrt(b * b + 1) - b;\r\n\r\n\t\t\t // workaround for floating point precision bug when sq = 0, log = -Infinite,\r\n\t\t\t // thus triggering an infinite loop in flyTo\r\n\t\t\t var log = sq < 0.000000001 ? -18 : Math.log(sq);\r\n\r\n\t\t\treturn log;\r\n\t\t}\r\n\r\n\t\tfunction sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }\r\n\t\tfunction cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }\r\n\t\tfunction tanh(n) { return sinh(n) / cosh(n); }\r\n\r\n\t\tvar r0 = r(0);\r\n\r\n\t\tfunction w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }\r\n\t\tfunction u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }\r\n\r\n\t\tfunction easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }\r\n\r\n\t\tvar start = Date.now(),\r\n\t\t S = (r(1) - r0) / rho,\r\n\t\t duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;\r\n\r\n\t\tfunction frame() {\r\n\t\t\tvar t = (Date.now() - start) / duration,\r\n\t\t\t s = easeOut(t) * S;\r\n\r\n\t\t\tif (t <= 1) {\r\n\t\t\t\tthis._flyToFrame = requestAnimFrame(frame, this);\r\n\r\n\t\t\t\tthis._move(\r\n\t\t\t\t\tthis.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),\r\n\t\t\t\t\tthis.getScaleZoom(w0 / w(s), startZoom),\r\n\t\t\t\t\t{flyTo: true});\r\n\r\n\t\t\t} else {\r\n\t\t\t\tthis\r\n\t\t\t\t\t._move(targetCenter, targetZoom)\r\n\t\t\t\t\t._moveEnd(true);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis._moveStart(true, options.noMoveStart);\r\n\r\n\t\tframe.call(this);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this\r\n\t// Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),\r\n\t// but takes a bounds parameter like [`fitBounds`](#map-fitbounds).\r\n\tflyToBounds: function (bounds, options) {\r\n\t\tvar target = this._getBoundsCenterZoom(bounds, options);\r\n\t\treturn this.flyTo(target.center, target.zoom, options);\r\n\t},\r\n\r\n\t// @method setMaxBounds(bounds: Bounds): this\r\n\t// Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).\r\n\tsetMaxBounds: function (bounds) {\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tif (!bounds.isValid()) {\r\n\t\t\tthis.options.maxBounds = null;\r\n\t\t\treturn this.off('moveend', this._panInsideMaxBounds);\r\n\t\t} else if (this.options.maxBounds) {\r\n\t\t\tthis.off('moveend', this._panInsideMaxBounds);\r\n\t\t}\r\n\r\n\t\tthis.options.maxBounds = bounds;\r\n\r\n\t\tif (this._loaded) {\r\n\t\t\tthis._panInsideMaxBounds();\r\n\t\t}\r\n\r\n\t\treturn this.on('moveend', this._panInsideMaxBounds);\r\n\t},\r\n\r\n\t// @method setMinZoom(zoom: Number): this\r\n\t// Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).\r\n\tsetMinZoom: function (zoom) {\r\n\t\tvar oldZoom = this.options.minZoom;\r\n\t\tthis.options.minZoom = zoom;\r\n\r\n\t\tif (this._loaded && oldZoom !== zoom) {\r\n\t\t\tthis.fire('zoomlevelschange');\r\n\r\n\t\t\tif (this.getZoom() < this.options.minZoom) {\r\n\t\t\t\treturn this.setZoom(zoom);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setMaxZoom(zoom: Number): this\r\n\t// Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).\r\n\tsetMaxZoom: function (zoom) {\r\n\t\tvar oldZoom = this.options.maxZoom;\r\n\t\tthis.options.maxZoom = zoom;\r\n\r\n\t\tif (this._loaded && oldZoom !== zoom) {\r\n\t\t\tthis.fire('zoomlevelschange');\r\n\r\n\t\t\tif (this.getZoom() > this.options.maxZoom) {\r\n\t\t\t\treturn this.setZoom(zoom);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this\r\n\t// Pans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any.\r\n\tpanInsideBounds: function (bounds, options) {\r\n\t\tthis._enforcingBounds = true;\r\n\t\tvar center = this.getCenter(),\r\n\t\t newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));\r\n\r\n\t\tif (!center.equals(newCenter)) {\r\n\t\t\tthis.panTo(newCenter, options);\r\n\t\t}\r\n\r\n\t\tthis._enforcingBounds = false;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method panInside(latlng: LatLng, options?: options): this\r\n\t// Pans the map the minimum amount to make the `latlng` visible. Use\r\n\t// `padding`, `paddingTopLeft` and `paddingTopRight` options to fit\r\n\t// the display to more restricted bounds, like [`fitBounds`](#map-fitbounds).\r\n\t// If `latlng` is already within the (optionally padded) display bounds,\r\n\t// the map will not be panned.\r\n\tpanInside: function (latlng, options) {\r\n\t\toptions = options || {};\r\n\r\n\t\tvar paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),\r\n\t\t paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),\r\n\t\t center = this.getCenter(),\r\n\t\t pixelCenter = this.project(center),\r\n\t\t pixelPoint = this.project(latlng),\r\n\t\t pixelBounds = this.getPixelBounds(),\r\n\t\t halfPixelBounds = pixelBounds.getSize().divideBy(2),\r\n\t\t paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]);\r\n\r\n\t\tif (!paddedBounds.contains(pixelPoint)) {\r\n\t\t\tthis._enforcingBounds = true;\r\n\t\t\tvar diff = pixelCenter.subtract(pixelPoint),\r\n\t\t\t newCenter = toPoint(pixelPoint.x + diff.x, pixelPoint.y + diff.y);\r\n\r\n\t\t\tif (pixelPoint.x < paddedBounds.min.x || pixelPoint.x > paddedBounds.max.x) {\r\n\t\t\t\tnewCenter.x = pixelCenter.x - diff.x;\r\n\t\t\t\tif (diff.x > 0) {\r\n\t\t\t\t\tnewCenter.x += halfPixelBounds.x - paddingTL.x;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tnewCenter.x -= halfPixelBounds.x - paddingBR.x;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (pixelPoint.y < paddedBounds.min.y || pixelPoint.y > paddedBounds.max.y) {\r\n\t\t\t\tnewCenter.y = pixelCenter.y - diff.y;\r\n\t\t\t\tif (diff.y > 0) {\r\n\t\t\t\t\tnewCenter.y += halfPixelBounds.y - paddingTL.y;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tnewCenter.y -= halfPixelBounds.y - paddingBR.y;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tthis.panTo(this.unproject(newCenter), options);\r\n\t\t\tthis._enforcingBounds = false;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method invalidateSize(options: Zoom/pan options): this\r\n\t// Checks if the map container size changed and updates the map if so —\r\n\t// call it after you've changed the map size dynamically, also animating\r\n\t// pan by default. If `options.pan` is `false`, panning will not occur.\r\n\t// If `options.debounceMoveend` is `true`, it will delay `moveend` event so\r\n\t// that it doesn't happen often even if the method is called many\r\n\t// times in a row.\r\n\r\n\t// @alternative\r\n\t// @method invalidateSize(animate: Boolean): this\r\n\t// Checks if the map container size changed and updates the map if so —\r\n\t// call it after you've changed the map size dynamically, also animating\r\n\t// pan by default.\r\n\tinvalidateSize: function (options) {\r\n\t\tif (!this._loaded) { return this; }\r\n\r\n\t\toptions = extend({\r\n\t\t\tanimate: false,\r\n\t\t\tpan: true\r\n\t\t}, options === true ? {animate: true} : options);\r\n\r\n\t\tvar oldSize = this.getSize();\r\n\t\tthis._sizeChanged = true;\r\n\t\tthis._lastCenter = null;\r\n\r\n\t\tvar newSize = this.getSize(),\r\n\t\t oldCenter = oldSize.divideBy(2).round(),\r\n\t\t newCenter = newSize.divideBy(2).round(),\r\n\t\t offset = oldCenter.subtract(newCenter);\r\n\r\n\t\tif (!offset.x && !offset.y) { return this; }\r\n\r\n\t\tif (options.animate && options.pan) {\r\n\t\t\tthis.panBy(offset);\r\n\r\n\t\t} else {\r\n\t\t\tif (options.pan) {\r\n\t\t\t\tthis._rawPanBy(offset);\r\n\t\t\t}\r\n\r\n\t\t\tthis.fire('move');\r\n\r\n\t\t\tif (options.debounceMoveend) {\r\n\t\t\t\tclearTimeout(this._sizeTimer);\r\n\t\t\t\tthis._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);\r\n\t\t\t} else {\r\n\t\t\t\tthis.fire('moveend');\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// @section Map state change events\r\n\t\t// @event resize: ResizeEvent\r\n\t\t// Fired when the map is resized.\r\n\t\treturn this.fire('resize', {\r\n\t\t\toldSize: oldSize,\r\n\t\t\tnewSize: newSize\r\n\t\t});\r\n\t},\r\n\r\n\t// @section Methods for modifying map state\r\n\t// @method stop(): this\r\n\t// Stops the currently running `panTo` or `flyTo` animation, if any.\r\n\tstop: function () {\r\n\t\tthis.setZoom(this._limitZoom(this._zoom));\r\n\t\tif (!this.options.zoomSnap) {\r\n\t\t\tthis.fire('viewreset');\r\n\t\t}\r\n\t\treturn this._stop();\r\n\t},\r\n\r\n\t// @section Geolocation methods\r\n\t// @method locate(options?: Locate options): this\r\n\t// Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)\r\n\t// event with location data on success or a [`locationerror`](#map-locationerror) event on failure,\r\n\t// and optionally sets the map view to the user's location with respect to\r\n\t// detection accuracy (or to the world view if geolocation failed).\r\n\t// Note that, if your page doesn't use HTTPS, this method will fail in\r\n\t// modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))\r\n\t// See `Locate options` for more details.\r\n\tlocate: function (options) {\r\n\r\n\t\toptions = this._locateOptions = extend({\r\n\t\t\ttimeout: 10000,\r\n\t\t\twatch: false\r\n\t\t\t// setView: false\r\n\t\t\t// maxZoom: \r\n\t\t\t// maximumAge: 0\r\n\t\t\t// enableHighAccuracy: false\r\n\t\t}, options);\r\n\r\n\t\tif (!('geolocation' in navigator)) {\r\n\t\t\tthis._handleGeolocationError({\r\n\t\t\t\tcode: 0,\r\n\t\t\t\tmessage: 'Geolocation not supported.'\r\n\t\t\t});\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tvar onResponse = bind(this._handleGeolocationResponse, this),\r\n\t\t onError = bind(this._handleGeolocationError, this);\r\n\r\n\t\tif (options.watch) {\r\n\t\t\tthis._locationWatchId =\r\n\t\t\t navigator.geolocation.watchPosition(onResponse, onError, options);\r\n\t\t} else {\r\n\t\t\tnavigator.geolocation.getCurrentPosition(onResponse, onError, options);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method stopLocate(): this\r\n\t// Stops watching location previously initiated by `map.locate({watch: true})`\r\n\t// and aborts resetting the map view if map.locate was called with\r\n\t// `{setView: true}`.\r\n\tstopLocate: function () {\r\n\t\tif (navigator.geolocation && navigator.geolocation.clearWatch) {\r\n\t\t\tnavigator.geolocation.clearWatch(this._locationWatchId);\r\n\t\t}\r\n\t\tif (this._locateOptions) {\r\n\t\t\tthis._locateOptions.setView = false;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_handleGeolocationError: function (error) {\r\n\t\tvar c = error.code,\r\n\t\t message = error.message ||\r\n\t\t (c === 1 ? 'permission denied' :\r\n\t\t (c === 2 ? 'position unavailable' : 'timeout'));\r\n\r\n\t\tif (this._locateOptions.setView && !this._loaded) {\r\n\t\t\tthis.fitWorld();\r\n\t\t}\r\n\r\n\t\t// @section Location events\r\n\t\t// @event locationerror: ErrorEvent\r\n\t\t// Fired when geolocation (using the [`locate`](#map-locate) method) failed.\r\n\t\tthis.fire('locationerror', {\r\n\t\t\tcode: c,\r\n\t\t\tmessage: 'Geolocation error: ' + message + '.'\r\n\t\t});\r\n\t},\r\n\r\n\t_handleGeolocationResponse: function (pos) {\r\n\t\tvar lat = pos.coords.latitude,\r\n\t\t lng = pos.coords.longitude,\r\n\t\t latlng = new LatLng(lat, lng),\r\n\t\t bounds = latlng.toBounds(pos.coords.accuracy * 2),\r\n\t\t options = this._locateOptions;\r\n\r\n\t\tif (options.setView) {\r\n\t\t\tvar zoom = this.getBoundsZoom(bounds);\r\n\t\t\tthis.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);\r\n\t\t}\r\n\r\n\t\tvar data = {\r\n\t\t\tlatlng: latlng,\r\n\t\t\tbounds: bounds,\r\n\t\t\ttimestamp: pos.timestamp\r\n\t\t};\r\n\r\n\t\tfor (var i in pos.coords) {\r\n\t\t\tif (typeof pos.coords[i] === 'number') {\r\n\t\t\t\tdata[i] = pos.coords[i];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// @event locationfound: LocationEvent\r\n\t\t// Fired when geolocation (using the [`locate`](#map-locate) method)\r\n\t\t// went successfully.\r\n\t\tthis.fire('locationfound', data);\r\n\t},\r\n\r\n\t// TODO Appropriate docs section?\r\n\t// @section Other Methods\r\n\t// @method addHandler(name: String, HandlerClass: Function): this\r\n\t// Adds a new `Handler` to the map, given its name and constructor function.\r\n\taddHandler: function (name, HandlerClass) {\r\n\t\tif (!HandlerClass) { return this; }\r\n\r\n\t\tvar handler = this[name] = new HandlerClass(this);\r\n\r\n\t\tthis._handlers.push(handler);\r\n\r\n\t\tif (this.options[name]) {\r\n\t\t\thandler.enable();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method remove(): this\r\n\t// Destroys the map and clears all related event listeners.\r\n\tremove: function () {\r\n\r\n\t\tthis._initEvents(true);\r\n\r\n\t\tif (this._containerId !== this._container._leaflet_id) {\r\n\t\t\tthrow new Error('Map container is being reused by another instance');\r\n\t\t}\r\n\r\n\t\ttry {\r\n\t\t\t// throws error in IE6-8\r\n\t\t\tdelete this._container._leaflet_id;\r\n\t\t\tdelete this._containerId;\r\n\t\t} catch (e) {\r\n\t\t\t/*eslint-disable */\r\n\t\t\tthis._container._leaflet_id = undefined;\r\n\t\t\t/* eslint-enable */\r\n\t\t\tthis._containerId = undefined;\r\n\t\t}\r\n\r\n\t\tif (this._locationWatchId !== undefined) {\r\n\t\t\tthis.stopLocate();\r\n\t\t}\r\n\r\n\t\tthis._stop();\r\n\r\n\t\tremove(this._mapPane);\r\n\r\n\t\tif (this._clearControlPos) {\r\n\t\t\tthis._clearControlPos();\r\n\t\t}\r\n\t\tif (this._resizeRequest) {\r\n\t\t\tcancelAnimFrame(this._resizeRequest);\r\n\t\t\tthis._resizeRequest = null;\r\n\t\t}\r\n\r\n\t\tthis._clearHandlers();\r\n\r\n\t\tif (this._loaded) {\r\n\t\t\t// @section Map state change events\r\n\t\t\t// @event unload: Event\r\n\t\t\t// Fired when the map is destroyed with [remove](#map-remove) method.\r\n\t\t\tthis.fire('unload');\r\n\t\t}\r\n\r\n\t\tvar i;\r\n\t\tfor (i in this._layers) {\r\n\t\t\tthis._layers[i].remove();\r\n\t\t}\r\n\t\tfor (i in this._panes) {\r\n\t\t\tremove(this._panes[i]);\r\n\t\t}\r\n\r\n\t\tthis._layers = [];\r\n\t\tthis._panes = [];\r\n\t\tdelete this._mapPane;\r\n\t\tdelete this._renderer;\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @section Other Methods\r\n\t// @method createPane(name: String, container?: HTMLElement): HTMLElement\r\n\t// Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,\r\n\t// then returns it. The pane is created as a child of `container`, or\r\n\t// as a child of the main map pane if not set.\r\n\tcreatePane: function (name, container) {\r\n\t\tvar className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),\r\n\t\t pane = create$1('div', className, container || this._mapPane);\r\n\r\n\t\tif (name) {\r\n\t\t\tthis._panes[name] = pane;\r\n\t\t}\r\n\t\treturn pane;\r\n\t},\r\n\r\n\t// @section Methods for Getting Map State\r\n\r\n\t// @method getCenter(): LatLng\r\n\t// Returns the geographical center of the map view\r\n\tgetCenter: function () {\r\n\t\tthis._checkIfLoaded();\r\n\r\n\t\tif (this._lastCenter && !this._moved()) {\r\n\t\t\treturn this._lastCenter;\r\n\t\t}\r\n\t\treturn this.layerPointToLatLng(this._getCenterLayerPoint());\r\n\t},\r\n\r\n\t// @method getZoom(): Number\r\n\t// Returns the current zoom level of the map view\r\n\tgetZoom: function () {\r\n\t\treturn this._zoom;\r\n\t},\r\n\r\n\t// @method getBounds(): LatLngBounds\r\n\t// Returns the geographical bounds visible in the current map view\r\n\tgetBounds: function () {\r\n\t\tvar bounds = this.getPixelBounds(),\r\n\t\t sw = this.unproject(bounds.getBottomLeft()),\r\n\t\t ne = this.unproject(bounds.getTopRight());\r\n\r\n\t\treturn new LatLngBounds(sw, ne);\r\n\t},\r\n\r\n\t// @method getMinZoom(): Number\r\n\t// Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default.\r\n\tgetMinZoom: function () {\r\n\t\treturn this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;\r\n\t},\r\n\r\n\t// @method getMaxZoom(): Number\r\n\t// Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).\r\n\tgetMaxZoom: function () {\r\n\t\treturn this.options.maxZoom === undefined ?\r\n\t\t\t(this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :\r\n\t\t\tthis.options.maxZoom;\r\n\t},\r\n\r\n\t// @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number\r\n\t// Returns the maximum zoom level on which the given bounds fit to the map\r\n\t// view in its entirety. If `inside` (optional) is set to `true`, the method\r\n\t// instead returns the minimum zoom level on which the map view fits into\r\n\t// the given bounds in its entirety.\r\n\tgetBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\t\tpadding = toPoint(padding || [0, 0]);\r\n\r\n\t\tvar zoom = this.getZoom() || 0,\r\n\t\t min = this.getMinZoom(),\r\n\t\t max = this.getMaxZoom(),\r\n\t\t nw = bounds.getNorthWest(),\r\n\t\t se = bounds.getSouthEast(),\r\n\t\t size = this.getSize().subtract(padding),\r\n\t\t boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),\r\n\t\t snap = any3d ? this.options.zoomSnap : 1,\r\n\t\t scalex = size.x / boundsSize.x,\r\n\t\t scaley = size.y / boundsSize.y,\r\n\t\t scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);\r\n\r\n\t\tzoom = this.getScaleZoom(scale, zoom);\r\n\r\n\t\tif (snap) {\r\n\t\t\tzoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level\r\n\t\t\tzoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;\r\n\t\t}\r\n\r\n\t\treturn Math.max(min, Math.min(max, zoom));\r\n\t},\r\n\r\n\t// @method getSize(): Point\r\n\t// Returns the current size of the map container (in pixels).\r\n\tgetSize: function () {\r\n\t\tif (!this._size || this._sizeChanged) {\r\n\t\t\tthis._size = new Point(\r\n\t\t\t\tthis._container.clientWidth || 0,\r\n\t\t\t\tthis._container.clientHeight || 0);\r\n\r\n\t\t\tthis._sizeChanged = false;\r\n\t\t}\r\n\t\treturn this._size.clone();\r\n\t},\r\n\r\n\t// @method getPixelBounds(): Bounds\r\n\t// Returns the bounds of the current map view in projected pixel\r\n\t// coordinates (sometimes useful in layer and overlay implementations).\r\n\tgetPixelBounds: function (center, zoom) {\r\n\t\tvar topLeftPoint = this._getTopLeftPoint(center, zoom);\r\n\t\treturn new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));\r\n\t},\r\n\r\n\t// TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to\r\n\t// the map pane? \"left point of the map layer\" can be confusing, specially\r\n\t// since there can be negative offsets.\r\n\t// @method getPixelOrigin(): Point\r\n\t// Returns the projected pixel coordinates of the top left point of\r\n\t// the map layer (useful in custom layer and overlay implementations).\r\n\tgetPixelOrigin: function () {\r\n\t\tthis._checkIfLoaded();\r\n\t\treturn this._pixelOrigin;\r\n\t},\r\n\r\n\t// @method getPixelWorldBounds(zoom?: Number): Bounds\r\n\t// Returns the world's bounds in pixel coordinates for zoom level `zoom`.\r\n\t// If `zoom` is omitted, the map's current zoom level is used.\r\n\tgetPixelWorldBounds: function (zoom) {\r\n\t\treturn this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);\r\n\t},\r\n\r\n\t// @section Other Methods\r\n\r\n\t// @method getPane(pane: String|HTMLElement): HTMLElement\r\n\t// Returns a [map pane](#map-pane), given its name or its HTML element (its identity).\r\n\tgetPane: function (pane) {\r\n\t\treturn typeof pane === 'string' ? this._panes[pane] : pane;\r\n\t},\r\n\r\n\t// @method getPanes(): Object\r\n\t// Returns a plain object containing the names of all [panes](#map-pane) as keys and\r\n\t// the panes as values.\r\n\tgetPanes: function () {\r\n\t\treturn this._panes;\r\n\t},\r\n\r\n\t// @method getContainer: HTMLElement\r\n\t// Returns the HTML element that contains the map.\r\n\tgetContainer: function () {\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\r\n\t// @section Conversion Methods\r\n\r\n\t// @method getZoomScale(toZoom: Number, fromZoom: Number): Number\r\n\t// Returns the scale factor to be applied to a map transition from zoom level\r\n\t// `fromZoom` to `toZoom`. Used internally to help with zoom animations.\r\n\tgetZoomScale: function (toZoom, fromZoom) {\r\n\t\t// TODO replace with universal implementation after refactoring projections\r\n\t\tvar crs = this.options.crs;\r\n\t\tfromZoom = fromZoom === undefined ? this._zoom : fromZoom;\r\n\t\treturn crs.scale(toZoom) / crs.scale(fromZoom);\r\n\t},\r\n\r\n\t// @method getScaleZoom(scale: Number, fromZoom: Number): Number\r\n\t// Returns the zoom level that the map would end up at, if it is at `fromZoom`\r\n\t// level and everything is scaled by a factor of `scale`. Inverse of\r\n\t// [`getZoomScale`](#map-getZoomScale).\r\n\tgetScaleZoom: function (scale, fromZoom) {\r\n\t\tvar crs = this.options.crs;\r\n\t\tfromZoom = fromZoom === undefined ? this._zoom : fromZoom;\r\n\t\tvar zoom = crs.zoom(scale * crs.scale(fromZoom));\r\n\t\treturn isNaN(zoom) ? Infinity : zoom;\r\n\t},\r\n\r\n\t// @method project(latlng: LatLng, zoom: Number): Point\r\n\t// Projects a geographical coordinate `LatLng` according to the projection\r\n\t// of the map's CRS, then scales it according to `zoom` and the CRS's\r\n\t// `Transformation`. The result is pixel coordinate relative to\r\n\t// the CRS origin.\r\n\tproject: function (latlng, zoom) {\r\n\t\tzoom = zoom === undefined ? this._zoom : zoom;\r\n\t\treturn this.options.crs.latLngToPoint(toLatLng(latlng), zoom);\r\n\t},\r\n\r\n\t// @method unproject(point: Point, zoom: Number): LatLng\r\n\t// Inverse of [`project`](#map-project).\r\n\tunproject: function (point, zoom) {\r\n\t\tzoom = zoom === undefined ? this._zoom : zoom;\r\n\t\treturn this.options.crs.pointToLatLng(toPoint(point), zoom);\r\n\t},\r\n\r\n\t// @method layerPointToLatLng(point: Point): LatLng\r\n\t// Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),\r\n\t// returns the corresponding geographical coordinate (for the current zoom level).\r\n\tlayerPointToLatLng: function (point) {\r\n\t\tvar projectedPoint = toPoint(point).add(this.getPixelOrigin());\r\n\t\treturn this.unproject(projectedPoint);\r\n\t},\r\n\r\n\t// @method latLngToLayerPoint(latlng: LatLng): Point\r\n\t// Given a geographical coordinate, returns the corresponding pixel coordinate\r\n\t// relative to the [origin pixel](#map-getpixelorigin).\r\n\tlatLngToLayerPoint: function (latlng) {\r\n\t\tvar projectedPoint = this.project(toLatLng(latlng))._round();\r\n\t\treturn projectedPoint._subtract(this.getPixelOrigin());\r\n\t},\r\n\r\n\t// @method wrapLatLng(latlng: LatLng): LatLng\r\n\t// Returns a `LatLng` where `lat` and `lng` has been wrapped according to the\r\n\t// map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the\r\n\t// CRS's bounds.\r\n\t// By default this means longitude is wrapped around the dateline so its\r\n\t// value is between -180 and +180 degrees.\r\n\twrapLatLng: function (latlng) {\r\n\t\treturn this.options.crs.wrapLatLng(toLatLng(latlng));\r\n\t},\r\n\r\n\t// @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds\r\n\t// Returns a `LatLngBounds` with the same size as the given one, ensuring that\r\n\t// its center is within the CRS's bounds.\r\n\t// By default this means the center longitude is wrapped around the dateline so its\r\n\t// value is between -180 and +180 degrees, and the majority of the bounds\r\n\t// overlaps the CRS's bounds.\r\n\twrapLatLngBounds: function (latlng) {\r\n\t\treturn this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));\r\n\t},\r\n\r\n\t// @method distance(latlng1: LatLng, latlng2: LatLng): Number\r\n\t// Returns the distance between two geographical coordinates according to\r\n\t// the map's CRS. By default this measures distance in meters.\r\n\tdistance: function (latlng1, latlng2) {\r\n\t\treturn this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));\r\n\t},\r\n\r\n\t// @method containerPointToLayerPoint(point: Point): Point\r\n\t// Given a pixel coordinate relative to the map container, returns the corresponding\r\n\t// pixel coordinate relative to the [origin pixel](#map-getpixelorigin).\r\n\tcontainerPointToLayerPoint: function (point) { // (Point)\r\n\t\treturn toPoint(point).subtract(this._getMapPanePos());\r\n\t},\r\n\r\n\t// @method layerPointToContainerPoint(point: Point): Point\r\n\t// Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),\r\n\t// returns the corresponding pixel coordinate relative to the map container.\r\n\tlayerPointToContainerPoint: function (point) { // (Point)\r\n\t\treturn toPoint(point).add(this._getMapPanePos());\r\n\t},\r\n\r\n\t// @method containerPointToLatLng(point: Point): LatLng\r\n\t// Given a pixel coordinate relative to the map container, returns\r\n\t// the corresponding geographical coordinate (for the current zoom level).\r\n\tcontainerPointToLatLng: function (point) {\r\n\t\tvar layerPoint = this.containerPointToLayerPoint(toPoint(point));\r\n\t\treturn this.layerPointToLatLng(layerPoint);\r\n\t},\r\n\r\n\t// @method latLngToContainerPoint(latlng: LatLng): Point\r\n\t// Given a geographical coordinate, returns the corresponding pixel coordinate\r\n\t// relative to the map container.\r\n\tlatLngToContainerPoint: function (latlng) {\r\n\t\treturn this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));\r\n\t},\r\n\r\n\t// @method mouseEventToContainerPoint(ev: MouseEvent): Point\r\n\t// Given a MouseEvent object, returns the pixel coordinate relative to the\r\n\t// map container where the event took place.\r\n\tmouseEventToContainerPoint: function (e) {\r\n\t\treturn getMousePosition(e, this._container);\r\n\t},\r\n\r\n\t// @method mouseEventToLayerPoint(ev: MouseEvent): Point\r\n\t// Given a MouseEvent object, returns the pixel coordinate relative to\r\n\t// the [origin pixel](#map-getpixelorigin) where the event took place.\r\n\tmouseEventToLayerPoint: function (e) {\r\n\t\treturn this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));\r\n\t},\r\n\r\n\t// @method mouseEventToLatLng(ev: MouseEvent): LatLng\r\n\t// Given a MouseEvent object, returns geographical coordinate where the\r\n\t// event took place.\r\n\tmouseEventToLatLng: function (e) { // (MouseEvent)\r\n\t\treturn this.layerPointToLatLng(this.mouseEventToLayerPoint(e));\r\n\t},\r\n\r\n\r\n\t// map initialization methods\r\n\r\n\t_initContainer: function (id) {\r\n\t\tvar container = this._container = get(id);\r\n\r\n\t\tif (!container) {\r\n\t\t\tthrow new Error('Map container not found.');\r\n\t\t} else if (container._leaflet_id) {\r\n\t\t\tthrow new Error('Map container is already initialized.');\r\n\t\t}\r\n\r\n\t\ton(container, 'scroll', this._onScroll, this);\r\n\t\tthis._containerId = stamp(container);\r\n\t},\r\n\r\n\t_initLayout: function () {\r\n\t\tvar container = this._container;\r\n\r\n\t\tthis._fadeAnimated = this.options.fadeAnimation && any3d;\r\n\r\n\t\taddClass(container, 'leaflet-container' +\r\n\t\t\t(touch ? ' leaflet-touch' : '') +\r\n\t\t\t(retina ? ' leaflet-retina' : '') +\r\n\t\t\t(ielt9 ? ' leaflet-oldie' : '') +\r\n\t\t\t(safari ? ' leaflet-safari' : '') +\r\n\t\t\t(this._fadeAnimated ? ' leaflet-fade-anim' : ''));\r\n\r\n\t\tvar position = getStyle(container, 'position');\r\n\r\n\t\tif (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {\r\n\t\t\tcontainer.style.position = 'relative';\r\n\t\t}\r\n\r\n\t\tthis._initPanes();\r\n\r\n\t\tif (this._initControlPos) {\r\n\t\t\tthis._initControlPos();\r\n\t\t}\r\n\t},\r\n\r\n\t_initPanes: function () {\r\n\t\tvar panes = this._panes = {};\r\n\t\tthis._paneRenderers = {};\r\n\r\n\t\t// @section\r\n\t\t//\r\n\t\t// Panes are DOM elements used to control the ordering of layers on the map. You\r\n\t\t// can access panes with [`map.getPane`](#map-getpane) or\r\n\t\t// [`map.getPanes`](#map-getpanes) methods. New panes can be created with the\r\n\t\t// [`map.createPane`](#map-createpane) method.\r\n\t\t//\r\n\t\t// Every map has the following default panes that differ only in zIndex.\r\n\t\t//\r\n\t\t// @pane mapPane: HTMLElement = 'auto'\r\n\t\t// Pane that contains all other map panes\r\n\r\n\t\tthis._mapPane = this.createPane('mapPane', this._container);\r\n\t\tsetPosition(this._mapPane, new Point(0, 0));\r\n\r\n\t\t// @pane tilePane: HTMLElement = 200\r\n\t\t// Pane for `GridLayer`s and `TileLayer`s\r\n\t\tthis.createPane('tilePane');\r\n\t\t// @pane overlayPane: HTMLElement = 400\r\n\t\t// Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s\r\n\t\tthis.createPane('shadowPane');\r\n\t\t// @pane shadowPane: HTMLElement = 500\r\n\t\t// Pane for overlay shadows (e.g. `Marker` shadows)\r\n\t\tthis.createPane('overlayPane');\r\n\t\t// @pane markerPane: HTMLElement = 600\r\n\t\t// Pane for `Icon`s of `Marker`s\r\n\t\tthis.createPane('markerPane');\r\n\t\t// @pane tooltipPane: HTMLElement = 650\r\n\t\t// Pane for `Tooltip`s.\r\n\t\tthis.createPane('tooltipPane');\r\n\t\t// @pane popupPane: HTMLElement = 700\r\n\t\t// Pane for `Popup`s.\r\n\t\tthis.createPane('popupPane');\r\n\r\n\t\tif (!this.options.markerZoomAnimation) {\r\n\t\t\taddClass(panes.markerPane, 'leaflet-zoom-hide');\r\n\t\t\taddClass(panes.shadowPane, 'leaflet-zoom-hide');\r\n\t\t}\r\n\t},\r\n\r\n\r\n\t// private methods that modify map state\r\n\r\n\t// @section Map state change events\r\n\t_resetView: function (center, zoom) {\r\n\t\tsetPosition(this._mapPane, new Point(0, 0));\r\n\r\n\t\tvar loading = !this._loaded;\r\n\t\tthis._loaded = true;\r\n\t\tzoom = this._limitZoom(zoom);\r\n\r\n\t\tthis.fire('viewprereset');\r\n\r\n\t\tvar zoomChanged = this._zoom !== zoom;\r\n\t\tthis\r\n\t\t\t._moveStart(zoomChanged, false)\r\n\t\t\t._move(center, zoom)\r\n\t\t\t._moveEnd(zoomChanged);\r\n\r\n\t\t// @event viewreset: Event\r\n\t\t// Fired when the map needs to redraw its content (this usually happens\r\n\t\t// on map zoom or load). Very useful for creating custom overlays.\r\n\t\tthis.fire('viewreset');\r\n\r\n\t\t// @event load: Event\r\n\t\t// Fired when the map is initialized (when its center and zoom are set\r\n\t\t// for the first time).\r\n\t\tif (loading) {\r\n\t\t\tthis.fire('load');\r\n\t\t}\r\n\t},\r\n\r\n\t_moveStart: function (zoomChanged, noMoveStart) {\r\n\t\t// @event zoomstart: Event\r\n\t\t// Fired when the map zoom is about to change (e.g. before zoom animation).\r\n\t\t// @event movestart: Event\r\n\t\t// Fired when the view of the map starts changing (e.g. user starts dragging the map).\r\n\t\tif (zoomChanged) {\r\n\t\t\tthis.fire('zoomstart');\r\n\t\t}\r\n\t\tif (!noMoveStart) {\r\n\t\t\tthis.fire('movestart');\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_move: function (center, zoom, data) {\r\n\t\tif (zoom === undefined) {\r\n\t\t\tzoom = this._zoom;\r\n\t\t}\r\n\t\tvar zoomChanged = this._zoom !== zoom;\r\n\r\n\t\tthis._zoom = zoom;\r\n\t\tthis._lastCenter = center;\r\n\t\tthis._pixelOrigin = this._getNewPixelOrigin(center);\r\n\r\n\t\t// @event zoom: Event\r\n\t\t// Fired repeatedly during any change in zoom level, including zoom\r\n\t\t// and fly animations.\r\n\t\tif (zoomChanged || (data && data.pinch)) {\t// Always fire 'zoom' if pinching because #3530\r\n\t\t\tthis.fire('zoom', data);\r\n\t\t}\r\n\r\n\t\t// @event move: Event\r\n\t\t// Fired repeatedly during any movement of the map, including pan and\r\n\t\t// fly animations.\r\n\t\treturn this.fire('move', data);\r\n\t},\r\n\r\n\t_moveEnd: function (zoomChanged) {\r\n\t\t// @event zoomend: Event\r\n\t\t// Fired when the map has changed, after any animations.\r\n\t\tif (zoomChanged) {\r\n\t\t\tthis.fire('zoomend');\r\n\t\t}\r\n\r\n\t\t// @event moveend: Event\r\n\t\t// Fired when the center of the map stops changing (e.g. user stopped\r\n\t\t// dragging the map).\r\n\t\treturn this.fire('moveend');\r\n\t},\r\n\r\n\t_stop: function () {\r\n\t\tcancelAnimFrame(this._flyToFrame);\r\n\t\tif (this._panAnim) {\r\n\t\t\tthis._panAnim.stop();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_rawPanBy: function (offset) {\r\n\t\tsetPosition(this._mapPane, this._getMapPanePos().subtract(offset));\r\n\t},\r\n\r\n\t_getZoomSpan: function () {\r\n\t\treturn this.getMaxZoom() - this.getMinZoom();\r\n\t},\r\n\r\n\t_panInsideMaxBounds: function () {\r\n\t\tif (!this._enforcingBounds) {\r\n\t\t\tthis.panInsideBounds(this.options.maxBounds);\r\n\t\t}\r\n\t},\r\n\r\n\t_checkIfLoaded: function () {\r\n\t\tif (!this._loaded) {\r\n\t\t\tthrow new Error('Set map center and zoom first.');\r\n\t\t}\r\n\t},\r\n\r\n\t// DOM event handling\r\n\r\n\t// @section Interaction events\r\n\t_initEvents: function (remove$$1) {\r\n\t\tthis._targets = {};\r\n\t\tthis._targets[stamp(this._container)] = this;\r\n\r\n\t\tvar onOff = remove$$1 ? off : on;\r\n\r\n\t\t// @event click: MouseEvent\r\n\t\t// Fired when the user clicks (or taps) the map.\r\n\t\t// @event dblclick: MouseEvent\r\n\t\t// Fired when the user double-clicks (or double-taps) the map.\r\n\t\t// @event mousedown: MouseEvent\r\n\t\t// Fired when the user pushes the mouse button on the map.\r\n\t\t// @event mouseup: MouseEvent\r\n\t\t// Fired when the user releases the mouse button on the map.\r\n\t\t// @event mouseover: MouseEvent\r\n\t\t// Fired when the mouse enters the map.\r\n\t\t// @event mouseout: MouseEvent\r\n\t\t// Fired when the mouse leaves the map.\r\n\t\t// @event mousemove: MouseEvent\r\n\t\t// Fired while the mouse moves over the map.\r\n\t\t// @event contextmenu: MouseEvent\r\n\t\t// Fired when the user pushes the right mouse button on the map, prevents\r\n\t\t// default browser context menu from showing if there are listeners on\r\n\t\t// this event. Also fired on mobile when the user holds a single touch\r\n\t\t// for a second (also called long press).\r\n\t\t// @event keypress: KeyboardEvent\r\n\t\t// Fired when the user presses a key from the keyboard that produces a character value while the map is focused.\r\n\t\t// @event keydown: KeyboardEvent\r\n\t\t// Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,\r\n\t\t// the `keydown` event is fired for keys that produce a character value and for keys\r\n\t\t// that do not produce a character value.\r\n\t\t// @event keyup: KeyboardEvent\r\n\t\t// Fired when the user releases a key from the keyboard while the map is focused.\r\n\t\tonOff(this._container, 'click dblclick mousedown mouseup ' +\r\n\t\t\t'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);\r\n\r\n\t\tif (this.options.trackResize) {\r\n\t\t\tonOff(window, 'resize', this._onResize, this);\r\n\t\t}\r\n\r\n\t\tif (any3d && this.options.transform3DLimit) {\r\n\t\t\t(remove$$1 ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);\r\n\t\t}\r\n\t},\r\n\r\n\t_onResize: function () {\r\n\t\tcancelAnimFrame(this._resizeRequest);\r\n\t\tthis._resizeRequest = requestAnimFrame(\r\n\t\t function () { this.invalidateSize({debounceMoveend: true}); }, this);\r\n\t},\r\n\r\n\t_onScroll: function () {\r\n\t\tthis._container.scrollTop = 0;\r\n\t\tthis._container.scrollLeft = 0;\r\n\t},\r\n\r\n\t_onMoveEnd: function () {\r\n\t\tvar pos = this._getMapPanePos();\r\n\t\tif (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {\r\n\t\t\t// https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have\r\n\t\t\t// a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/\r\n\t\t\tthis._resetView(this.getCenter(), this.getZoom());\r\n\t\t}\r\n\t},\r\n\r\n\t_findEventTargets: function (e, type) {\r\n\t\tvar targets = [],\r\n\t\t target,\r\n\t\t isHover = type === 'mouseout' || type === 'mouseover',\r\n\t\t src = e.target || e.srcElement,\r\n\t\t dragging = false;\r\n\r\n\t\twhile (src) {\r\n\t\t\ttarget = this._targets[stamp(src)];\r\n\t\t\tif (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {\r\n\t\t\t\t// Prevent firing click after you just dragged an object.\r\n\t\t\t\tdragging = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (target && target.listens(type, true)) {\r\n\t\t\t\tif (isHover && !isExternalTarget(src, e)) { break; }\r\n\t\t\t\ttargets.push(target);\r\n\t\t\t\tif (isHover) { break; }\r\n\t\t\t}\r\n\t\t\tif (src === this._container) { break; }\r\n\t\t\tsrc = src.parentNode;\r\n\t\t}\r\n\t\tif (!targets.length && !dragging && !isHover && isExternalTarget(src, e)) {\r\n\t\t\ttargets = [this];\r\n\t\t}\r\n\t\treturn targets;\r\n\t},\r\n\r\n\t_handleDOMEvent: function (e) {\r\n\t\tif (!this._loaded || skipped(e)) { return; }\r\n\r\n\t\tvar type = e.type;\r\n\r\n\t\tif (type === 'mousedown' || type === 'keypress' || type === 'keyup' || type === 'keydown') {\r\n\t\t\t// prevents outline when clicking on keyboard-focusable element\r\n\t\t\tpreventOutline(e.target || e.srcElement);\r\n\t\t}\r\n\r\n\t\tthis._fireDOMEvent(e, type);\r\n\t},\r\n\r\n\t_mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],\r\n\r\n\t_fireDOMEvent: function (e, type, targets) {\r\n\r\n\t\tif (e.type === 'click') {\r\n\t\t\t// Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).\r\n\t\t\t// @event preclick: MouseEvent\r\n\t\t\t// Fired before mouse click on the map (sometimes useful when you\r\n\t\t\t// want something to happen on click before any existing click\r\n\t\t\t// handlers start running).\r\n\t\t\tvar synth = extend({}, e);\r\n\t\t\tsynth.type = 'preclick';\r\n\t\t\tthis._fireDOMEvent(synth, synth.type, targets);\r\n\t\t}\r\n\r\n\t\tif (e._stopped) { return; }\r\n\r\n\t\t// Find the layer the event is propagating from and its parents.\r\n\t\ttargets = (targets || []).concat(this._findEventTargets(e, type));\r\n\r\n\t\tif (!targets.length) { return; }\r\n\r\n\t\tvar target = targets[0];\r\n\t\tif (type === 'contextmenu' && target.listens(type, true)) {\r\n\t\t\tpreventDefault(e);\r\n\t\t}\r\n\r\n\t\tvar data = {\r\n\t\t\toriginalEvent: e\r\n\t\t};\r\n\r\n\t\tif (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {\r\n\t\t\tvar isMarker = target.getLatLng && (!target._radius || target._radius <= 10);\r\n\t\t\tdata.containerPoint = isMarker ?\r\n\t\t\t\tthis.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);\r\n\t\t\tdata.layerPoint = this.containerPointToLayerPoint(data.containerPoint);\r\n\t\t\tdata.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);\r\n\t\t}\r\n\r\n\t\tfor (var i = 0; i < targets.length; i++) {\r\n\t\t\ttargets[i].fire(type, data, true);\r\n\t\t\tif (data.originalEvent._stopped ||\r\n\t\t\t\t(targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }\r\n\t\t}\r\n\t},\r\n\r\n\t_draggableMoved: function (obj) {\r\n\t\tobj = obj.dragging && obj.dragging.enabled() ? obj : this;\r\n\t\treturn (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());\r\n\t},\r\n\r\n\t_clearHandlers: function () {\r\n\t\tfor (var i = 0, len = this._handlers.length; i < len; i++) {\r\n\t\t\tthis._handlers[i].disable();\r\n\t\t}\r\n\t},\r\n\r\n\t// @section Other Methods\r\n\r\n\t// @method whenReady(fn: Function, context?: Object): this\r\n\t// Runs the given function `fn` when the map gets initialized with\r\n\t// a view (center and zoom) and at least one layer, or immediately\r\n\t// if it's already initialized, optionally passing a function context.\r\n\twhenReady: function (callback, context) {\r\n\t\tif (this._loaded) {\r\n\t\t\tcallback.call(context || this, {target: this});\r\n\t\t} else {\r\n\t\t\tthis.on('load', callback, context);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\r\n\t// private methods for getting map state\r\n\r\n\t_getMapPanePos: function () {\r\n\t\treturn getPosition(this._mapPane) || new Point(0, 0);\r\n\t},\r\n\r\n\t_moved: function () {\r\n\t\tvar pos = this._getMapPanePos();\r\n\t\treturn pos && !pos.equals([0, 0]);\r\n\t},\r\n\r\n\t_getTopLeftPoint: function (center, zoom) {\r\n\t\tvar pixelOrigin = center && zoom !== undefined ?\r\n\t\t\tthis._getNewPixelOrigin(center, zoom) :\r\n\t\t\tthis.getPixelOrigin();\r\n\t\treturn pixelOrigin.subtract(this._getMapPanePos());\r\n\t},\r\n\r\n\t_getNewPixelOrigin: function (center, zoom) {\r\n\t\tvar viewHalf = this.getSize()._divideBy(2);\r\n\t\treturn this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();\r\n\t},\r\n\r\n\t_latLngToNewLayerPoint: function (latlng, zoom, center) {\r\n\t\tvar topLeft = this._getNewPixelOrigin(center, zoom);\r\n\t\treturn this.project(latlng, zoom)._subtract(topLeft);\r\n\t},\r\n\r\n\t_latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {\r\n\t\tvar topLeft = this._getNewPixelOrigin(center, zoom);\r\n\t\treturn toBounds([\r\n\t\t\tthis.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),\r\n\t\t\tthis.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),\r\n\t\t\tthis.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),\r\n\t\t\tthis.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)\r\n\t\t]);\r\n\t},\r\n\r\n\t// layer point of the current center\r\n\t_getCenterLayerPoint: function () {\r\n\t\treturn this.containerPointToLayerPoint(this.getSize()._divideBy(2));\r\n\t},\r\n\r\n\t// offset of the specified place to the current center in pixels\r\n\t_getCenterOffset: function (latlng) {\r\n\t\treturn this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());\r\n\t},\r\n\r\n\t// adjust center for view to get inside bounds\r\n\t_limitCenter: function (center, zoom, bounds) {\r\n\r\n\t\tif (!bounds) { return center; }\r\n\r\n\t\tvar centerPoint = this.project(center, zoom),\r\n\t\t viewHalf = this.getSize().divideBy(2),\r\n\t\t viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),\r\n\t\t offset = this._getBoundsOffset(viewBounds, bounds, zoom);\r\n\r\n\t\t// If offset is less than a pixel, ignore.\r\n\t\t// This prevents unstable projections from getting into\r\n\t\t// an infinite loop of tiny offsets.\r\n\t\tif (offset.round().equals([0, 0])) {\r\n\t\t\treturn center;\r\n\t\t}\r\n\r\n\t\treturn this.unproject(centerPoint.add(offset), zoom);\r\n\t},\r\n\r\n\t// adjust offset for view to get inside bounds\r\n\t_limitOffset: function (offset, bounds) {\r\n\t\tif (!bounds) { return offset; }\r\n\r\n\t\tvar viewBounds = this.getPixelBounds(),\r\n\t\t newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));\r\n\r\n\t\treturn offset.add(this._getBoundsOffset(newBounds, bounds));\r\n\t},\r\n\r\n\t// returns offset needed for pxBounds to get inside maxBounds at a specified zoom\r\n\t_getBoundsOffset: function (pxBounds, maxBounds, zoom) {\r\n\t\tvar projectedMaxBounds = toBounds(\r\n\t\t this.project(maxBounds.getNorthEast(), zoom),\r\n\t\t this.project(maxBounds.getSouthWest(), zoom)\r\n\t\t ),\r\n\t\t minOffset = projectedMaxBounds.min.subtract(pxBounds.min),\r\n\t\t maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),\r\n\r\n\t\t dx = this._rebound(minOffset.x, -maxOffset.x),\r\n\t\t dy = this._rebound(minOffset.y, -maxOffset.y);\r\n\r\n\t\treturn new Point(dx, dy);\r\n\t},\r\n\r\n\t_rebound: function (left, right) {\r\n\t\treturn left + right > 0 ?\r\n\t\t\tMath.round(left - right) / 2 :\r\n\t\t\tMath.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));\r\n\t},\r\n\r\n\t_limitZoom: function (zoom) {\r\n\t\tvar min = this.getMinZoom(),\r\n\t\t max = this.getMaxZoom(),\r\n\t\t snap = any3d ? this.options.zoomSnap : 1;\r\n\t\tif (snap) {\r\n\t\t\tzoom = Math.round(zoom / snap) * snap;\r\n\t\t}\r\n\t\treturn Math.max(min, Math.min(max, zoom));\r\n\t},\r\n\r\n\t_onPanTransitionStep: function () {\r\n\t\tthis.fire('move');\r\n\t},\r\n\r\n\t_onPanTransitionEnd: function () {\r\n\t\tremoveClass(this._mapPane, 'leaflet-pan-anim');\r\n\t\tthis.fire('moveend');\r\n\t},\r\n\r\n\t_tryAnimatedPan: function (center, options) {\r\n\t\t// difference between the new and current centers in pixels\r\n\t\tvar offset = this._getCenterOffset(center)._trunc();\r\n\r\n\t\t// don't animate too far unless animate: true specified in options\r\n\t\tif ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }\r\n\r\n\t\tthis.panBy(offset, options);\r\n\r\n\t\treturn true;\r\n\t},\r\n\r\n\t_createAnimProxy: function () {\r\n\r\n\t\tvar proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');\r\n\t\tthis._panes.mapPane.appendChild(proxy);\r\n\r\n\t\tthis.on('zoomanim', function (e) {\r\n\t\t\tvar prop = TRANSFORM,\r\n\t\t\t transform = this._proxy.style[prop];\r\n\r\n\t\t\tsetTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));\r\n\r\n\t\t\t// workaround for case when transform is the same and so transitionend event is not fired\r\n\t\t\tif (transform === this._proxy.style[prop] && this._animatingZoom) {\r\n\t\t\t\tthis._onZoomTransitionEnd();\r\n\t\t\t}\r\n\t\t}, this);\r\n\r\n\t\tthis.on('load moveend', function () {\r\n\t\t\tvar c = this.getCenter(),\r\n\t\t\t z = this.getZoom();\r\n\t\t\tsetTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));\r\n\t\t}, this);\r\n\r\n\t\tthis._on('unload', this._destroyAnimProxy, this);\r\n\t},\r\n\r\n\t_destroyAnimProxy: function () {\r\n\t\tremove(this._proxy);\r\n\t\tdelete this._proxy;\r\n\t},\r\n\r\n\t_catchTransitionEnd: function (e) {\r\n\t\tif (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {\r\n\t\t\tthis._onZoomTransitionEnd();\r\n\t\t}\r\n\t},\r\n\r\n\t_nothingToAnimate: function () {\r\n\t\treturn !this._container.getElementsByClassName('leaflet-zoom-animated').length;\r\n\t},\r\n\r\n\t_tryAnimatedZoom: function (center, zoom, options) {\r\n\r\n\t\tif (this._animatingZoom) { return true; }\r\n\r\n\t\toptions = options || {};\r\n\r\n\t\t// don't animate if disabled, not supported or zoom difference is too large\r\n\t\tif (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||\r\n\t\t Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }\r\n\r\n\t\t// offset is the pixel coords of the zoom origin relative to the current center\r\n\t\tvar scale = this.getZoomScale(zoom),\r\n\t\t offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);\r\n\r\n\t\t// don't animate if the zoom origin isn't within one screen from the current center, unless forced\r\n\t\tif (options.animate !== true && !this.getSize().contains(offset)) { return false; }\r\n\r\n\t\trequestAnimFrame(function () {\r\n\t\t\tthis\r\n\t\t\t ._moveStart(true, false)\r\n\t\t\t ._animateZoom(center, zoom, true);\r\n\t\t}, this);\r\n\r\n\t\treturn true;\r\n\t},\r\n\r\n\t_animateZoom: function (center, zoom, startAnim, noUpdate) {\r\n\t\tif (!this._mapPane) { return; }\r\n\r\n\t\tif (startAnim) {\r\n\t\t\tthis._animatingZoom = true;\r\n\r\n\t\t\t// remember what center/zoom to set after animation\r\n\t\t\tthis._animateToCenter = center;\r\n\t\t\tthis._animateToZoom = zoom;\r\n\r\n\t\t\taddClass(this._mapPane, 'leaflet-zoom-anim');\r\n\t\t}\r\n\r\n\t\t// @event zoomanim: ZoomAnimEvent\r\n\t\t// Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.\r\n\t\tthis.fire('zoomanim', {\r\n\t\t\tcenter: center,\r\n\t\t\tzoom: zoom,\r\n\t\t\tnoUpdate: noUpdate\r\n\t\t});\r\n\r\n\t\t// Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693\r\n\t\tsetTimeout(bind(this._onZoomTransitionEnd, this), 250);\r\n\t},\r\n\r\n\t_onZoomTransitionEnd: function () {\r\n\t\tif (!this._animatingZoom) { return; }\r\n\r\n\t\tif (this._mapPane) {\r\n\t\t\tremoveClass(this._mapPane, 'leaflet-zoom-anim');\r\n\t\t}\r\n\r\n\t\tthis._animatingZoom = false;\r\n\r\n\t\tthis._move(this._animateToCenter, this._animateToZoom);\r\n\r\n\t\t// This anim frame should prevent an obscure iOS webkit tile loading race condition.\r\n\t\trequestAnimFrame(function () {\r\n\t\t\tthis._moveEnd(true);\r\n\t\t}, this);\r\n\t}\r\n});\r\n\r\n// @section\r\n\r\n// @factory L.map(id: String, options?: Map options)\r\n// Instantiates a map object given the DOM ID of a `
    ` element\r\n// and optionally an object literal with `Map options`.\r\n//\r\n// @alternative\r\n// @factory L.map(el: HTMLElement, options?: Map options)\r\n// Instantiates a map object given an instance of a `
    ` HTML element\r\n// and optionally an object literal with `Map options`.\r\nfunction createMap(id, options) {\r\n\treturn new Map(id, options);\r\n}\n\n/*\r\n * @class Control\r\n * @aka L.Control\r\n * @inherits Class\r\n *\r\n * L.Control is a base class for implementing map controls. Handles positioning.\r\n * All other controls extend from this class.\r\n */\r\n\r\nvar Control = Class.extend({\r\n\t// @section\r\n\t// @aka Control options\r\n\toptions: {\r\n\t\t// @option position: String = 'topright'\r\n\t\t// The position of the control (one of the map corners). Possible values are `'topleft'`,\r\n\t\t// `'topright'`, `'bottomleft'` or `'bottomright'`\r\n\t\tposition: 'topright'\r\n\t},\r\n\r\n\tinitialize: function (options) {\r\n\t\tsetOptions(this, options);\r\n\t},\r\n\r\n\t/* @section\r\n\t * Classes extending L.Control will inherit the following methods:\r\n\t *\r\n\t * @method getPosition: string\r\n\t * Returns the position of the control.\r\n\t */\r\n\tgetPosition: function () {\r\n\t\treturn this.options.position;\r\n\t},\r\n\r\n\t// @method setPosition(position: string): this\r\n\t// Sets the position of the control.\r\n\tsetPosition: function (position) {\r\n\t\tvar map = this._map;\r\n\r\n\t\tif (map) {\r\n\t\t\tmap.removeControl(this);\r\n\t\t}\r\n\r\n\t\tthis.options.position = position;\r\n\r\n\t\tif (map) {\r\n\t\t\tmap.addControl(this);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getContainer: HTMLElement\r\n\t// Returns the HTMLElement that contains the control.\r\n\tgetContainer: function () {\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\t// @method addTo(map: Map): this\r\n\t// Adds the control to the given map.\r\n\taddTo: function (map) {\r\n\t\tthis.remove();\r\n\t\tthis._map = map;\r\n\r\n\t\tvar container = this._container = this.onAdd(map),\r\n\t\t pos = this.getPosition(),\r\n\t\t corner = map._controlCorners[pos];\r\n\r\n\t\taddClass(container, 'leaflet-control');\r\n\r\n\t\tif (pos.indexOf('bottom') !== -1) {\r\n\t\t\tcorner.insertBefore(container, corner.firstChild);\r\n\t\t} else {\r\n\t\t\tcorner.appendChild(container);\r\n\t\t}\r\n\r\n\t\tthis._map.on('unload', this.remove, this);\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method remove: this\r\n\t// Removes the control from the map it is currently active on.\r\n\tremove: function () {\r\n\t\tif (!this._map) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tremove(this._container);\r\n\r\n\t\tif (this.onRemove) {\r\n\t\t\tthis.onRemove(this._map);\r\n\t\t}\r\n\r\n\t\tthis._map.off('unload', this.remove, this);\r\n\t\tthis._map = null;\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_refocusOnMap: function (e) {\r\n\t\t// if map exists and event is not a keyboard event\r\n\t\tif (this._map && e && e.screenX > 0 && e.screenY > 0) {\r\n\t\t\tthis._map.getContainer().focus();\r\n\t\t}\r\n\t}\r\n});\r\n\r\nvar control = function (options) {\r\n\treturn new Control(options);\r\n};\r\n\r\n/* @section Extension methods\r\n * @uninheritable\r\n *\r\n * Every control should extend from `L.Control` and (re-)implement the following methods.\r\n *\r\n * @method onAdd(map: Map): HTMLElement\r\n * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).\r\n *\r\n * @method onRemove(map: Map)\r\n * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).\r\n */\r\n\r\n/* @namespace Map\r\n * @section Methods for Layers and Controls\r\n */\r\nMap.include({\r\n\t// @method addControl(control: Control): this\r\n\t// Adds the given control to the map\r\n\taddControl: function (control) {\r\n\t\tcontrol.addTo(this);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeControl(control: Control): this\r\n\t// Removes the given control from the map\r\n\tremoveControl: function (control) {\r\n\t\tcontrol.remove();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_initControlPos: function () {\r\n\t\tvar corners = this._controlCorners = {},\r\n\t\t l = 'leaflet-',\r\n\t\t container = this._controlContainer =\r\n\t\t create$1('div', l + 'control-container', this._container);\r\n\r\n\t\tfunction createCorner(vSide, hSide) {\r\n\t\t\tvar className = l + vSide + ' ' + l + hSide;\r\n\r\n\t\t\tcorners[vSide + hSide] = create$1('div', className, container);\r\n\t\t}\r\n\r\n\t\tcreateCorner('top', 'left');\r\n\t\tcreateCorner('top', 'right');\r\n\t\tcreateCorner('bottom', 'left');\r\n\t\tcreateCorner('bottom', 'right');\r\n\t},\r\n\r\n\t_clearControlPos: function () {\r\n\t\tfor (var i in this._controlCorners) {\r\n\t\t\tremove(this._controlCorners[i]);\r\n\t\t}\r\n\t\tremove(this._controlContainer);\r\n\t\tdelete this._controlCorners;\r\n\t\tdelete this._controlContainer;\r\n\t}\r\n});\n\n/*\r\n * @class Control.Layers\r\n * @aka L.Control.Layers\r\n * @inherits Control\r\n *\r\n * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](http://leafletjs.com/examples/layers-control/)). Extends `Control`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var baseLayers = {\r\n * \t\"Mapbox\": mapbox,\r\n * \t\"OpenStreetMap\": osm\r\n * };\r\n *\r\n * var overlays = {\r\n * \t\"Marker\": marker,\r\n * \t\"Roads\": roadsLayer\r\n * };\r\n *\r\n * L.control.layers(baseLayers, overlays).addTo(map);\r\n * ```\r\n *\r\n * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:\r\n *\r\n * ```js\r\n * {\r\n * \"\": layer1,\r\n * \"\": layer2\r\n * }\r\n * ```\r\n *\r\n * The layer names can contain HTML, which allows you to add additional styling to the items:\r\n *\r\n * ```js\r\n * {\" My Layer\": myLayer}\r\n * ```\r\n */\r\n\r\nvar Layers = Control.extend({\r\n\t// @section\r\n\t// @aka Control.Layers options\r\n\toptions: {\r\n\t\t// @option collapsed: Boolean = true\r\n\t\t// If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.\r\n\t\tcollapsed: true,\r\n\t\tposition: 'topright',\r\n\r\n\t\t// @option autoZIndex: Boolean = true\r\n\t\t// If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.\r\n\t\tautoZIndex: true,\r\n\r\n\t\t// @option hideSingleBase: Boolean = false\r\n\t\t// If `true`, the base layers in the control will be hidden when there is only one.\r\n\t\thideSingleBase: false,\r\n\r\n\t\t// @option sortLayers: Boolean = false\r\n\t\t// Whether to sort the layers. When `false`, layers will keep the order\r\n\t\t// in which they were added to the control.\r\n\t\tsortLayers: false,\r\n\r\n\t\t// @option sortFunction: Function = *\r\n\t\t// A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)\r\n\t\t// that will be used for sorting the layers, when `sortLayers` is `true`.\r\n\t\t// The function receives both the `L.Layer` instances and their names, as in\r\n\t\t// `sortFunction(layerA, layerB, nameA, nameB)`.\r\n\t\t// By default, it sorts layers alphabetically by their name.\r\n\t\tsortFunction: function (layerA, layerB, nameA, nameB) {\r\n\t\t\treturn nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);\r\n\t\t}\r\n\t},\r\n\r\n\tinitialize: function (baseLayers, overlays, options) {\r\n\t\tsetOptions(this, options);\r\n\r\n\t\tthis._layerControlInputs = [];\r\n\t\tthis._layers = [];\r\n\t\tthis._lastZIndex = 0;\r\n\t\tthis._handlingClick = false;\r\n\r\n\t\tfor (var i in baseLayers) {\r\n\t\t\tthis._addLayer(baseLayers[i], i);\r\n\t\t}\r\n\r\n\t\tfor (i in overlays) {\r\n\t\t\tthis._addLayer(overlays[i], i, true);\r\n\t\t}\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis._initLayout();\r\n\t\tthis._update();\r\n\r\n\t\tthis._map = map;\r\n\t\tmap.on('zoomend', this._checkDisabledLayers, this);\r\n\r\n\t\tfor (var i = 0; i < this._layers.length; i++) {\r\n\t\t\tthis._layers[i].layer.on('add remove', this._onLayerChange, this);\r\n\t\t}\r\n\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\taddTo: function (map) {\r\n\t\tControl.prototype.addTo.call(this, map);\r\n\t\t// Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.\r\n\t\treturn this._expandIfNotCollapsed();\r\n\t},\r\n\r\n\tonRemove: function () {\r\n\t\tthis._map.off('zoomend', this._checkDisabledLayers, this);\r\n\r\n\t\tfor (var i = 0; i < this._layers.length; i++) {\r\n\t\t\tthis._layers[i].layer.off('add remove', this._onLayerChange, this);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method addBaseLayer(layer: Layer, name: String): this\r\n\t// Adds a base layer (radio button entry) with the given name to the control.\r\n\taddBaseLayer: function (layer, name) {\r\n\t\tthis._addLayer(layer, name);\r\n\t\treturn (this._map) ? this._update() : this;\r\n\t},\r\n\r\n\t// @method addOverlay(layer: Layer, name: String): this\r\n\t// Adds an overlay (checkbox entry) with the given name to the control.\r\n\taddOverlay: function (layer, name) {\r\n\t\tthis._addLayer(layer, name, true);\r\n\t\treturn (this._map) ? this._update() : this;\r\n\t},\r\n\r\n\t// @method removeLayer(layer: Layer): this\r\n\t// Remove the given layer from the control.\r\n\tremoveLayer: function (layer) {\r\n\t\tlayer.off('add remove', this._onLayerChange, this);\r\n\r\n\t\tvar obj = this._getLayer(stamp(layer));\r\n\t\tif (obj) {\r\n\t\t\tthis._layers.splice(this._layers.indexOf(obj), 1);\r\n\t\t}\r\n\t\treturn (this._map) ? this._update() : this;\r\n\t},\r\n\r\n\t// @method expand(): this\r\n\t// Expand the control container if collapsed.\r\n\texpand: function () {\r\n\t\taddClass(this._container, 'leaflet-control-layers-expanded');\r\n\t\tthis._section.style.height = null;\r\n\t\tvar acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);\r\n\t\tif (acceptableHeight < this._section.clientHeight) {\r\n\t\t\taddClass(this._section, 'leaflet-control-layers-scrollbar');\r\n\t\t\tthis._section.style.height = acceptableHeight + 'px';\r\n\t\t} else {\r\n\t\t\tremoveClass(this._section, 'leaflet-control-layers-scrollbar');\r\n\t\t}\r\n\t\tthis._checkDisabledLayers();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method collapse(): this\r\n\t// Collapse the control container if expanded.\r\n\tcollapse: function () {\r\n\t\tremoveClass(this._container, 'leaflet-control-layers-expanded');\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_initLayout: function () {\r\n\t\tvar className = 'leaflet-control-layers',\r\n\t\t container = this._container = create$1('div', className),\r\n\t\t collapsed = this.options.collapsed;\r\n\r\n\t\t// makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released\r\n\t\tcontainer.setAttribute('aria-haspopup', true);\r\n\r\n\t\tdisableClickPropagation(container);\r\n\t\tdisableScrollPropagation(container);\r\n\r\n\t\tvar section = this._section = create$1('section', className + '-list');\r\n\r\n\t\tif (collapsed) {\r\n\t\t\tthis._map.on('click', this.collapse, this);\r\n\r\n\t\t\tif (!android) {\r\n\t\t\t\ton(container, {\r\n\t\t\t\t\tmouseenter: this.expand,\r\n\t\t\t\t\tmouseleave: this.collapse\r\n\t\t\t\t}, this);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvar link = this._layersLink = create$1('a', className + '-toggle', container);\r\n\t\tlink.href = '#';\r\n\t\tlink.title = 'Layers';\r\n\r\n\t\tif (touch) {\r\n\t\t\ton(link, 'click', stop);\r\n\t\t\ton(link, 'click', this.expand, this);\r\n\t\t} else {\r\n\t\t\ton(link, 'focus', this.expand, this);\r\n\t\t}\r\n\r\n\t\tif (!collapsed) {\r\n\t\t\tthis.expand();\r\n\t\t}\r\n\r\n\t\tthis._baseLayersList = create$1('div', className + '-base', section);\r\n\t\tthis._separator = create$1('div', className + '-separator', section);\r\n\t\tthis._overlaysList = create$1('div', className + '-overlays', section);\r\n\r\n\t\tcontainer.appendChild(section);\r\n\t},\r\n\r\n\t_getLayer: function (id) {\r\n\t\tfor (var i = 0; i < this._layers.length; i++) {\r\n\r\n\t\t\tif (this._layers[i] && stamp(this._layers[i].layer) === id) {\r\n\t\t\t\treturn this._layers[i];\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t_addLayer: function (layer, name, overlay) {\r\n\t\tif (this._map) {\r\n\t\t\tlayer.on('add remove', this._onLayerChange, this);\r\n\t\t}\r\n\r\n\t\tthis._layers.push({\r\n\t\t\tlayer: layer,\r\n\t\t\tname: name,\r\n\t\t\toverlay: overlay\r\n\t\t});\r\n\r\n\t\tif (this.options.sortLayers) {\r\n\t\t\tthis._layers.sort(bind(function (a, b) {\r\n\t\t\t\treturn this.options.sortFunction(a.layer, b.layer, a.name, b.name);\r\n\t\t\t}, this));\r\n\t\t}\r\n\r\n\t\tif (this.options.autoZIndex && layer.setZIndex) {\r\n\t\t\tthis._lastZIndex++;\r\n\t\t\tlayer.setZIndex(this._lastZIndex);\r\n\t\t}\r\n\r\n\t\tthis._expandIfNotCollapsed();\r\n\t},\r\n\r\n\t_update: function () {\r\n\t\tif (!this._container) { return this; }\r\n\r\n\t\tempty(this._baseLayersList);\r\n\t\tempty(this._overlaysList);\r\n\r\n\t\tthis._layerControlInputs = [];\r\n\t\tvar baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;\r\n\r\n\t\tfor (i = 0; i < this._layers.length; i++) {\r\n\t\t\tobj = this._layers[i];\r\n\t\t\tthis._addItem(obj);\r\n\t\t\toverlaysPresent = overlaysPresent || obj.overlay;\r\n\t\t\tbaseLayersPresent = baseLayersPresent || !obj.overlay;\r\n\t\t\tbaseLayersCount += !obj.overlay ? 1 : 0;\r\n\t\t}\r\n\r\n\t\t// Hide base layers section if there's only one layer.\r\n\t\tif (this.options.hideSingleBase) {\r\n\t\t\tbaseLayersPresent = baseLayersPresent && baseLayersCount > 1;\r\n\t\t\tthis._baseLayersList.style.display = baseLayersPresent ? '' : 'none';\r\n\t\t}\r\n\r\n\t\tthis._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_onLayerChange: function (e) {\r\n\t\tif (!this._handlingClick) {\r\n\t\t\tthis._update();\r\n\t\t}\r\n\r\n\t\tvar obj = this._getLayer(stamp(e.target));\r\n\r\n\t\t// @namespace Map\r\n\t\t// @section Layer events\r\n\t\t// @event baselayerchange: LayersControlEvent\r\n\t\t// Fired when the base layer is changed through the [layer control](#control-layers).\r\n\t\t// @event overlayadd: LayersControlEvent\r\n\t\t// Fired when an overlay is selected through the [layer control](#control-layers).\r\n\t\t// @event overlayremove: LayersControlEvent\r\n\t\t// Fired when an overlay is deselected through the [layer control](#control-layers).\r\n\t\t// @namespace Control.Layers\r\n\t\tvar type = obj.overlay ?\r\n\t\t\t(e.type === 'add' ? 'overlayadd' : 'overlayremove') :\r\n\t\t\t(e.type === 'add' ? 'baselayerchange' : null);\r\n\r\n\t\tif (type) {\r\n\t\t\tthis._map.fire(type, obj);\r\n\t\t}\r\n\t},\r\n\r\n\t// IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)\r\n\t_createRadioElement: function (name, checked) {\r\n\r\n\t\tvar radioHtml = '';\r\n\r\n\t\tvar radioFragment = document.createElement('div');\r\n\t\tradioFragment.innerHTML = radioHtml;\r\n\r\n\t\treturn radioFragment.firstChild;\r\n\t},\r\n\r\n\t_addItem: function (obj) {\r\n\t\tvar label = document.createElement('label'),\r\n\t\t checked = this._map.hasLayer(obj.layer),\r\n\t\t input;\r\n\r\n\t\tif (obj.overlay) {\r\n\t\t\tinput = document.createElement('input');\r\n\t\t\tinput.type = 'checkbox';\r\n\t\t\tinput.className = 'leaflet-control-layers-selector';\r\n\t\t\tinput.defaultChecked = checked;\r\n\t\t} else {\r\n\t\t\tinput = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked);\r\n\t\t}\r\n\r\n\t\tthis._layerControlInputs.push(input);\r\n\t\tinput.layerId = stamp(obj.layer);\r\n\r\n\t\ton(input, 'click', this._onInputClick, this);\r\n\r\n\t\tvar name = document.createElement('span');\r\n\t\tname.innerHTML = ' ' + obj.name;\r\n\r\n\t\t// Helps from preventing layer control flicker when checkboxes are disabled\r\n\t\t// https://github.com/Leaflet/Leaflet/issues/2771\r\n\t\tvar holder = document.createElement('div');\r\n\r\n\t\tlabel.appendChild(holder);\r\n\t\tholder.appendChild(input);\r\n\t\tholder.appendChild(name);\r\n\r\n\t\tvar container = obj.overlay ? this._overlaysList : this._baseLayersList;\r\n\t\tcontainer.appendChild(label);\r\n\r\n\t\tthis._checkDisabledLayers();\r\n\t\treturn label;\r\n\t},\r\n\r\n\t_onInputClick: function () {\r\n\t\tvar inputs = this._layerControlInputs,\r\n\t\t input, layer;\r\n\t\tvar addedLayers = [],\r\n\t\t removedLayers = [];\r\n\r\n\t\tthis._handlingClick = true;\r\n\r\n\t\tfor (var i = inputs.length - 1; i >= 0; i--) {\r\n\t\t\tinput = inputs[i];\r\n\t\t\tlayer = this._getLayer(input.layerId).layer;\r\n\r\n\t\t\tif (input.checked) {\r\n\t\t\t\taddedLayers.push(layer);\r\n\t\t\t} else if (!input.checked) {\r\n\t\t\t\tremovedLayers.push(layer);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Bugfix issue 2318: Should remove all old layers before readding new ones\r\n\t\tfor (i = 0; i < removedLayers.length; i++) {\r\n\t\t\tif (this._map.hasLayer(removedLayers[i])) {\r\n\t\t\t\tthis._map.removeLayer(removedLayers[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (i = 0; i < addedLayers.length; i++) {\r\n\t\t\tif (!this._map.hasLayer(addedLayers[i])) {\r\n\t\t\t\tthis._map.addLayer(addedLayers[i]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis._handlingClick = false;\r\n\r\n\t\tthis._refocusOnMap();\r\n\t},\r\n\r\n\t_checkDisabledLayers: function () {\r\n\t\tvar inputs = this._layerControlInputs,\r\n\t\t input,\r\n\t\t layer,\r\n\t\t zoom = this._map.getZoom();\r\n\r\n\t\tfor (var i = inputs.length - 1; i >= 0; i--) {\r\n\t\t\tinput = inputs[i];\r\n\t\t\tlayer = this._getLayer(input.layerId).layer;\r\n\t\t\tinput.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||\r\n\t\t\t (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);\r\n\r\n\t\t}\r\n\t},\r\n\r\n\t_expandIfNotCollapsed: function () {\r\n\t\tif (this._map && !this.options.collapsed) {\r\n\t\t\tthis.expand();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_expand: function () {\r\n\t\t// Backward compatibility, remove me in 1.1.\r\n\t\treturn this.expand();\r\n\t},\r\n\r\n\t_collapse: function () {\r\n\t\t// Backward compatibility, remove me in 1.1.\r\n\t\treturn this.collapse();\r\n\t}\r\n\r\n});\r\n\r\n\r\n// @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)\r\n// Creates an attribution control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.\r\nvar layers = function (baseLayers, overlays, options) {\r\n\treturn new Layers(baseLayers, overlays, options);\r\n};\n\n/*\r\n * @class Control.Zoom\r\n * @aka L.Control.Zoom\r\n * @inherits Control\r\n *\r\n * A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its [`zoomControl` option](#map-zoomcontrol) to `false`. Extends `Control`.\r\n */\r\n\r\nvar Zoom = Control.extend({\r\n\t// @section\r\n\t// @aka Control.Zoom options\r\n\toptions: {\r\n\t\tposition: 'topleft',\r\n\r\n\t\t// @option zoomInText: String = '+'\r\n\t\t// The text set on the 'zoom in' button.\r\n\t\tzoomInText: '+',\r\n\r\n\t\t// @option zoomInTitle: String = 'Zoom in'\r\n\t\t// The title set on the 'zoom in' button.\r\n\t\tzoomInTitle: 'Zoom in',\r\n\r\n\t\t// @option zoomOutText: String = '−'\r\n\t\t// The text set on the 'zoom out' button.\r\n\t\tzoomOutText: '−',\r\n\r\n\t\t// @option zoomOutTitle: String = 'Zoom out'\r\n\t\t// The title set on the 'zoom out' button.\r\n\t\tzoomOutTitle: 'Zoom out'\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tvar zoomName = 'leaflet-control-zoom',\r\n\t\t container = create$1('div', zoomName + ' leaflet-bar'),\r\n\t\t options = this.options;\r\n\r\n\t\tthis._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,\r\n\t\t zoomName + '-in', container, this._zoomIn);\r\n\t\tthis._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,\r\n\t\t zoomName + '-out', container, this._zoomOut);\r\n\r\n\t\tthis._updateDisabled();\r\n\t\tmap.on('zoomend zoomlevelschange', this._updateDisabled, this);\r\n\r\n\t\treturn container;\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tmap.off('zoomend zoomlevelschange', this._updateDisabled, this);\r\n\t},\r\n\r\n\tdisable: function () {\r\n\t\tthis._disabled = true;\r\n\t\tthis._updateDisabled();\r\n\t\treturn this;\r\n\t},\r\n\r\n\tenable: function () {\r\n\t\tthis._disabled = false;\r\n\t\tthis._updateDisabled();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_zoomIn: function (e) {\r\n\t\tif (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {\r\n\t\t\tthis._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));\r\n\t\t}\r\n\t},\r\n\r\n\t_zoomOut: function (e) {\r\n\t\tif (!this._disabled && this._map._zoom > this._map.getMinZoom()) {\r\n\t\t\tthis._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));\r\n\t\t}\r\n\t},\r\n\r\n\t_createButton: function (html, title, className, container, fn) {\r\n\t\tvar link = create$1('a', className, container);\r\n\t\tlink.innerHTML = html;\r\n\t\tlink.href = '#';\r\n\t\tlink.title = title;\r\n\r\n\t\t/*\r\n\t\t * Will force screen readers like VoiceOver to read this as \"Zoom in - button\"\r\n\t\t */\r\n\t\tlink.setAttribute('role', 'button');\r\n\t\tlink.setAttribute('aria-label', title);\r\n\r\n\t\tdisableClickPropagation(link);\r\n\t\ton(link, 'click', stop);\r\n\t\ton(link, 'click', fn, this);\r\n\t\ton(link, 'click', this._refocusOnMap, this);\r\n\r\n\t\treturn link;\r\n\t},\r\n\r\n\t_updateDisabled: function () {\r\n\t\tvar map = this._map,\r\n\t\t className = 'leaflet-disabled';\r\n\r\n\t\tremoveClass(this._zoomInButton, className);\r\n\t\tremoveClass(this._zoomOutButton, className);\r\n\r\n\t\tif (this._disabled || map._zoom === map.getMinZoom()) {\r\n\t\t\taddClass(this._zoomOutButton, className);\r\n\t\t}\r\n\t\tif (this._disabled || map._zoom === map.getMaxZoom()) {\r\n\t\t\taddClass(this._zoomInButton, className);\r\n\t\t}\r\n\t}\r\n});\r\n\r\n// @namespace Map\r\n// @section Control options\r\n// @option zoomControl: Boolean = true\r\n// Whether a [zoom control](#control-zoom) is added to the map by default.\r\nMap.mergeOptions({\r\n\tzoomControl: true\r\n});\r\n\r\nMap.addInitHook(function () {\r\n\tif (this.options.zoomControl) {\r\n\t\t// @section Controls\r\n\t\t// @property zoomControl: Control.Zoom\r\n\t\t// The default zoom control (only available if the\r\n\t\t// [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).\r\n\t\tthis.zoomControl = new Zoom();\r\n\t\tthis.addControl(this.zoomControl);\r\n\t}\r\n});\r\n\r\n// @namespace Control.Zoom\r\n// @factory L.control.zoom(options: Control.Zoom options)\r\n// Creates a zoom control\r\nvar zoom = function (options) {\r\n\treturn new Zoom(options);\r\n};\n\n/*\n * @class Control.Scale\n * @aka L.Control.Scale\n * @inherits Control\n *\n * A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) systems. Extends `Control`.\n *\n * @example\n *\n * ```js\n * L.control.scale().addTo(map);\n * ```\n */\n\nvar Scale = Control.extend({\n\t// @section\n\t// @aka Control.Scale options\n\toptions: {\n\t\tposition: 'bottomleft',\n\n\t\t// @option maxWidth: Number = 100\n\t\t// Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).\n\t\tmaxWidth: 100,\n\n\t\t// @option metric: Boolean = True\n\t\t// Whether to show the metric scale line (m/km).\n\t\tmetric: true,\n\n\t\t// @option imperial: Boolean = True\n\t\t// Whether to show the imperial scale line (mi/ft).\n\t\timperial: true\n\n\t\t// @option updateWhenIdle: Boolean = false\n\t\t// If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).\n\t},\n\n\tonAdd: function (map) {\n\t\tvar className = 'leaflet-control-scale',\n\t\t container = create$1('div', className),\n\t\t options = this.options;\n\n\t\tthis._addScales(options, className + '-line', container);\n\n\t\tmap.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);\n\t\tmap.whenReady(this._update, this);\n\n\t\treturn container;\n\t},\n\n\tonRemove: function (map) {\n\t\tmap.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);\n\t},\n\n\t_addScales: function (options, className, container) {\n\t\tif (options.metric) {\n\t\t\tthis._mScale = create$1('div', className, container);\n\t\t}\n\t\tif (options.imperial) {\n\t\t\tthis._iScale = create$1('div', className, container);\n\t\t}\n\t},\n\n\t_update: function () {\n\t\tvar map = this._map,\n\t\t y = map.getSize().y / 2;\n\n\t\tvar maxMeters = map.distance(\n\t\t\tmap.containerPointToLatLng([0, y]),\n\t\t\tmap.containerPointToLatLng([this.options.maxWidth, y]));\n\n\t\tthis._updateScales(maxMeters);\n\t},\n\n\t_updateScales: function (maxMeters) {\n\t\tif (this.options.metric && maxMeters) {\n\t\t\tthis._updateMetric(maxMeters);\n\t\t}\n\t\tif (this.options.imperial && maxMeters) {\n\t\t\tthis._updateImperial(maxMeters);\n\t\t}\n\t},\n\n\t_updateMetric: function (maxMeters) {\n\t\tvar meters = this._getRoundNum(maxMeters),\n\t\t label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';\n\n\t\tthis._updateScale(this._mScale, label, meters / maxMeters);\n\t},\n\n\t_updateImperial: function (maxMeters) {\n\t\tvar maxFeet = maxMeters * 3.2808399,\n\t\t maxMiles, miles, feet;\n\n\t\tif (maxFeet > 5280) {\n\t\t\tmaxMiles = maxFeet / 5280;\n\t\t\tmiles = this._getRoundNum(maxMiles);\n\t\t\tthis._updateScale(this._iScale, miles + ' mi', miles / maxMiles);\n\n\t\t} else {\n\t\t\tfeet = this._getRoundNum(maxFeet);\n\t\t\tthis._updateScale(this._iScale, feet + ' ft', feet / maxFeet);\n\t\t}\n\t},\n\n\t_updateScale: function (scale, text, ratio) {\n\t\tscale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';\n\t\tscale.innerHTML = text;\n\t},\n\n\t_getRoundNum: function (num) {\n\t\tvar pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),\n\t\t d = num / pow10;\n\n\t\td = d >= 10 ? 10 :\n\t\t d >= 5 ? 5 :\n\t\t d >= 3 ? 3 :\n\t\t d >= 2 ? 2 : 1;\n\n\t\treturn pow10 * d;\n\t}\n});\n\n\n// @factory L.control.scale(options?: Control.Scale options)\n// Creates an scale control with the given options.\nvar scale = function (options) {\n\treturn new Scale(options);\n};\n\n/*\r\n * @class Control.Attribution\r\n * @aka L.Control.Attribution\r\n * @inherits Control\r\n *\r\n * The attribution control allows you to display attribution data in a small text box on a map. It is put on the map by default unless you set its [`attributionControl` option](#map-attributioncontrol) to `false`, and it fetches attribution texts from layers with the [`getAttribution` method](#layer-getattribution) automatically. Extends Control.\r\n */\r\n\r\nvar Attribution = Control.extend({\r\n\t// @section\r\n\t// @aka Control.Attribution options\r\n\toptions: {\r\n\t\tposition: 'bottomright',\r\n\r\n\t\t// @option prefix: String = 'Leaflet'\r\n\t\t// The HTML text shown before the attributions. Pass `false` to disable.\r\n\t\tprefix: 'Leaflet'\r\n\t},\r\n\r\n\tinitialize: function (options) {\r\n\t\tsetOptions(this, options);\r\n\r\n\t\tthis._attributions = {};\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tmap.attributionControl = this;\r\n\t\tthis._container = create$1('div', 'leaflet-control-attribution');\r\n\t\tdisableClickPropagation(this._container);\r\n\r\n\t\t// TODO ugly, refactor\r\n\t\tfor (var i in map._layers) {\r\n\t\t\tif (map._layers[i].getAttribution) {\r\n\t\t\t\tthis.addAttribution(map._layers[i].getAttribution());\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis._update();\r\n\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\t// @method setPrefix(prefix: String): this\r\n\t// Sets the text before the attributions.\r\n\tsetPrefix: function (prefix) {\r\n\t\tthis.options.prefix = prefix;\r\n\t\tthis._update();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method addAttribution(text: String): this\r\n\t// Adds an attribution text (e.g. `'Vector data © Mapbox'`).\r\n\taddAttribution: function (text) {\r\n\t\tif (!text) { return this; }\r\n\r\n\t\tif (!this._attributions[text]) {\r\n\t\t\tthis._attributions[text] = 0;\r\n\t\t}\r\n\t\tthis._attributions[text]++;\r\n\r\n\t\tthis._update();\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeAttribution(text: String): this\r\n\t// Removes an attribution text.\r\n\tremoveAttribution: function (text) {\r\n\t\tif (!text) { return this; }\r\n\r\n\t\tif (this._attributions[text]) {\r\n\t\t\tthis._attributions[text]--;\r\n\t\t\tthis._update();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_update: function () {\r\n\t\tif (!this._map) { return; }\r\n\r\n\t\tvar attribs = [];\r\n\r\n\t\tfor (var i in this._attributions) {\r\n\t\t\tif (this._attributions[i]) {\r\n\t\t\t\tattribs.push(i);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvar prefixAndAttribs = [];\r\n\r\n\t\tif (this.options.prefix) {\r\n\t\t\tprefixAndAttribs.push(this.options.prefix);\r\n\t\t}\r\n\t\tif (attribs.length) {\r\n\t\t\tprefixAndAttribs.push(attribs.join(', '));\r\n\t\t}\r\n\r\n\t\tthis._container.innerHTML = prefixAndAttribs.join(' | ');\r\n\t}\r\n});\r\n\r\n// @namespace Map\r\n// @section Control options\r\n// @option attributionControl: Boolean = true\r\n// Whether a [attribution control](#control-attribution) is added to the map by default.\r\nMap.mergeOptions({\r\n\tattributionControl: true\r\n});\r\n\r\nMap.addInitHook(function () {\r\n\tif (this.options.attributionControl) {\r\n\t\tnew Attribution().addTo(this);\r\n\t}\r\n});\r\n\r\n// @namespace Control.Attribution\r\n// @factory L.control.attribution(options: Control.Attribution options)\r\n// Creates an attribution control.\r\nvar attribution = function (options) {\r\n\treturn new Attribution(options);\r\n};\n\nControl.Layers = Layers;\nControl.Zoom = Zoom;\nControl.Scale = Scale;\nControl.Attribution = Attribution;\n\ncontrol.layers = layers;\ncontrol.zoom = zoom;\ncontrol.scale = scale;\ncontrol.attribution = attribution;\n\n/*\n\tL.Handler is a base class for handler classes that are used internally to inject\n\tinteraction features like dragging to classes like Map and Marker.\n*/\n\n// @class Handler\n// @aka L.Handler\n// Abstract class for map interaction handlers\n\nvar Handler = Class.extend({\n\tinitialize: function (map) {\n\t\tthis._map = map;\n\t},\n\n\t// @method enable(): this\n\t// Enables the handler\n\tenable: function () {\n\t\tif (this._enabled) { return this; }\n\n\t\tthis._enabled = true;\n\t\tthis.addHooks();\n\t\treturn this;\n\t},\n\n\t// @method disable(): this\n\t// Disables the handler\n\tdisable: function () {\n\t\tif (!this._enabled) { return this; }\n\n\t\tthis._enabled = false;\n\t\tthis.removeHooks();\n\t\treturn this;\n\t},\n\n\t// @method enabled(): Boolean\n\t// Returns `true` if the handler is enabled\n\tenabled: function () {\n\t\treturn !!this._enabled;\n\t}\n\n\t// @section Extension methods\n\t// Classes inheriting from `Handler` must implement the two following methods:\n\t// @method addHooks()\n\t// Called when the handler is enabled, should add event hooks.\n\t// @method removeHooks()\n\t// Called when the handler is disabled, should remove the event hooks added previously.\n});\n\n// @section There is static function which can be called without instantiating L.Handler:\n// @function addTo(map: Map, name: String): this\n// Adds a new Handler to the given map with the given name.\nHandler.addTo = function (map, name) {\n\tmap.addHandler(name, this);\n\treturn this;\n};\n\nvar Mixin = {Events: Events};\n\n/*\r\n * @class Draggable\r\n * @aka L.Draggable\r\n * @inherits Evented\r\n *\r\n * A class for making DOM elements draggable (including touch support).\r\n * Used internally for map and marker dragging. Only works for elements\r\n * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).\r\n *\r\n * @example\r\n * ```js\r\n * var draggable = new L.Draggable(elementToDrag);\r\n * draggable.enable();\r\n * ```\r\n */\r\n\r\nvar START = touch ? 'touchstart mousedown' : 'mousedown';\r\nvar END = {\r\n\tmousedown: 'mouseup',\r\n\ttouchstart: 'touchend',\r\n\tpointerdown: 'touchend',\r\n\tMSPointerDown: 'touchend'\r\n};\r\nvar MOVE = {\r\n\tmousedown: 'mousemove',\r\n\ttouchstart: 'touchmove',\r\n\tpointerdown: 'touchmove',\r\n\tMSPointerDown: 'touchmove'\r\n};\r\n\r\n\r\nvar Draggable = Evented.extend({\r\n\r\n\toptions: {\r\n\t\t// @section\r\n\t\t// @aka Draggable options\r\n\t\t// @option clickTolerance: Number = 3\r\n\t\t// The max number of pixels a user can shift the mouse pointer during a click\r\n\t\t// for it to be considered a valid click (as opposed to a mouse drag).\r\n\t\tclickTolerance: 3\r\n\t},\r\n\r\n\t// @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)\r\n\t// Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).\r\n\tinitialize: function (element, dragStartTarget, preventOutline$$1, options) {\r\n\t\tsetOptions(this, options);\r\n\r\n\t\tthis._element = element;\r\n\t\tthis._dragStartTarget = dragStartTarget || element;\r\n\t\tthis._preventOutline = preventOutline$$1;\r\n\t},\r\n\r\n\t// @method enable()\r\n\t// Enables the dragging ability\r\n\tenable: function () {\r\n\t\tif (this._enabled) { return; }\r\n\r\n\t\ton(this._dragStartTarget, START, this._onDown, this);\r\n\r\n\t\tthis._enabled = true;\r\n\t},\r\n\r\n\t// @method disable()\r\n\t// Disables the dragging ability\r\n\tdisable: function () {\r\n\t\tif (!this._enabled) { return; }\r\n\r\n\t\t// If we're currently dragging this draggable,\r\n\t\t// disabling it counts as first ending the drag.\r\n\t\tif (Draggable._dragging === this) {\r\n\t\t\tthis.finishDrag();\r\n\t\t}\r\n\r\n\t\toff(this._dragStartTarget, START, this._onDown, this);\r\n\r\n\t\tthis._enabled = false;\r\n\t\tthis._moved = false;\r\n\t},\r\n\r\n\t_onDown: function (e) {\r\n\t\t// Ignore simulated events, since we handle both touch and\r\n\t\t// mouse explicitly; otherwise we risk getting duplicates of\r\n\t\t// touch events, see #4315.\r\n\t\t// Also ignore the event if disabled; this happens in IE11\r\n\t\t// under some circumstances, see #3666.\r\n\t\tif (e._simulated || !this._enabled) { return; }\r\n\r\n\t\tthis._moved = false;\r\n\r\n\t\tif (hasClass(this._element, 'leaflet-zoom-anim')) { return; }\r\n\r\n\t\tif (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }\r\n\t\tDraggable._dragging = this; // Prevent dragging multiple objects at once.\r\n\r\n\t\tif (this._preventOutline) {\r\n\t\t\tpreventOutline(this._element);\r\n\t\t}\r\n\r\n\t\tdisableImageDrag();\r\n\t\tdisableTextSelection();\r\n\r\n\t\tif (this._moving) { return; }\r\n\r\n\t\t// @event down: Event\r\n\t\t// Fired when a drag is about to start.\r\n\t\tthis.fire('down');\r\n\r\n\t\tvar first = e.touches ? e.touches[0] : e,\r\n\t\t sizedParent = getSizedParentNode(this._element);\r\n\r\n\t\tthis._startPoint = new Point(first.clientX, first.clientY);\r\n\r\n\t\t// Cache the scale, so that we can continuously compensate for it during drag (_onMove).\r\n\t\tthis._parentScale = getScale(sizedParent);\r\n\r\n\t\ton(document, MOVE[e.type], this._onMove, this);\r\n\t\ton(document, END[e.type], this._onUp, this);\r\n\t},\r\n\r\n\t_onMove: function (e) {\r\n\t\t// Ignore simulated events, since we handle both touch and\r\n\t\t// mouse explicitly; otherwise we risk getting duplicates of\r\n\t\t// touch events, see #4315.\r\n\t\t// Also ignore the event if disabled; this happens in IE11\r\n\t\t// under some circumstances, see #3666.\r\n\t\tif (e._simulated || !this._enabled) { return; }\r\n\r\n\t\tif (e.touches && e.touches.length > 1) {\r\n\t\t\tthis._moved = true;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),\r\n\t\t offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);\r\n\r\n\t\tif (!offset.x && !offset.y) { return; }\r\n\t\tif (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }\r\n\r\n\t\t// We assume that the parent container's position, border and scale do not change for the duration of the drag.\r\n\t\t// Therefore there is no need to account for the position and border (they are eliminated by the subtraction)\r\n\t\t// and we can use the cached value for the scale.\r\n\t\toffset.x /= this._parentScale.x;\r\n\t\toffset.y /= this._parentScale.y;\r\n\r\n\t\tpreventDefault(e);\r\n\r\n\t\tif (!this._moved) {\r\n\t\t\t// @event dragstart: Event\r\n\t\t\t// Fired when a drag starts\r\n\t\t\tthis.fire('dragstart');\r\n\r\n\t\t\tthis._moved = true;\r\n\t\t\tthis._startPos = getPosition(this._element).subtract(offset);\r\n\r\n\t\t\taddClass(document.body, 'leaflet-dragging');\r\n\r\n\t\t\tthis._lastTarget = e.target || e.srcElement;\r\n\t\t\t// IE and Edge do not give the element, so fetch it\r\n\t\t\t// if necessary\r\n\t\t\tif ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {\r\n\t\t\t\tthis._lastTarget = this._lastTarget.correspondingUseElement;\r\n\t\t\t}\r\n\t\t\taddClass(this._lastTarget, 'leaflet-drag-target');\r\n\t\t}\r\n\r\n\t\tthis._newPos = this._startPos.add(offset);\r\n\t\tthis._moving = true;\r\n\r\n\t\tcancelAnimFrame(this._animRequest);\r\n\t\tthis._lastEvent = e;\r\n\t\tthis._animRequest = requestAnimFrame(this._updatePosition, this, true);\r\n\t},\r\n\r\n\t_updatePosition: function () {\r\n\t\tvar e = {originalEvent: this._lastEvent};\r\n\r\n\t\t// @event predrag: Event\r\n\t\t// Fired continuously during dragging *before* each corresponding\r\n\t\t// update of the element's position.\r\n\t\tthis.fire('predrag', e);\r\n\t\tsetPosition(this._element, this._newPos);\r\n\r\n\t\t// @event drag: Event\r\n\t\t// Fired continuously during dragging.\r\n\t\tthis.fire('drag', e);\r\n\t},\r\n\r\n\t_onUp: function (e) {\r\n\t\t// Ignore simulated events, since we handle both touch and\r\n\t\t// mouse explicitly; otherwise we risk getting duplicates of\r\n\t\t// touch events, see #4315.\r\n\t\t// Also ignore the event if disabled; this happens in IE11\r\n\t\t// under some circumstances, see #3666.\r\n\t\tif (e._simulated || !this._enabled) { return; }\r\n\t\tthis.finishDrag();\r\n\t},\r\n\r\n\tfinishDrag: function () {\r\n\t\tremoveClass(document.body, 'leaflet-dragging');\r\n\r\n\t\tif (this._lastTarget) {\r\n\t\t\tremoveClass(this._lastTarget, 'leaflet-drag-target');\r\n\t\t\tthis._lastTarget = null;\r\n\t\t}\r\n\r\n\t\tfor (var i in MOVE) {\r\n\t\t\toff(document, MOVE[i], this._onMove, this);\r\n\t\t\toff(document, END[i], this._onUp, this);\r\n\t\t}\r\n\r\n\t\tenableImageDrag();\r\n\t\tenableTextSelection();\r\n\r\n\t\tif (this._moved && this._moving) {\r\n\t\t\t// ensure drag is not fired after dragend\r\n\t\t\tcancelAnimFrame(this._animRequest);\r\n\r\n\t\t\t// @event dragend: DragEndEvent\r\n\t\t\t// Fired when the drag ends.\r\n\t\t\tthis.fire('dragend', {\r\n\t\t\t\tdistance: this._newPos.distanceTo(this._startPos)\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tthis._moving = false;\r\n\t\tDraggable._dragging = false;\r\n\t}\r\n\r\n});\n\n/*\r\n * @namespace LineUtil\r\n *\r\n * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.\r\n */\r\n\r\n// Simplify polyline with vertex reduction and Douglas-Peucker simplification.\r\n// Improves rendering performance dramatically by lessening the number of points to draw.\r\n\r\n// @function simplify(points: Point[], tolerance: Number): Point[]\r\n// Dramatically reduces the number of points in a polyline while retaining\r\n// its shape and returns a new array of simplified points, using the\r\n// [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).\r\n// Used for a huge performance boost when processing/displaying Leaflet polylines for\r\n// each zoom level and also reducing visual noise. tolerance affects the amount of\r\n// simplification (lesser value means higher quality but slower and with more points).\r\n// Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).\r\nfunction simplify(points, tolerance) {\r\n\tif (!tolerance || !points.length) {\r\n\t\treturn points.slice();\r\n\t}\r\n\r\n\tvar sqTolerance = tolerance * tolerance;\r\n\r\n\t // stage 1: vertex reduction\r\n\t points = _reducePoints(points, sqTolerance);\r\n\r\n\t // stage 2: Douglas-Peucker simplification\r\n\t points = _simplifyDP(points, sqTolerance);\r\n\r\n\treturn points;\r\n}\r\n\r\n// @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number\r\n// Returns the distance between point `p` and segment `p1` to `p2`.\r\nfunction pointToSegmentDistance(p, p1, p2) {\r\n\treturn Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));\r\n}\r\n\r\n// @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number\r\n// Returns the closest point from a point `p` on a segment `p1` to `p2`.\r\nfunction closestPointOnSegment(p, p1, p2) {\r\n\treturn _sqClosestPointOnSegment(p, p1, p2);\r\n}\r\n\r\n// Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm\r\nfunction _simplifyDP(points, sqTolerance) {\r\n\r\n\tvar len = points.length,\r\n\t ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,\r\n\t markers = new ArrayConstructor(len);\r\n\r\n\t markers[0] = markers[len - 1] = 1;\r\n\r\n\t_simplifyDPStep(points, markers, sqTolerance, 0, len - 1);\r\n\r\n\tvar i,\r\n\t newPoints = [];\r\n\r\n\tfor (i = 0; i < len; i++) {\r\n\t\tif (markers[i]) {\r\n\t\t\tnewPoints.push(points[i]);\r\n\t\t}\r\n\t}\r\n\r\n\treturn newPoints;\r\n}\r\n\r\nfunction _simplifyDPStep(points, markers, sqTolerance, first, last) {\r\n\r\n\tvar maxSqDist = 0,\r\n\tindex, i, sqDist;\r\n\r\n\tfor (i = first + 1; i <= last - 1; i++) {\r\n\t\tsqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);\r\n\r\n\t\tif (sqDist > maxSqDist) {\r\n\t\t\tindex = i;\r\n\t\t\tmaxSqDist = sqDist;\r\n\t\t}\r\n\t}\r\n\r\n\tif (maxSqDist > sqTolerance) {\r\n\t\tmarkers[index] = 1;\r\n\r\n\t\t_simplifyDPStep(points, markers, sqTolerance, first, index);\r\n\t\t_simplifyDPStep(points, markers, sqTolerance, index, last);\r\n\t}\r\n}\r\n\r\n// reduce points that are too close to each other to a single point\r\nfunction _reducePoints(points, sqTolerance) {\r\n\tvar reducedPoints = [points[0]];\r\n\r\n\tfor (var i = 1, prev = 0, len = points.length; i < len; i++) {\r\n\t\tif (_sqDist(points[i], points[prev]) > sqTolerance) {\r\n\t\t\treducedPoints.push(points[i]);\r\n\t\t\tprev = i;\r\n\t\t}\r\n\t}\r\n\tif (prev < len - 1) {\r\n\t\treducedPoints.push(points[len - 1]);\r\n\t}\r\n\treturn reducedPoints;\r\n}\r\n\r\nvar _lastCode;\r\n\r\n// @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean\r\n// Clips the segment a to b by rectangular bounds with the\r\n// [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)\r\n// (modifying the segment points directly!). Used by Leaflet to only show polyline\r\n// points that are on the screen or near, increasing performance.\r\nfunction clipSegment(a, b, bounds, useLastCode, round) {\r\n\tvar codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),\r\n\t codeB = _getBitCode(b, bounds),\r\n\r\n\t codeOut, p, newCode;\r\n\r\n\t // save 2nd code to avoid calculating it on the next segment\r\n\t _lastCode = codeB;\r\n\r\n\twhile (true) {\r\n\t\t// if a,b is inside the clip window (trivial accept)\r\n\t\tif (!(codeA | codeB)) {\r\n\t\t\treturn [a, b];\r\n\t\t}\r\n\r\n\t\t// if a,b is outside the clip window (trivial reject)\r\n\t\tif (codeA & codeB) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t// other cases\r\n\t\tcodeOut = codeA || codeB;\r\n\t\tp = _getEdgeIntersection(a, b, codeOut, bounds, round);\r\n\t\tnewCode = _getBitCode(p, bounds);\r\n\r\n\t\tif (codeOut === codeA) {\r\n\t\t\ta = p;\r\n\t\t\tcodeA = newCode;\r\n\t\t} else {\r\n\t\t\tb = p;\r\n\t\t\tcodeB = newCode;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunction _getEdgeIntersection(a, b, code, bounds, round) {\r\n\tvar dx = b.x - a.x,\r\n\t dy = b.y - a.y,\r\n\t min = bounds.min,\r\n\t max = bounds.max,\r\n\t x, y;\r\n\r\n\tif (code & 8) { // top\r\n\t\tx = a.x + dx * (max.y - a.y) / dy;\r\n\t\ty = max.y;\r\n\r\n\t} else if (code & 4) { // bottom\r\n\t\tx = a.x + dx * (min.y - a.y) / dy;\r\n\t\ty = min.y;\r\n\r\n\t} else if (code & 2) { // right\r\n\t\tx = max.x;\r\n\t\ty = a.y + dy * (max.x - a.x) / dx;\r\n\r\n\t} else if (code & 1) { // left\r\n\t\tx = min.x;\r\n\t\ty = a.y + dy * (min.x - a.x) / dx;\r\n\t}\r\n\r\n\treturn new Point(x, y, round);\r\n}\r\n\r\nfunction _getBitCode(p, bounds) {\r\n\tvar code = 0;\r\n\r\n\tif (p.x < bounds.min.x) { // left\r\n\t\tcode |= 1;\r\n\t} else if (p.x > bounds.max.x) { // right\r\n\t\tcode |= 2;\r\n\t}\r\n\r\n\tif (p.y < bounds.min.y) { // bottom\r\n\t\tcode |= 4;\r\n\t} else if (p.y > bounds.max.y) { // top\r\n\t\tcode |= 8;\r\n\t}\r\n\r\n\treturn code;\r\n}\r\n\r\n// square distance (to avoid unnecessary Math.sqrt calls)\r\nfunction _sqDist(p1, p2) {\r\n\tvar dx = p2.x - p1.x,\r\n\t dy = p2.y - p1.y;\r\n\treturn dx * dx + dy * dy;\r\n}\r\n\r\n// return closest point on segment or distance to that point\r\nfunction _sqClosestPointOnSegment(p, p1, p2, sqDist) {\r\n\tvar x = p1.x,\r\n\t y = p1.y,\r\n\t dx = p2.x - x,\r\n\t dy = p2.y - y,\r\n\t dot = dx * dx + dy * dy,\r\n\t t;\r\n\r\n\tif (dot > 0) {\r\n\t\tt = ((p.x - x) * dx + (p.y - y) * dy) / dot;\r\n\r\n\t\tif (t > 1) {\r\n\t\t\tx = p2.x;\r\n\t\t\ty = p2.y;\r\n\t\t} else if (t > 0) {\r\n\t\t\tx += dx * t;\r\n\t\t\ty += dy * t;\r\n\t\t}\r\n\t}\r\n\r\n\tdx = p.x - x;\r\n\tdy = p.y - y;\r\n\r\n\treturn sqDist ? dx * dx + dy * dy : new Point(x, y);\r\n}\r\n\r\n\r\n// @function isFlat(latlngs: LatLng[]): Boolean\r\n// Returns true if `latlngs` is a flat array, false is nested.\r\nfunction isFlat(latlngs) {\r\n\treturn !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');\r\n}\r\n\r\nfunction _flat(latlngs) {\r\n\tconsole.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');\r\n\treturn isFlat(latlngs);\r\n}\r\n\n\nvar LineUtil = (Object.freeze || Object)({\n\tsimplify: simplify,\n\tpointToSegmentDistance: pointToSegmentDistance,\n\tclosestPointOnSegment: closestPointOnSegment,\n\tclipSegment: clipSegment,\n\t_getEdgeIntersection: _getEdgeIntersection,\n\t_getBitCode: _getBitCode,\n\t_sqClosestPointOnSegment: _sqClosestPointOnSegment,\n\tisFlat: isFlat,\n\t_flat: _flat\n});\n\n/*\r\n * @namespace PolyUtil\r\n * Various utility functions for polygon geometries.\r\n */\r\n\r\n/* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]\r\n * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)).\r\n * Used by Leaflet to only show polygon points that are on the screen or near, increasing\r\n * performance. Note that polygon points needs different algorithm for clipping\r\n * than polyline, so there's a separate method for it.\r\n */\r\nfunction clipPolygon(points, bounds, round) {\r\n\tvar clippedPoints,\r\n\t edges = [1, 4, 2, 8],\r\n\t i, j, k,\r\n\t a, b,\r\n\t len, edge, p;\r\n\r\n\tfor (i = 0, len = points.length; i < len; i++) {\r\n\t\tpoints[i]._code = _getBitCode(points[i], bounds);\r\n\t}\r\n\r\n\t// for each edge (left, bottom, right, top)\r\n\tfor (k = 0; k < 4; k++) {\r\n\t\tedge = edges[k];\r\n\t\tclippedPoints = [];\r\n\r\n\t\tfor (i = 0, len = points.length, j = len - 1; i < len; j = i++) {\r\n\t\t\ta = points[i];\r\n\t\t\tb = points[j];\r\n\r\n\t\t\t// if a is inside the clip window\r\n\t\t\tif (!(a._code & edge)) {\r\n\t\t\t\t// if b is outside the clip window (a->b goes out of screen)\r\n\t\t\t\tif (b._code & edge) {\r\n\t\t\t\t\tp = _getEdgeIntersection(b, a, edge, bounds, round);\r\n\t\t\t\t\tp._code = _getBitCode(p, bounds);\r\n\t\t\t\t\tclippedPoints.push(p);\r\n\t\t\t\t}\r\n\t\t\t\tclippedPoints.push(a);\r\n\r\n\t\t\t// else if b is inside the clip window (a->b enters the screen)\r\n\t\t\t} else if (!(b._code & edge)) {\r\n\t\t\t\tp = _getEdgeIntersection(b, a, edge, bounds, round);\r\n\t\t\t\tp._code = _getBitCode(p, bounds);\r\n\t\t\t\tclippedPoints.push(p);\r\n\t\t\t}\r\n\t\t}\r\n\t\tpoints = clippedPoints;\r\n\t}\r\n\r\n\treturn points;\r\n}\r\n\n\nvar PolyUtil = (Object.freeze || Object)({\n\tclipPolygon: clipPolygon\n});\n\n/*\r\n * @namespace Projection\r\n * @section\r\n * Leaflet comes with a set of already defined Projections out of the box:\r\n *\r\n * @projection L.Projection.LonLat\r\n *\r\n * Equirectangular, or Plate Carree projection — the most simple projection,\r\n * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as\r\n * latitude. Also suitable for flat worlds, e.g. game maps. Used by the\r\n * `EPSG:4326` and `Simple` CRS.\r\n */\r\n\r\nvar LonLat = {\r\n\tproject: function (latlng) {\r\n\t\treturn new Point(latlng.lng, latlng.lat);\r\n\t},\r\n\r\n\tunproject: function (point) {\r\n\t\treturn new LatLng(point.y, point.x);\r\n\t},\r\n\r\n\tbounds: new Bounds([-180, -90], [180, 90])\r\n};\n\n/*\r\n * @namespace Projection\r\n * @projection L.Projection.Mercator\r\n *\r\n * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.\r\n */\r\n\r\nvar Mercator = {\r\n\tR: 6378137,\r\n\tR_MINOR: 6356752.314245179,\r\n\r\n\tbounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),\r\n\r\n\tproject: function (latlng) {\r\n\t\tvar d = Math.PI / 180,\r\n\t\t r = this.R,\r\n\t\t y = latlng.lat * d,\r\n\t\t tmp = this.R_MINOR / r,\r\n\t\t e = Math.sqrt(1 - tmp * tmp),\r\n\t\t con = e * Math.sin(y);\r\n\r\n\t\tvar ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);\r\n\t\ty = -r * Math.log(Math.max(ts, 1E-10));\r\n\r\n\t\treturn new Point(latlng.lng * d * r, y);\r\n\t},\r\n\r\n\tunproject: function (point) {\r\n\t\tvar d = 180 / Math.PI,\r\n\t\t r = this.R,\r\n\t\t tmp = this.R_MINOR / r,\r\n\t\t e = Math.sqrt(1 - tmp * tmp),\r\n\t\t ts = Math.exp(-point.y / r),\r\n\t\t phi = Math.PI / 2 - 2 * Math.atan(ts);\r\n\r\n\t\tfor (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {\r\n\t\t\tcon = e * Math.sin(phi);\r\n\t\t\tcon = Math.pow((1 - con) / (1 + con), e / 2);\r\n\t\t\tdphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;\r\n\t\t\tphi += dphi;\r\n\t\t}\r\n\r\n\t\treturn new LatLng(phi * d, point.x * d / r);\r\n\t}\r\n};\n\n/*\n * @class Projection\n\n * An object with methods for projecting geographical coordinates of the world onto\n * a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection).\n\n * @property bounds: Bounds\n * The bounds (specified in CRS units) where the projection is valid\n\n * @method project(latlng: LatLng): Point\n * Projects geographical coordinates into a 2D point.\n * Only accepts actual `L.LatLng` instances, not arrays.\n\n * @method unproject(point: Point): LatLng\n * The inverse of `project`. Projects a 2D point into a geographical location.\n * Only accepts actual `L.Point` instances, not arrays.\n\n * Note that the projection instances do not inherit from Leafet's `Class` object,\n * and can't be instantiated. Also, new classes can't inherit from them,\n * and methods can't be added to them with the `include` function.\n\n */\n\n\n\n\nvar index = (Object.freeze || Object)({\n\tLonLat: LonLat,\n\tMercator: Mercator,\n\tSphericalMercator: SphericalMercator\n});\n\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.EPSG3395\r\n *\r\n * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.\r\n */\r\nvar EPSG3395 = extend({}, Earth, {\r\n\tcode: 'EPSG:3395',\r\n\tprojection: Mercator,\r\n\r\n\ttransformation: (function () {\r\n\t\tvar scale = 0.5 / (Math.PI * Mercator.R);\r\n\t\treturn toTransformation(scale, 0.5, -scale, 0.5);\r\n\t}())\r\n});\n\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.EPSG4326\r\n *\r\n * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.\r\n *\r\n * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),\r\n * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`\r\n * with this CRS, ensure that there are two 256x256 pixel tiles covering the\r\n * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),\r\n * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.\r\n */\r\n\r\nvar EPSG4326 = extend({}, Earth, {\r\n\tcode: 'EPSG:4326',\r\n\tprojection: LonLat,\r\n\ttransformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)\r\n});\n\n/*\n * @namespace CRS\n * @crs L.CRS.Simple\n *\n * A simple CRS that maps longitude and latitude into `x` and `y` directly.\n * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`\n * axis should still be inverted (going from bottom to top). `distance()` returns\n * simple euclidean distance.\n */\n\nvar Simple = extend({}, CRS, {\n\tprojection: LonLat,\n\ttransformation: toTransformation(1, 0, -1, 0),\n\n\tscale: function (zoom) {\n\t\treturn Math.pow(2, zoom);\n\t},\n\n\tzoom: function (scale) {\n\t\treturn Math.log(scale) / Math.LN2;\n\t},\n\n\tdistance: function (latlng1, latlng2) {\n\t\tvar dx = latlng2.lng - latlng1.lng,\n\t\t dy = latlng2.lat - latlng1.lat;\n\n\t\treturn Math.sqrt(dx * dx + dy * dy);\n\t},\n\n\tinfinite: true\n});\n\nCRS.Earth = Earth;\nCRS.EPSG3395 = EPSG3395;\nCRS.EPSG3857 = EPSG3857;\nCRS.EPSG900913 = EPSG900913;\nCRS.EPSG4326 = EPSG4326;\nCRS.Simple = Simple;\n\n/*\n * @class Layer\n * @inherits Evented\n * @aka L.Layer\n * @aka ILayer\n *\n * A set of methods from the Layer base class that all Leaflet layers use.\n * Inherits all methods, options and events from `L.Evented`.\n *\n * @example\n *\n * ```js\n * var layer = L.marker(latlng).addTo(map);\n * layer.addTo(map);\n * layer.remove();\n * ```\n *\n * @event add: Event\n * Fired after the layer is added to a map\n *\n * @event remove: Event\n * Fired after the layer is removed from a map\n */\n\n\nvar Layer = Evented.extend({\n\n\t// Classes extending `L.Layer` will inherit the following options:\n\toptions: {\n\t\t// @option pane: String = 'overlayPane'\n\t\t// By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default.\n\t\tpane: 'overlayPane',\n\n\t\t// @option attribution: String = null\n\t\t// String to be shown in the attribution control, e.g. \"© OpenStreetMap contributors\". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.\n\t\tattribution: null,\n\n\t\tbubblingMouseEvents: true\n\t},\n\n\t/* @section\n\t * Classes extending `L.Layer` will inherit the following methods:\n\t *\n\t * @method addTo(map: Map|LayerGroup): this\n\t * Adds the layer to the given map or layer group.\n\t */\n\taddTo: function (map) {\n\t\tmap.addLayer(this);\n\t\treturn this;\n\t},\n\n\t// @method remove: this\n\t// Removes the layer from the map it is currently active on.\n\tremove: function () {\n\t\treturn this.removeFrom(this._map || this._mapToAdd);\n\t},\n\n\t// @method removeFrom(map: Map): this\n\t// Removes the layer from the given map\n\tremoveFrom: function (obj) {\n\t\tif (obj) {\n\t\t\tobj.removeLayer(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method getPane(name? : String): HTMLElement\n\t// Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.\n\tgetPane: function (name) {\n\t\treturn this._map.getPane(name ? (this.options[name] || name) : this.options.pane);\n\t},\n\n\taddInteractiveTarget: function (targetEl) {\n\t\tthis._map._targets[stamp(targetEl)] = this;\n\t\treturn this;\n\t},\n\n\tremoveInteractiveTarget: function (targetEl) {\n\t\tdelete this._map._targets[stamp(targetEl)];\n\t\treturn this;\n\t},\n\n\t// @method getAttribution: String\n\t// Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).\n\tgetAttribution: function () {\n\t\treturn this.options.attribution;\n\t},\n\n\t_layerAdd: function (e) {\n\t\tvar map = e.target;\n\n\t\t// check in case layer gets added and then removed before the map is ready\n\t\tif (!map.hasLayer(this)) { return; }\n\n\t\tthis._map = map;\n\t\tthis._zoomAnimated = map._zoomAnimated;\n\n\t\tif (this.getEvents) {\n\t\t\tvar events = this.getEvents();\n\t\t\tmap.on(events, this);\n\t\t\tthis.once('remove', function () {\n\t\t\t\tmap.off(events, this);\n\t\t\t}, this);\n\t\t}\n\n\t\tthis.onAdd(map);\n\n\t\tif (this.getAttribution && map.attributionControl) {\n\t\t\tmap.attributionControl.addAttribution(this.getAttribution());\n\t\t}\n\n\t\tthis.fire('add');\n\t\tmap.fire('layeradd', {layer: this});\n\t}\n});\n\n/* @section Extension methods\n * @uninheritable\n *\n * Every layer should extend from `L.Layer` and (re-)implement the following methods.\n *\n * @method onAdd(map: Map): this\n * Should contain code that creates DOM elements for the layer, adds them to `map panes` where they should belong and puts listeners on relevant map events. Called on [`map.addLayer(layer)`](#map-addlayer).\n *\n * @method onRemove(map: Map): this\n * Should contain all clean up code that removes the layer's elements from the DOM and removes listeners previously added in [`onAdd`](#layer-onadd). Called on [`map.removeLayer(layer)`](#map-removelayer).\n *\n * @method getEvents(): Object\n * This optional method should return an object like `{ viewreset: this._reset }` for [`addEventListener`](#evented-addeventlistener). The event handlers in this object will be automatically added and removed from the map with your layer.\n *\n * @method getAttribution(): String\n * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.\n *\n * @method beforeAdd(map: Map): this\n * Optional method. Called on [`map.addLayer(layer)`](#map-addlayer), before the layer is added to the map, before events are initialized, without waiting until the map is in a usable state. Use for early initialization only.\n */\n\n\n/* @namespace Map\n * @section Layer events\n *\n * @event layeradd: LayerEvent\n * Fired when a new layer is added to the map.\n *\n * @event layerremove: LayerEvent\n * Fired when some layer is removed from the map\n *\n * @section Methods for Layers and Controls\n */\nMap.include({\n\t// @method addLayer(layer: Layer): this\n\t// Adds the given layer to the map\n\taddLayer: function (layer) {\n\t\tif (!layer._layerAdd) {\n\t\t\tthrow new Error('The provided object is not a Layer.');\n\t\t}\n\n\t\tvar id = stamp(layer);\n\t\tif (this._layers[id]) { return this; }\n\t\tthis._layers[id] = layer;\n\n\t\tlayer._mapToAdd = this;\n\n\t\tif (layer.beforeAdd) {\n\t\t\tlayer.beforeAdd(this);\n\t\t}\n\n\t\tthis.whenReady(layer._layerAdd, layer);\n\n\t\treturn this;\n\t},\n\n\t// @method removeLayer(layer: Layer): this\n\t// Removes the given layer from the map.\n\tremoveLayer: function (layer) {\n\t\tvar id = stamp(layer);\n\n\t\tif (!this._layers[id]) { return this; }\n\n\t\tif (this._loaded) {\n\t\t\tlayer.onRemove(this);\n\t\t}\n\n\t\tif (layer.getAttribution && this.attributionControl) {\n\t\t\tthis.attributionControl.removeAttribution(layer.getAttribution());\n\t\t}\n\n\t\tdelete this._layers[id];\n\n\t\tif (this._loaded) {\n\t\t\tthis.fire('layerremove', {layer: layer});\n\t\t\tlayer.fire('remove');\n\t\t}\n\n\t\tlayer._map = layer._mapToAdd = null;\n\n\t\treturn this;\n\t},\n\n\t// @method hasLayer(layer: Layer): Boolean\n\t// Returns `true` if the given layer is currently added to the map\n\thasLayer: function (layer) {\n\t\treturn !!layer && (stamp(layer) in this._layers);\n\t},\n\n\t/* @method eachLayer(fn: Function, context?: Object): this\n\t * Iterates over the layers of the map, optionally specifying context of the iterator function.\n\t * ```\n\t * map.eachLayer(function(layer){\n\t * layer.bindPopup('Hello');\n\t * });\n\t * ```\n\t */\n\teachLayer: function (method, context) {\n\t\tfor (var i in this._layers) {\n\t\t\tmethod.call(context, this._layers[i]);\n\t\t}\n\t\treturn this;\n\t},\n\n\t_addLayers: function (layers) {\n\t\tlayers = layers ? (isArray(layers) ? layers : [layers]) : [];\n\n\t\tfor (var i = 0, len = layers.length; i < len; i++) {\n\t\t\tthis.addLayer(layers[i]);\n\t\t}\n\t},\n\n\t_addZoomLimit: function (layer) {\n\t\tif (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {\n\t\t\tthis._zoomBoundLayers[stamp(layer)] = layer;\n\t\t\tthis._updateZoomLevels();\n\t\t}\n\t},\n\n\t_removeZoomLimit: function (layer) {\n\t\tvar id = stamp(layer);\n\n\t\tif (this._zoomBoundLayers[id]) {\n\t\t\tdelete this._zoomBoundLayers[id];\n\t\t\tthis._updateZoomLevels();\n\t\t}\n\t},\n\n\t_updateZoomLevels: function () {\n\t\tvar minZoom = Infinity,\n\t\t maxZoom = -Infinity,\n\t\t oldZoomSpan = this._getZoomSpan();\n\n\t\tfor (var i in this._zoomBoundLayers) {\n\t\t\tvar options = this._zoomBoundLayers[i].options;\n\n\t\t\tminZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);\n\t\t\tmaxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);\n\t\t}\n\n\t\tthis._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;\n\t\tthis._layersMinZoom = minZoom === Infinity ? undefined : minZoom;\n\n\t\t// @section Map state change events\n\t\t// @event zoomlevelschange: Event\n\t\t// Fired when the number of zoomlevels on the map is changed due\n\t\t// to adding or removing a layer.\n\t\tif (oldZoomSpan !== this._getZoomSpan()) {\n\t\t\tthis.fire('zoomlevelschange');\n\t\t}\n\n\t\tif (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {\n\t\t\tthis.setZoom(this._layersMaxZoom);\n\t\t}\n\t\tif (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {\n\t\t\tthis.setZoom(this._layersMinZoom);\n\t\t}\n\t}\n});\n\n/*\r\n * @class LayerGroup\r\n * @aka L.LayerGroup\r\n * @inherits Layer\r\n *\r\n * Used to group several layers and handle them as one. If you add it to the map,\r\n * any layers added or removed from the group will be added/removed on the map as\r\n * well. Extends `Layer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.layerGroup([marker1, marker2])\r\n * \t.addLayer(polyline)\r\n * \t.addTo(map);\r\n * ```\r\n */\r\n\r\nvar LayerGroup = Layer.extend({\r\n\r\n\tinitialize: function (layers, options) {\r\n\t\tsetOptions(this, options);\r\n\r\n\t\tthis._layers = {};\r\n\r\n\t\tvar i, len;\r\n\r\n\t\tif (layers) {\r\n\t\t\tfor (i = 0, len = layers.length; i < len; i++) {\r\n\t\t\t\tthis.addLayer(layers[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t// @method addLayer(layer: Layer): this\r\n\t// Adds the given layer to the group.\r\n\taddLayer: function (layer) {\r\n\t\tvar id = this.getLayerId(layer);\r\n\r\n\t\tthis._layers[id] = layer;\r\n\r\n\t\tif (this._map) {\r\n\t\t\tthis._map.addLayer(layer);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeLayer(layer: Layer): this\r\n\t// Removes the given layer from the group.\r\n\t// @alternative\r\n\t// @method removeLayer(id: Number): this\r\n\t// Removes the layer with the given internal ID from the group.\r\n\tremoveLayer: function (layer) {\r\n\t\tvar id = layer in this._layers ? layer : this.getLayerId(layer);\r\n\r\n\t\tif (this._map && this._layers[id]) {\r\n\t\t\tthis._map.removeLayer(this._layers[id]);\r\n\t\t}\r\n\r\n\t\tdelete this._layers[id];\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method hasLayer(layer: Layer): Boolean\r\n\t// Returns `true` if the given layer is currently added to the group.\r\n\t// @alternative\r\n\t// @method hasLayer(id: Number): Boolean\r\n\t// Returns `true` if the given internal ID is currently added to the group.\r\n\thasLayer: function (layer) {\r\n\t\treturn !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);\r\n\t},\r\n\r\n\t// @method clearLayers(): this\r\n\t// Removes all the layers from the group.\r\n\tclearLayers: function () {\r\n\t\treturn this.eachLayer(this.removeLayer, this);\r\n\t},\r\n\r\n\t// @method invoke(methodName: String, …): this\r\n\t// Calls `methodName` on every layer contained in this group, passing any\r\n\t// additional parameters. Has no effect if the layers contained do not\r\n\t// implement `methodName`.\r\n\tinvoke: function (methodName) {\r\n\t\tvar args = Array.prototype.slice.call(arguments, 1),\r\n\t\t i, layer;\r\n\r\n\t\tfor (i in this._layers) {\r\n\t\t\tlayer = this._layers[i];\r\n\r\n\t\t\tif (layer[methodName]) {\r\n\t\t\t\tlayer[methodName].apply(layer, args);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis.eachLayer(map.addLayer, map);\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tthis.eachLayer(map.removeLayer, map);\r\n\t},\r\n\r\n\t// @method eachLayer(fn: Function, context?: Object): this\r\n\t// Iterates over the layers of the group, optionally specifying context of the iterator function.\r\n\t// ```js\r\n\t// group.eachLayer(function (layer) {\r\n\t// \tlayer.bindPopup('Hello');\r\n\t// });\r\n\t// ```\r\n\teachLayer: function (method, context) {\r\n\t\tfor (var i in this._layers) {\r\n\t\t\tmethod.call(context, this._layers[i]);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getLayer(id: Number): Layer\r\n\t// Returns the layer with the given internal ID.\r\n\tgetLayer: function (id) {\r\n\t\treturn this._layers[id];\r\n\t},\r\n\r\n\t// @method getLayers(): Layer[]\r\n\t// Returns an array of all the layers added to the group.\r\n\tgetLayers: function () {\r\n\t\tvar layers = [];\r\n\t\tthis.eachLayer(layers.push, layers);\r\n\t\treturn layers;\r\n\t},\r\n\r\n\t// @method setZIndex(zIndex: Number): this\r\n\t// Calls `setZIndex` on every layer contained in this group, passing the z-index.\r\n\tsetZIndex: function (zIndex) {\r\n\t\treturn this.invoke('setZIndex', zIndex);\r\n\t},\r\n\r\n\t// @method getLayerId(layer: Layer): Number\r\n\t// Returns the internal ID for a layer\r\n\tgetLayerId: function (layer) {\r\n\t\treturn stamp(layer);\r\n\t}\r\n});\r\n\r\n\r\n// @factory L.layerGroup(layers?: Layer[], options?: Object)\r\n// Create a layer group, optionally given an initial set of layers and an `options` object.\r\nvar layerGroup = function (layers, options) {\r\n\treturn new LayerGroup(layers, options);\r\n};\n\n/*\r\n * @class FeatureGroup\r\n * @aka L.FeatureGroup\r\n * @inherits LayerGroup\r\n *\r\n * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:\r\n * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))\r\n * * Events are propagated to the `FeatureGroup`, so if the group has an event\r\n * handler, it will handle events from any of the layers. This includes mouse events\r\n * and custom events.\r\n * * Has `layeradd` and `layerremove` events\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.featureGroup([marker1, marker2, polyline])\r\n * \t.bindPopup('Hello world!')\r\n * \t.on('click', function() { alert('Clicked on a member of the group!'); })\r\n * \t.addTo(map);\r\n * ```\r\n */\r\n\r\nvar FeatureGroup = LayerGroup.extend({\r\n\r\n\taddLayer: function (layer) {\r\n\t\tif (this.hasLayer(layer)) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tlayer.addEventParent(this);\r\n\r\n\t\tLayerGroup.prototype.addLayer.call(this, layer);\r\n\r\n\t\t// @event layeradd: LayerEvent\r\n\t\t// Fired when a layer is added to this `FeatureGroup`\r\n\t\treturn this.fire('layeradd', {layer: layer});\r\n\t},\r\n\r\n\tremoveLayer: function (layer) {\r\n\t\tif (!this.hasLayer(layer)) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\t\tif (layer in this._layers) {\r\n\t\t\tlayer = this._layers[layer];\r\n\t\t}\r\n\r\n\t\tlayer.removeEventParent(this);\r\n\r\n\t\tLayerGroup.prototype.removeLayer.call(this, layer);\r\n\r\n\t\t// @event layerremove: LayerEvent\r\n\t\t// Fired when a layer is removed from this `FeatureGroup`\r\n\t\treturn this.fire('layerremove', {layer: layer});\r\n\t},\r\n\r\n\t// @method setStyle(style: Path options): this\r\n\t// Sets the given path options to each layer of the group that has a `setStyle` method.\r\n\tsetStyle: function (style) {\r\n\t\treturn this.invoke('setStyle', style);\r\n\t},\r\n\r\n\t// @method bringToFront(): this\r\n\t// Brings the layer group to the top of all other layers\r\n\tbringToFront: function () {\r\n\t\treturn this.invoke('bringToFront');\r\n\t},\r\n\r\n\t// @method bringToBack(): this\r\n\t// Brings the layer group to the back of all other layers\r\n\tbringToBack: function () {\r\n\t\treturn this.invoke('bringToBack');\r\n\t},\r\n\r\n\t// @method getBounds(): LatLngBounds\r\n\t// Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).\r\n\tgetBounds: function () {\r\n\t\tvar bounds = new LatLngBounds();\r\n\r\n\t\tfor (var id in this._layers) {\r\n\t\t\tvar layer = this._layers[id];\r\n\t\t\tbounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());\r\n\t\t}\r\n\t\treturn bounds;\r\n\t}\r\n});\r\n\r\n// @factory L.featureGroup(layers: Layer[])\r\n// Create a feature group, optionally given an initial set of layers.\r\nvar featureGroup = function (layers) {\r\n\treturn new FeatureGroup(layers);\r\n};\n\n/*\r\n * @class Icon\r\n * @aka L.Icon\r\n *\r\n * Represents an icon to provide when creating a marker.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var myIcon = L.icon({\r\n * iconUrl: 'my-icon.png',\r\n * iconRetinaUrl: 'my-icon@2x.png',\r\n * iconSize: [38, 95],\r\n * iconAnchor: [22, 94],\r\n * popupAnchor: [-3, -76],\r\n * shadowUrl: 'my-icon-shadow.png',\r\n * shadowRetinaUrl: 'my-icon-shadow@2x.png',\r\n * shadowSize: [68, 95],\r\n * shadowAnchor: [22, 94]\r\n * });\r\n *\r\n * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);\r\n * ```\r\n *\r\n * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.\r\n *\r\n */\r\n\r\nvar Icon = Class.extend({\r\n\r\n\t/* @section\r\n\t * @aka Icon options\r\n\t *\r\n\t * @option iconUrl: String = null\r\n\t * **(required)** The URL to the icon image (absolute or relative to your script path).\r\n\t *\r\n\t * @option iconRetinaUrl: String = null\r\n\t * The URL to a retina sized version of the icon image (absolute or relative to your\r\n\t * script path). Used for Retina screen devices.\r\n\t *\r\n\t * @option iconSize: Point = null\r\n\t * Size of the icon image in pixels.\r\n\t *\r\n\t * @option iconAnchor: Point = null\r\n\t * The coordinates of the \"tip\" of the icon (relative to its top left corner). The icon\r\n\t * will be aligned so that this point is at the marker's geographical location. Centered\r\n\t * by default if size is specified, also can be set in CSS with negative margins.\r\n\t *\r\n\t * @option popupAnchor: Point = [0, 0]\r\n\t * The coordinates of the point from which popups will \"open\", relative to the icon anchor.\r\n\t *\r\n\t * @option tooltipAnchor: Point = [0, 0]\r\n\t * The coordinates of the point from which tooltips will \"open\", relative to the icon anchor.\r\n\t *\r\n\t * @option shadowUrl: String = null\r\n\t * The URL to the icon shadow image. If not specified, no shadow image will be created.\r\n\t *\r\n\t * @option shadowRetinaUrl: String = null\r\n\t *\r\n\t * @option shadowSize: Point = null\r\n\t * Size of the shadow image in pixels.\r\n\t *\r\n\t * @option shadowAnchor: Point = null\r\n\t * The coordinates of the \"tip\" of the shadow (relative to its top left corner) (the same\r\n\t * as iconAnchor if not specified).\r\n\t *\r\n\t * @option className: String = ''\r\n\t * A custom class name to assign to both icon and shadow images. Empty by default.\r\n\t */\r\n\r\n\toptions: {\r\n\t\tpopupAnchor: [0, 0],\r\n\t\ttooltipAnchor: [0, 0]\r\n\t},\r\n\r\n\tinitialize: function (options) {\r\n\t\tsetOptions(this, options);\r\n\t},\r\n\r\n\t// @method createIcon(oldIcon?: HTMLElement): HTMLElement\r\n\t// Called internally when the icon has to be shown, returns a `` HTML element\r\n\t// styled according to the options.\r\n\tcreateIcon: function (oldIcon) {\r\n\t\treturn this._createIcon('icon', oldIcon);\r\n\t},\r\n\r\n\t// @method createShadow(oldIcon?: HTMLElement): HTMLElement\r\n\t// As `createIcon`, but for the shadow beneath it.\r\n\tcreateShadow: function (oldIcon) {\r\n\t\treturn this._createIcon('shadow', oldIcon);\r\n\t},\r\n\r\n\t_createIcon: function (name, oldIcon) {\r\n\t\tvar src = this._getIconUrl(name);\r\n\r\n\t\tif (!src) {\r\n\t\t\tif (name === 'icon') {\r\n\t\t\t\tthrow new Error('iconUrl not set in Icon options (see the docs).');\r\n\t\t\t}\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tvar img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);\r\n\t\tthis._setIconStyles(img, name);\r\n\r\n\t\treturn img;\r\n\t},\r\n\r\n\t_setIconStyles: function (img, name) {\r\n\t\tvar options = this.options;\r\n\t\tvar sizeOption = options[name + 'Size'];\r\n\r\n\t\tif (typeof sizeOption === 'number') {\r\n\t\t\tsizeOption = [sizeOption, sizeOption];\r\n\t\t}\r\n\r\n\t\tvar size = toPoint(sizeOption),\r\n\t\t anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||\r\n\t\t size && size.divideBy(2, true));\r\n\r\n\t\timg.className = 'leaflet-marker-' + name + ' ' + (options.className || '');\r\n\r\n\t\tif (anchor) {\r\n\t\t\timg.style.marginLeft = (-anchor.x) + 'px';\r\n\t\t\timg.style.marginTop = (-anchor.y) + 'px';\r\n\t\t}\r\n\r\n\t\tif (size) {\r\n\t\t\timg.style.width = size.x + 'px';\r\n\t\t\timg.style.height = size.y + 'px';\r\n\t\t}\r\n\t},\r\n\r\n\t_createImg: function (src, el) {\r\n\t\tel = el || document.createElement('img');\r\n\t\tel.src = src;\r\n\t\treturn el;\r\n\t},\r\n\r\n\t_getIconUrl: function (name) {\r\n\t\treturn retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];\r\n\t}\r\n});\r\n\r\n\r\n// @factory L.icon(options: Icon options)\r\n// Creates an icon instance with the given options.\r\nfunction icon(options) {\r\n\treturn new Icon(options);\r\n}\n\n/*\n * @miniclass Icon.Default (Icon)\n * @aka L.Icon.Default\n * @section\n *\n * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when\n * no icon is specified. Points to the blue marker image distributed with Leaflet\n * releases.\n *\n * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`\n * (which is a set of `Icon options`).\n *\n * If you want to _completely_ replace the default icon, override the\n * `L.Marker.prototype.options.icon` with your own icon instead.\n */\n\nvar IconDefault = Icon.extend({\n\n\toptions: {\n\t\ticonUrl: 'marker-icon.png',\n\t\ticonRetinaUrl: 'marker-icon-2x.png',\n\t\tshadowUrl: 'marker-shadow.png',\n\t\ticonSize: [25, 41],\n\t\ticonAnchor: [12, 41],\n\t\tpopupAnchor: [1, -34],\n\t\ttooltipAnchor: [16, -28],\n\t\tshadowSize: [41, 41]\n\t},\n\n\t_getIconUrl: function (name) {\n\t\tif (!IconDefault.imagePath) {\t// Deprecated, backwards-compatibility only\n\t\t\tIconDefault.imagePath = this._detectIconPath();\n\t\t}\n\n\t\t// @option imagePath: String\n\t\t// `Icon.Default` will try to auto-detect the location of the\n\t\t// blue icon images. If you are placing these images in a non-standard\n\t\t// way, set this option to point to the right path.\n\t\treturn (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);\n\t},\n\n\t_detectIconPath: function () {\n\t\tvar el = create$1('div', 'leaflet-default-icon-path', document.body);\n\t\tvar path = getStyle(el, 'background-image') ||\n\t\t getStyle(el, 'backgroundImage');\t// IE8\n\n\t\tdocument.body.removeChild(el);\n\n\t\tif (path === null || path.indexOf('url') !== 0) {\n\t\t\tpath = '';\n\t\t} else {\n\t\t\tpath = path.replace(/^url\\([\"']?/, '').replace(/marker-icon\\.png[\"']?\\)$/, '');\n\t\t}\n\n\t\treturn path;\n\t}\n});\n\n/*\n * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.\n */\n\n\n/* @namespace Marker\n * @section Interaction handlers\n *\n * Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see `Handler` methods). Example:\n *\n * ```js\n * marker.dragging.disable();\n * ```\n *\n * @property dragging: Handler\n * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).\n */\n\nvar MarkerDrag = Handler.extend({\n\tinitialize: function (marker) {\n\t\tthis._marker = marker;\n\t},\n\n\taddHooks: function () {\n\t\tvar icon = this._marker._icon;\n\n\t\tif (!this._draggable) {\n\t\t\tthis._draggable = new Draggable(icon, icon, true);\n\t\t}\n\n\t\tthis._draggable.on({\n\t\t\tdragstart: this._onDragStart,\n\t\t\tpredrag: this._onPreDrag,\n\t\t\tdrag: this._onDrag,\n\t\t\tdragend: this._onDragEnd\n\t\t}, this).enable();\n\n\t\taddClass(icon, 'leaflet-marker-draggable');\n\t},\n\n\tremoveHooks: function () {\n\t\tthis._draggable.off({\n\t\t\tdragstart: this._onDragStart,\n\t\t\tpredrag: this._onPreDrag,\n\t\t\tdrag: this._onDrag,\n\t\t\tdragend: this._onDragEnd\n\t\t}, this).disable();\n\n\t\tif (this._marker._icon) {\n\t\t\tremoveClass(this._marker._icon, 'leaflet-marker-draggable');\n\t\t}\n\t},\n\n\tmoved: function () {\n\t\treturn this._draggable && this._draggable._moved;\n\t},\n\n\t_adjustPan: function (e) {\n\t\tvar marker = this._marker,\n\t\t map = marker._map,\n\t\t speed = this._marker.options.autoPanSpeed,\n\t\t padding = this._marker.options.autoPanPadding,\n\t\t iconPos = getPosition(marker._icon),\n\t\t bounds = map.getPixelBounds(),\n\t\t origin = map.getPixelOrigin();\n\n\t\tvar panBounds = toBounds(\n\t\t\tbounds.min._subtract(origin).add(padding),\n\t\t\tbounds.max._subtract(origin).subtract(padding)\n\t\t);\n\n\t\tif (!panBounds.contains(iconPos)) {\n\t\t\t// Compute incremental movement\n\t\t\tvar movement = toPoint(\n\t\t\t\t(Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -\n\t\t\t\t(Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),\n\n\t\t\t\t(Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -\n\t\t\t\t(Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)\n\t\t\t).multiplyBy(speed);\n\n\t\t\tmap.panBy(movement, {animate: false});\n\n\t\t\tthis._draggable._newPos._add(movement);\n\t\t\tthis._draggable._startPos._add(movement);\n\n\t\t\tsetPosition(marker._icon, this._draggable._newPos);\n\t\t\tthis._onDrag(e);\n\n\t\t\tthis._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));\n\t\t}\n\t},\n\n\t_onDragStart: function () {\n\t\t// @section Dragging events\n\t\t// @event dragstart: Event\n\t\t// Fired when the user starts dragging the marker.\n\n\t\t// @event movestart: Event\n\t\t// Fired when the marker starts moving (because of dragging).\n\n\t\tthis._oldLatLng = this._marker.getLatLng();\n\t\tthis._marker\n\t\t .closePopup()\n\t\t .fire('movestart')\n\t\t .fire('dragstart');\n\t},\n\n\t_onPreDrag: function (e) {\n\t\tif (this._marker.options.autoPan) {\n\t\t\tcancelAnimFrame(this._panRequest);\n\t\t\tthis._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));\n\t\t}\n\t},\n\n\t_onDrag: function (e) {\n\t\tvar marker = this._marker,\n\t\t shadow = marker._shadow,\n\t\t iconPos = getPosition(marker._icon),\n\t\t latlng = marker._map.layerPointToLatLng(iconPos);\n\n\t\t// update shadow position\n\t\tif (shadow) {\n\t\t\tsetPosition(shadow, iconPos);\n\t\t}\n\n\t\tmarker._latlng = latlng;\n\t\te.latlng = latlng;\n\t\te.oldLatLng = this._oldLatLng;\n\n\t\t// @event drag: Event\n\t\t// Fired repeatedly while the user drags the marker.\n\t\tmarker\n\t\t .fire('move', e)\n\t\t .fire('drag', e);\n\t},\n\n\t_onDragEnd: function (e) {\n\t\t// @event dragend: DragEndEvent\n\t\t// Fired when the user stops dragging the marker.\n\n\t\t cancelAnimFrame(this._panRequest);\n\n\t\t// @event moveend: Event\n\t\t// Fired when the marker stops moving (because of dragging).\n\t\tdelete this._oldLatLng;\n\t\tthis._marker\n\t\t .fire('moveend')\n\t\t .fire('dragend', e);\n\t}\n});\n\n/*\r\n * @class Marker\r\n * @inherits Interactive layer\r\n * @aka L.Marker\r\n * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.marker([50.5, 30.5]).addTo(map);\r\n * ```\r\n */\r\n\r\nvar Marker = Layer.extend({\r\n\r\n\t// @section\r\n\t// @aka Marker options\r\n\toptions: {\r\n\t\t// @option icon: Icon = *\r\n\t\t// Icon instance to use for rendering the marker.\r\n\t\t// See [Icon documentation](#L.Icon) for details on how to customize the marker icon.\r\n\t\t// If not specified, a common instance of `L.Icon.Default` is used.\r\n\t\ticon: new IconDefault(),\r\n\r\n\t\t// Option inherited from \"Interactive layer\" abstract class\r\n\t\tinteractive: true,\r\n\r\n\t\t// @option keyboard: Boolean = true\r\n\t\t// Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.\r\n\t\tkeyboard: true,\r\n\r\n\t\t// @option title: String = ''\r\n\t\t// Text for the browser tooltip that appear on marker hover (no tooltip by default).\r\n\t\ttitle: '',\r\n\r\n\t\t// @option alt: String = ''\r\n\t\t// Text for the `alt` attribute of the icon image (useful for accessibility).\r\n\t\talt: '',\r\n\r\n\t\t// @option zIndexOffset: Number = 0\r\n\t\t// By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like `1000` (or high negative value, respectively).\r\n\t\tzIndexOffset: 0,\r\n\r\n\t\t// @option opacity: Number = 1.0\r\n\t\t// The opacity of the marker.\r\n\t\topacity: 1,\r\n\r\n\t\t// @option riseOnHover: Boolean = false\r\n\t\t// If `true`, the marker will get on top of others when you hover the mouse over it.\r\n\t\triseOnHover: false,\r\n\r\n\t\t// @option riseOffset: Number = 250\r\n\t\t// The z-index offset used for the `riseOnHover` feature.\r\n\t\triseOffset: 250,\r\n\r\n\t\t// @option pane: String = 'markerPane'\r\n\t\t// `Map pane` where the markers icon will be added.\r\n\t\tpane: 'markerPane',\r\n\r\n\t\t// @option pane: String = 'shadowPane'\r\n\t\t// `Map pane` where the markers shadow will be added.\r\n\t\tshadowPane: 'shadowPane',\r\n\r\n\t\t// @option bubblingMouseEvents: Boolean = false\r\n\t\t// When `true`, a mouse event on this marker will trigger the same event on the map\r\n\t\t// (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).\r\n\t\tbubblingMouseEvents: false,\r\n\r\n\t\t// @section Draggable marker options\r\n\t\t// @option draggable: Boolean = false\r\n\t\t// Whether the marker is draggable with mouse/touch or not.\r\n\t\tdraggable: false,\r\n\r\n\t\t// @option autoPan: Boolean = false\r\n\t\t// Whether to pan the map when dragging this marker near its edge or not.\r\n\t\tautoPan: false,\r\n\r\n\t\t// @option autoPanPadding: Point = Point(50, 50)\r\n\t\t// Distance (in pixels to the left/right and to the top/bottom) of the\r\n\t\t// map edge to start panning the map.\r\n\t\tautoPanPadding: [50, 50],\r\n\r\n\t\t// @option autoPanSpeed: Number = 10\r\n\t\t// Number of pixels the map should pan by.\r\n\t\tautoPanSpeed: 10\r\n\t},\r\n\r\n\t/* @section\r\n\t *\r\n\t * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:\r\n\t */\r\n\r\n\tinitialize: function (latlng, options) {\r\n\t\tsetOptions(this, options);\r\n\t\tthis._latlng = toLatLng(latlng);\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tmap.on('zoomanim', this._animateZoom, this);\r\n\t\t}\r\n\r\n\t\tthis._initIcon();\r\n\t\tthis.update();\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tif (this.dragging && this.dragging.enabled()) {\r\n\t\t\tthis.options.draggable = true;\r\n\t\t\tthis.dragging.removeHooks();\r\n\t\t}\r\n\t\tdelete this.dragging;\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tmap.off('zoomanim', this._animateZoom, this);\r\n\t\t}\r\n\r\n\t\tthis._removeIcon();\r\n\t\tthis._removeShadow();\r\n\t},\r\n\r\n\tgetEvents: function () {\r\n\t\treturn {\r\n\t\t\tzoom: this.update,\r\n\t\t\tviewreset: this.update\r\n\t\t};\r\n\t},\r\n\r\n\t// @method getLatLng: LatLng\r\n\t// Returns the current geographical position of the marker.\r\n\tgetLatLng: function () {\r\n\t\treturn this._latlng;\r\n\t},\r\n\r\n\t// @method setLatLng(latlng: LatLng): this\r\n\t// Changes the marker position to the given point.\r\n\tsetLatLng: function (latlng) {\r\n\t\tvar oldLatLng = this._latlng;\r\n\t\tthis._latlng = toLatLng(latlng);\r\n\t\tthis.update();\r\n\r\n\t\t// @event move: Event\r\n\t\t// Fired when the marker is moved via [`setLatLng`](#marker-setlatlng) or by [dragging](#marker-dragging). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.\r\n\t\treturn this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});\r\n\t},\r\n\r\n\t// @method setZIndexOffset(offset: Number): this\r\n\t// Changes the [zIndex offset](#marker-zindexoffset) of the marker.\r\n\tsetZIndexOffset: function (offset) {\r\n\t\tthis.options.zIndexOffset = offset;\r\n\t\treturn this.update();\r\n\t},\r\n\r\n\t// @method getIcon: Icon\r\n\t// Returns the current icon used by the marker\r\n\tgetIcon: function () {\r\n\t\treturn this.options.icon;\r\n\t},\r\n\r\n\t// @method setIcon(icon: Icon): this\r\n\t// Changes the marker icon.\r\n\tsetIcon: function (icon) {\r\n\r\n\t\tthis.options.icon = icon;\r\n\r\n\t\tif (this._map) {\r\n\t\t\tthis._initIcon();\r\n\t\t\tthis.update();\r\n\t\t}\r\n\r\n\t\tif (this._popup) {\r\n\t\t\tthis.bindPopup(this._popup, this._popup.options);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\tgetElement: function () {\r\n\t\treturn this._icon;\r\n\t},\r\n\r\n\tupdate: function () {\r\n\r\n\t\tif (this._icon && this._map) {\r\n\t\t\tvar pos = this._map.latLngToLayerPoint(this._latlng).round();\r\n\t\t\tthis._setPos(pos);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_initIcon: function () {\r\n\t\tvar options = this.options,\r\n\t\t classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');\r\n\r\n\t\tvar icon = options.icon.createIcon(this._icon),\r\n\t\t addIcon = false;\r\n\r\n\t\t// if we're not reusing the icon, remove the old one and init new one\r\n\t\tif (icon !== this._icon) {\r\n\t\t\tif (this._icon) {\r\n\t\t\t\tthis._removeIcon();\r\n\t\t\t}\r\n\t\t\taddIcon = true;\r\n\r\n\t\t\tif (options.title) {\r\n\t\t\t\ticon.title = options.title;\r\n\t\t\t}\r\n\r\n\t\t\tif (icon.tagName === 'IMG') {\r\n\t\t\t\ticon.alt = options.alt || '';\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\taddClass(icon, classToAdd);\r\n\r\n\t\tif (options.keyboard) {\r\n\t\t\ticon.tabIndex = '0';\r\n\t\t}\r\n\r\n\t\tthis._icon = icon;\r\n\r\n\t\tif (options.riseOnHover) {\r\n\t\t\tthis.on({\r\n\t\t\t\tmouseover: this._bringToFront,\r\n\t\t\t\tmouseout: this._resetZIndex\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tvar newShadow = options.icon.createShadow(this._shadow),\r\n\t\t addShadow = false;\r\n\r\n\t\tif (newShadow !== this._shadow) {\r\n\t\t\tthis._removeShadow();\r\n\t\t\taddShadow = true;\r\n\t\t}\r\n\r\n\t\tif (newShadow) {\r\n\t\t\taddClass(newShadow, classToAdd);\r\n\t\t\tnewShadow.alt = '';\r\n\t\t}\r\n\t\tthis._shadow = newShadow;\r\n\r\n\r\n\t\tif (options.opacity < 1) {\r\n\t\t\tthis._updateOpacity();\r\n\t\t}\r\n\r\n\r\n\t\tif (addIcon) {\r\n\t\t\tthis.getPane().appendChild(this._icon);\r\n\t\t}\r\n\t\tthis._initInteraction();\r\n\t\tif (newShadow && addShadow) {\r\n\t\t\tthis.getPane(options.shadowPane).appendChild(this._shadow);\r\n\t\t}\r\n\t},\r\n\r\n\t_removeIcon: function () {\r\n\t\tif (this.options.riseOnHover) {\r\n\t\t\tthis.off({\r\n\t\t\t\tmouseover: this._bringToFront,\r\n\t\t\t\tmouseout: this._resetZIndex\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tremove(this._icon);\r\n\t\tthis.removeInteractiveTarget(this._icon);\r\n\r\n\t\tthis._icon = null;\r\n\t},\r\n\r\n\t_removeShadow: function () {\r\n\t\tif (this._shadow) {\r\n\t\t\tremove(this._shadow);\r\n\t\t}\r\n\t\tthis._shadow = null;\r\n\t},\r\n\r\n\t_setPos: function (pos) {\r\n\t\tsetPosition(this._icon, pos);\r\n\r\n\t\tif (this._shadow) {\r\n\t\t\tsetPosition(this._shadow, pos);\r\n\t\t}\r\n\r\n\t\tthis._zIndex = pos.y + this.options.zIndexOffset;\r\n\r\n\t\tthis._resetZIndex();\r\n\t},\r\n\r\n\t_updateZIndex: function (offset) {\r\n\t\tthis._icon.style.zIndex = this._zIndex + offset;\r\n\t},\r\n\r\n\t_animateZoom: function (opt) {\r\n\t\tvar pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();\r\n\r\n\t\tthis._setPos(pos);\r\n\t},\r\n\r\n\t_initInteraction: function () {\r\n\r\n\t\tif (!this.options.interactive) { return; }\r\n\r\n\t\taddClass(this._icon, 'leaflet-interactive');\r\n\r\n\t\tthis.addInteractiveTarget(this._icon);\r\n\r\n\t\tif (MarkerDrag) {\r\n\t\t\tvar draggable = this.options.draggable;\r\n\t\t\tif (this.dragging) {\r\n\t\t\t\tdraggable = this.dragging.enabled();\r\n\t\t\t\tthis.dragging.disable();\r\n\t\t\t}\r\n\r\n\t\t\tthis.dragging = new MarkerDrag(this);\r\n\r\n\t\t\tif (draggable) {\r\n\t\t\t\tthis.dragging.enable();\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t// @method setOpacity(opacity: Number): this\r\n\t// Changes the opacity of the marker.\r\n\tsetOpacity: function (opacity) {\r\n\t\tthis.options.opacity = opacity;\r\n\t\tif (this._map) {\r\n\t\t\tthis._updateOpacity();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_updateOpacity: function () {\r\n\t\tvar opacity = this.options.opacity;\r\n\r\n\t\tif (this._icon) {\r\n\t\t\tsetOpacity(this._icon, opacity);\r\n\t\t}\r\n\r\n\t\tif (this._shadow) {\r\n\t\t\tsetOpacity(this._shadow, opacity);\r\n\t\t}\r\n\t},\r\n\r\n\t_bringToFront: function () {\r\n\t\tthis._updateZIndex(this.options.riseOffset);\r\n\t},\r\n\r\n\t_resetZIndex: function () {\r\n\t\tthis._updateZIndex(0);\r\n\t},\r\n\r\n\t_getPopupAnchor: function () {\r\n\t\treturn this.options.icon.options.popupAnchor;\r\n\t},\r\n\r\n\t_getTooltipAnchor: function () {\r\n\t\treturn this.options.icon.options.tooltipAnchor;\r\n\t}\r\n});\r\n\r\n\r\n// factory L.marker(latlng: LatLng, options? : Marker options)\r\n\r\n// @factory L.marker(latlng: LatLng, options? : Marker options)\r\n// Instantiates a Marker object given a geographical point and optionally an options object.\r\nfunction marker(latlng, options) {\r\n\treturn new Marker(latlng, options);\r\n}\n\n/*\n * @class Path\n * @aka L.Path\n * @inherits Interactive layer\n *\n * An abstract class that contains options and constants shared between vector\n * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.\n */\n\nvar Path = Layer.extend({\n\n\t// @section\n\t// @aka Path options\n\toptions: {\n\t\t// @option stroke: Boolean = true\n\t\t// Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.\n\t\tstroke: true,\n\n\t\t// @option color: String = '#3388ff'\n\t\t// Stroke color\n\t\tcolor: '#3388ff',\n\n\t\t// @option weight: Number = 3\n\t\t// Stroke width in pixels\n\t\tweight: 3,\n\n\t\t// @option opacity: Number = 1.0\n\t\t// Stroke opacity\n\t\topacity: 1,\n\n\t\t// @option lineCap: String= 'round'\n\t\t// A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.\n\t\tlineCap: 'round',\n\n\t\t// @option lineJoin: String = 'round'\n\t\t// A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.\n\t\tlineJoin: 'round',\n\n\t\t// @option dashArray: String = null\n\t\t// A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).\n\t\tdashArray: null,\n\n\t\t// @option dashOffset: String = null\n\t\t// A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).\n\t\tdashOffset: null,\n\n\t\t// @option fill: Boolean = depends\n\t\t// Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.\n\t\tfill: false,\n\n\t\t// @option fillColor: String = *\n\t\t// Fill color. Defaults to the value of the [`color`](#path-color) option\n\t\tfillColor: null,\n\n\t\t// @option fillOpacity: Number = 0.2\n\t\t// Fill opacity.\n\t\tfillOpacity: 0.2,\n\n\t\t// @option fillRule: String = 'evenodd'\n\t\t// A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.\n\t\tfillRule: 'evenodd',\n\n\t\t// className: '',\n\n\t\t// Option inherited from \"Interactive layer\" abstract class\n\t\tinteractive: true,\n\n\t\t// @option bubblingMouseEvents: Boolean = true\n\t\t// When `true`, a mouse event on this path will trigger the same event on the map\n\t\t// (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).\n\t\tbubblingMouseEvents: true\n\t},\n\n\tbeforeAdd: function (map) {\n\t\t// Renderer is set here because we need to call renderer.getEvents\n\t\t// before this.getEvents.\n\t\tthis._renderer = map.getRenderer(this);\n\t},\n\n\tonAdd: function () {\n\t\tthis._renderer._initPath(this);\n\t\tthis._reset();\n\t\tthis._renderer._addPath(this);\n\t},\n\n\tonRemove: function () {\n\t\tthis._renderer._removePath(this);\n\t},\n\n\t// @method redraw(): this\n\t// Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.\n\tredraw: function () {\n\t\tif (this._map) {\n\t\t\tthis._renderer._updatePath(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method setStyle(style: Path options): this\n\t// Changes the appearance of a Path based on the options in the `Path options` object.\n\tsetStyle: function (style) {\n\t\tsetOptions(this, style);\n\t\tif (this._renderer) {\n\t\t\tthis._renderer._updateStyle(this);\n\t\t\tif (this.options.stroke && style.hasOwnProperty('weight')) {\n\t\t\t\tthis._updateBounds();\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method bringToFront(): this\n\t// Brings the layer to the top of all path layers.\n\tbringToFront: function () {\n\t\tif (this._renderer) {\n\t\t\tthis._renderer._bringToFront(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method bringToBack(): this\n\t// Brings the layer to the bottom of all path layers.\n\tbringToBack: function () {\n\t\tif (this._renderer) {\n\t\t\tthis._renderer._bringToBack(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\tgetElement: function () {\n\t\treturn this._path;\n\t},\n\n\t_reset: function () {\n\t\t// defined in child classes\n\t\tthis._project();\n\t\tthis._update();\n\t},\n\n\t_clickTolerance: function () {\n\t\t// used when doing hit detection for Canvas layers\n\t\treturn (this.options.stroke ? this.options.weight / 2 : 0) + this._renderer.options.tolerance;\n\t}\n});\n\n/*\n * @class CircleMarker\n * @aka L.CircleMarker\n * @inherits Path\n *\n * A circle of a fixed size with radius specified in pixels. Extends `Path`.\n */\n\nvar CircleMarker = Path.extend({\n\n\t// @section\n\t// @aka CircleMarker options\n\toptions: {\n\t\tfill: true,\n\n\t\t// @option radius: Number = 10\n\t\t// Radius of the circle marker, in pixels\n\t\tradius: 10\n\t},\n\n\tinitialize: function (latlng, options) {\n\t\tsetOptions(this, options);\n\t\tthis._latlng = toLatLng(latlng);\n\t\tthis._radius = this.options.radius;\n\t},\n\n\t// @method setLatLng(latLng: LatLng): this\n\t// Sets the position of a circle marker to a new location.\n\tsetLatLng: function (latlng) {\n\t\tthis._latlng = toLatLng(latlng);\n\t\tthis.redraw();\n\t\treturn this.fire('move', {latlng: this._latlng});\n\t},\n\n\t// @method getLatLng(): LatLng\n\t// Returns the current geographical position of the circle marker\n\tgetLatLng: function () {\n\t\treturn this._latlng;\n\t},\n\n\t// @method setRadius(radius: Number): this\n\t// Sets the radius of a circle marker. Units are in pixels.\n\tsetRadius: function (radius) {\n\t\tthis.options.radius = this._radius = radius;\n\t\treturn this.redraw();\n\t},\n\n\t// @method getRadius(): Number\n\t// Returns the current radius of the circle\n\tgetRadius: function () {\n\t\treturn this._radius;\n\t},\n\n\tsetStyle : function (options) {\n\t\tvar radius = options && options.radius || this._radius;\n\t\tPath.prototype.setStyle.call(this, options);\n\t\tthis.setRadius(radius);\n\t\treturn this;\n\t},\n\n\t_project: function () {\n\t\tthis._point = this._map.latLngToLayerPoint(this._latlng);\n\t\tthis._updateBounds();\n\t},\n\n\t_updateBounds: function () {\n\t\tvar r = this._radius,\n\t\t r2 = this._radiusY || r,\n\t\t w = this._clickTolerance(),\n\t\t p = [r + w, r2 + w];\n\t\tthis._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));\n\t},\n\n\t_update: function () {\n\t\tif (this._map) {\n\t\t\tthis._updatePath();\n\t\t}\n\t},\n\n\t_updatePath: function () {\n\t\tthis._renderer._updateCircle(this);\n\t},\n\n\t_empty: function () {\n\t\treturn this._radius && !this._renderer._bounds.intersects(this._pxBounds);\n\t},\n\n\t// Needed by the `Canvas` renderer for interactivity\n\t_containsPoint: function (p) {\n\t\treturn p.distanceTo(this._point) <= this._radius + this._clickTolerance();\n\t}\n});\n\n\n// @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)\n// Instantiates a circle marker object given a geographical point, and an optional options object.\nfunction circleMarker(latlng, options) {\n\treturn new CircleMarker(latlng, options);\n}\n\n/*\n * @class Circle\n * @aka L.Circle\n * @inherits CircleMarker\n *\n * A class for drawing circle overlays on a map. Extends `CircleMarker`.\n *\n * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).\n *\n * @example\n *\n * ```js\n * L.circle([50.5, 30.5], {radius: 200}).addTo(map);\n * ```\n */\n\nvar Circle = CircleMarker.extend({\n\n\tinitialize: function (latlng, options, legacyOptions) {\n\t\tif (typeof options === 'number') {\n\t\t\t// Backwards compatibility with 0.7.x factory (latlng, radius, options?)\n\t\t\toptions = extend({}, legacyOptions, {radius: options});\n\t\t}\n\t\tsetOptions(this, options);\n\t\tthis._latlng = toLatLng(latlng);\n\n\t\tif (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }\n\n\t\t// @section\n\t\t// @aka Circle options\n\t\t// @option radius: Number; Radius of the circle, in meters.\n\t\tthis._mRadius = this.options.radius;\n\t},\n\n\t// @method setRadius(radius: Number): this\n\t// Sets the radius of a circle. Units are in meters.\n\tsetRadius: function (radius) {\n\t\tthis._mRadius = radius;\n\t\treturn this.redraw();\n\t},\n\n\t// @method getRadius(): Number\n\t// Returns the current radius of a circle. Units are in meters.\n\tgetRadius: function () {\n\t\treturn this._mRadius;\n\t},\n\n\t// @method getBounds(): LatLngBounds\n\t// Returns the `LatLngBounds` of the path.\n\tgetBounds: function () {\n\t\tvar half = [this._radius, this._radiusY || this._radius];\n\n\t\treturn new LatLngBounds(\n\t\t\tthis._map.layerPointToLatLng(this._point.subtract(half)),\n\t\t\tthis._map.layerPointToLatLng(this._point.add(half)));\n\t},\n\n\tsetStyle: Path.prototype.setStyle,\n\n\t_project: function () {\n\n\t\tvar lng = this._latlng.lng,\n\t\t lat = this._latlng.lat,\n\t\t map = this._map,\n\t\t crs = map.options.crs;\n\n\t\tif (crs.distance === Earth.distance) {\n\t\t\tvar d = Math.PI / 180,\n\t\t\t latR = (this._mRadius / Earth.R) / d,\n\t\t\t top = map.project([lat + latR, lng]),\n\t\t\t bottom = map.project([lat - latR, lng]),\n\t\t\t p = top.add(bottom).divideBy(2),\n\t\t\t lat2 = map.unproject(p).lat,\n\t\t\t lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /\n\t\t\t (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;\n\n\t\t\tif (isNaN(lngR) || lngR === 0) {\n\t\t\t\tlngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425\n\t\t\t}\n\n\t\t\tthis._point = p.subtract(map.getPixelOrigin());\n\t\t\tthis._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;\n\t\t\tthis._radiusY = p.y - top.y;\n\n\t\t} else {\n\t\t\tvar latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));\n\n\t\t\tthis._point = map.latLngToLayerPoint(this._latlng);\n\t\t\tthis._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;\n\t\t}\n\n\t\tthis._updateBounds();\n\t}\n});\n\n// @factory L.circle(latlng: LatLng, options?: Circle options)\n// Instantiates a circle object given a geographical point, and an options object\n// which contains the circle radius.\n// @alternative\n// @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)\n// Obsolete way of instantiating a circle, for compatibility with 0.7.x code.\n// Do not use in new applications or plugins.\nfunction circle(latlng, options, legacyOptions) {\n\treturn new Circle(latlng, options, legacyOptions);\n}\n\n/*\n * @class Polyline\n * @aka L.Polyline\n * @inherits Path\n *\n * A class for drawing polyline overlays on a map. Extends `Path`.\n *\n * @example\n *\n * ```js\n * // create a red polyline from an array of LatLng points\n * var latlngs = [\n * \t[45.51, -122.68],\n * \t[37.77, -122.43],\n * \t[34.04, -118.2]\n * ];\n *\n * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);\n *\n * // zoom the map to the polyline\n * map.fitBounds(polyline.getBounds());\n * ```\n *\n * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:\n *\n * ```js\n * // create a red polyline from an array of arrays of LatLng points\n * var latlngs = [\n * \t[[45.51, -122.68],\n * \t [37.77, -122.43],\n * \t [34.04, -118.2]],\n * \t[[40.78, -73.91],\n * \t [41.83, -87.62],\n * \t [32.76, -96.72]]\n * ];\n * ```\n */\n\n\nvar Polyline = Path.extend({\n\n\t// @section\n\t// @aka Polyline options\n\toptions: {\n\t\t// @option smoothFactor: Number = 1.0\n\t\t// How much to simplify the polyline on each zoom level. More means\n\t\t// better performance and smoother look, and less means more accurate representation.\n\t\tsmoothFactor: 1.0,\n\n\t\t// @option noClip: Boolean = false\n\t\t// Disable polyline clipping.\n\t\tnoClip: false\n\t},\n\n\tinitialize: function (latlngs, options) {\n\t\tsetOptions(this, options);\n\t\tthis._setLatLngs(latlngs);\n\t},\n\n\t// @method getLatLngs(): LatLng[]\n\t// Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.\n\tgetLatLngs: function () {\n\t\treturn this._latlngs;\n\t},\n\n\t// @method setLatLngs(latlngs: LatLng[]): this\n\t// Replaces all the points in the polyline with the given array of geographical points.\n\tsetLatLngs: function (latlngs) {\n\t\tthis._setLatLngs(latlngs);\n\t\treturn this.redraw();\n\t},\n\n\t// @method isEmpty(): Boolean\n\t// Returns `true` if the Polyline has no LatLngs.\n\tisEmpty: function () {\n\t\treturn !this._latlngs.length;\n\t},\n\n\t// @method closestLayerPoint(p: Point): Point\n\t// Returns the point closest to `p` on the Polyline.\n\tclosestLayerPoint: function (p) {\n\t\tvar minDistance = Infinity,\n\t\t minPoint = null,\n\t\t closest = _sqClosestPointOnSegment,\n\t\t p1, p2;\n\n\t\tfor (var j = 0, jLen = this._parts.length; j < jLen; j++) {\n\t\t\tvar points = this._parts[j];\n\n\t\t\tfor (var i = 1, len = points.length; i < len; i++) {\n\t\t\t\tp1 = points[i - 1];\n\t\t\t\tp2 = points[i];\n\n\t\t\t\tvar sqDist = closest(p, p1, p2, true);\n\n\t\t\t\tif (sqDist < minDistance) {\n\t\t\t\t\tminDistance = sqDist;\n\t\t\t\t\tminPoint = closest(p, p1, p2);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (minPoint) {\n\t\t\tminPoint.distance = Math.sqrt(minDistance);\n\t\t}\n\t\treturn minPoint;\n\t},\n\n\t// @method getCenter(): LatLng\n\t// Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.\n\tgetCenter: function () {\n\t\t// throws error when not yet added to map as this center calculation requires projected coordinates\n\t\tif (!this._map) {\n\t\t\tthrow new Error('Must add layer to map before using getCenter()');\n\t\t}\n\n\t\tvar i, halfDist, segDist, dist, p1, p2, ratio,\n\t\t points = this._rings[0],\n\t\t len = points.length;\n\n\t\tif (!len) { return null; }\n\n\t\t// polyline centroid algorithm; only uses the first ring if there are multiple\n\n\t\tfor (i = 0, halfDist = 0; i < len - 1; i++) {\n\t\t\thalfDist += points[i].distanceTo(points[i + 1]) / 2;\n\t\t}\n\n\t\t// The line is so small in the current view that all points are on the same pixel.\n\t\tif (halfDist === 0) {\n\t\t\treturn this._map.layerPointToLatLng(points[0]);\n\t\t}\n\n\t\tfor (i = 0, dist = 0; i < len - 1; i++) {\n\t\t\tp1 = points[i];\n\t\t\tp2 = points[i + 1];\n\t\t\tsegDist = p1.distanceTo(p2);\n\t\t\tdist += segDist;\n\n\t\t\tif (dist > halfDist) {\n\t\t\t\tratio = (dist - halfDist) / segDist;\n\t\t\t\treturn this._map.layerPointToLatLng([\n\t\t\t\t\tp2.x - ratio * (p2.x - p1.x),\n\t\t\t\t\tp2.y - ratio * (p2.y - p1.y)\n\t\t\t\t]);\n\t\t\t}\n\t\t}\n\t},\n\n\t// @method getBounds(): LatLngBounds\n\t// Returns the `LatLngBounds` of the path.\n\tgetBounds: function () {\n\t\treturn this._bounds;\n\t},\n\n\t// @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this\n\t// Adds a given point to the polyline. By default, adds to the first ring of\n\t// the polyline in case of a multi-polyline, but can be overridden by passing\n\t// a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).\n\taddLatLng: function (latlng, latlngs) {\n\t\tlatlngs = latlngs || this._defaultShape();\n\t\tlatlng = toLatLng(latlng);\n\t\tlatlngs.push(latlng);\n\t\tthis._bounds.extend(latlng);\n\t\treturn this.redraw();\n\t},\n\n\t_setLatLngs: function (latlngs) {\n\t\tthis._bounds = new LatLngBounds();\n\t\tthis._latlngs = this._convertLatLngs(latlngs);\n\t},\n\n\t_defaultShape: function () {\n\t\treturn isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];\n\t},\n\n\t// recursively convert latlngs input into actual LatLng instances; calculate bounds along the way\n\t_convertLatLngs: function (latlngs) {\n\t\tvar result = [],\n\t\t flat = isFlat(latlngs);\n\n\t\tfor (var i = 0, len = latlngs.length; i < len; i++) {\n\t\t\tif (flat) {\n\t\t\t\tresult[i] = toLatLng(latlngs[i]);\n\t\t\t\tthis._bounds.extend(result[i]);\n\t\t\t} else {\n\t\t\t\tresult[i] = this._convertLatLngs(latlngs[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t},\n\n\t_project: function () {\n\t\tvar pxBounds = new Bounds();\n\t\tthis._rings = [];\n\t\tthis._projectLatlngs(this._latlngs, this._rings, pxBounds);\n\n\t\tif (this._bounds.isValid() && pxBounds.isValid()) {\n\t\t\tthis._rawPxBounds = pxBounds;\n\t\t\tthis._updateBounds();\n\t\t}\n\t},\n\n\t_updateBounds: function () {\n\t\tvar w = this._clickTolerance(),\n\t\t p = new Point(w, w);\n\t\tthis._pxBounds = new Bounds([\n\t\t\tthis._rawPxBounds.min.subtract(p),\n\t\t\tthis._rawPxBounds.max.add(p)\n\t\t]);\n\t},\n\n\t// recursively turns latlngs into a set of rings with projected coordinates\n\t_projectLatlngs: function (latlngs, result, projectedBounds) {\n\t\tvar flat = latlngs[0] instanceof LatLng,\n\t\t len = latlngs.length,\n\t\t i, ring;\n\n\t\tif (flat) {\n\t\t\tring = [];\n\t\t\tfor (i = 0; i < len; i++) {\n\t\t\t\tring[i] = this._map.latLngToLayerPoint(latlngs[i]);\n\t\t\t\tprojectedBounds.extend(ring[i]);\n\t\t\t}\n\t\t\tresult.push(ring);\n\t\t} else {\n\t\t\tfor (i = 0; i < len; i++) {\n\t\t\t\tthis._projectLatlngs(latlngs[i], result, projectedBounds);\n\t\t\t}\n\t\t}\n\t},\n\n\t// clip polyline by renderer bounds so that we have less to render for performance\n\t_clipPoints: function () {\n\t\tvar bounds = this._renderer._bounds;\n\n\t\tthis._parts = [];\n\t\tif (!this._pxBounds || !this._pxBounds.intersects(bounds)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.options.noClip) {\n\t\t\tthis._parts = this._rings;\n\t\t\treturn;\n\t\t}\n\n\t\tvar parts = this._parts,\n\t\t i, j, k, len, len2, segment, points;\n\n\t\tfor (i = 0, k = 0, len = this._rings.length; i < len; i++) {\n\t\t\tpoints = this._rings[i];\n\n\t\t\tfor (j = 0, len2 = points.length; j < len2 - 1; j++) {\n\t\t\t\tsegment = clipSegment(points[j], points[j + 1], bounds, j, true);\n\n\t\t\t\tif (!segment) { continue; }\n\n\t\t\t\tparts[k] = parts[k] || [];\n\t\t\t\tparts[k].push(segment[0]);\n\n\t\t\t\t// if segment goes out of screen, or it's the last one, it's the end of the line part\n\t\t\t\tif ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {\n\t\t\t\t\tparts[k].push(segment[1]);\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n\n\t// simplify each clipped part of the polyline for performance\n\t_simplifyPoints: function () {\n\t\tvar parts = this._parts,\n\t\t tolerance = this.options.smoothFactor;\n\n\t\tfor (var i = 0, len = parts.length; i < len; i++) {\n\t\t\tparts[i] = simplify(parts[i], tolerance);\n\t\t}\n\t},\n\n\t_update: function () {\n\t\tif (!this._map) { return; }\n\n\t\tthis._clipPoints();\n\t\tthis._simplifyPoints();\n\t\tthis._updatePath();\n\t},\n\n\t_updatePath: function () {\n\t\tthis._renderer._updatePoly(this);\n\t},\n\n\t// Needed by the `Canvas` renderer for interactivity\n\t_containsPoint: function (p, closed) {\n\t\tvar i, j, k, len, len2, part,\n\t\t w = this._clickTolerance();\n\n\t\tif (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }\n\n\t\t// hit detection for polylines\n\t\tfor (i = 0, len = this._parts.length; i < len; i++) {\n\t\t\tpart = this._parts[i];\n\n\t\t\tfor (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {\n\t\t\t\tif (!closed && (j === 0)) { continue; }\n\n\t\t\t\tif (pointToSegmentDistance(p, part[k], part[j]) <= w) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n});\n\n// @factory L.polyline(latlngs: LatLng[], options?: Polyline options)\n// Instantiates a polyline object given an array of geographical points and\n// optionally an options object. You can create a `Polyline` object with\n// multiple separate lines (`MultiPolyline`) by passing an array of arrays\n// of geographic points.\nfunction polyline(latlngs, options) {\n\treturn new Polyline(latlngs, options);\n}\n\n// Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.\nPolyline._flat = _flat;\n\n/*\n * @class Polygon\n * @aka L.Polygon\n * @inherits Polyline\n *\n * A class for drawing polygon overlays on a map. Extends `Polyline`.\n *\n * Note that points you pass when creating a polygon shouldn't have an additional last point equal to the first one — it's better to filter out such points.\n *\n *\n * @example\n *\n * ```js\n * // create a red polygon from an array of LatLng points\n * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];\n *\n * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);\n *\n * // zoom the map to the polygon\n * map.fitBounds(polygon.getBounds());\n * ```\n *\n * You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape:\n *\n * ```js\n * var latlngs = [\n * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring\n * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole\n * ];\n * ```\n *\n * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.\n *\n * ```js\n * var latlngs = [\n * [ // first polygon\n * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring\n * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole\n * ],\n * [ // second polygon\n * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]\n * ]\n * ];\n * ```\n */\n\nvar Polygon = Polyline.extend({\n\n\toptions: {\n\t\tfill: true\n\t},\n\n\tisEmpty: function () {\n\t\treturn !this._latlngs.length || !this._latlngs[0].length;\n\t},\n\n\tgetCenter: function () {\n\t\t// throws error when not yet added to map as this center calculation requires projected coordinates\n\t\tif (!this._map) {\n\t\t\tthrow new Error('Must add layer to map before using getCenter()');\n\t\t}\n\n\t\tvar i, j, p1, p2, f, area, x, y, center,\n\t\t points = this._rings[0],\n\t\t len = points.length;\n\n\t\tif (!len) { return null; }\n\n\t\t// polygon centroid algorithm; only uses the first ring if there are multiple\n\n\t\tarea = x = y = 0;\n\n\t\tfor (i = 0, j = len - 1; i < len; j = i++) {\n\t\t\tp1 = points[i];\n\t\t\tp2 = points[j];\n\n\t\t\tf = p1.y * p2.x - p2.y * p1.x;\n\t\t\tx += (p1.x + p2.x) * f;\n\t\t\ty += (p1.y + p2.y) * f;\n\t\t\tarea += f * 3;\n\t\t}\n\n\t\tif (area === 0) {\n\t\t\t// Polygon is so small that all points are on same pixel.\n\t\t\tcenter = points[0];\n\t\t} else {\n\t\t\tcenter = [x / area, y / area];\n\t\t}\n\t\treturn this._map.layerPointToLatLng(center);\n\t},\n\n\t_convertLatLngs: function (latlngs) {\n\t\tvar result = Polyline.prototype._convertLatLngs.call(this, latlngs),\n\t\t len = result.length;\n\n\t\t// remove last point if it equals first one\n\t\tif (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {\n\t\t\tresult.pop();\n\t\t}\n\t\treturn result;\n\t},\n\n\t_setLatLngs: function (latlngs) {\n\t\tPolyline.prototype._setLatLngs.call(this, latlngs);\n\t\tif (isFlat(this._latlngs)) {\n\t\t\tthis._latlngs = [this._latlngs];\n\t\t}\n\t},\n\n\t_defaultShape: function () {\n\t\treturn isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];\n\t},\n\n\t_clipPoints: function () {\n\t\t// polygons need a different clipping algorithm so we redefine that\n\n\t\tvar bounds = this._renderer._bounds,\n\t\t w = this.options.weight,\n\t\t p = new Point(w, w);\n\n\t\t// increase clip padding by stroke width to avoid stroke on clip edges\n\t\tbounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));\n\n\t\tthis._parts = [];\n\t\tif (!this._pxBounds || !this._pxBounds.intersects(bounds)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.options.noClip) {\n\t\t\tthis._parts = this._rings;\n\t\t\treturn;\n\t\t}\n\n\t\tfor (var i = 0, len = this._rings.length, clipped; i < len; i++) {\n\t\t\tclipped = clipPolygon(this._rings[i], bounds, true);\n\t\t\tif (clipped.length) {\n\t\t\t\tthis._parts.push(clipped);\n\t\t\t}\n\t\t}\n\t},\n\n\t_updatePath: function () {\n\t\tthis._renderer._updatePoly(this, true);\n\t},\n\n\t// Needed by the `Canvas` renderer for interactivity\n\t_containsPoint: function (p) {\n\t\tvar inside = false,\n\t\t part, p1, p2, i, j, k, len, len2;\n\n\t\tif (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }\n\n\t\t// ray casting algorithm for detecting if point is in polygon\n\t\tfor (i = 0, len = this._parts.length; i < len; i++) {\n\t\t\tpart = this._parts[i];\n\n\t\t\tfor (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {\n\t\t\t\tp1 = part[j];\n\t\t\t\tp2 = part[k];\n\n\t\t\t\tif (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {\n\t\t\t\t\tinside = !inside;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// also check if it's on polygon stroke\n\t\treturn inside || Polyline.prototype._containsPoint.call(this, p, true);\n\t}\n\n});\n\n\n// @factory L.polygon(latlngs: LatLng[], options?: Polyline options)\nfunction polygon(latlngs, options) {\n\treturn new Polygon(latlngs, options);\n}\n\n/*\r\n * @class GeoJSON\r\n * @aka L.GeoJSON\r\n * @inherits FeatureGroup\r\n *\r\n * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse\r\n * GeoJSON data and display it on the map. Extends `FeatureGroup`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.geoJSON(data, {\r\n * \tstyle: function (feature) {\r\n * \t\treturn {color: feature.properties.color};\r\n * \t}\r\n * }).bindPopup(function (layer) {\r\n * \treturn layer.feature.properties.description;\r\n * }).addTo(map);\r\n * ```\r\n */\r\n\r\nvar GeoJSON = FeatureGroup.extend({\r\n\r\n\t/* @section\r\n\t * @aka GeoJSON options\r\n\t *\r\n\t * @option pointToLayer: Function = *\r\n\t * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally\r\n\t * called when data is added, passing the GeoJSON point feature and its `LatLng`.\r\n\t * The default is to spawn a default `Marker`:\r\n\t * ```js\r\n\t * function(geoJsonPoint, latlng) {\r\n\t * \treturn L.marker(latlng);\r\n\t * }\r\n\t * ```\r\n\t *\r\n\t * @option style: Function = *\r\n\t * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,\r\n\t * called internally when data is added.\r\n\t * The default value is to not override any defaults:\r\n\t * ```js\r\n\t * function (geoJsonFeature) {\r\n\t * \treturn {}\r\n\t * }\r\n\t * ```\r\n\t *\r\n\t * @option onEachFeature: Function = *\r\n\t * A `Function` that will be called once for each created `Feature`, after it has\r\n\t * been created and styled. Useful for attaching events and popups to features.\r\n\t * The default is to do nothing with the newly created layers:\r\n\t * ```js\r\n\t * function (feature, layer) {}\r\n\t * ```\r\n\t *\r\n\t * @option filter: Function = *\r\n\t * A `Function` that will be used to decide whether to include a feature or not.\r\n\t * The default is to include all features:\r\n\t * ```js\r\n\t * function (geoJsonFeature) {\r\n\t * \treturn true;\r\n\t * }\r\n\t * ```\r\n\t * Note: dynamically changing the `filter` option will have effect only on newly\r\n\t * added data. It will _not_ re-evaluate already included features.\r\n\t *\r\n\t * @option coordsToLatLng: Function = *\r\n\t * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.\r\n\t * The default is the `coordsToLatLng` static method.\r\n\t */\r\n\r\n\tinitialize: function (geojson, options) {\r\n\t\tsetOptions(this, options);\r\n\r\n\t\tthis._layers = {};\r\n\r\n\t\tif (geojson) {\r\n\t\t\tthis.addData(geojson);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method addData( data ): this\r\n\t// Adds a GeoJSON object to the layer.\r\n\taddData: function (geojson) {\r\n\t\tvar features = isArray(geojson) ? geojson : geojson.features,\r\n\t\t i, len, feature;\r\n\r\n\t\tif (features) {\r\n\t\t\tfor (i = 0, len = features.length; i < len; i++) {\r\n\t\t\t\t// only add this if geometry or geometries are set and not null\r\n\t\t\t\tfeature = features[i];\r\n\t\t\t\tif (feature.geometries || feature.geometry || feature.features || feature.coordinates) {\r\n\t\t\t\t\tthis.addData(feature);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tvar options = this.options;\r\n\r\n\t\tif (options.filter && !options.filter(geojson)) { return this; }\r\n\r\n\t\tvar layer = geometryToLayer(geojson, options);\r\n\t\tif (!layer) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\t\tlayer.feature = asFeature(geojson);\r\n\r\n\t\tlayer.defaultOptions = layer.options;\r\n\t\tthis.resetStyle(layer);\r\n\r\n\t\tif (options.onEachFeature) {\r\n\t\t\toptions.onEachFeature(geojson, layer);\r\n\t\t}\r\n\r\n\t\treturn this.addLayer(layer);\r\n\t},\r\n\r\n\t// @method resetStyle( layer ): this\r\n\t// Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.\r\n\tresetStyle: function (layer) {\r\n\t\t// reset any custom styles\r\n\t\tlayer.options = extend({}, layer.defaultOptions);\r\n\t\tthis._setLayerStyle(layer, this.options.style);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setStyle( style ): this\r\n\t// Changes styles of GeoJSON vector layers with the given style function.\r\n\tsetStyle: function (style) {\r\n\t\treturn this.eachLayer(function (layer) {\r\n\t\t\tthis._setLayerStyle(layer, style);\r\n\t\t}, this);\r\n\t},\r\n\r\n\t_setLayerStyle: function (layer, style) {\r\n\t\tif (layer.setStyle) {\r\n\t\t\tif (typeof style === 'function') {\r\n\t\t\t\tstyle = style(layer.feature);\r\n\t\t\t}\r\n\t\t\tlayer.setStyle(style);\r\n\t\t}\r\n\t}\r\n});\r\n\r\n// @section\r\n// There are several static functions which can be called without instantiating L.GeoJSON:\r\n\r\n// @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer\r\n// Creates a `Layer` from a given GeoJSON feature. Can use a custom\r\n// [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)\r\n// functions if provided as options.\r\nfunction geometryToLayer(geojson, options) {\r\n\r\n\tvar geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,\r\n\t coords = geometry ? geometry.coordinates : null,\r\n\t layers = [],\r\n\t pointToLayer = options && options.pointToLayer,\r\n\t _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,\r\n\t latlng, latlngs, i, len;\r\n\r\n\tif (!coords && !geometry) {\r\n\t\treturn null;\r\n\t}\r\n\r\n\tswitch (geometry.type) {\r\n\tcase 'Point':\r\n\t\tlatlng = _coordsToLatLng(coords);\r\n\t\treturn pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng);\r\n\r\n\tcase 'MultiPoint':\r\n\t\tfor (i = 0, len = coords.length; i < len; i++) {\r\n\t\t\tlatlng = _coordsToLatLng(coords[i]);\r\n\t\t\tlayers.push(pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng));\r\n\t\t}\r\n\t\treturn new FeatureGroup(layers);\r\n\r\n\tcase 'LineString':\r\n\tcase 'MultiLineString':\r\n\t\tlatlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);\r\n\t\treturn new Polyline(latlngs, options);\r\n\r\n\tcase 'Polygon':\r\n\tcase 'MultiPolygon':\r\n\t\tlatlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);\r\n\t\treturn new Polygon(latlngs, options);\r\n\r\n\tcase 'GeometryCollection':\r\n\t\tfor (i = 0, len = geometry.geometries.length; i < len; i++) {\r\n\t\t\tvar layer = geometryToLayer({\r\n\t\t\t\tgeometry: geometry.geometries[i],\r\n\t\t\t\ttype: 'Feature',\r\n\t\t\t\tproperties: geojson.properties\r\n\t\t\t}, options);\r\n\r\n\t\t\tif (layer) {\r\n\t\t\t\tlayers.push(layer);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn new FeatureGroup(layers);\r\n\r\n\tdefault:\r\n\t\tthrow new Error('Invalid GeoJSON object.');\r\n\t}\r\n}\r\n\r\n// @function coordsToLatLng(coords: Array): LatLng\r\n// Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)\r\n// or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.\r\nfunction coordsToLatLng(coords) {\r\n\treturn new LatLng(coords[1], coords[0], coords[2]);\r\n}\r\n\r\n// @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array\r\n// Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.\r\n// `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).\r\n// Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.\r\nfunction coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {\r\n\tvar latlngs = [];\r\n\r\n\tfor (var i = 0, len = coords.length, latlng; i < len; i++) {\r\n\t\tlatlng = levelsDeep ?\r\n\t\t\tcoordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :\r\n\t\t\t(_coordsToLatLng || coordsToLatLng)(coords[i]);\r\n\r\n\t\tlatlngs.push(latlng);\r\n\t}\r\n\r\n\treturn latlngs;\r\n}\r\n\r\n// @function latLngToCoords(latlng: LatLng, precision?: Number): Array\r\n// Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)\r\nfunction latLngToCoords(latlng, precision) {\r\n\tprecision = typeof precision === 'number' ? precision : 6;\r\n\treturn latlng.alt !== undefined ?\r\n\t\t[formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :\r\n\t\t[formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];\r\n}\r\n\r\n// @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array\r\n// Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)\r\n// `closed` determines whether the first point should be appended to the end of the array to close the feature, only used when `levelsDeep` is 0. False by default.\r\nfunction latLngsToCoords(latlngs, levelsDeep, closed, precision) {\r\n\tvar coords = [];\r\n\r\n\tfor (var i = 0, len = latlngs.length; i < len; i++) {\r\n\t\tcoords.push(levelsDeep ?\r\n\t\t\tlatLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) :\r\n\t\t\tlatLngToCoords(latlngs[i], precision));\r\n\t}\r\n\r\n\tif (!levelsDeep && closed) {\r\n\t\tcoords.push(coords[0]);\r\n\t}\r\n\r\n\treturn coords;\r\n}\r\n\r\nfunction getFeature(layer, newGeometry) {\r\n\treturn layer.feature ?\r\n\t\textend({}, layer.feature, {geometry: newGeometry}) :\r\n\t\tasFeature(newGeometry);\r\n}\r\n\r\n// @function asFeature(geojson: Object): Object\r\n// Normalize GeoJSON geometries/features into GeoJSON features.\r\nfunction asFeature(geojson) {\r\n\tif (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {\r\n\t\treturn geojson;\r\n\t}\r\n\r\n\treturn {\r\n\t\ttype: 'Feature',\r\n\t\tproperties: {},\r\n\t\tgeometry: geojson\r\n\t};\r\n}\r\n\r\nvar PointToGeoJSON = {\r\n\ttoGeoJSON: function (precision) {\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: 'Point',\r\n\t\t\tcoordinates: latLngToCoords(this.getLatLng(), precision)\r\n\t\t});\r\n\t}\r\n};\r\n\r\n// @namespace Marker\r\n// @method toGeoJSON(precision?: Number): Object\r\n// `precision` is the number of decimal places for coordinates.\r\n// The default value is 6 places.\r\n// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).\r\nMarker.include(PointToGeoJSON);\r\n\r\n// @namespace CircleMarker\r\n// @method toGeoJSON(precision?: Number): Object\r\n// `precision` is the number of decimal places for coordinates.\r\n// The default value is 6 places.\r\n// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).\r\nCircle.include(PointToGeoJSON);\r\nCircleMarker.include(PointToGeoJSON);\r\n\r\n\r\n// @namespace Polyline\r\n// @method toGeoJSON(precision?: Number): Object\r\n// `precision` is the number of decimal places for coordinates.\r\n// The default value is 6 places.\r\n// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).\r\nPolyline.include({\r\n\ttoGeoJSON: function (precision) {\r\n\t\tvar multi = !isFlat(this._latlngs);\r\n\r\n\t\tvar coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);\r\n\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: (multi ? 'Multi' : '') + 'LineString',\r\n\t\t\tcoordinates: coords\r\n\t\t});\r\n\t}\r\n});\r\n\r\n// @namespace Polygon\r\n// @method toGeoJSON(precision?: Number): Object\r\n// `precision` is the number of decimal places for coordinates.\r\n// The default value is 6 places.\r\n// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).\r\nPolygon.include({\r\n\ttoGeoJSON: function (precision) {\r\n\t\tvar holes = !isFlat(this._latlngs),\r\n\t\t multi = holes && !isFlat(this._latlngs[0]);\r\n\r\n\t\tvar coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);\r\n\r\n\t\tif (!holes) {\r\n\t\t\tcoords = [coords];\r\n\t\t}\r\n\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: (multi ? 'Multi' : '') + 'Polygon',\r\n\t\t\tcoordinates: coords\r\n\t\t});\r\n\t}\r\n});\r\n\r\n\r\n// @namespace LayerGroup\r\nLayerGroup.include({\r\n\ttoMultiPoint: function (precision) {\r\n\t\tvar coords = [];\r\n\r\n\t\tthis.eachLayer(function (layer) {\r\n\t\t\tcoords.push(layer.toGeoJSON(precision).geometry.coordinates);\r\n\t\t});\r\n\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: 'MultiPoint',\r\n\t\t\tcoordinates: coords\r\n\t\t});\r\n\t},\r\n\r\n\t// @method toGeoJSON(precision?: Number): Object\r\n\t// `precision` is the number of decimal places for coordinates.\r\n\t// The default value is 6 places.\r\n\t// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).\r\n\ttoGeoJSON: function (precision) {\r\n\r\n\t\tvar type = this.feature && this.feature.geometry && this.feature.geometry.type;\r\n\r\n\t\tif (type === 'MultiPoint') {\r\n\t\t\treturn this.toMultiPoint(precision);\r\n\t\t}\r\n\r\n\t\tvar isGeometryCollection = type === 'GeometryCollection',\r\n\t\t jsons = [];\r\n\r\n\t\tthis.eachLayer(function (layer) {\r\n\t\t\tif (layer.toGeoJSON) {\r\n\t\t\t\tvar json = layer.toGeoJSON(precision);\r\n\t\t\t\tif (isGeometryCollection) {\r\n\t\t\t\t\tjsons.push(json.geometry);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tvar feature = asFeature(json);\r\n\t\t\t\t\t// Squash nested feature collections\r\n\t\t\t\t\tif (feature.type === 'FeatureCollection') {\r\n\t\t\t\t\t\tjsons.push.apply(jsons, feature.features);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tjsons.push(feature);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tif (isGeometryCollection) {\r\n\t\t\treturn getFeature(this, {\r\n\t\t\t\tgeometries: jsons,\r\n\t\t\t\ttype: 'GeometryCollection'\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\treturn {\r\n\t\t\ttype: 'FeatureCollection',\r\n\t\t\tfeatures: jsons\r\n\t\t};\r\n\t}\r\n});\r\n\r\n// @namespace GeoJSON\r\n// @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)\r\n// Creates a GeoJSON layer. Optionally accepts an object in\r\n// [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map\r\n// (you can alternatively add it later with `addData` method) and an `options` object.\r\nfunction geoJSON(geojson, options) {\r\n\treturn new GeoJSON(geojson, options);\r\n}\r\n\r\n// Backward compatibility.\r\nvar geoJson = geoJSON;\n\n/*\r\n * @class ImageOverlay\r\n * @aka L.ImageOverlay\r\n * @inherits Interactive layer\r\n *\r\n * Used to load and display a single image over specific bounds of the map. Extends `Layer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',\r\n * \timageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];\r\n * L.imageOverlay(imageUrl, imageBounds).addTo(map);\r\n * ```\r\n */\r\n\r\nvar ImageOverlay = Layer.extend({\r\n\r\n\t// @section\r\n\t// @aka ImageOverlay options\r\n\toptions: {\r\n\t\t// @option opacity: Number = 1.0\r\n\t\t// The opacity of the image overlay.\r\n\t\topacity: 1,\r\n\r\n\t\t// @option alt: String = ''\r\n\t\t// Text for the `alt` attribute of the image (useful for accessibility).\r\n\t\talt: '',\r\n\r\n\t\t// @option interactive: Boolean = false\r\n\t\t// If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.\r\n\t\tinteractive: false,\r\n\r\n\t\t// @option crossOrigin: Boolean|String = false\r\n\t\t// Whether the crossOrigin attribute will be added to the image.\r\n\t\t// If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data.\r\n\t\t// Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.\r\n\t\tcrossOrigin: false,\r\n\r\n\t\t// @option errorOverlayUrl: String = ''\r\n\t\t// URL to the overlay image to show in place of the overlay that failed to load.\r\n\t\terrorOverlayUrl: '',\r\n\r\n\t\t// @option zIndex: Number = 1\r\n\t\t// The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.\r\n\t\tzIndex: 1,\r\n\r\n\t\t// @option className: String = ''\r\n\t\t// A custom class name to assign to the image. Empty by default.\r\n\t\tclassName: ''\r\n\t},\r\n\r\n\tinitialize: function (url, bounds, options) { // (String, LatLngBounds, Object)\r\n\t\tthis._url = url;\r\n\t\tthis._bounds = toLatLngBounds(bounds);\r\n\r\n\t\tsetOptions(this, options);\r\n\t},\r\n\r\n\tonAdd: function () {\r\n\t\tif (!this._image) {\r\n\t\t\tthis._initImage();\r\n\r\n\t\t\tif (this.options.opacity < 1) {\r\n\t\t\t\tthis._updateOpacity();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (this.options.interactive) {\r\n\t\t\taddClass(this._image, 'leaflet-interactive');\r\n\t\t\tthis.addInteractiveTarget(this._image);\r\n\t\t}\r\n\r\n\t\tthis.getPane().appendChild(this._image);\r\n\t\tthis._reset();\r\n\t},\r\n\r\n\tonRemove: function () {\r\n\t\tremove(this._image);\r\n\t\tif (this.options.interactive) {\r\n\t\t\tthis.removeInteractiveTarget(this._image);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method setOpacity(opacity: Number): this\r\n\t// Sets the opacity of the overlay.\r\n\tsetOpacity: function (opacity) {\r\n\t\tthis.options.opacity = opacity;\r\n\r\n\t\tif (this._image) {\r\n\t\t\tthis._updateOpacity();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\tsetStyle: function (styleOpts) {\r\n\t\tif (styleOpts.opacity) {\r\n\t\t\tthis.setOpacity(styleOpts.opacity);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method bringToFront(): this\r\n\t// Brings the layer to the top of all overlays.\r\n\tbringToFront: function () {\r\n\t\tif (this._map) {\r\n\t\t\ttoFront(this._image);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method bringToBack(): this\r\n\t// Brings the layer to the bottom of all overlays.\r\n\tbringToBack: function () {\r\n\t\tif (this._map) {\r\n\t\t\ttoBack(this._image);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setUrl(url: String): this\r\n\t// Changes the URL of the image.\r\n\tsetUrl: function (url) {\r\n\t\tthis._url = url;\r\n\r\n\t\tif (this._image) {\r\n\t\t\tthis._image.src = url;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setBounds(bounds: LatLngBounds): this\r\n\t// Update the bounds that this ImageOverlay covers\r\n\tsetBounds: function (bounds) {\r\n\t\tthis._bounds = toLatLngBounds(bounds);\r\n\r\n\t\tif (this._map) {\r\n\t\t\tthis._reset();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\tgetEvents: function () {\r\n\t\tvar events = {\r\n\t\t\tzoom: this._reset,\r\n\t\t\tviewreset: this._reset\r\n\t\t};\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tevents.zoomanim = this._animateZoom;\r\n\t\t}\r\n\r\n\t\treturn events;\r\n\t},\r\n\r\n\t// @method setZIndex(value: Number): this\r\n\t// Changes the [zIndex](#imageoverlay-zindex) of the image overlay.\r\n\tsetZIndex: function (value) {\r\n\t\tthis.options.zIndex = value;\r\n\t\tthis._updateZIndex();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getBounds(): LatLngBounds\r\n\t// Get the bounds that this ImageOverlay covers\r\n\tgetBounds: function () {\r\n\t\treturn this._bounds;\r\n\t},\r\n\r\n\t// @method getElement(): HTMLElement\r\n\t// Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)\r\n\t// used by this overlay.\r\n\tgetElement: function () {\r\n\t\treturn this._image;\r\n\t},\r\n\r\n\t_initImage: function () {\r\n\t\tvar wasElementSupplied = this._url.tagName === 'IMG';\r\n\t\tvar img = this._image = wasElementSupplied ? this._url : create$1('img');\r\n\r\n\t\taddClass(img, 'leaflet-image-layer');\r\n\t\tif (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }\r\n\t\tif (this.options.className) { addClass(img, this.options.className); }\r\n\r\n\t\timg.onselectstart = falseFn;\r\n\t\timg.onmousemove = falseFn;\r\n\r\n\t\t// @event load: Event\r\n\t\t// Fired when the ImageOverlay layer has loaded its image\r\n\t\timg.onload = bind(this.fire, this, 'load');\r\n\t\timg.onerror = bind(this._overlayOnError, this, 'error');\r\n\r\n\t\tif (this.options.crossOrigin || this.options.crossOrigin === '') {\r\n\t\t\timg.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;\r\n\t\t}\r\n\r\n\t\tif (this.options.zIndex) {\r\n\t\t\tthis._updateZIndex();\r\n\t\t}\r\n\r\n\t\tif (wasElementSupplied) {\r\n\t\t\tthis._url = img.src;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\timg.src = this._url;\r\n\t\timg.alt = this.options.alt;\r\n\t},\r\n\r\n\t_animateZoom: function (e) {\r\n\t\tvar scale = this._map.getZoomScale(e.zoom),\r\n\t\t offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;\r\n\r\n\t\tsetTransform(this._image, offset, scale);\r\n\t},\r\n\r\n\t_reset: function () {\r\n\t\tvar image = this._image,\r\n\t\t bounds = new Bounds(\r\n\t\t this._map.latLngToLayerPoint(this._bounds.getNorthWest()),\r\n\t\t this._map.latLngToLayerPoint(this._bounds.getSouthEast())),\r\n\t\t size = bounds.getSize();\r\n\r\n\t\tsetPosition(image, bounds.min);\r\n\r\n\t\timage.style.width = size.x + 'px';\r\n\t\timage.style.height = size.y + 'px';\r\n\t},\r\n\r\n\t_updateOpacity: function () {\r\n\t\tsetOpacity(this._image, this.options.opacity);\r\n\t},\r\n\r\n\t_updateZIndex: function () {\r\n\t\tif (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {\r\n\t\t\tthis._image.style.zIndex = this.options.zIndex;\r\n\t\t}\r\n\t},\r\n\r\n\t_overlayOnError: function () {\r\n\t\t// @event error: Event\r\n\t\t// Fired when the ImageOverlay layer fails to load its image\r\n\t\tthis.fire('error');\r\n\r\n\t\tvar errorUrl = this.options.errorOverlayUrl;\r\n\t\tif (errorUrl && this._url !== errorUrl) {\r\n\t\t\tthis._url = errorUrl;\r\n\t\t\tthis._image.src = errorUrl;\r\n\t\t}\r\n\t}\r\n});\r\n\r\n// @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)\r\n// Instantiates an image overlay object given the URL of the image and the\r\n// geographical bounds it is tied to.\r\nvar imageOverlay = function (url, bounds, options) {\r\n\treturn new ImageOverlay(url, bounds, options);\r\n};\n\n/*\r\n * @class VideoOverlay\r\n * @aka L.VideoOverlay\r\n * @inherits ImageOverlay\r\n *\r\n * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.\r\n *\r\n * A video overlay uses the [`
    \n `;\n return input.tip\n ? html`\n \n ${avatar}\n \n `\n : avatar;\n};\n","import { LitElement, PropertyValueMap } from 'lit';\nimport { CustomEventType } from './interfaces';\nimport { Color, log } from './utils';\n\nconst showUpdates = (\n ele: HTMLElement,\n changes: Map,\n firstUpdated = false\n) => {\n if (ele['DEBUG_UPDATES'] || ele['DEBUG']) {\n if (changes.size > 0) {\n const fromto = {};\n for (const key of changes.keys()) {\n fromto[key] = [changes[key], ele[key]];\n }\n\n log(ele.tagName, Color.PURPLE, [\n firstUpdated ? '' : '',\n fromto,\n ]);\n }\n }\n};\n\nconst showEvent = (ele: HTMLElement, type: string, details = undefined) => {\n if (ele['DEBUG_EVENTS'] || ele['DEBUG']) {\n if (details !== undefined) {\n log(ele.tagName, Color.GREEN, [type, details]);\n } else {\n log(ele.tagName, Color.GREEN, [type]);\n }\n }\n};\n\nexport interface EventHandler {\n event: string;\n method: EventListener;\n isDocument?: boolean;\n isWindow?: boolean;\n}\n\nexport class RapidElement extends LitElement {\n DEBUG = false;\n DEBUG_UPDATES = false;\n DEBUG_EVENTS = false;\n\n private eles: { [selector: string]: HTMLDivElement } = {};\n public getEventHandlers(): EventHandler[] {\n return [];\n }\n\n connectedCallback() {\n super.connectedCallback();\n\n for (const handler of this.getEventHandlers()) {\n if (handler.isDocument) {\n document.addEventListener(handler.event, handler.method.bind(this));\n } else if (handler.isWindow) {\n window.addEventListener(handler.event, handler.method.bind(this));\n } else {\n this.addEventListener(handler.event, handler.method.bind(this));\n }\n }\n }\n\n disconnectedCallback() {\n for (const handler of this.getEventHandlers()) {\n if (handler.isDocument) {\n document.removeEventListener(handler.event, handler.method);\n } else if (handler.isWindow) {\n window.removeEventListener(handler.event, handler.method);\n } else {\n this.removeEventListener(handler.event, handler.method);\n }\n }\n super.disconnectedCallback();\n }\n\n protected firstUpdated(\n changes: PropertyValueMap | Map\n ): void {\n super.firstUpdated(changes);\n showUpdates(this, changes, true);\n }\n\n protected updated(\n changes: PropertyValueMap | Map\n ): void {\n super.updated(changes);\n showUpdates(this, changes, false);\n }\n\n public fireEvent(type: string): any {\n showEvent(this, type);\n\n return this.dispatchEvent(\n new Event(type, {\n bubbles: true,\n composed: true,\n })\n );\n }\n\n swallowEvent(event: Event) {\n event.stopPropagation();\n event.preventDefault();\n }\n\n public fireCustomEvent(type: CustomEventType, detail: any = {}): any {\n if (this['DEBUG_EVENTS']) {\n showEvent(this, type, detail);\n }\n\n const event = new CustomEvent(type, {\n detail,\n bubbles: true,\n composed: true,\n });\n\n return this.dispatchEvent(event);\n }\n\n public dispatchEvent(event: any): any {\n super.dispatchEvent(event);\n const ele = event.target;\n if (ele) {\n // lookup events with - prefix and try to invoke them\n const eventFire = (ele as any)['-' + event.type];\n if (eventFire) {\n return eventFire(event);\n } else {\n const func = new Function(\n 'event',\n `\n with(document) {\n with(this) {\n let handler = ${ele.getAttribute('-' + event.type)};\n if(typeof handler === 'function') { \n handler(event);\n }\n }\n }\n `\n );\n return func.call(ele, event);\n }\n }\n }\n\n public closestElement(selector: string, base: Element = this) {\n function __closestFrom(el: Element | Window | Document): Element {\n if (!el || el === document || el === window) return null;\n if ((el as any).assignedSlot) el = (el as any).assignedSlot;\n const found = (el as Element).closest(selector);\n return found\n ? found\n : __closestFrom(((el as Element).getRootNode() as ShadowRoot).host);\n }\n return __closestFrom(base);\n }\n\n public getDiv(selector: string) {\n let ele = this.eles[selector];\n if (ele) {\n return ele;\n }\n\n ele = this.shadowRoot.querySelector(selector);\n if (ele) {\n this.eles[selector] = ele;\n }\n return ele;\n }\n\n public stopEvent(event: Event) {\n if (event) {\n event.stopPropagation();\n event.preventDefault();\n }\n }\n\n public isMobile() {\n const win = window as any;\n if (win.isMobile) {\n return win.isMobile();\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=t=>(e,o)=>{void 0!==o?o.addInitializer((()=>{customElements.define(t,e)})):customElements.define(t,e)};export{t as customElement};\n//# sourceMappingURL=custom-element.js.map\n","import{defaultConverter as t,notEqual as e}from\"../reactive-element.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const o={attribute:!0,type:String,converter:t,reflect:!1,hasChanged:e},r=(t=o,e,r)=>{const{kind:n,metadata:i}=r;let s=globalThis.litPropertyMetadata.get(i);if(void 0===s&&globalThis.litPropertyMetadata.set(i,s=new Map),s.set(r.name,t),\"accessor\"===n){const{name:o}=r;return{set(r){const n=e.get.call(this);e.set.call(this,r),this.requestUpdate(o,n,t)},init(e){return void 0!==e&&this.P(o,void 0,t),e}}}if(\"setter\"===n){const{name:o}=r;return function(r){const n=this[o];e.call(this,r),this.requestUpdate(o,n,t)}}throw Error(\"Unsupported decorator location: \"+n)};function n(t){return(e,o)=>\"object\"==typeof o?r(t,e,o):((t,e,o)=>{const r=e.hasOwnProperty(o);return e.constructor.createProperty(o,r?{...t,wrapped:!0}:t),r?Object.getOwnPropertyDescriptor(e,o):void 0})(t,e,o)}export{n as property,r as standardProperty};\n//# sourceMappingURL=property.js.map\n","import { RapidElement } from './RapidElement';\nimport { property } from 'lit/decorators.js';\n\n/**\n * FormElement is a component that appends a hidden input (outside of\n * its own shadow) with its value to be included in forms.\n */\nexport class FormElement extends RapidElement {\n @property({ type: String })\n name = '';\n\n @property({ type: String, attribute: 'help_text' })\n helpText: string;\n\n @property({ type: Boolean, attribute: 'help_always' })\n helpAlways: boolean;\n\n @property({ type: Boolean, attribute: 'widget_only' })\n widgetOnly: boolean;\n\n @property({ type: Boolean, attribute: 'hide_label' })\n hideLabel: boolean;\n\n @property({ type: String })\n label: string;\n\n @property({ type: Array })\n errors: string[];\n\n @property({ type: String })\n value = null;\n\n @property({ attribute: false })\n inputRoot: HTMLElement = this;\n\n @property({ type: Boolean })\n disabled = false;\n static formAssociated = true;\n\n protected internals: ElementInternals;\n\n constructor() {\n super();\n this.internals = this.attachInternals();\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n if (changedProperties.has('value')) {\n this.internals.setFormValue(this.value);\n }\n }\n\n get form() {\n return this.internals.form;\n }\n\n public setValue(value: any) {\n this.value = this.serializeValue(value);\n }\n\n public getDeserializedValue(): any {\n return JSON.parse(this.value);\n }\n\n public serializeValue(value: any): string {\n return JSON.stringify(value);\n }\n}\n","// for cache busting we dynamically generate a fingerprint, use yarn svg to update\nexport const SVG_FINGERPRINT = 'e5bcaf1a10896e9b870da4b40474d67b';\n\n// only icons below are included in the sprite sheet\nexport enum Icon {\n alert_warning = 'alert-square',\n account = 'user-01',\n active = 'play',\n add = 'plus',\n add_note = 'file-02',\n airtime = 'bank-note-01',\n analytics = 'bar-chart-01',\n archive = 'archive',\n arrow_up = 'chevron-up',\n arrow_down = 'chevron-down',\n arrow_left = 'chevron-left',\n arrow_right = 'chevron-right',\n attachment = 'paperclip',\n attachment_audio = 'volume-min',\n attachment_document = 'file-06',\n attachment_image = 'image-01',\n attachment_location = 'marker-pin-01',\n attachment_video = 'video-recorder',\n branding = 'brush-02',\n branding_hostname = 'server-05',\n branding_notifications = 'mail-01',\n branding_styling = 'palette',\n branding_raw = 'pencil-01',\n broadcast = 'announcement-01',\n call = 'phone-call-01',\n call_missed = 'phone-call-02',\n campaign = 'clock-refresh',\n campaign_active = 'play',\n campaign_archived = 'archive',\n campaigns = 'clock-refresh',\n channel = 'zap',\n children = 'git-branch-01',\n check = 'check',\n checkbox = 'square',\n checkbox_checked = 'check-square',\n checkbox_partial = 'stop-square',\n classifier_wit = 'classifier-wit',\n classifier_luis = 'classifier-luis',\n classifier_bothub = 'classifier-bothub',\n close = 'x',\n compose = 'send-01',\n contact = 'user-01',\n contact_archived = 'archive',\n contact_blocked = 'message-x-square',\n contact_export = 'download-cloud-01',\n contact_import = 'upload-cloud-01',\n contact_stopped = 'slash-octagon',\n contact_updated = 'user-edit',\n contacts = 'user-01',\n copy = 'copy-04',\n dashboard = 'pie-chart-01',\n delete = 'trash-03',\n delete_small = 'x',\n down = 'chevron-down',\n download = 'download-01',\n edit = 'edit-03',\n email = 'mail-01',\n error = 'alert-circle',\n event = 'zap',\n expressions = 'at-sign',\n fields = 'user-edit',\n filter = 'filter-funnel-01',\n flow = 'flow',\n flow_background = 'layers-two-01',\n flow_interrupted = 'x-close',\n flow_ivr = 'phone',\n flow_message = 'message-square-02',\n flow_surveyor = 'tablet-01',\n flow_user = 'hard-drive',\n flows = 'flow',\n global = 'at-sign',\n grid = 'dots-grid',\n group = 'users-01',\n group_exclude = 'users-x',\n group_include = 'users-check',\n group_smart = 'atom-01',\n help = 'help-circle',\n hide = 'eye-off',\n home = 'settings-02',\n image = 'image-01',\n inbox = 'inbox-01',\n incidents = 'alert-square',\n incoming_call = 'phone-incoming-01',\n integrations = 'layers-three-01',\n info = 'user-square',\n issue = 'alert-square',\n label = 'tag-01',\n language = 'translate-01',\n link = 'link-external-01',\n location = 'marker-pin-01',\n log = 'file-02',\n logout = 'log-out-04',\n menu = 'menu-01',\n menu_collapse = 'chevron-left-double',\n message = 'message-square-02',\n message_export = 'download-cloud-01',\n messages = 'message-square-02',\n missing = 'maximize-02',\n missed_call = 'phone-x',\n new = 'plus',\n next_schedule = 'alarm-clock',\n notification = 'bell-01',\n number = 'hash-01',\n optin_requested = 'message-notification-circle',\n optin = 'message-check-circle',\n optout = 'message-x-circle',\n org_active = 'credit-card-02',\n org_anonymous = 'glasses-01',\n org_bulk = 'credit-card-plus',\n org_flagged = 'flag-01',\n org_new = 'stars-02',\n org_suspended = 'slash-circle-01',\n org_verified = 'check-verified-02',\n overview = 'pie-chart-01',\n prometheus = 'prometheus',\n progress_spinner = 'refresh-cw-04',\n featured = 'star-01',\n quick_replies = 'dotpoints-01',\n recording = 'microphone-01',\n resend = 'refresh-cw-05',\n reset = 'flip-backward',\n resthooks = 'share-07',\n restore = 'play',\n results_export = 'download-cloud-01',\n retry = 'refresh-cw-05',\n revisions = 'clock-rewind',\n rocketchat = 'rocketchat',\n runs = 'rows-03',\n schedule = 'calendar',\n search = 'search-refraction',\n select_open = 'chevron-down',\n select_clear = 'x',\n send = 'send-03',\n service = 'magic-wand-01',\n service_end = 'log-out-04',\n settings = 'settings-02',\n show = 'eye',\n simulator = 'phone-02',\n sort = 'chevron-selector-vertical',\n sort_down = 'sort-arrow-down',\n sort_up = 'sort-arrow-up',\n staff = 'hard-drive',\n submit = 'check',\n success = 'check',\n template_approved = 'check-circle',\n template_pending = 'hourglass-01',\n template_rejected = 'alert-circle',\n template_unsupported = 'alert-circle',\n tickets = 'agent',\n tickets_all = 'archive',\n tickets_closed = 'check',\n tickets_mine = 'coffee',\n tickets_open = 'inbox-01',\n tickets_export = 'download-cloud-01',\n tickets_unassigned = 'inbox-01',\n topic = 'message-text-circle-02',\n two_factor_enabled = 'shield-02',\n two_factor_disabled = 'shield-01',\n trigger = 'signal-01',\n trigger_active = 'play',\n trigger_archived = 'archive',\n trigger_new = 'plus',\n trigger_keyword = 'message-check-square',\n trigger_catch_all = 'message-question-square',\n trigger_inbound_call = 'phone-incoming-01',\n trigger_missed_call = 'phone-hang-up',\n trigger_schedule = 'calendar',\n trigger_new_conversation = 'message-chat-square',\n trigger_referral = 'user-right-01',\n trigger_closed_ticket = 'agent',\n trigger_opt_in = 'message-check-circle',\n trigger_opt_out = 'message-x-circle',\n triggers = 'signal-01',\n updated = 'edit-02',\n up = 'chevron-up',\n upload = 'upload-cloud-01',\n upload_image = 'camera-01',\n usages = 'link-04',\n user = 'users-01',\n users = 'users-01',\n user_beta = 'shield-zap',\n webhook = 'link-external-01',\n wit = 'wit',\n workspace = 'folder',\n zapier = 'zapier',\n zendesk = 'zendesk',\n\n // channel types\n channel_a = 'channel-android',\n channel_ac = 'zap', // TODO https://www.arabiacell.com/\n channel_at = 'zap', // TODO https://africastalking.com/\n channel_bs = 'zap', // TODO https://burstsms.com/\n channel_bw = 'zap', // TODO https://www.bandwidth.com/\n channel_cs = 'zap', // TODO https://www.clicksend.com/\n channel_ct = 'channel-clickatell',\n channel_d3 = 'channel-whatsapp',\n channel_d3c = 'channel-whatsapp',\n channel_da = 'zap', // TODO https://dartmedia.co.id/\n channel_ds = 'channel-discord',\n channel_ex = 'zap',\n channel_fb = 'channel-facebook',\n channel_fba = 'channel-facebook',\n channel_fc = 'channel-freshchat',\n channel_fcm = 'channel-firebase',\n channel_hm = 'zap', // TODO https://hormuud.com/\n channel_ib = 'zap', // TODO https://www.infobip.com/\n channel_ig = 'channel-instagram',\n channel_jc = 'channel-jiochat',\n channel_kn = 'channel-kannel',\n channel_kwa = 'channel-whatsapp',\n channel_ln = 'channel-line',\n channel_mt = 'channel-mtarget',\n channel_mtn = 'zap', // TODO https://mtn.com/\n channel_nx = 'channel-vonage',\n channel_pl = 'channel-plivo',\n channel_rc = 'channel-rocketchat',\n channel_sl = 'channel-slack',\n channel_sq = 'zap', // TODO https://shaqodoon.org/\n channel_st = 'zap', // TODO https://bulk.startmobile.ua\n channel_sw = 'channel-signalwire',\n channel_t = 'channel-twilio',\n channel_tg = 'channel-telegram',\n channel_tms = 'channel-twilio',\n channel_tq = 'channel-thinq',\n channel_tw = 'zap', // TODO https://www.somleng.org/\n channel_twa = 'channel-whatsapp',\n channel_twc = 'zap', // TODO\n channel_twt = 'channel-twitter',\n channel_vk = 'channel-vk',\n channel_vp = 'channel-viber',\n channel_wa = 'channel-whatsapp',\n channel_wac = 'channel-whatsapp',\n channel_wc = 'channel-wechat',\n channel_yo = 'zap', // TODO https://www.yo.co.ug/\n channel_zvw = 'channel-whatsapp',\n\n bothub = 'bothub',\n chatbase = 'chatbase',\n dtone = 'dtone',\n\n // demo\n default = 'list',\n datepicker = 'calendar',\n slider = 'sliders-02',\n select = 'browser',\n input = 'edit-05',\n}\n","import { TemplateResult, html, css } from 'lit';\nimport { FormElement } from '../FormElement';\nimport { property } from 'lit/decorators.js';\nimport { Icon } from '../vectoricon';\n\nexport class Checkbox extends FormElement {\n static get styles() {\n return css`\n :host {\n color: var(--color-text);\n display: inline-block;\n }\n\n :host([label]) {\n width: 100%;\n }\n\n .wrapper.label {\n padding: var(--checkbox-padding, 10px);\n border-radius: var(--curvature);\n }\n\n .wrapper.label:hover {\n background: #f9f9f9;\n }\n\n temba-field {\n --help-text-margin-left: 24px;\n cursor: pointer;\n }\n\n .checkbox-container {\n cursor: pointer;\n display: flex;\n user-select: none;\n -webkit-user-select: none;\n }\n\n .checkbox-label {\n font-family: var(--font-family);\n padding: 0px;\n margin-left: 8px;\n font-size: 14px;\n line-height: 19px;\n flex-grow: 1;\n }\n\n .far {\n height: 16px;\n margin-top: 1px;\n }\n\n .disabled {\n cursor: not-allowed;\n --icon-color: #ccc;\n }\n `;\n }\n\n @property({ type: String })\n name = '';\n\n @property({ type: Boolean })\n checked: boolean;\n\n @property({ type: Boolean })\n partial: boolean;\n\n @property({ type: Boolean })\n disabled = false;\n\n @property({ type: Number })\n size = 1.2;\n\n @property({ type: String })\n animateChange = 'pulse';\n\n public updated(changes: Map) {\n super.updated(changes);\n if (changes.has('checked') || changes.has('value')) {\n if (this.checked || this.partial) {\n this.internals.setFormValue(this.value || '1');\n } else {\n this.internals.setFormValue(undefined);\n }\n this.fireEvent('change');\n }\n }\n\n public serializeValue(value: any): string {\n return value;\n }\n\n private handleClick(): void {\n if (!this.disabled) {\n this.checked = !this.checked;\n }\n }\n\n public click(): void {\n this.handleClick();\n super.click();\n }\n\n public render(): TemplateResult {\n const icon = html``;\n\n this.label = this.label ? this.label.trim() : null;\n\n return html`\n
    \n \n
    \n ${icon}\n ${this.label\n ? html`
    ${this.label}
    `\n : null}\n
    \n \n
    \n `;\n }\n}\n","import{nothing as t}from\"../lit-html.js\";\n/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const o=o=>o??t;export{o as ifDefined};\n//# sourceMappingURL=if-defined.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},e=t=>(...e)=>({_$litDirective$:t,values:e});class i{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}}export{i as Directive,t as PartType,e as directive};\n//# sourceMappingURL=directive.js.map\n","import{noChange as t}from\"../lit-html.js\";import{directive as e,Directive as r,PartType as s}from\"../directive.js\";\n/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const n=\"important\",i=\" !\"+n,o=e(class extends r{constructor(t){if(super(t),t.type!==s.ATTRIBUTE||\"style\"!==t.name||t.strings?.length>2)throw Error(\"The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.\")}render(t){return Object.keys(t).reduce(((e,r)=>{const s=t[r];return null==s?e:e+`${r=r.includes(\"-\")?r:r.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,\"-$&\").toLowerCase()}:${s};`}),\"\")}update(e,[r]){const{style:s}=e.element;if(void 0===this.ft)return this.ft=new Set(Object.keys(r)),this.render(r);for(const t of this.ft)null==r[t]&&(this.ft.delete(t),t.includes(\"-\")?s.removeProperty(t):s[t]=null);for(const t in r){const e=r[t];if(null!=e){this.ft.add(t);const r=\"string\"==typeof e&&e.endsWith(i);t.includes(\"-\")||r?s.setProperty(t,r?e.slice(0,-11):e,r?n:\"\"):s[t]=e}}return t}});export{o as styleMap};\n//# sourceMappingURL=style-map.js.map\n","import { TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { ifDefined } from 'lit-html/directives/if-defined.js';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { FormElement } from '../FormElement';\nimport { Modax } from '../dialog/Modax';\nimport { sanitize } from './helpers';\nimport { CharCount } from '../charcount/CharCount';\n\nexport enum InputType {\n Text = 'text',\n Password = 'password',\n Number = 'number',\n}\n\nexport class TextInput extends FormElement {\n static get styles() {\n return css`\n .input-container {\n border-radius: var(--curvature-widget);\n cursor: var(--input-cursor);\n background: var(--color-widget-bg);\n border: 1px solid var(--color-widget-border);\n transition: all ease-in-out var(--transition-speed);\n display: flex;\n flex-direction: row;\n align-items: stretch;\n box-shadow: var(--widget-box-shadow);\n caret-color: var(--input-caret);\n }\n\n .clear-icon {\n --icon-color: var(--color-text-dark-secondary);\n cursor: pointer;\n margin: auto;\n padding-right: 10px;\n line-height: 1;\n }\n\n .clear-icon:hover {\n --icon-color: var(--color-text-dark);\n }\n\n .hidden {\n visibility: hidden;\n position: absolute;\n }\n\n .input-container:focus-within {\n border-color: var(--color-focus);\n background: var(--color-widget-bg-focused);\n box-shadow: var(--widget-box-shadow-focused);\n position: relative;\n }\n\n .input-container:hover {\n }\n\n textarea {\n height: var(--textarea-height);\n min-height: var(--textarea-min-height, var(--textarea-height));\n transition: height var(--transition-speed) ease-in-out;\n }\n\n .textinput {\n padding: var(--temba-textinput-padding);\n border: none;\n flex: 1;\n margin: 0;\n background: none;\n background-color: transparent;\n color: var(--color-widget-text);\n font-family: var(--font-family);\n font-size: var(--temba-textinput-font-size);\n line-height: normal;\n cursor: var(--input-cursor);\n resize: none;\n width: 100%;\n }\n\n .textinput:focus {\n outline: none;\n box-shadow: none;\n cursor: text;\n color: var(--color-widget-text-focused, var(--color-widget-text));\n }\n\n .textinput::placeholder {\n color: var(--color-placeholder);\n }\n\n .grow-wrap {\n display: flex;\n align-items: stretch;\n width: 100%;\n }\n\n .grow-wrap > div {\n border: 0px solid green;\n width: 100%;\n padding: var(--temba-textinput-padding);\n flex: 1;\n margin: 0;\n background: none;\n color: var(--color-widget-text);\n font-family: var(--font-family);\n font-size: var(--temba-textinput-font-size);\n line-height: normal;\n cursor: text;\n resize: none;\n width: 100%;\n visibility: hidden;\n word-break: break-word;\n }\n\n .grow-wrap textarea {\n margin-left: -100%;\n }\n\n input[type='number'] {\n appearance: none;\n }\n\n input[type='number']::-webkit-inner-spin-button {\n display: none;\n }\n\n .type-icon {\n color: #e3e3e3;\n }\n `;\n }\n\n @property({ type: Boolean })\n textarea: boolean;\n\n @property({ type: String })\n placeholder = '';\n\n @property({ type: Boolean })\n password: boolean;\n\n @property({ type: Number })\n maxlength: number;\n\n @property({ type: Object })\n inputElement: HTMLInputElement;\n\n @property({ type: Boolean })\n clearable: boolean;\n\n @property({ type: Boolean })\n gsm: boolean;\n\n @property({ type: String })\n counter: string;\n\n // if we are still loading\n @property({ type: Boolean })\n loading = true;\n\n @property({ type: Boolean })\n submitOnEnter = true;\n\n @property()\n onBlur: any;\n\n @property({ type: Boolean })\n autogrow = false;\n\n @property({ type: String })\n type = InputType.Text;\n\n counterElement: CharCount = null;\n cursorStart = -1;\n cursorEnd = -1;\n\n public constructor() {\n super();\n }\n\n public firstUpdated(changes: Map) {\n super.firstUpdated(changes);\n\n this.inputElement = this.shadowRoot.querySelector('.textinput');\n\n if (changes.has('counter')) {\n let root = this.getParentModax() as any;\n if (root) {\n root = root.shadowRoot;\n }\n if (!root) {\n root = document;\n }\n this.counterElement = root.querySelector(this.counter);\n this.counterElement.text = this.value;\n }\n }\n\n public updated(changes: Map) {\n super.updated(changes);\n\n if (changes.has('value')) {\n if (changes.get('value') !== undefined) {\n this.fireEvent('change');\n }\n\n if (this.textarea && this.autogrow) {\n const autogrow = this.shadowRoot.querySelector(\n '.grow-wrap > div'\n ) as HTMLDivElement;\n autogrow.innerText = this.value + String.fromCharCode(10);\n }\n\n if (this.cursorStart > -1 && this.cursorEnd > -1) {\n this.inputElement.setSelectionRange(this.cursorStart, this.cursorEnd);\n this.cursorStart = -1;\n this.cursorEnd = -1;\n }\n }\n }\n\n public getDisplayValue() {\n return this.inputElement.value;\n }\n\n private handleClear(event: any): void {\n event.stopPropagation();\n event.preventDefault();\n this.value = null;\n }\n\n private updateValue(value: string): void {\n const cursorStart = this.inputElement.selectionStart;\n const cursorEnd = this.inputElement.selectionEnd;\n\n const sanitized = this.sanitizeGSM(value);\n\n if (sanitized !== value) {\n this.cursorStart = cursorStart;\n this.cursorEnd = cursorEnd;\n }\n\n this.value = sanitized;\n\n if (this.textarea) {\n this.inputElement.value = this.value;\n }\n\n if (this.counterElement) {\n this.counterElement.text = value;\n }\n }\n\n private sanitizeGSM(text: string): string {\n return this.gsm ? sanitize(text) : text;\n }\n\n private handleChange(update: any): void {\n if (this.disabled) {\n return;\n }\n this.updateValue(update.target.value);\n this.fireEvent('change');\n }\n\n private handleContainerClick(): void {\n if (this.disabled) {\n return;\n }\n if (this.inputElement) {\n this.inputElement.click();\n }\n }\n\n private handleContainerFocus(): void {\n if (this.disabled) {\n return;\n }\n if (this.inputElement) {\n this.inputElement.focus();\n }\n }\n\n private handleInput(update: any): void {\n if (this.disabled) {\n return;\n }\n\n this.updateValue(update.target.value);\n this.fireEvent('input');\n }\n\n /** we just return the value since it should be a string */\n public serializeValue(value: any): string {\n return value;\n }\n\n public getParentModax(): Modax {\n let parent = this as HTMLElement;\n\n while (parent) {\n if (parent.parentElement) {\n parent = parent.parentElement;\n } else {\n parent = (parent as any).getRootNode().host;\n }\n\n if (!parent) {\n return null;\n }\n\n if (parent.tagName == 'TEMBA-MODAX') {\n return parent as Modax;\n }\n }\n }\n\n public getParentForm(): HTMLFormElement {\n let parent = this as HTMLElement;\n\n while (parent) {\n if (parent.parentElement) {\n parent = parent.parentElement;\n } else {\n parent = (parent as any).getRootNode().host;\n }\n\n if (!parent) {\n return null;\n }\n\n if (parent.tagName === 'FORM') {\n return parent as HTMLFormElement;\n }\n }\n }\n\n public click(): void {\n super.click();\n this.handleContainerClick();\n }\n\n public focus(): void {\n super.focus();\n this.handleContainerFocus();\n }\n\n // TODO make this a formelement and have contactsearch set the root\n public render(): TemplateResult {\n const containerStyle = {\n height: `${this.textarea ? '100%' : 'auto'}`,\n };\n\n const clear =\n this.clearable && this.inputElement && this.inputElement.value\n ? html``\n : null;\n\n let input = html`\n {\n if (e.key === 'Enter') {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const input = this;\n\n if (this.submitOnEnter) {\n const parentModax = input.getParentModax();\n const parentForm = !parentModax ? input.getParentForm() : null;\n\n // if we don't have something to submit then bail\n if (!parentModax && !parentForm) {\n return false;\n }\n\n // don't submit disabled forms on enter\n if (parentModax && parentModax.disabled) {\n return false;\n }\n\n input.blur();\n\n // look for a form to submit\n window.setTimeout(function () {\n // first, look for a modax that contains us\n const modax = input.getParentModax();\n if (modax) {\n input.blur();\n\n modax.submit();\n } else {\n // otherwise, just look for a vanilla submit button\n const form = input.getParentForm();\n\n if (form) {\n const submitButton = form.querySelector(\n \"input[type='submit']\"\n ) as HTMLInputElement;\n if (submitButton) {\n submitButton.click();\n } else {\n form.submit();\n }\n }\n }\n }, 10);\n // this is needed for firefox, would be nice to\n // find a way to do this with a callback instead\n }\n }\n }}\n placeholder=${this.placeholder}\n .value=${this.value}\n .disabled=${this.disabled}\n />\n `;\n\n if (this.textarea) {\n input = html`\n \n `;\n\n if (this.autogrow) {\n input = html`
    \n
    \n ${input}\n
    `;\n }\n }\n\n return html`\n \n \n \n\n ${input} ${clear}\n ${this.type === InputType.Number\n ? html``\n : null}\n \n
    \n \n `;\n }\n}\n","export interface Workspace {\n uuid: string;\n name: string;\n country: string;\n languages: string[];\n timezone: string;\n date_style: DateStyle;\n anon: boolean;\n}\n\nexport interface Language {\n iso: string;\n name: string;\n}\n\nexport interface Attachment {\n uuid: string;\n content_type: string;\n url: string;\n filename: string;\n size: number;\n error: string;\n}\n\nexport enum DateStyle {\n DayFirst = 'day_first',\n MonthFirst = 'month_first',\n YearFirst = 'year_first',\n}\n\nexport enum ScheduledEventType {\n CampaignEvent = 'campaign_event',\n ScheduledBroadcast = 'scheduled_broadcast',\n ScheduledTrigger = 'scheduled_trigger',\n}\n\nexport enum TicketStatus {\n Open = 'open',\n Closed = 'closed',\n}\n\nexport interface ScheduledEvent {\n type: ScheduledEventType;\n scheduled: string;\n repeat_period: string;\n campaign?: ObjectReference;\n flow?: ObjectReference;\n message?: string;\n}\n\nexport interface User {\n id?: number;\n first_name?: string;\n last_name?: string;\n email?: string;\n role?: string;\n created_on?: string;\n avatar?: string;\n}\n\nexport interface Ticket {\n uuid: string;\n subject: string;\n body?: string;\n closed_on: string;\n opened_on: string;\n status: string;\n contact: ObjectReference;\n topic: ObjectReference;\n assignee?: { email: string; name: string; avatar?: string };\n}\n\nexport interface FlowResult {\n key: string;\n name: string;\n categories: string[];\n node_uuids: string[];\n}\n\nexport interface FlowDetails {\n name: string;\n results: FlowResult[];\n modified_on: string;\n runs: {\n active: number;\n completed: number;\n expired: number;\n interrupted: number;\n };\n}\n\nexport interface Msg {\n text: string;\n status: string;\n channel: ObjectReference;\n quick_replies: string[];\n urn: string;\n id: number;\n direction: string;\n type: string;\n attachments: string[];\n}\n\nexport interface ObjectReference {\n uuid: string;\n name: string;\n}\n\nexport interface ContactField {\n key: string;\n label: string;\n value_type: string;\n featured: boolean;\n priority: number;\n agent_access: string;\n type: string;\n usages: { campaign_events: number; flows: number; groups: number };\n}\n\nexport interface ContactGroup {\n uuid: string;\n count: number;\n name: string;\n query?: string;\n status: string;\n}\n\nexport interface URN {\n scheme: string;\n path: string;\n}\n\nexport interface Group {\n name: string;\n uuid: string;\n is_dynamic?: boolean;\n}\n\nexport interface ContactTicket {\n name: string;\n uuid: string;\n status: string;\n\n contact: {\n uuid: string;\n name: string;\n created_on: Date;\n last_seen_on: Date;\n };\n}\n\nexport interface Contact {\n name: string;\n uuid: string;\n stopped: boolean;\n blocked: boolean;\n urns: string[];\n language?: string;\n fields: { [key: string]: string };\n groups: Group[];\n modified_on: string;\n created_on: string;\n last_seen_on: string;\n status: string;\n\n anon_display?: string;\n flow?: ObjectReference;\n last_msg?: Msg;\n direction?: string;\n ticket: {\n uuid: string;\n subject: string;\n closed_on?: string;\n last_activity_on: string;\n assignee?: User;\n topic?: ObjectReference;\n };\n}\n\nexport interface FeatureProperties {\n name: string;\n osm_id: string;\n level: number;\n children?: FeatureProperties[];\n has_children?: boolean;\n aliases?: string;\n parent_osm_id?: string;\n id?: number;\n path?: string;\n}\n\nexport interface Position {\n top: number;\n left: number;\n}\n\nexport interface FunctionExample {\n template: string;\n output: string;\n}\n\nexport interface CompletionOption {\n name?: string;\n summary: string;\n\n // functions\n signature?: string;\n detail?: string;\n examples?: FunctionExample[];\n}\n\nexport interface CompletionResult {\n anchorPosition: Position;\n query: string;\n options: CompletionOption[];\n currentFunction: CompletionOption;\n}\n\nexport interface CompletionProperty {\n key: string;\n help: string;\n type: string;\n}\n\nexport interface CompletionType {\n name: string;\n\n key_source?: string;\n property_template?: CompletionProperty;\n properties?: CompletionProperty[];\n}\n\nexport interface CompletionSchema {\n types: CompletionType[];\n root: CompletionProperty[];\n root_no_session: CompletionProperty[];\n}\n\nexport type KeyedAssets = { [assetType: string]: string[] };\n\nexport enum CustomEventType {\n Loaded = 'temba-loaded',\n Canceled = 'temba-canceled',\n CursorChanged = 'temba-cursor-changed',\n Refreshed = 'temba-refreshed',\n Selection = 'temba-selection',\n ButtonClicked = 'temba-button-clicked',\n DialogHidden = 'temba-dialog-hidden',\n ScrollThreshold = 'temba-scroll-threshold',\n ContentChanged = 'temba-content-changed',\n ContextChanged = 'temba-context-changed',\n FetchComplete = 'temba-fetch-complete',\n MessageSent = 'temba-message-sent',\n Submitted = 'temba-submitted',\n Redirected = 'temba-redirected',\n NoPath = 'temba-no-path',\n StoreUpdated = 'temba-store-updated',\n Ready = 'temba-ready',\n OrderChanged = 'temba-order-changed',\n DragStart = 'temba-drag-start',\n DragStop = 'temba-drag-stop',\n Resized = 'temba-resized',\n}\n","export const sanitize = (text: string): string => {\n if (text) {\n return text\n .replace(/[\\u2018\\u2019]/g, \"'\") // Smart single quotes\n .replace(/[\\u201C\\u201D]/g, '\"') // Smart double quotes\n .replace(/[\\u2013\\u2014]/g, '-') // En/em dash\n .replace(/\\u2026/g, '...') // Horizontal ellipsis\n .replace(/\\u2002/g, ' '); // En space\n }\n return text;\n};\n","/**\n * tiny-lru\n *\n * @copyright 2023 Jason Mulligan \n * @license BSD-3-Clause\n * @version 11.2.5\n */\nclass LRU {\r\n\tconstructor (max = 0, ttl = 0, resetTtl = false) {\r\n\t\tthis.first = null;\r\n\t\tthis.items = Object.create(null);\r\n\t\tthis.last = null;\r\n\t\tthis.max = max;\r\n\t\tthis.resetTtl = resetTtl;\r\n\t\tthis.size = 0;\r\n\t\tthis.ttl = ttl;\r\n\t}\r\n\r\n\tclear () {\r\n\t\tthis.first = null;\r\n\t\tthis.items = Object.create(null);\r\n\t\tthis.last = null;\r\n\t\tthis.size = 0;\r\n\r\n\t\treturn this;\r\n\t}\r\n\r\n\tdelete (key) {\r\n\t\tif (this.has(key)) {\r\n\t\t\tconst item = this.items[key];\r\n\r\n\t\t\tdelete this.items[key];\r\n\t\t\tthis.size--;\r\n\r\n\t\t\tif (item.prev !== null) {\r\n\t\t\t\titem.prev.next = item.next;\r\n\t\t\t}\r\n\r\n\t\t\tif (item.next !== null) {\r\n\t\t\t\titem.next.prev = item.prev;\r\n\t\t\t}\r\n\r\n\t\t\tif (this.first === item) {\r\n\t\t\t\tthis.first = item.next;\r\n\t\t\t}\r\n\r\n\t\t\tif (this.last === item) {\r\n\t\t\t\tthis.last = item.prev;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t}\r\n\r\n\tentries (keys = this.keys()) {\r\n\t\treturn keys.map(key => [key, this.get(key)]);\r\n\t}\r\n\r\n\tevict (bypass = false) {\r\n\t\tif (bypass || this.size > 0) {\r\n\t\t\tconst item = this.first;\r\n\r\n\t\t\tdelete this.items[item.key];\r\n\r\n\t\t\tif (--this.size === 0) {\r\n\t\t\t\tthis.first = null;\r\n\t\t\t\tthis.last = null;\r\n\t\t\t} else {\r\n\t\t\t\tthis.first = item.next;\r\n\t\t\t\tthis.first.prev = null;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t}\r\n\r\n\texpiresAt (key) {\r\n\t\tlet result;\r\n\r\n\t\tif (this.has(key)) {\r\n\t\t\tresult = this.items[key].expiry;\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tget (key) {\r\n\t\tlet result;\r\n\r\n\t\tif (this.has(key)) {\r\n\t\t\tconst item = this.items[key];\r\n\r\n\t\t\tif (this.ttl > 0 && item.expiry <= Date.now()) {\r\n\t\t\t\tthis.delete(key);\r\n\t\t\t} else {\r\n\t\t\t\tresult = item.value;\r\n\t\t\t\tthis.set(key, result, true);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\thas (key) {\r\n\t\treturn key in this.items;\r\n\t}\r\n\r\n\tkeys () {\r\n\t\tconst result = [];\r\n\t\tlet x = this.first;\r\n\r\n\t\twhile (x !== null) {\r\n\t\t\tresult.push(x.key);\r\n\t\t\tx = x.next;\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tset (key, value, bypass = false, resetTtl = this.resetTtl) {\r\n\t\tlet item;\r\n\r\n\t\tif (bypass || this.has(key)) {\r\n\t\t\titem = this.items[key];\r\n\t\t\titem.value = value;\r\n\r\n\t\t\tif (bypass === false && resetTtl) {\r\n\t\t\t\titem.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl;\r\n\t\t\t}\r\n\r\n\t\t\tif (this.last !== item) {\r\n\t\t\t\tconst last = this.last,\r\n\t\t\t\t\tnext = item.next,\r\n\t\t\t\t\tprev = item.prev;\r\n\r\n\t\t\t\tif (this.first === item) {\r\n\t\t\t\t\tthis.first = item.next;\r\n\t\t\t\t}\r\n\r\n\t\t\t\titem.next = null;\r\n\t\t\t\titem.prev = this.last;\r\n\t\t\t\tlast.next = item;\r\n\r\n\t\t\t\tif (prev !== null) {\r\n\t\t\t\t\tprev.next = next;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (next !== null) {\r\n\t\t\t\t\tnext.prev = prev;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif (this.max > 0 && this.size === this.max) {\r\n\t\t\t\tthis.evict(true);\r\n\t\t\t}\r\n\r\n\t\t\titem = this.items[key] = {\r\n\t\t\t\texpiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,\r\n\t\t\t\tkey: key,\r\n\t\t\t\tprev: this.last,\r\n\t\t\t\tnext: null,\r\n\t\t\t\tvalue\r\n\t\t\t};\r\n\r\n\t\t\tif (++this.size === 1) {\r\n\t\t\t\tthis.first = item;\r\n\t\t\t} else {\r\n\t\t\t\tthis.last.next = item;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis.last = item;\r\n\r\n\t\treturn this;\r\n\t}\r\n\r\n\tvalues (keys = this.keys()) {\r\n\t\treturn keys.map(key => this.get(key));\r\n\t}\r\n}\r\n\r\nfunction lru (max = 1000, ttl = 0, resetTtl = false) {\r\n\tif (isNaN(max) || max < 0) {\r\n\t\tthrow new TypeError(\"Invalid max value\");\r\n\t}\r\n\r\n\tif (isNaN(ttl) || ttl < 0) {\r\n\t\tthrow new TypeError(\"Invalid ttl value\");\r\n\t}\r\n\r\n\tif (typeof resetTtl !== \"boolean\") {\r\n\t\tthrow new TypeError(\"Invalid resetTtl value\");\r\n\t}\r\n\r\n\treturn new LRU(max, ttl, resetTtl);\r\n}export{LRU,lru};","// these aren't really private, but nor are they really useful to document\n\n/**\n * @private\n */\nclass LuxonError extends Error {}\n\n/**\n * @private\n */\nexport class InvalidDateTimeError extends LuxonError {\n constructor(reason) {\n super(`Invalid DateTime: ${reason.toMessage()}`);\n }\n}\n\n/**\n * @private\n */\nexport class InvalidIntervalError extends LuxonError {\n constructor(reason) {\n super(`Invalid Interval: ${reason.toMessage()}`);\n }\n}\n\n/**\n * @private\n */\nexport class InvalidDurationError extends LuxonError {\n constructor(reason) {\n super(`Invalid Duration: ${reason.toMessage()}`);\n }\n}\n\n/**\n * @private\n */\nexport class ConflictingSpecificationError extends LuxonError {}\n\n/**\n * @private\n */\nexport class InvalidUnitError extends LuxonError {\n constructor(unit) {\n super(`Invalid unit ${unit}`);\n }\n}\n\n/**\n * @private\n */\nexport class InvalidArgumentError extends LuxonError {}\n\n/**\n * @private\n */\nexport class ZoneIsAbstractError extends LuxonError {\n constructor() {\n super(\"Zone is an abstract class\");\n }\n}\n","/**\n * @private\n */\n\nconst n = \"numeric\",\n s = \"short\",\n l = \"long\";\n\nexport const DATE_SHORT = {\n year: n,\n month: n,\n day: n,\n};\n\nexport const DATE_MED = {\n year: n,\n month: s,\n day: n,\n};\n\nexport const DATE_MED_WITH_WEEKDAY = {\n year: n,\n month: s,\n day: n,\n weekday: s,\n};\n\nexport const DATE_FULL = {\n year: n,\n month: l,\n day: n,\n};\n\nexport const DATE_HUGE = {\n year: n,\n month: l,\n day: n,\n weekday: l,\n};\n\nexport const TIME_SIMPLE = {\n hour: n,\n minute: n,\n};\n\nexport const TIME_WITH_SECONDS = {\n hour: n,\n minute: n,\n second: n,\n};\n\nexport const TIME_WITH_SHORT_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n timeZoneName: s,\n};\n\nexport const TIME_WITH_LONG_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n timeZoneName: l,\n};\n\nexport const TIME_24_SIMPLE = {\n hour: n,\n minute: n,\n hourCycle: \"h23\",\n};\n\nexport const TIME_24_WITH_SECONDS = {\n hour: n,\n minute: n,\n second: n,\n hourCycle: \"h23\",\n};\n\nexport const TIME_24_WITH_SHORT_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n hourCycle: \"h23\",\n timeZoneName: s,\n};\n\nexport const TIME_24_WITH_LONG_OFFSET = {\n hour: n,\n minute: n,\n second: n,\n hourCycle: \"h23\",\n timeZoneName: l,\n};\n\nexport const DATETIME_SHORT = {\n year: n,\n month: n,\n day: n,\n hour: n,\n minute: n,\n};\n\nexport const DATETIME_SHORT_WITH_SECONDS = {\n year: n,\n month: n,\n day: n,\n hour: n,\n minute: n,\n second: n,\n};\n\nexport const DATETIME_MED = {\n year: n,\n month: s,\n day: n,\n hour: n,\n minute: n,\n};\n\nexport const DATETIME_MED_WITH_SECONDS = {\n year: n,\n month: s,\n day: n,\n hour: n,\n minute: n,\n second: n,\n};\n\nexport const DATETIME_MED_WITH_WEEKDAY = {\n year: n,\n month: s,\n day: n,\n weekday: s,\n hour: n,\n minute: n,\n};\n\nexport const DATETIME_FULL = {\n year: n,\n month: l,\n day: n,\n hour: n,\n minute: n,\n timeZoneName: s,\n};\n\nexport const DATETIME_FULL_WITH_SECONDS = {\n year: n,\n month: l,\n day: n,\n hour: n,\n minute: n,\n second: n,\n timeZoneName: s,\n};\n\nexport const DATETIME_HUGE = {\n year: n,\n month: l,\n day: n,\n weekday: l,\n hour: n,\n minute: n,\n timeZoneName: l,\n};\n\nexport const DATETIME_HUGE_WITH_SECONDS = {\n year: n,\n month: l,\n day: n,\n weekday: l,\n hour: n,\n minute: n,\n second: n,\n timeZoneName: l,\n};\n","/*\n This is just a junk drawer, containing anything used across multiple classes.\n Because Luxon is small(ish), this should stay small and we won't worry about splitting\n it up into, say, parsingUtil.js and basicUtil.js and so on. But they are divided up by feature area.\n*/\n\nimport { InvalidArgumentError } from \"../errors.js\";\n\n/**\n * @private\n */\n\n// TYPES\n\nexport function isUndefined(o) {\n return typeof o === \"undefined\";\n}\n\nexport function isNumber(o) {\n return typeof o === \"number\";\n}\n\nexport function isInteger(o) {\n return typeof o === \"number\" && o % 1 === 0;\n}\n\nexport function isString(o) {\n return typeof o === \"string\";\n}\n\nexport function isDate(o) {\n return Object.prototype.toString.call(o) === \"[object Date]\";\n}\n\n// CAPABILITIES\n\nexport function hasRelative() {\n try {\n return typeof Intl !== \"undefined\" && !!Intl.RelativeTimeFormat;\n } catch (e) {\n return false;\n }\n}\n\n// OBJECTS AND ARRAYS\n\nexport function maybeArray(thing) {\n return Array.isArray(thing) ? thing : [thing];\n}\n\nexport function bestBy(arr, by, compare) {\n if (arr.length === 0) {\n return undefined;\n }\n return arr.reduce((best, next) => {\n const pair = [by(next), next];\n if (!best) {\n return pair;\n } else if (compare(best[0], pair[0]) === best[0]) {\n return best;\n } else {\n return pair;\n }\n }, null)[1];\n}\n\nexport function pick(obj, keys) {\n return keys.reduce((a, k) => {\n a[k] = obj[k];\n return a;\n }, {});\n}\n\nexport function hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\n// NUMBERS AND STRINGS\n\nexport function integerBetween(thing, bottom, top) {\n return isInteger(thing) && thing >= bottom && thing <= top;\n}\n\n// x % n but takes the sign of n instead of x\nexport function floorMod(x, n) {\n return x - n * Math.floor(x / n);\n}\n\nexport function padStart(input, n = 2) {\n const isNeg = input < 0;\n let padded;\n if (isNeg) {\n padded = \"-\" + (\"\" + -input).padStart(n, \"0\");\n } else {\n padded = (\"\" + input).padStart(n, \"0\");\n }\n return padded;\n}\n\nexport function parseInteger(string) {\n if (isUndefined(string) || string === null || string === \"\") {\n return undefined;\n } else {\n return parseInt(string, 10);\n }\n}\n\nexport function parseFloating(string) {\n if (isUndefined(string) || string === null || string === \"\") {\n return undefined;\n } else {\n return parseFloat(string);\n }\n}\n\nexport function parseMillis(fraction) {\n // Return undefined (instead of 0) in these cases, where fraction is not set\n if (isUndefined(fraction) || fraction === null || fraction === \"\") {\n return undefined;\n } else {\n const f = parseFloat(\"0.\" + fraction) * 1000;\n return Math.floor(f);\n }\n}\n\nexport function roundTo(number, digits, towardZero = false) {\n const factor = 10 ** digits,\n rounder = towardZero ? Math.trunc : Math.round;\n return rounder(number * factor) / factor;\n}\n\n// DATE BASICS\n\nexport function isLeapYear(year) {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n\nexport function daysInYear(year) {\n return isLeapYear(year) ? 366 : 365;\n}\n\nexport function daysInMonth(year, month) {\n const modMonth = floorMod(month - 1, 12) + 1,\n modYear = year + (month - modMonth) / 12;\n\n if (modMonth === 2) {\n return isLeapYear(modYear) ? 29 : 28;\n } else {\n return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];\n }\n}\n\n// covert a calendar object to a local timestamp (epoch, but with the offset baked in)\nexport function objToLocalTS(obj) {\n let d = Date.UTC(\n obj.year,\n obj.month - 1,\n obj.day,\n obj.hour,\n obj.minute,\n obj.second,\n obj.millisecond\n );\n\n // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that\n if (obj.year < 100 && obj.year >= 0) {\n d = new Date(d);\n d.setUTCFullYear(d.getUTCFullYear() - 1900);\n }\n return +d;\n}\n\nexport function weeksInWeekYear(weekYear) {\n const p1 =\n (weekYear +\n Math.floor(weekYear / 4) -\n Math.floor(weekYear / 100) +\n Math.floor(weekYear / 400)) %\n 7,\n last = weekYear - 1,\n p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7;\n return p1 === 4 || p2 === 3 ? 53 : 52;\n}\n\nexport function untruncateYear(year) {\n if (year > 99) {\n return year;\n } else return year > 60 ? 1900 + year : 2000 + year;\n}\n\n// PARSING\n\nexport function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) {\n const date = new Date(ts),\n intlOpts = {\n hourCycle: \"h23\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n };\n\n if (timeZone) {\n intlOpts.timeZone = timeZone;\n }\n\n const modified = { timeZoneName: offsetFormat, ...intlOpts };\n\n const parsed = new Intl.DateTimeFormat(locale, modified)\n .formatToParts(date)\n .find((m) => m.type.toLowerCase() === \"timezonename\");\n return parsed ? parsed.value : null;\n}\n\n// signedOffset('-5', '30') -> -330\nexport function signedOffset(offHourStr, offMinuteStr) {\n let offHour = parseInt(offHourStr, 10);\n\n // don't || this because we want to preserve -0\n if (Number.isNaN(offHour)) {\n offHour = 0;\n }\n\n const offMin = parseInt(offMinuteStr, 10) || 0,\n offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;\n return offHour * 60 + offMinSigned;\n}\n\n// COERCION\n\nexport function asNumber(value) {\n const numericValue = Number(value);\n if (typeof value === \"boolean\" || value === \"\" || Number.isNaN(numericValue))\n throw new InvalidArgumentError(`Invalid unit value ${value}`);\n return numericValue;\n}\n\nexport function normalizeObject(obj, normalizer) {\n const normalized = {};\n for (const u in obj) {\n if (hasOwnProperty(obj, u)) {\n const v = obj[u];\n if (v === undefined || v === null) continue;\n normalized[normalizer(u)] = asNumber(v);\n }\n }\n return normalized;\n}\n\nexport function formatOffset(offset, format) {\n const hours = Math.trunc(Math.abs(offset / 60)),\n minutes = Math.trunc(Math.abs(offset % 60)),\n sign = offset >= 0 ? \"+\" : \"-\";\n\n switch (format) {\n case \"short\":\n return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`;\n case \"narrow\":\n return `${sign}${hours}${minutes > 0 ? `:${minutes}` : \"\"}`;\n case \"techie\":\n return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`;\n default:\n throw new RangeError(`Value format ${format} is out of range for property format`);\n }\n}\n\nexport function timeObject(obj) {\n return pick(obj, [\"hour\", \"minute\", \"second\", \"millisecond\"]);\n}\n\nexport const ianaRegex =\n /[A-Za-z_+-]{1,256}(?::?\\/[A-Za-z0-9_+-]{1,256}(?:\\/[A-Za-z0-9_+-]{1,256})?)?/;\n","import * as Formats from \"./formats.js\";\nimport { pick } from \"./util.js\";\n\nfunction stringify(obj) {\n return JSON.stringify(obj, Object.keys(obj).sort());\n}\n\n/**\n * @private\n */\n\nexport const monthsLong = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\nexport const monthsShort = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n];\n\nexport const monthsNarrow = [\"J\", \"F\", \"M\", \"A\", \"M\", \"J\", \"J\", \"A\", \"S\", \"O\", \"N\", \"D\"];\n\nexport function months(length) {\n switch (length) {\n case \"narrow\":\n return [...monthsNarrow];\n case \"short\":\n return [...monthsShort];\n case \"long\":\n return [...monthsLong];\n case \"numeric\":\n return [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\"];\n case \"2-digit\":\n return [\"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\", \"11\", \"12\"];\n default:\n return null;\n }\n}\n\nexport const weekdaysLong = [\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n \"Sunday\",\n];\n\nexport const weekdaysShort = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"];\n\nexport const weekdaysNarrow = [\"M\", \"T\", \"W\", \"T\", \"F\", \"S\", \"S\"];\n\nexport function weekdays(length) {\n switch (length) {\n case \"narrow\":\n return [...weekdaysNarrow];\n case \"short\":\n return [...weekdaysShort];\n case \"long\":\n return [...weekdaysLong];\n case \"numeric\":\n return [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\"];\n default:\n return null;\n }\n}\n\nexport const meridiems = [\"AM\", \"PM\"];\n\nexport const erasLong = [\"Before Christ\", \"Anno Domini\"];\n\nexport const erasShort = [\"BC\", \"AD\"];\n\nexport const erasNarrow = [\"B\", \"A\"];\n\nexport function eras(length) {\n switch (length) {\n case \"narrow\":\n return [...erasNarrow];\n case \"short\":\n return [...erasShort];\n case \"long\":\n return [...erasLong];\n default:\n return null;\n }\n}\n\nexport function meridiemForDateTime(dt) {\n return meridiems[dt.hour < 12 ? 0 : 1];\n}\n\nexport function weekdayForDateTime(dt, length) {\n return weekdays(length)[dt.weekday - 1];\n}\n\nexport function monthForDateTime(dt, length) {\n return months(length)[dt.month - 1];\n}\n\nexport function eraForDateTime(dt, length) {\n return eras(length)[dt.year < 0 ? 0 : 1];\n}\n\nexport function formatRelativeTime(unit, count, numeric = \"always\", narrow = false) {\n const units = {\n years: [\"year\", \"yr.\"],\n quarters: [\"quarter\", \"qtr.\"],\n months: [\"month\", \"mo.\"],\n weeks: [\"week\", \"wk.\"],\n days: [\"day\", \"day\", \"days\"],\n hours: [\"hour\", \"hr.\"],\n minutes: [\"minute\", \"min.\"],\n seconds: [\"second\", \"sec.\"],\n };\n\n const lastable = [\"hours\", \"minutes\", \"seconds\"].indexOf(unit) === -1;\n\n if (numeric === \"auto\" && lastable) {\n const isDay = unit === \"days\";\n switch (count) {\n case 1:\n return isDay ? \"tomorrow\" : `next ${units[unit][0]}`;\n case -1:\n return isDay ? \"yesterday\" : `last ${units[unit][0]}`;\n case 0:\n return isDay ? \"today\" : `this ${units[unit][0]}`;\n default: // fall through\n }\n }\n\n const isInPast = Object.is(count, -0) || count < 0,\n fmtValue = Math.abs(count),\n singular = fmtValue === 1,\n lilUnits = units[unit],\n fmtUnit = narrow\n ? singular\n ? lilUnits[1]\n : lilUnits[2] || lilUnits[1]\n : singular\n ? units[unit][0]\n : unit;\n return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;\n}\n\nexport function formatString(knownFormat) {\n // these all have the offsets removed because we don't have access to them\n // without all the intl stuff this is backfilling\n const filtered = pick(knownFormat, [\n \"weekday\",\n \"era\",\n \"year\",\n \"month\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n \"timeZoneName\",\n \"hourCycle\",\n ]),\n key = stringify(filtered),\n dateTimeHuge = \"EEEE, LLLL d, yyyy, h:mm a\";\n switch (key) {\n case stringify(Formats.DATE_SHORT):\n return \"M/d/yyyy\";\n case stringify(Formats.DATE_MED):\n return \"LLL d, yyyy\";\n case stringify(Formats.DATE_MED_WITH_WEEKDAY):\n return \"EEE, LLL d, yyyy\";\n case stringify(Formats.DATE_FULL):\n return \"LLLL d, yyyy\";\n case stringify(Formats.DATE_HUGE):\n return \"EEEE, LLLL d, yyyy\";\n case stringify(Formats.TIME_SIMPLE):\n return \"h:mm a\";\n case stringify(Formats.TIME_WITH_SECONDS):\n return \"h:mm:ss a\";\n case stringify(Formats.TIME_WITH_SHORT_OFFSET):\n return \"h:mm a\";\n case stringify(Formats.TIME_WITH_LONG_OFFSET):\n return \"h:mm a\";\n case stringify(Formats.TIME_24_SIMPLE):\n return \"HH:mm\";\n case stringify(Formats.TIME_24_WITH_SECONDS):\n return \"HH:mm:ss\";\n case stringify(Formats.TIME_24_WITH_SHORT_OFFSET):\n return \"HH:mm\";\n case stringify(Formats.TIME_24_WITH_LONG_OFFSET):\n return \"HH:mm\";\n case stringify(Formats.DATETIME_SHORT):\n return \"M/d/yyyy, h:mm a\";\n case stringify(Formats.DATETIME_MED):\n return \"LLL d, yyyy, h:mm a\";\n case stringify(Formats.DATETIME_FULL):\n return \"LLLL d, yyyy, h:mm a\";\n case stringify(Formats.DATETIME_HUGE):\n return dateTimeHuge;\n case stringify(Formats.DATETIME_SHORT_WITH_SECONDS):\n return \"M/d/yyyy, h:mm:ss a\";\n case stringify(Formats.DATETIME_MED_WITH_SECONDS):\n return \"LLL d, yyyy, h:mm:ss a\";\n case stringify(Formats.DATETIME_MED_WITH_WEEKDAY):\n return \"EEE, d LLL yyyy, h:mm a\";\n case stringify(Formats.DATETIME_FULL_WITH_SECONDS):\n return \"LLLL d, yyyy, h:mm:ss a\";\n case stringify(Formats.DATETIME_HUGE_WITH_SECONDS):\n return \"EEEE, LLLL d, yyyy, h:mm:ss a\";\n default:\n return dateTimeHuge;\n }\n}\n","import * as English from \"./english.js\";\nimport * as Formats from \"./formats.js\";\nimport { padStart } from \"./util.js\";\n\nfunction stringifyTokens(splits, tokenToString) {\n let s = \"\";\n for (const token of splits) {\n if (token.literal) {\n s += token.val;\n } else {\n s += tokenToString(token.val);\n }\n }\n return s;\n}\n\nconst macroTokenToFormatOpts = {\n D: Formats.DATE_SHORT,\n DD: Formats.DATE_MED,\n DDD: Formats.DATE_FULL,\n DDDD: Formats.DATE_HUGE,\n t: Formats.TIME_SIMPLE,\n tt: Formats.TIME_WITH_SECONDS,\n ttt: Formats.TIME_WITH_SHORT_OFFSET,\n tttt: Formats.TIME_WITH_LONG_OFFSET,\n T: Formats.TIME_24_SIMPLE,\n TT: Formats.TIME_24_WITH_SECONDS,\n TTT: Formats.TIME_24_WITH_SHORT_OFFSET,\n TTTT: Formats.TIME_24_WITH_LONG_OFFSET,\n f: Formats.DATETIME_SHORT,\n ff: Formats.DATETIME_MED,\n fff: Formats.DATETIME_FULL,\n ffff: Formats.DATETIME_HUGE,\n F: Formats.DATETIME_SHORT_WITH_SECONDS,\n FF: Formats.DATETIME_MED_WITH_SECONDS,\n FFF: Formats.DATETIME_FULL_WITH_SECONDS,\n FFFF: Formats.DATETIME_HUGE_WITH_SECONDS,\n};\n\n/**\n * @private\n */\n\nexport default class Formatter {\n static create(locale, opts = {}) {\n return new Formatter(locale, opts);\n }\n\n static parseFormat(fmt) {\n let current = null,\n currentFull = \"\",\n bracketed = false;\n const splits = [];\n for (let i = 0; i < fmt.length; i++) {\n const c = fmt.charAt(i);\n if (c === \"'\") {\n if (currentFull.length > 0) {\n splits.push({ literal: bracketed, val: currentFull });\n }\n current = null;\n currentFull = \"\";\n bracketed = !bracketed;\n } else if (bracketed) {\n currentFull += c;\n } else if (c === current) {\n currentFull += c;\n } else {\n if (currentFull.length > 0) {\n splits.push({ literal: false, val: currentFull });\n }\n currentFull = c;\n current = c;\n }\n }\n\n if (currentFull.length > 0) {\n splits.push({ literal: bracketed, val: currentFull });\n }\n\n return splits;\n }\n\n static macroTokenToFormatOpts(token) {\n return macroTokenToFormatOpts[token];\n }\n\n constructor(locale, formatOpts) {\n this.opts = formatOpts;\n this.loc = locale;\n this.systemLoc = null;\n }\n\n formatWithSystemDefault(dt, opts) {\n if (this.systemLoc === null) {\n this.systemLoc = this.loc.redefaultToSystem();\n }\n const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts });\n return df.format();\n }\n\n formatDateTime(dt, opts = {}) {\n const df = this.loc.dtFormatter(dt, { ...this.opts, ...opts });\n return df.format();\n }\n\n formatDateTimeParts(dt, opts = {}) {\n const df = this.loc.dtFormatter(dt, { ...this.opts, ...opts });\n return df.formatToParts();\n }\n\n resolvedOptions(dt, opts = {}) {\n const df = this.loc.dtFormatter(dt, { ...this.opts, ...opts });\n return df.resolvedOptions();\n }\n\n num(n, p = 0) {\n // we get some perf out of doing this here, annoyingly\n if (this.opts.forceSimple) {\n return padStart(n, p);\n }\n\n const opts = { ...this.opts };\n\n if (p > 0) {\n opts.padTo = p;\n }\n\n return this.loc.numberFormatter(opts).format(n);\n }\n\n formatDateTimeFromString(dt, fmt) {\n const knownEnglish = this.loc.listingMode() === \"en\",\n useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== \"gregory\",\n string = (opts, extract) => this.loc.extract(dt, opts, extract),\n formatOffset = (opts) => {\n if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {\n return \"Z\";\n }\n\n return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : \"\";\n },\n meridiem = () =>\n knownEnglish\n ? English.meridiemForDateTime(dt)\n : string({ hour: \"numeric\", hourCycle: \"h12\" }, \"dayperiod\"),\n month = (length, standalone) =>\n knownEnglish\n ? English.monthForDateTime(dt, length)\n : string(standalone ? { month: length } : { month: length, day: \"numeric\" }, \"month\"),\n weekday = (length, standalone) =>\n knownEnglish\n ? English.weekdayForDateTime(dt, length)\n : string(\n standalone ? { weekday: length } : { weekday: length, month: \"long\", day: \"numeric\" },\n \"weekday\"\n ),\n maybeMacro = (token) => {\n const formatOpts = Formatter.macroTokenToFormatOpts(token);\n if (formatOpts) {\n return this.formatWithSystemDefault(dt, formatOpts);\n } else {\n return token;\n }\n },\n era = (length) =>\n knownEnglish ? English.eraForDateTime(dt, length) : string({ era: length }, \"era\"),\n tokenToString = (token) => {\n // Where possible: http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles\n switch (token) {\n // ms\n case \"S\":\n return this.num(dt.millisecond);\n case \"u\":\n // falls through\n case \"SSS\":\n return this.num(dt.millisecond, 3);\n // seconds\n case \"s\":\n return this.num(dt.second);\n case \"ss\":\n return this.num(dt.second, 2);\n // fractional seconds\n case \"uu\":\n return this.num(Math.floor(dt.millisecond / 10), 2);\n case \"uuu\":\n return this.num(Math.floor(dt.millisecond / 100));\n // minutes\n case \"m\":\n return this.num(dt.minute);\n case \"mm\":\n return this.num(dt.minute, 2);\n // hours\n case \"h\":\n return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);\n case \"hh\":\n return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);\n case \"H\":\n return this.num(dt.hour);\n case \"HH\":\n return this.num(dt.hour, 2);\n // offset\n case \"Z\":\n // like +6\n return formatOffset({ format: \"narrow\", allowZ: this.opts.allowZ });\n case \"ZZ\":\n // like +06:00\n return formatOffset({ format: \"short\", allowZ: this.opts.allowZ });\n case \"ZZZ\":\n // like +0600\n return formatOffset({ format: \"techie\", allowZ: this.opts.allowZ });\n case \"ZZZZ\":\n // like EST\n return dt.zone.offsetName(dt.ts, { format: \"short\", locale: this.loc.locale });\n case \"ZZZZZ\":\n // like Eastern Standard Time\n return dt.zone.offsetName(dt.ts, { format: \"long\", locale: this.loc.locale });\n // zone\n case \"z\":\n // like America/New_York\n return dt.zoneName;\n // meridiems\n case \"a\":\n return meridiem();\n // dates\n case \"d\":\n return useDateTimeFormatter ? string({ day: \"numeric\" }, \"day\") : this.num(dt.day);\n case \"dd\":\n return useDateTimeFormatter ? string({ day: \"2-digit\" }, \"day\") : this.num(dt.day, 2);\n // weekdays - standalone\n case \"c\":\n // like 1\n return this.num(dt.weekday);\n case \"ccc\":\n // like 'Tues'\n return weekday(\"short\", true);\n case \"cccc\":\n // like 'Tuesday'\n return weekday(\"long\", true);\n case \"ccccc\":\n // like 'T'\n return weekday(\"narrow\", true);\n // weekdays - format\n case \"E\":\n // like 1\n return this.num(dt.weekday);\n case \"EEE\":\n // like 'Tues'\n return weekday(\"short\", false);\n case \"EEEE\":\n // like 'Tuesday'\n return weekday(\"long\", false);\n case \"EEEEE\":\n // like 'T'\n return weekday(\"narrow\", false);\n // months - standalone\n case \"L\":\n // like 1\n return useDateTimeFormatter\n ? string({ month: \"numeric\", day: \"numeric\" }, \"month\")\n : this.num(dt.month);\n case \"LL\":\n // like 01, doesn't seem to work\n return useDateTimeFormatter\n ? string({ month: \"2-digit\", day: \"numeric\" }, \"month\")\n : this.num(dt.month, 2);\n case \"LLL\":\n // like Jan\n return month(\"short\", true);\n case \"LLLL\":\n // like January\n return month(\"long\", true);\n case \"LLLLL\":\n // like J\n return month(\"narrow\", true);\n // months - format\n case \"M\":\n // like 1\n return useDateTimeFormatter\n ? string({ month: \"numeric\" }, \"month\")\n : this.num(dt.month);\n case \"MM\":\n // like 01\n return useDateTimeFormatter\n ? string({ month: \"2-digit\" }, \"month\")\n : this.num(dt.month, 2);\n case \"MMM\":\n // like Jan\n return month(\"short\", false);\n case \"MMMM\":\n // like January\n return month(\"long\", false);\n case \"MMMMM\":\n // like J\n return month(\"narrow\", false);\n // years\n case \"y\":\n // like 2014\n return useDateTimeFormatter ? string({ year: \"numeric\" }, \"year\") : this.num(dt.year);\n case \"yy\":\n // like 14\n return useDateTimeFormatter\n ? string({ year: \"2-digit\" }, \"year\")\n : this.num(dt.year.toString().slice(-2), 2);\n case \"yyyy\":\n // like 0012\n return useDateTimeFormatter\n ? string({ year: \"numeric\" }, \"year\")\n : this.num(dt.year, 4);\n case \"yyyyyy\":\n // like 000012\n return useDateTimeFormatter\n ? string({ year: \"numeric\" }, \"year\")\n : this.num(dt.year, 6);\n // eras\n case \"G\":\n // like AD\n return era(\"short\");\n case \"GG\":\n // like Anno Domini\n return era(\"long\");\n case \"GGGGG\":\n return era(\"narrow\");\n case \"kk\":\n return this.num(dt.weekYear.toString().slice(-2), 2);\n case \"kkkk\":\n return this.num(dt.weekYear, 4);\n case \"W\":\n return this.num(dt.weekNumber);\n case \"WW\":\n return this.num(dt.weekNumber, 2);\n case \"o\":\n return this.num(dt.ordinal);\n case \"ooo\":\n return this.num(dt.ordinal, 3);\n case \"q\":\n // like 1\n return this.num(dt.quarter);\n case \"qq\":\n // like 01\n return this.num(dt.quarter, 2);\n case \"X\":\n return this.num(Math.floor(dt.ts / 1000));\n case \"x\":\n return this.num(dt.ts);\n default:\n return maybeMacro(token);\n }\n };\n\n return stringifyTokens(Formatter.parseFormat(fmt), tokenToString);\n }\n\n formatDurationFromString(dur, fmt) {\n const tokenToField = (token) => {\n switch (token[0]) {\n case \"S\":\n return \"millisecond\";\n case \"s\":\n return \"second\";\n case \"m\":\n return \"minute\";\n case \"h\":\n return \"hour\";\n case \"d\":\n return \"day\";\n case \"w\":\n return \"week\";\n case \"M\":\n return \"month\";\n case \"y\":\n return \"year\";\n default:\n return null;\n }\n },\n tokenToString = (lildur) => (token) => {\n const mapped = tokenToField(token);\n if (mapped) {\n return this.num(lildur.get(mapped), token.length);\n } else {\n return token;\n }\n },\n tokens = Formatter.parseFormat(fmt),\n realTokens = tokens.reduce(\n (found, { literal, val }) => (literal ? found : found.concat(val)),\n []\n ),\n collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t));\n return stringifyTokens(tokens, tokenToString(collapsed));\n }\n}\n","export default class Invalid {\n constructor(reason, explanation) {\n this.reason = reason;\n this.explanation = explanation;\n }\n\n toMessage() {\n if (this.explanation) {\n return `${this.reason}: ${this.explanation}`;\n } else {\n return this.reason;\n }\n }\n}\n","import { ZoneIsAbstractError } from \"./errors.js\";\n\n/**\n * @interface\n */\nexport default class Zone {\n /**\n * The type of zone\n * @abstract\n * @type {string}\n */\n get type() {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * The name of this zone.\n * @abstract\n * @type {string}\n */\n get name() {\n throw new ZoneIsAbstractError();\n }\n\n get ianaName() {\n return this.name;\n }\n\n /**\n * Returns whether the offset is known to be fixed for the whole year.\n * @abstract\n * @type {boolean}\n */\n get isUniversal() {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Returns the offset's common name (such as EST) at the specified timestamp\n * @abstract\n * @param {number} ts - Epoch milliseconds for which to get the name\n * @param {Object} opts - Options to affect the format\n * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.\n * @param {string} opts.locale - What locale to return the offset name in.\n * @return {string}\n */\n offsetName(ts, opts) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Returns the offset's value as a string\n * @abstract\n * @param {number} ts - Epoch milliseconds for which to get the offset\n * @param {string} format - What style of offset to return.\n * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively\n * @return {string}\n */\n formatOffset(ts, format) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Return the offset in minutes for this zone at the specified timestamp.\n * @abstract\n * @param {number} ts - Epoch milliseconds for which to compute the offset\n * @return {number}\n */\n offset(ts) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Return whether this Zone is equal to another zone\n * @abstract\n * @param {Zone} otherZone - the zone to compare\n * @return {boolean}\n */\n equals(otherZone) {\n throw new ZoneIsAbstractError();\n }\n\n /**\n * Return whether this Zone is valid.\n * @abstract\n * @type {boolean}\n */\n get isValid() {\n throw new ZoneIsAbstractError();\n }\n}\n","import { formatOffset, parseZoneInfo } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet singleton = null;\n\n/**\n * Represents the local zone for this JavaScript environment.\n * @implements {Zone}\n */\nexport default class SystemZone extends Zone {\n /**\n * Get a singleton instance of the local zone\n * @return {SystemZone}\n */\n static get instance() {\n if (singleton === null) {\n singleton = new SystemZone();\n }\n return singleton;\n }\n\n /** @override **/\n get type() {\n return \"system\";\n }\n\n /** @override **/\n get name() {\n return new Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n /** @override **/\n get isUniversal() {\n return false;\n }\n\n /** @override **/\n offsetName(ts, { format, locale }) {\n return parseZoneInfo(ts, format, locale);\n }\n\n /** @override **/\n formatOffset(ts, format) {\n return formatOffset(this.offset(ts), format);\n }\n\n /** @override **/\n offset(ts) {\n return -new Date(ts).getTimezoneOffset();\n }\n\n /** @override **/\n equals(otherZone) {\n return otherZone.type === \"system\";\n }\n\n /** @override **/\n get isValid() {\n return true;\n }\n}\n","import { formatOffset, parseZoneInfo, isUndefined, objToLocalTS } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet dtfCache = {};\nfunction makeDTF(zone) {\n if (!dtfCache[zone]) {\n dtfCache[zone] = new Intl.DateTimeFormat(\"en-US\", {\n hour12: false,\n timeZone: zone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n era: \"short\",\n });\n }\n return dtfCache[zone];\n}\n\nconst typeToPos = {\n year: 0,\n month: 1,\n day: 2,\n era: 3,\n hour: 4,\n minute: 5,\n second: 6,\n};\n\nfunction hackyOffset(dtf, date) {\n const formatted = dtf.format(date).replace(/\\u200E/g, \"\"),\n parsed = /(\\d+)\\/(\\d+)\\/(\\d+) (AD|BC),? (\\d+):(\\d+):(\\d+)/.exec(formatted),\n [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed;\n return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];\n}\n\nfunction partsOffset(dtf, date) {\n const formatted = dtf.formatToParts(date);\n const filled = [];\n for (let i = 0; i < formatted.length; i++) {\n const { type, value } = formatted[i];\n const pos = typeToPos[type];\n\n if (type === \"era\") {\n filled[pos] = value;\n } else if (!isUndefined(pos)) {\n filled[pos] = parseInt(value, 10);\n }\n }\n return filled;\n}\n\nlet ianaZoneCache = {};\n/**\n * A zone identified by an IANA identifier, like America/New_York\n * @implements {Zone}\n */\nexport default class IANAZone extends Zone {\n /**\n * @param {string} name - Zone name\n * @return {IANAZone}\n */\n static create(name) {\n if (!ianaZoneCache[name]) {\n ianaZoneCache[name] = new IANAZone(name);\n }\n return ianaZoneCache[name];\n }\n\n /**\n * Reset local caches. Should only be necessary in testing scenarios.\n * @return {void}\n */\n static resetCache() {\n ianaZoneCache = {};\n dtfCache = {};\n }\n\n /**\n * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.\n * @param {string} s - The string to check validity on\n * @example IANAZone.isValidSpecifier(\"America/New_York\") //=> true\n * @example IANAZone.isValidSpecifier(\"Sport~~blorp\") //=> false\n * @deprecated This method returns false for some valid IANA names. Use isValidZone instead.\n * @return {boolean}\n */\n static isValidSpecifier(s) {\n return this.isValidZone(s);\n }\n\n /**\n * Returns whether the provided string identifies a real zone\n * @param {string} zone - The string to check\n * @example IANAZone.isValidZone(\"America/New_York\") //=> true\n * @example IANAZone.isValidZone(\"Fantasia/Castle\") //=> false\n * @example IANAZone.isValidZone(\"Sport~~blorp\") //=> false\n * @return {boolean}\n */\n static isValidZone(zone) {\n if (!zone) {\n return false;\n }\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: zone }).format();\n return true;\n } catch (e) {\n return false;\n }\n }\n\n constructor(name) {\n super();\n /** @private **/\n this.zoneName = name;\n /** @private **/\n this.valid = IANAZone.isValidZone(name);\n }\n\n /** @override **/\n get type() {\n return \"iana\";\n }\n\n /** @override **/\n get name() {\n return this.zoneName;\n }\n\n /** @override **/\n get isUniversal() {\n return false;\n }\n\n /** @override **/\n offsetName(ts, { format, locale }) {\n return parseZoneInfo(ts, format, locale, this.name);\n }\n\n /** @override **/\n formatOffset(ts, format) {\n return formatOffset(this.offset(ts), format);\n }\n\n /** @override **/\n offset(ts) {\n const date = new Date(ts);\n\n if (isNaN(date)) return NaN;\n\n const dtf = makeDTF(this.name);\n let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts\n ? partsOffset(dtf, date)\n : hackyOffset(dtf, date);\n\n if (adOrBc === \"BC\") {\n year = -Math.abs(year) + 1;\n }\n\n // because we're using hour12 and https://bugs.chromium.org/p/chromium/issues/detail?id=1025564&can=2&q=%2224%3A00%22%20datetimeformat\n const adjustedHour = hour === 24 ? 0 : hour;\n\n const asUTC = objToLocalTS({\n year,\n month,\n day,\n hour: adjustedHour,\n minute,\n second,\n millisecond: 0,\n });\n\n let asTS = +date;\n const over = asTS % 1000;\n asTS -= over >= 0 ? over : 1000 + over;\n return (asUTC - asTS) / (60 * 1000);\n }\n\n /** @override **/\n equals(otherZone) {\n return otherZone.type === \"iana\" && otherZone.name === this.name;\n }\n\n /** @override **/\n get isValid() {\n return this.valid;\n }\n}\n","import { formatOffset, signedOffset } from \"../impl/util.js\";\nimport Zone from \"../zone.js\";\n\nlet singleton = null;\n\n/**\n * A zone with a fixed offset (meaning no DST)\n * @implements {Zone}\n */\nexport default class FixedOffsetZone extends Zone {\n /**\n * Get a singleton instance of UTC\n * @return {FixedOffsetZone}\n */\n static get utcInstance() {\n if (singleton === null) {\n singleton = new FixedOffsetZone(0);\n }\n return singleton;\n }\n\n /**\n * Get an instance with a specified offset\n * @param {number} offset - The offset in minutes\n * @return {FixedOffsetZone}\n */\n static instance(offset) {\n return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset);\n }\n\n /**\n * Get an instance of FixedOffsetZone from a UTC offset string, like \"UTC+6\"\n * @param {string} s - The offset string to parse\n * @example FixedOffsetZone.parseSpecifier(\"UTC+6\")\n * @example FixedOffsetZone.parseSpecifier(\"UTC+06\")\n * @example FixedOffsetZone.parseSpecifier(\"UTC-6:00\")\n * @return {FixedOffsetZone}\n */\n static parseSpecifier(s) {\n if (s) {\n const r = s.match(/^utc(?:([+-]\\d{1,2})(?::(\\d{2}))?)?$/i);\n if (r) {\n return new FixedOffsetZone(signedOffset(r[1], r[2]));\n }\n }\n return null;\n }\n\n constructor(offset) {\n super();\n /** @private **/\n this.fixed = offset;\n }\n\n /** @override **/\n get type() {\n return \"fixed\";\n }\n\n /** @override **/\n get name() {\n return this.fixed === 0 ? \"UTC\" : `UTC${formatOffset(this.fixed, \"narrow\")}`;\n }\n\n get ianaName() {\n if (this.fixed === 0) {\n return \"Etc/UTC\";\n } else {\n return `Etc/GMT${formatOffset(-this.fixed, \"narrow\")}`;\n }\n }\n\n /** @override **/\n offsetName() {\n return this.name;\n }\n\n /** @override **/\n formatOffset(ts, format) {\n return formatOffset(this.fixed, format);\n }\n\n /** @override **/\n get isUniversal() {\n return true;\n }\n\n /** @override **/\n offset() {\n return this.fixed;\n }\n\n /** @override **/\n equals(otherZone) {\n return otherZone.type === \"fixed\" && otherZone.fixed === this.fixed;\n }\n\n /** @override **/\n get isValid() {\n return true;\n }\n}\n","import Zone from \"../zone.js\";\n\n/**\n * A zone that failed to parse. You should never need to instantiate this.\n * @implements {Zone}\n */\nexport default class InvalidZone extends Zone {\n constructor(zoneName) {\n super();\n /** @private */\n this.zoneName = zoneName;\n }\n\n /** @override **/\n get type() {\n return \"invalid\";\n }\n\n /** @override **/\n get name() {\n return this.zoneName;\n }\n\n /** @override **/\n get isUniversal() {\n return false;\n }\n\n /** @override **/\n offsetName() {\n return null;\n }\n\n /** @override **/\n formatOffset() {\n return \"\";\n }\n\n /** @override **/\n offset() {\n return NaN;\n }\n\n /** @override **/\n equals() {\n return false;\n }\n\n /** @override **/\n get isValid() {\n return false;\n }\n}\n","/**\n * @private\n */\n\nimport Zone from \"../zone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport InvalidZone from \"../zones/invalidZone.js\";\n\nimport { isUndefined, isString, isNumber } from \"./util.js\";\n\nexport function normalizeZone(input, defaultZone) {\n let offset;\n if (isUndefined(input) || input === null) {\n return defaultZone;\n } else if (input instanceof Zone) {\n return input;\n } else if (isString(input)) {\n const lowered = input.toLowerCase();\n if (lowered === \"local\" || lowered === \"system\") return defaultZone;\n else if (lowered === \"utc\" || lowered === \"gmt\") return FixedOffsetZone.utcInstance;\n else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input);\n } else if (isNumber(input)) {\n return FixedOffsetZone.instance(input);\n } else if (typeof input === \"object\" && input.offset && typeof input.offset === \"number\") {\n // This is dumb, but the instanceof check above doesn't seem to really work\n // so we're duck checking it\n return input;\n } else {\n return new InvalidZone(input);\n }\n}\n","import SystemZone from \"./zones/systemZone.js\";\nimport IANAZone from \"./zones/IANAZone.js\";\nimport Locale from \"./impl/locale.js\";\n\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\n\nlet now = () => Date.now(),\n defaultZone = \"system\",\n defaultLocale = null,\n defaultNumberingSystem = null,\n defaultOutputCalendar = null,\n throwOnInvalid;\n\n/**\n * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here.\n */\nexport default class Settings {\n /**\n * Get the callback for returning the current timestamp.\n * @type {function}\n */\n static get now() {\n return now;\n }\n\n /**\n * Set the callback for returning the current timestamp.\n * The function should return a number, which will be interpreted as an Epoch millisecond count\n * @type {function}\n * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future\n * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time\n */\n static set now(n) {\n now = n;\n }\n\n /**\n * Set the default time zone to create DateTimes in. Does not affect existing instances.\n * Use the value \"system\" to reset this value to the system's time zone.\n * @type {string}\n */\n static set defaultZone(zone) {\n defaultZone = zone;\n }\n\n /**\n * Get the default time zone object currently used to create DateTimes. Does not affect existing instances.\n * The default value is the system's time zone (the one set on the machine that runs this code).\n * @type {Zone}\n */\n static get defaultZone() {\n return normalizeZone(defaultZone, SystemZone.instance);\n }\n\n /**\n * Get the default locale to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static get defaultLocale() {\n return defaultLocale;\n }\n\n /**\n * Set the default locale to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static set defaultLocale(locale) {\n defaultLocale = locale;\n }\n\n /**\n * Get the default numbering system to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static get defaultNumberingSystem() {\n return defaultNumberingSystem;\n }\n\n /**\n * Set the default numbering system to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static set defaultNumberingSystem(numberingSystem) {\n defaultNumberingSystem = numberingSystem;\n }\n\n /**\n * Get the default output calendar to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static get defaultOutputCalendar() {\n return defaultOutputCalendar;\n }\n\n /**\n * Set the default output calendar to create DateTimes with. Does not affect existing instances.\n * @type {string}\n */\n static set defaultOutputCalendar(outputCalendar) {\n defaultOutputCalendar = outputCalendar;\n }\n\n /**\n * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals\n * @type {boolean}\n */\n static get throwOnInvalid() {\n return throwOnInvalid;\n }\n\n /**\n * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals\n * @type {boolean}\n */\n static set throwOnInvalid(t) {\n throwOnInvalid = t;\n }\n\n /**\n * Reset Luxon's global caches. Should only be necessary in testing scenarios.\n * @return {void}\n */\n static resetCaches() {\n Locale.resetCache();\n IANAZone.resetCache();\n }\n}\n","import { padStart, roundTo, hasRelative } from \"./util.js\";\nimport * as English from \"./english.js\";\nimport Settings from \"../settings.js\";\nimport DateTime from \"../datetime.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\n\n// todo - remap caching\n\nlet intlLFCache = {};\nfunction getCachedLF(locString, opts = {}) {\n const key = JSON.stringify([locString, opts]);\n let dtf = intlLFCache[key];\n if (!dtf) {\n dtf = new Intl.ListFormat(locString, opts);\n intlLFCache[key] = dtf;\n }\n return dtf;\n}\n\nlet intlDTCache = {};\nfunction getCachedDTF(locString, opts = {}) {\n const key = JSON.stringify([locString, opts]);\n let dtf = intlDTCache[key];\n if (!dtf) {\n dtf = new Intl.DateTimeFormat(locString, opts);\n intlDTCache[key] = dtf;\n }\n return dtf;\n}\n\nlet intlNumCache = {};\nfunction getCachedINF(locString, opts = {}) {\n const key = JSON.stringify([locString, opts]);\n let inf = intlNumCache[key];\n if (!inf) {\n inf = new Intl.NumberFormat(locString, opts);\n intlNumCache[key] = inf;\n }\n return inf;\n}\n\nlet intlRelCache = {};\nfunction getCachedRTF(locString, opts = {}) {\n const { base, ...cacheKeyOpts } = opts; // exclude `base` from the options\n const key = JSON.stringify([locString, cacheKeyOpts]);\n let inf = intlRelCache[key];\n if (!inf) {\n inf = new Intl.RelativeTimeFormat(locString, opts);\n intlRelCache[key] = inf;\n }\n return inf;\n}\n\nlet sysLocaleCache = null;\nfunction systemLocale() {\n if (sysLocaleCache) {\n return sysLocaleCache;\n } else {\n sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale;\n return sysLocaleCache;\n }\n}\n\nfunction parseLocaleString(localeStr) {\n // I really want to avoid writing a BCP 47 parser\n // see, e.g. https://github.com/wooorm/bcp-47\n // Instead, we'll do this:\n\n // a) if the string has no -u extensions, just leave it alone\n // b) if it does, use Intl to resolve everything\n // c) if Intl fails, try again without the -u\n\n const uIndex = localeStr.indexOf(\"-u-\");\n if (uIndex === -1) {\n return [localeStr];\n } else {\n let options;\n const smaller = localeStr.substring(0, uIndex);\n try {\n options = getCachedDTF(localeStr).resolvedOptions();\n } catch (e) {\n options = getCachedDTF(smaller).resolvedOptions();\n }\n\n const { numberingSystem, calendar } = options;\n // return the smaller one so that we can append the calendar and numbering overrides to it\n return [smaller, numberingSystem, calendar];\n }\n}\n\nfunction intlConfigString(localeStr, numberingSystem, outputCalendar) {\n if (outputCalendar || numberingSystem) {\n localeStr += \"-u\";\n\n if (outputCalendar) {\n localeStr += `-ca-${outputCalendar}`;\n }\n\n if (numberingSystem) {\n localeStr += `-nu-${numberingSystem}`;\n }\n return localeStr;\n } else {\n return localeStr;\n }\n}\n\nfunction mapMonths(f) {\n const ms = [];\n for (let i = 1; i <= 12; i++) {\n const dt = DateTime.utc(2016, i, 1);\n ms.push(f(dt));\n }\n return ms;\n}\n\nfunction mapWeekdays(f) {\n const ms = [];\n for (let i = 1; i <= 7; i++) {\n const dt = DateTime.utc(2016, 11, 13 + i);\n ms.push(f(dt));\n }\n return ms;\n}\n\nfunction listStuff(loc, length, defaultOK, englishFn, intlFn) {\n const mode = loc.listingMode(defaultOK);\n\n if (mode === \"error\") {\n return null;\n } else if (mode === \"en\") {\n return englishFn(length);\n } else {\n return intlFn(length);\n }\n}\n\nfunction supportsFastNumbers(loc) {\n if (loc.numberingSystem && loc.numberingSystem !== \"latn\") {\n return false;\n } else {\n return (\n loc.numberingSystem === \"latn\" ||\n !loc.locale ||\n loc.locale.startsWith(\"en\") ||\n new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === \"latn\"\n );\n }\n}\n\n/**\n * @private\n */\n\nclass PolyNumberFormatter {\n constructor(intl, forceSimple, opts) {\n this.padTo = opts.padTo || 0;\n this.floor = opts.floor || false;\n\n const { padTo, floor, ...otherOpts } = opts;\n\n if (!forceSimple || Object.keys(otherOpts).length > 0) {\n const intlOpts = { useGrouping: false, ...opts };\n if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo;\n this.inf = getCachedINF(intl, intlOpts);\n }\n }\n\n format(i) {\n if (this.inf) {\n const fixed = this.floor ? Math.floor(i) : i;\n return this.inf.format(fixed);\n } else {\n // to match the browser's numberformatter defaults\n const fixed = this.floor ? Math.floor(i) : roundTo(i, 3);\n return padStart(fixed, this.padTo);\n }\n }\n}\n\n/**\n * @private\n */\n\nclass PolyDateFormatter {\n constructor(dt, intl, opts) {\n this.opts = opts;\n\n let z;\n if (dt.zone.isUniversal) {\n // UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like.\n // That is why fixed-offset TZ is set to that unless it is:\n // 1. Representing offset 0 when UTC is used to maintain previous behavior and does not become GMT.\n // 2. Unsupported by the browser:\n // - some do not support Etc/\n // - < Etc/GMT-14, > Etc/GMT+12, and 30-minute or 45-minute offsets are not part of tzdata\n const gmtOffset = -1 * (dt.offset / 60);\n const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`;\n if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) {\n z = offsetZ;\n this.dt = dt;\n } else {\n // Not all fixed-offset zones like Etc/+4:30 are present in tzdata.\n // So we have to make do. Two cases:\n // 1. The format options tell us to show the zone. We can't do that, so the best\n // we can do is format the date in UTC.\n // 2. The format options don't tell us to show the zone. Then we can adjust them\n // the time and tell the formatter to show it to us in UTC, so that the time is right\n // and the bad zone doesn't show up.\n z = \"UTC\";\n if (opts.timeZoneName) {\n this.dt = dt;\n } else {\n this.dt = dt.offset === 0 ? dt : DateTime.fromMillis(dt.ts + dt.offset * 60 * 1000);\n }\n }\n } else if (dt.zone.type === \"system\") {\n this.dt = dt;\n } else {\n this.dt = dt;\n z = dt.zone.name;\n }\n\n const intlOpts = { ...this.opts };\n if (z) {\n intlOpts.timeZone = z;\n }\n this.dtf = getCachedDTF(intl, intlOpts);\n }\n\n format() {\n return this.dtf.format(this.dt.toJSDate());\n }\n\n formatToParts() {\n return this.dtf.formatToParts(this.dt.toJSDate());\n }\n\n resolvedOptions() {\n return this.dtf.resolvedOptions();\n }\n}\n\n/**\n * @private\n */\nclass PolyRelFormatter {\n constructor(intl, isEnglish, opts) {\n this.opts = { style: \"long\", ...opts };\n if (!isEnglish && hasRelative()) {\n this.rtf = getCachedRTF(intl, opts);\n }\n }\n\n format(count, unit) {\n if (this.rtf) {\n return this.rtf.format(count, unit);\n } else {\n return English.formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== \"long\");\n }\n }\n\n formatToParts(count, unit) {\n if (this.rtf) {\n return this.rtf.formatToParts(count, unit);\n } else {\n return [];\n }\n }\n}\n\n/**\n * @private\n */\n\nexport default class Locale {\n static fromOpts(opts) {\n return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN);\n }\n\n static create(locale, numberingSystem, outputCalendar, defaultToEN = false) {\n const specifiedLocale = locale || Settings.defaultLocale;\n // the system locale is useful for human readable strings but annoying for parsing/formatting known formats\n const localeR = specifiedLocale || (defaultToEN ? \"en-US\" : systemLocale());\n const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem;\n const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;\n return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale);\n }\n\n static resetCache() {\n sysLocaleCache = null;\n intlDTCache = {};\n intlNumCache = {};\n intlRelCache = {};\n }\n\n static fromObject({ locale, numberingSystem, outputCalendar } = {}) {\n return Locale.create(locale, numberingSystem, outputCalendar);\n }\n\n constructor(locale, numbering, outputCalendar, specifiedLocale) {\n const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale);\n\n this.locale = parsedLocale;\n this.numberingSystem = numbering || parsedNumberingSystem || null;\n this.outputCalendar = outputCalendar || parsedOutputCalendar || null;\n this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);\n\n this.weekdaysCache = { format: {}, standalone: {} };\n this.monthsCache = { format: {}, standalone: {} };\n this.meridiemCache = null;\n this.eraCache = {};\n\n this.specifiedLocale = specifiedLocale;\n this.fastNumbersCached = null;\n }\n\n get fastNumbers() {\n if (this.fastNumbersCached == null) {\n this.fastNumbersCached = supportsFastNumbers(this);\n }\n\n return this.fastNumbersCached;\n }\n\n listingMode() {\n const isActuallyEn = this.isEnglish();\n const hasNoWeirdness =\n (this.numberingSystem === null || this.numberingSystem === \"latn\") &&\n (this.outputCalendar === null || this.outputCalendar === \"gregory\");\n return isActuallyEn && hasNoWeirdness ? \"en\" : \"intl\";\n }\n\n clone(alts) {\n if (!alts || Object.getOwnPropertyNames(alts).length === 0) {\n return this;\n } else {\n return Locale.create(\n alts.locale || this.specifiedLocale,\n alts.numberingSystem || this.numberingSystem,\n alts.outputCalendar || this.outputCalendar,\n alts.defaultToEN || false\n );\n }\n }\n\n redefaultToEN(alts = {}) {\n return this.clone({ ...alts, defaultToEN: true });\n }\n\n redefaultToSystem(alts = {}) {\n return this.clone({ ...alts, defaultToEN: false });\n }\n\n months(length, format = false, defaultOK = true) {\n return listStuff(this, length, defaultOK, English.months, () => {\n const intl = format ? { month: length, day: \"numeric\" } : { month: length },\n formatStr = format ? \"format\" : \"standalone\";\n if (!this.monthsCache[formatStr][length]) {\n this.monthsCache[formatStr][length] = mapMonths((dt) => this.extract(dt, intl, \"month\"));\n }\n return this.monthsCache[formatStr][length];\n });\n }\n\n weekdays(length, format = false, defaultOK = true) {\n return listStuff(this, length, defaultOK, English.weekdays, () => {\n const intl = format\n ? { weekday: length, year: \"numeric\", month: \"long\", day: \"numeric\" }\n : { weekday: length },\n formatStr = format ? \"format\" : \"standalone\";\n if (!this.weekdaysCache[formatStr][length]) {\n this.weekdaysCache[formatStr][length] = mapWeekdays((dt) =>\n this.extract(dt, intl, \"weekday\")\n );\n }\n return this.weekdaysCache[formatStr][length];\n });\n }\n\n meridiems(defaultOK = true) {\n return listStuff(\n this,\n undefined,\n defaultOK,\n () => English.meridiems,\n () => {\n // In theory there could be aribitrary day periods. We're gonna assume there are exactly two\n // for AM and PM. This is probably wrong, but it's makes parsing way easier.\n if (!this.meridiemCache) {\n const intl = { hour: \"numeric\", hourCycle: \"h12\" };\n this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(\n (dt) => this.extract(dt, intl, \"dayperiod\")\n );\n }\n\n return this.meridiemCache;\n }\n );\n }\n\n eras(length, defaultOK = true) {\n return listStuff(this, length, defaultOK, English.eras, () => {\n const intl = { era: length };\n\n // This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates\n // to definitely enumerate them.\n if (!this.eraCache[length]) {\n this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map((dt) =>\n this.extract(dt, intl, \"era\")\n );\n }\n\n return this.eraCache[length];\n });\n }\n\n extract(dt, intlOpts, field) {\n const df = this.dtFormatter(dt, intlOpts),\n results = df.formatToParts(),\n matching = results.find((m) => m.type.toLowerCase() === field);\n return matching ? matching.value : null;\n }\n\n numberFormatter(opts = {}) {\n // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave)\n // (in contrast, the rest of the condition is used heavily)\n return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);\n }\n\n dtFormatter(dt, intlOpts = {}) {\n return new PolyDateFormatter(dt, this.intl, intlOpts);\n }\n\n relFormatter(opts = {}) {\n return new PolyRelFormatter(this.intl, this.isEnglish(), opts);\n }\n\n listFormatter(opts = {}) {\n return getCachedLF(this.intl, opts);\n }\n\n isEnglish() {\n return (\n this.locale === \"en\" ||\n this.locale.toLowerCase() === \"en-us\" ||\n new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith(\"en-us\")\n );\n }\n\n equals(other) {\n return (\n this.locale === other.locale &&\n this.numberingSystem === other.numberingSystem &&\n this.outputCalendar === other.outputCalendar\n );\n }\n}\n","import {\n untruncateYear,\n signedOffset,\n parseInteger,\n parseMillis,\n ianaRegex,\n isUndefined,\n parseFloating\n} from \"./util.js\";\nimport * as English from \"./english.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\n\n/*\n * This file handles parsing for well-specified formats. Here's how it works:\n * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match.\n * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object\n * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence.\n * Extractors can take a \"cursor\" representing the offset in the match to look at. This makes it easy to combine extractors.\n * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions.\n * Some extractions are super dumb and simpleParse and fromStrings help DRY them.\n */\n\nfunction combineRegexes(...regexes) {\n const full = regexes.reduce((f, r) => f + r.source, \"\");\n return RegExp(`^${full}$`);\n}\n\nfunction combineExtractors(...extractors) {\n return m =>\n extractors\n .reduce(\n ([mergedVals, mergedZone, cursor], ex) => {\n const [val, zone, next] = ex(m, cursor);\n return [{ ...mergedVals, ...val }, zone || mergedZone, next];\n },\n [{}, null, 1]\n )\n .slice(0, 2);\n}\n\nfunction parse(s, ...patterns) {\n if (s == null) {\n return [null, null];\n }\n\n for (const [regex, extractor] of patterns) {\n const m = regex.exec(s);\n if (m) {\n return extractor(m);\n }\n }\n return [null, null];\n}\n\nfunction simpleParse(...keys) {\n return (match, cursor) => {\n const ret = {};\n let i;\n\n for (i = 0; i < keys.length; i++) {\n ret[keys[i]] = parseInteger(match[cursor + i]);\n }\n return [ret, null, cursor + i];\n };\n}\n\n// ISO and SQL parsing\nconst offsetRegex = /(?:(Z)|([+-]\\d\\d)(?::?(\\d\\d))?)/;\nconst isoExtendedZone = `(?:${offsetRegex.source}?(?:\\\\[(${ianaRegex.source})\\\\])?)?`;\nconst isoTimeBaseRegex = /(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:[.,](\\d{1,30}))?)?)?/;\nconst isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`);\nconst isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`);\nconst isoYmdRegex = /([+-]\\d{6}|\\d{4})(?:-?(\\d\\d)(?:-?(\\d\\d))?)?/;\nconst isoWeekRegex = /(\\d{4})-?W(\\d\\d)(?:-?(\\d))?/;\nconst isoOrdinalRegex = /(\\d{4})-?(\\d{3})/;\nconst extractISOWeekData = simpleParse(\"weekYear\", \"weekNumber\", \"weekDay\");\nconst extractISOOrdinalData = simpleParse(\"year\", \"ordinal\");\nconst sqlYmdRegex = /(\\d{4})-(\\d\\d)-(\\d\\d)/; // dumbed-down version of the ISO one\nconst sqlTimeRegex = RegExp(\n `${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`\n);\nconst sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`);\n\nfunction int(match, pos, fallback) {\n const m = match[pos];\n return isUndefined(m) ? fallback : parseInteger(m);\n}\n\nfunction extractISOYmd(match, cursor) {\n const item = {\n year: int(match, cursor),\n month: int(match, cursor + 1, 1),\n day: int(match, cursor + 2, 1)\n };\n\n return [item, null, cursor + 3];\n}\n\nfunction extractISOTime(match, cursor) {\n const item = {\n hours: int(match, cursor, 0),\n minutes: int(match, cursor + 1, 0),\n seconds: int(match, cursor + 2, 0),\n milliseconds: parseMillis(match[cursor + 3])\n };\n\n return [item, null, cursor + 4];\n}\n\nfunction extractISOOffset(match, cursor) {\n const local = !match[cursor] && !match[cursor + 1],\n fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]),\n zone = local ? null : FixedOffsetZone.instance(fullOffset);\n return [{}, zone, cursor + 3];\n}\n\nfunction extractIANAZone(match, cursor) {\n const zone = match[cursor] ? IANAZone.create(match[cursor]) : null;\n return [{}, zone, cursor + 1];\n}\n\n// ISO time parsing\n\nconst isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`);\n\n// ISO duration parsing\n\nconst isoDuration = /^-?P(?:(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)Y)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)W)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)D)?(?:T(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)H)?(?:(-?\\d{1,20}(?:\\.\\d{1,20})?)M)?(?:(-?\\d{1,20})(?:[.,](-?\\d{1,20}))?S)?)?)$/;\n\nfunction extractISODuration(match) {\n const [\n s,\n yearStr,\n monthStr,\n weekStr,\n dayStr,\n hourStr,\n minuteStr,\n secondStr,\n millisecondsStr\n ] = match;\n\n const hasNegativePrefix = s[0] === \"-\";\n const negativeSeconds = secondStr && secondStr[0] === \"-\";\n\n const maybeNegate = (num, force = false) =>\n num !== undefined && (force || (num && hasNegativePrefix)) ? -num : num;\n\n return [\n {\n years: maybeNegate(parseFloating(yearStr)),\n months: maybeNegate(parseFloating(monthStr)),\n weeks: maybeNegate(parseFloating(weekStr)),\n days: maybeNegate(parseFloating(dayStr)),\n hours: maybeNegate(parseFloating(hourStr)),\n minutes: maybeNegate(parseFloating(minuteStr)),\n seconds: maybeNegate(parseFloating(secondStr), secondStr === \"-0\"),\n milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds)\n }\n ];\n}\n\n// These are a little braindead. EDT *should* tell us that we're in, say, America/New_York\n// and not just that we're in -240 *right now*. But since I don't think these are used that often\n// I'm just going to ignore that\nconst obsOffsets = {\n GMT: 0,\n EDT: -4 * 60,\n EST: -5 * 60,\n CDT: -5 * 60,\n CST: -6 * 60,\n MDT: -6 * 60,\n MST: -7 * 60,\n PDT: -7 * 60,\n PST: -8 * 60\n};\n\nfunction fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {\n const result = {\n year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),\n month: English.monthsShort.indexOf(monthStr) + 1,\n day: parseInteger(dayStr),\n hour: parseInteger(hourStr),\n minute: parseInteger(minuteStr)\n };\n\n if (secondStr) result.second = parseInteger(secondStr);\n if (weekdayStr) {\n result.weekday =\n weekdayStr.length > 3\n ? English.weekdaysLong.indexOf(weekdayStr) + 1\n : English.weekdaysShort.indexOf(weekdayStr) + 1;\n }\n\n return result;\n}\n\n// RFC 2822/5322\nconst rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s)?(\\d{1,2})\\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s(\\d{2,4})\\s(\\d\\d):(\\d\\d)(?::(\\d\\d))?\\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\\d\\d)(\\d\\d)))$/;\n\nfunction extractRFC2822(match) {\n const [\n ,\n weekdayStr,\n dayStr,\n monthStr,\n yearStr,\n hourStr,\n minuteStr,\n secondStr,\n obsOffset,\n milOffset,\n offHourStr,\n offMinuteStr\n ] = match,\n result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n\n let offset;\n if (obsOffset) {\n offset = obsOffsets[obsOffset];\n } else if (milOffset) {\n offset = 0;\n } else {\n offset = signedOffset(offHourStr, offMinuteStr);\n }\n\n return [result, new FixedOffsetZone(offset)];\n}\n\nfunction preprocessRFC2822(s) {\n // Remove comments and folding whitespace and replace multiple-spaces with a single space\n return s\n .replace(/\\([^()]*\\)|[\\n\\t]/g, \" \")\n .replace(/(\\s\\s+)/g, \" \")\n .trim();\n}\n\n// http date\n\nconst rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d\\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\\d{4}) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,\n rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d\\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) GMT$/,\n ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \\d|\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d) (\\d{4})$/;\n\nfunction extractRFC1123Or850(match) {\n const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match,\n result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n return [result, FixedOffsetZone.utcInstance];\n}\n\nfunction extractASCII(match) {\n const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match,\n result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);\n return [result, FixedOffsetZone.utcInstance];\n}\n\nconst isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);\nconst isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);\nconst isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);\nconst isoTimeCombinedRegex = combineRegexes(isoTimeRegex);\n\nconst extractISOYmdTimeAndOffset = combineExtractors(\n extractISOYmd,\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\nconst extractISOWeekTimeAndOffset = combineExtractors(\n extractISOWeekData,\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\nconst extractISOOrdinalDateAndTime = combineExtractors(\n extractISOOrdinalData,\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\nconst extractISOTimeAndOffset = combineExtractors(\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\n\n/*\n * @private\n */\n\nexport function parseISODate(s) {\n return parse(\n s,\n [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],\n [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset],\n [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime],\n [isoTimeCombinedRegex, extractISOTimeAndOffset]\n );\n}\n\nexport function parseRFC2822Date(s) {\n return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]);\n}\n\nexport function parseHTTPDate(s) {\n return parse(\n s,\n [rfc1123, extractRFC1123Or850],\n [rfc850, extractRFC1123Or850],\n [ascii, extractASCII]\n );\n}\n\nexport function parseISODuration(s) {\n return parse(s, [isoDuration, extractISODuration]);\n}\n\nconst extractISOTimeOnly = combineExtractors(extractISOTime);\n\nexport function parseISOTimeOnly(s) {\n return parse(s, [isoTimeOnly, extractISOTimeOnly]);\n}\n\nconst sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);\nconst sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);\n\nconst extractISOTimeOffsetAndIANAZone = combineExtractors(\n extractISOTime,\n extractISOOffset,\n extractIANAZone\n);\n\nexport function parseSQL(s) {\n return parse(\n s,\n [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset],\n [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]\n );\n}\n","import { InvalidArgumentError, InvalidDurationError, InvalidUnitError } from \"./errors.js\";\nimport Formatter from \"./impl/formatter.js\";\nimport Invalid from \"./impl/invalid.js\";\nimport Locale from \"./impl/locale.js\";\nimport { parseISODuration, parseISOTimeOnly } from \"./impl/regexParser.js\";\nimport {\n asNumber,\n hasOwnProperty,\n isNumber,\n isUndefined,\n normalizeObject,\n roundTo,\n} from \"./impl/util.js\";\nimport Settings from \"./settings.js\";\n\nconst INVALID = \"Invalid Duration\";\n\n// unit conversion constants\nexport const lowOrderMatrix = {\n weeks: {\n days: 7,\n hours: 7 * 24,\n minutes: 7 * 24 * 60,\n seconds: 7 * 24 * 60 * 60,\n milliseconds: 7 * 24 * 60 * 60 * 1000,\n },\n days: {\n hours: 24,\n minutes: 24 * 60,\n seconds: 24 * 60 * 60,\n milliseconds: 24 * 60 * 60 * 1000,\n },\n hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 },\n minutes: { seconds: 60, milliseconds: 60 * 1000 },\n seconds: { milliseconds: 1000 },\n },\n casualMatrix = {\n years: {\n quarters: 4,\n months: 12,\n weeks: 52,\n days: 365,\n hours: 365 * 24,\n minutes: 365 * 24 * 60,\n seconds: 365 * 24 * 60 * 60,\n milliseconds: 365 * 24 * 60 * 60 * 1000,\n },\n quarters: {\n months: 3,\n weeks: 13,\n days: 91,\n hours: 91 * 24,\n minutes: 91 * 24 * 60,\n seconds: 91 * 24 * 60 * 60,\n milliseconds: 91 * 24 * 60 * 60 * 1000,\n },\n months: {\n weeks: 4,\n days: 30,\n hours: 30 * 24,\n minutes: 30 * 24 * 60,\n seconds: 30 * 24 * 60 * 60,\n milliseconds: 30 * 24 * 60 * 60 * 1000,\n },\n\n ...lowOrderMatrix,\n },\n daysInYearAccurate = 146097.0 / 400,\n daysInMonthAccurate = 146097.0 / 4800,\n accurateMatrix = {\n years: {\n quarters: 4,\n months: 12,\n weeks: daysInYearAccurate / 7,\n days: daysInYearAccurate,\n hours: daysInYearAccurate * 24,\n minutes: daysInYearAccurate * 24 * 60,\n seconds: daysInYearAccurate * 24 * 60 * 60,\n milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000,\n },\n quarters: {\n months: 3,\n weeks: daysInYearAccurate / 28,\n days: daysInYearAccurate / 4,\n hours: (daysInYearAccurate * 24) / 4,\n minutes: (daysInYearAccurate * 24 * 60) / 4,\n seconds: (daysInYearAccurate * 24 * 60 * 60) / 4,\n milliseconds: (daysInYearAccurate * 24 * 60 * 60 * 1000) / 4,\n },\n months: {\n weeks: daysInMonthAccurate / 7,\n days: daysInMonthAccurate,\n hours: daysInMonthAccurate * 24,\n minutes: daysInMonthAccurate * 24 * 60,\n seconds: daysInMonthAccurate * 24 * 60 * 60,\n milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000,\n },\n ...lowOrderMatrix,\n };\n\n// units ordered by size\nconst orderedUnits = [\n \"years\",\n \"quarters\",\n \"months\",\n \"weeks\",\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n \"milliseconds\",\n];\n\nconst reverseUnits = orderedUnits.slice(0).reverse();\n\n// clone really means \"create another instance just like this one, but with these changes\"\nfunction clone(dur, alts, clear = false) {\n // deep merge for vals\n const conf = {\n values: clear ? alts.values : { ...dur.values, ...(alts.values || {}) },\n loc: dur.loc.clone(alts.loc),\n conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,\n };\n return new Duration(conf);\n}\n\nfunction antiTrunc(n) {\n return n < 0 ? Math.floor(n) : Math.ceil(n);\n}\n\n// NB: mutates parameters\nfunction convert(matrix, fromMap, fromUnit, toMap, toUnit) {\n const conv = matrix[toUnit][fromUnit],\n raw = fromMap[fromUnit] / conv,\n sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]),\n // ok, so this is wild, but see the matrix in the tests\n added =\n !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw);\n toMap[toUnit] += added;\n fromMap[fromUnit] -= added * conv;\n}\n\n// NB: mutates parameters\nfunction normalizeValues(matrix, vals) {\n reverseUnits.reduce((previous, current) => {\n if (!isUndefined(vals[current])) {\n if (previous) {\n convert(matrix, vals, previous, vals, current);\n }\n return current;\n } else {\n return previous;\n }\n }, null);\n}\n\n/**\n * A Duration object represents a period of time, like \"2 months\" or \"1 day, 1 hour\". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime#plus} to add a Duration object to a DateTime, producing another DateTime.\n *\n * Here is a brief overview of commonly used methods and getters in Duration:\n *\n * * **Creation** To create a Duration, use {@link Duration#fromMillis}, {@link Duration#fromObject}, or {@link Duration#fromISO}.\n * * **Unit values** See the {@link Duration#years}, {@link Duration#months}, {@link Duration#weeks}, {@link Duration#days}, {@link Duration#hours}, {@link Duration#minutes}, {@link Duration#seconds}, {@link Duration#milliseconds} accessors.\n * * **Configuration** See {@link Duration#locale} and {@link Duration#numberingSystem} accessors.\n * * **Transformation** To create new Durations out of old ones use {@link Duration#plus}, {@link Duration#minus}, {@link Duration#normalize}, {@link Duration#set}, {@link Duration#reconfigure}, {@link Duration#shiftTo}, and {@link Duration#negate}.\n * * **Output** To convert the Duration into other representations, see {@link Duration#as}, {@link Duration#toISO}, {@link Duration#toFormat}, and {@link Duration#toJSON}\n *\n * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation.\n */\nexport default class Duration {\n /**\n * @private\n */\n constructor(config) {\n const accurate = config.conversionAccuracy === \"longterm\" || false;\n /**\n * @access private\n */\n this.values = config.values;\n /**\n * @access private\n */\n this.loc = config.loc || Locale.create();\n /**\n * @access private\n */\n this.conversionAccuracy = accurate ? \"longterm\" : \"casual\";\n /**\n * @access private\n */\n this.invalid = config.invalid || null;\n /**\n * @access private\n */\n this.matrix = accurate ? accurateMatrix : casualMatrix;\n /**\n * @access private\n */\n this.isLuxonDuration = true;\n }\n\n /**\n * Create Duration from a number of milliseconds.\n * @param {number} count of milliseconds\n * @param {Object} opts - options for parsing\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @return {Duration}\n */\n static fromMillis(count, opts) {\n return Duration.fromObject({ milliseconds: count }, opts);\n }\n\n /**\n * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.\n * If this object is empty then a zero milliseconds duration is returned.\n * @param {Object} obj - the object to create the DateTime from\n * @param {number} obj.years\n * @param {number} obj.quarters\n * @param {number} obj.months\n * @param {number} obj.weeks\n * @param {number} obj.days\n * @param {number} obj.hours\n * @param {number} obj.minutes\n * @param {number} obj.seconds\n * @param {number} obj.milliseconds\n * @param {Object} [opts=[]] - options for creating this Duration\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @return {Duration}\n */\n static fromObject(obj, opts = {}) {\n if (obj == null || typeof obj !== \"object\") {\n throw new InvalidArgumentError(\n `Duration.fromObject: argument expected to be an object, got ${\n obj === null ? \"null\" : typeof obj\n }`\n );\n }\n\n return new Duration({\n values: normalizeObject(obj, Duration.normalizeUnit),\n loc: Locale.fromObject(opts),\n conversionAccuracy: opts.conversionAccuracy,\n });\n }\n\n /**\n * Create a Duration from DurationLike.\n *\n * @param {Object | number | Duration} durationLike\n * One of:\n * - object with keys like 'years' and 'hours'.\n * - number representing milliseconds\n * - Duration instance\n * @return {Duration}\n */\n static fromDurationLike(durationLike) {\n if (isNumber(durationLike)) {\n return Duration.fromMillis(durationLike);\n } else if (Duration.isDuration(durationLike)) {\n return durationLike;\n } else if (typeof durationLike === \"object\") {\n return Duration.fromObject(durationLike);\n } else {\n throw new InvalidArgumentError(\n `Unknown duration argument ${durationLike} of type ${typeof durationLike}`\n );\n }\n }\n\n /**\n * Create a Duration from an ISO 8601 duration string.\n * @param {string} text - text to parse\n * @param {Object} opts - options for parsing\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @see https://en.wikipedia.org/wiki/ISO_8601#Durations\n * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }\n * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }\n * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }\n * @return {Duration}\n */\n static fromISO(text, opts) {\n const [parsed] = parseISODuration(text);\n if (parsed) {\n return Duration.fromObject(parsed, opts);\n } else {\n return Duration.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n }\n }\n\n /**\n * Create a Duration from an ISO 8601 time string.\n * @param {string} text - text to parse\n * @param {Object} opts - options for parsing\n * @param {string} [opts.locale='en-US'] - the locale to use\n * @param {string} opts.numberingSystem - the numbering system to use\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @see https://en.wikipedia.org/wiki/ISO_8601#Times\n * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }\n * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }\n * @return {Duration}\n */\n static fromISOTime(text, opts) {\n const [parsed] = parseISOTimeOnly(text);\n if (parsed) {\n return Duration.fromObject(parsed, opts);\n } else {\n return Duration.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n }\n }\n\n /**\n * Create an invalid Duration.\n * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent\n * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n * @return {Duration}\n */\n static invalid(reason, explanation = null) {\n if (!reason) {\n throw new InvalidArgumentError(\"need to specify a reason the Duration is invalid\");\n }\n\n const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n if (Settings.throwOnInvalid) {\n throw new InvalidDurationError(invalid);\n } else {\n return new Duration({ invalid });\n }\n }\n\n /**\n * @private\n */\n static normalizeUnit(unit) {\n const normalized = {\n year: \"years\",\n years: \"years\",\n quarter: \"quarters\",\n quarters: \"quarters\",\n month: \"months\",\n months: \"months\",\n week: \"weeks\",\n weeks: \"weeks\",\n day: \"days\",\n days: \"days\",\n hour: \"hours\",\n hours: \"hours\",\n minute: \"minutes\",\n minutes: \"minutes\",\n second: \"seconds\",\n seconds: \"seconds\",\n millisecond: \"milliseconds\",\n milliseconds: \"milliseconds\",\n }[unit ? unit.toLowerCase() : unit];\n\n if (!normalized) throw new InvalidUnitError(unit);\n\n return normalized;\n }\n\n /**\n * Check if an object is a Duration. Works across context boundaries\n * @param {object} o\n * @return {boolean}\n */\n static isDuration(o) {\n return (o && o.isLuxonDuration) || false;\n }\n\n /**\n * Get the locale of a Duration, such 'en-GB'\n * @type {string}\n */\n get locale() {\n return this.isValid ? this.loc.locale : null;\n }\n\n /**\n * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration\n *\n * @type {string}\n */\n get numberingSystem() {\n return this.isValid ? this.loc.numberingSystem : null;\n }\n\n /**\n * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:\n * * `S` for milliseconds\n * * `s` for seconds\n * * `m` for minutes\n * * `h` for hours\n * * `d` for days\n * * `w` for weeks\n * * `M` for months\n * * `y` for years\n * Notes:\n * * Add padding by repeating the token, e.g. \"yy\" pads the years to two digits, \"hhhh\" pads the hours out to four digits\n * * Tokens can be escaped by wrapping with single quotes.\n * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.\n * @param {string} fmt - the format string\n * @param {Object} opts - options\n * @param {boolean} [opts.floor=true] - floor numerical values\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"y d s\") //=> \"1 6 2\"\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"yy dd sss\") //=> \"01 06 002\"\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat(\"M S\") //=> \"12 518402000\"\n * @return {string}\n */\n toFormat(fmt, opts = {}) {\n // reverse-compat since 1.2; we always round down now, never up, and we do it by default\n const fmtOpts = {\n ...opts,\n floor: opts.round !== false && opts.floor !== false,\n };\n return this.isValid\n ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt)\n : INVALID;\n }\n\n /**\n * Returns a string representation of a Duration with all units included.\n * To modify its behavior use the `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat\n * @param opts - On option object to override the formatting. Accepts the same keys as the options parameter of the native `Int.NumberFormat` constructor, as well as `listStyle`.\n * @example\n * ```js\n * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 })\n * dur.toHuman() //=> '1 day, 5 hours, 6 minutes'\n * dur.toHuman({ listStyle: \"long\" }) //=> '1 day, 5 hours, and 6 minutes'\n * dur.toHuman({ unitDisplay: \"short\" }) //=> '1 day, 5 hr, 6 min'\n * ```\n */\n toHuman(opts = {}) {\n const l = orderedUnits\n .map((unit) => {\n const val = this.values[unit];\n if (isUndefined(val)) {\n return null;\n }\n return this.loc\n .numberFormatter({ style: \"unit\", unitDisplay: \"long\", ...opts, unit: unit.slice(0, -1) })\n .format(val);\n })\n .filter((n) => n);\n\n return this.loc\n .listFormatter({ type: \"conjunction\", style: opts.listStyle || \"narrow\", ...opts })\n .format(l);\n }\n\n /**\n * Returns a JavaScript object with this Duration's values.\n * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }\n * @return {Object}\n */\n toObject() {\n if (!this.isValid) return {};\n return { ...this.values };\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this Duration.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Durations\n * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'\n * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'\n * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'\n * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'\n * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'\n * @return {string}\n */\n toISO() {\n // we could use the formatter, but this is an easier way to get the minimum string\n if (!this.isValid) return null;\n\n let s = \"P\";\n if (this.years !== 0) s += this.years + \"Y\";\n if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + \"M\";\n if (this.weeks !== 0) s += this.weeks + \"W\";\n if (this.days !== 0) s += this.days + \"D\";\n if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)\n s += \"T\";\n if (this.hours !== 0) s += this.hours + \"H\";\n if (this.minutes !== 0) s += this.minutes + \"M\";\n if (this.seconds !== 0 || this.milliseconds !== 0)\n // this will handle \"floating point madness\" by removing extra decimal places\n // https://stackoverflow.com/questions/588004/is-floating-point-math-broken\n s += roundTo(this.seconds + this.milliseconds / 1000, 3) + \"S\";\n if (s === \"P\") s += \"T0S\";\n return s;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.\n * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Times\n * @param {Object} opts - options\n * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n * @param {boolean} [opts.includePrefix=false] - include the `T` prefix\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'\n * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'\n * @return {string}\n */\n toISOTime(opts = {}) {\n if (!this.isValid) return null;\n\n const millis = this.toMillis();\n if (millis < 0 || millis >= 86400000) return null;\n\n opts = {\n suppressMilliseconds: false,\n suppressSeconds: false,\n includePrefix: false,\n format: \"extended\",\n ...opts,\n };\n\n const value = this.shiftTo(\"hours\", \"minutes\", \"seconds\", \"milliseconds\");\n\n let fmt = opts.format === \"basic\" ? \"hhmm\" : \"hh:mm\";\n\n if (!opts.suppressSeconds || value.seconds !== 0 || value.milliseconds !== 0) {\n fmt += opts.format === \"basic\" ? \"ss\" : \":ss\";\n if (!opts.suppressMilliseconds || value.milliseconds !== 0) {\n fmt += \".SSS\";\n }\n }\n\n let str = value.toFormat(fmt);\n\n if (opts.includePrefix) {\n str = \"T\" + str;\n }\n\n return str;\n }\n\n /**\n * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.\n * @return {string}\n */\n toJSON() {\n return this.toISO();\n }\n\n /**\n * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.\n * @return {string}\n */\n toString() {\n return this.toISO();\n }\n\n /**\n * Returns an milliseconds value of this Duration.\n * @return {number}\n */\n toMillis() {\n return this.as(\"milliseconds\");\n }\n\n /**\n * Returns an milliseconds value of this Duration. Alias of {@link toMillis}\n * @return {number}\n */\n valueOf() {\n return this.toMillis();\n }\n\n /**\n * Make this Duration longer by the specified amount. Return a newly-constructed Duration.\n * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n * @return {Duration}\n */\n plus(duration) {\n if (!this.isValid) return this;\n\n const dur = Duration.fromDurationLike(duration),\n result = {};\n\n for (const k of orderedUnits) {\n if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {\n result[k] = dur.get(k) + this.get(k);\n }\n }\n\n return clone(this, { values: result }, true);\n }\n\n /**\n * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.\n * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n * @return {Duration}\n */\n minus(duration) {\n if (!this.isValid) return this;\n\n const dur = Duration.fromDurationLike(duration);\n return this.plus(dur.negate());\n }\n\n /**\n * Scale this Duration by the specified amount. Return a newly-constructed Duration.\n * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.\n * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }\n * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === \"hour\" ? x * 2 : x) //=> { hours: 2, minutes: 30 }\n * @return {Duration}\n */\n mapUnits(fn) {\n if (!this.isValid) return this;\n const result = {};\n for (const k of Object.keys(this.values)) {\n result[k] = asNumber(fn(this.values[k], k));\n }\n return clone(this, { values: result }, true);\n }\n\n /**\n * Get the value of unit.\n * @param {string} unit - a unit such as 'minute' or 'day'\n * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2\n * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0\n * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3\n * @return {number}\n */\n get(unit) {\n return this[Duration.normalizeUnit(unit)];\n }\n\n /**\n * \"Set\" the values of specified units. Return a newly-constructed Duration.\n * @param {Object} values - a mapping of units to numbers\n * @example dur.set({ years: 2017 })\n * @example dur.set({ hours: 8, minutes: 30 })\n * @return {Duration}\n */\n set(values) {\n if (!this.isValid) return this;\n\n const mixed = { ...this.values, ...normalizeObject(values, Duration.normalizeUnit) };\n return clone(this, { values: mixed });\n }\n\n /**\n * \"Set\" the locale and/or numberingSystem. Returns a newly-constructed Duration.\n * @example dur.reconfigure({ locale: 'en-GB' })\n * @return {Duration}\n */\n reconfigure({ locale, numberingSystem, conversionAccuracy } = {}) {\n const loc = this.loc.clone({ locale, numberingSystem }),\n opts = { loc };\n\n if (conversionAccuracy) {\n opts.conversionAccuracy = conversionAccuracy;\n }\n\n return clone(this, opts);\n }\n\n /**\n * Return the length of the duration in the specified unit.\n * @param {string} unit - a unit such as 'minutes' or 'days'\n * @example Duration.fromObject({years: 1}).as('days') //=> 365\n * @example Duration.fromObject({years: 1}).as('months') //=> 12\n * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5\n * @return {number}\n */\n as(unit) {\n return this.isValid ? this.shiftTo(unit).get(unit) : NaN;\n }\n\n /**\n * Reduce this Duration to its canonical representation in its current units.\n * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }\n * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }\n * @return {Duration}\n */\n normalize() {\n if (!this.isValid) return this;\n const vals = this.toObject();\n normalizeValues(this.matrix, vals);\n return clone(this, { values: vals }, true);\n }\n\n /**\n * Convert this Duration into its representation in a different set of units.\n * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }\n * @return {Duration}\n */\n shiftTo(...units) {\n if (!this.isValid) return this;\n\n if (units.length === 0) {\n return this;\n }\n\n units = units.map((u) => Duration.normalizeUnit(u));\n\n const built = {},\n accumulated = {},\n vals = this.toObject();\n let lastUnit;\n\n for (const k of orderedUnits) {\n if (units.indexOf(k) >= 0) {\n lastUnit = k;\n\n let own = 0;\n\n // anything we haven't boiled down yet should get boiled to this unit\n for (const ak in accumulated) {\n own += this.matrix[ak][k] * accumulated[ak];\n accumulated[ak] = 0;\n }\n\n // plus anything that's already in this unit\n if (isNumber(vals[k])) {\n own += vals[k];\n }\n\n const i = Math.trunc(own);\n built[k] = i;\n accumulated[k] = (own * 1000 - i * 1000) / 1000;\n\n // plus anything further down the chain that should be rolled up in to this\n for (const down in vals) {\n if (orderedUnits.indexOf(down) > orderedUnits.indexOf(k)) {\n convert(this.matrix, vals, down, built, k);\n }\n }\n // otherwise, keep it in the wings to boil it later\n } else if (isNumber(vals[k])) {\n accumulated[k] = vals[k];\n }\n }\n\n // anything leftover becomes the decimal for the last unit\n // lastUnit must be defined since units is not empty\n for (const key in accumulated) {\n if (accumulated[key] !== 0) {\n built[lastUnit] +=\n key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];\n }\n }\n\n return clone(this, { values: built }, true).normalize();\n }\n\n /**\n * Return the negative of this Duration.\n * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }\n * @return {Duration}\n */\n negate() {\n if (!this.isValid) return this;\n const negated = {};\n for (const k of Object.keys(this.values)) {\n negated[k] = this.values[k] === 0 ? 0 : -this.values[k];\n }\n return clone(this, { values: negated }, true);\n }\n\n /**\n * Get the years.\n * @type {number}\n */\n get years() {\n return this.isValid ? this.values.years || 0 : NaN;\n }\n\n /**\n * Get the quarters.\n * @type {number}\n */\n get quarters() {\n return this.isValid ? this.values.quarters || 0 : NaN;\n }\n\n /**\n * Get the months.\n * @type {number}\n */\n get months() {\n return this.isValid ? this.values.months || 0 : NaN;\n }\n\n /**\n * Get the weeks\n * @type {number}\n */\n get weeks() {\n return this.isValid ? this.values.weeks || 0 : NaN;\n }\n\n /**\n * Get the days.\n * @type {number}\n */\n get days() {\n return this.isValid ? this.values.days || 0 : NaN;\n }\n\n /**\n * Get the hours.\n * @type {number}\n */\n get hours() {\n return this.isValid ? this.values.hours || 0 : NaN;\n }\n\n /**\n * Get the minutes.\n * @type {number}\n */\n get minutes() {\n return this.isValid ? this.values.minutes || 0 : NaN;\n }\n\n /**\n * Get the seconds.\n * @return {number}\n */\n get seconds() {\n return this.isValid ? this.values.seconds || 0 : NaN;\n }\n\n /**\n * Get the milliseconds.\n * @return {number}\n */\n get milliseconds() {\n return this.isValid ? this.values.milliseconds || 0 : NaN;\n }\n\n /**\n * Returns whether the Duration is invalid. Invalid durations are returned by diff operations\n * on invalid DateTimes or Intervals.\n * @return {boolean}\n */\n get isValid() {\n return this.invalid === null;\n }\n\n /**\n * Returns an error code if this Duration became invalid, or null if the Duration is valid\n * @return {string}\n */\n get invalidReason() {\n return this.invalid ? this.invalid.reason : null;\n }\n\n /**\n * Returns an explanation of why this Duration became invalid, or null if the Duration is valid\n * @type {string}\n */\n get invalidExplanation() {\n return this.invalid ? this.invalid.explanation : null;\n }\n\n /**\n * Equality check\n * Two Durations are equal iff they have the same units and the same values for each unit.\n * @param {Duration} other\n * @return {boolean}\n */\n equals(other) {\n if (!this.isValid || !other.isValid) {\n return false;\n }\n\n if (!this.loc.equals(other.loc)) {\n return false;\n }\n\n function eq(v1, v2) {\n // Consider 0 and undefined as equal\n if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0;\n return v1 === v2;\n }\n\n for (const u of orderedUnits) {\n if (!eq(this.values[u], other.values[u])) {\n return false;\n }\n }\n return true;\n }\n}\n","import DateTime, { friendlyDateTime } from \"./datetime.js\";\nimport Duration from \"./duration.js\";\nimport Settings from \"./settings.js\";\nimport { InvalidArgumentError, InvalidIntervalError } from \"./errors.js\";\nimport Invalid from \"./impl/invalid.js\";\n\nconst INVALID = \"Invalid Interval\";\n\n// checks if the start is equal to or before the end\nfunction validateStartEnd(start, end) {\n if (!start || !start.isValid) {\n return Interval.invalid(\"missing or invalid start\");\n } else if (!end || !end.isValid) {\n return Interval.invalid(\"missing or invalid end\");\n } else if (end < start) {\n return Interval.invalid(\n \"end before start\",\n `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`\n );\n } else {\n return null;\n }\n}\n\n/**\n * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them.\n *\n * Here is a brief overview of the most commonly used methods and getters in Interval:\n *\n * * **Creation** To create an Interval, use {@link Interval#fromDateTimes}, {@link Interval#after}, {@link Interval#before}, or {@link Interval#fromISO}.\n * * **Accessors** Use {@link Interval#start} and {@link Interval#end} to get the start and end.\n * * **Interrogation** To analyze the Interval, use {@link Interval#count}, {@link Interval#length}, {@link Interval#hasSame}, {@link Interval#contains}, {@link Interval#isAfter}, or {@link Interval#isBefore}.\n * * **Transformation** To create other Intervals out of this one, use {@link Interval#set}, {@link Interval#splitAt}, {@link Interval#splitBy}, {@link Interval#divideEqually}, {@link Interval#merge}, {@link Interval#xor}, {@link Interval#union}, {@link Interval#intersection}, or {@link Interval#difference}.\n * * **Comparison** To compare this Interval to another one, use {@link Interval#equals}, {@link Interval#overlaps}, {@link Interval#abutsStart}, {@link Interval#abutsEnd}, {@link Interval#engulfs}\n * * **Output** To convert the Interval into other representations, see {@link Interval#toString}, {@link Interval#toISO}, {@link Interval#toISODate}, {@link Interval#toISOTime}, {@link Interval#toFormat}, and {@link Interval#toDuration}.\n */\nexport default class Interval {\n /**\n * @private\n */\n constructor(config) {\n /**\n * @access private\n */\n this.s = config.start;\n /**\n * @access private\n */\n this.e = config.end;\n /**\n * @access private\n */\n this.invalid = config.invalid || null;\n /**\n * @access private\n */\n this.isLuxonInterval = true;\n }\n\n /**\n * Create an invalid Interval.\n * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent\n * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n * @return {Interval}\n */\n static invalid(reason, explanation = null) {\n if (!reason) {\n throw new InvalidArgumentError(\"need to specify a reason the Interval is invalid\");\n }\n\n const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n if (Settings.throwOnInvalid) {\n throw new InvalidIntervalError(invalid);\n } else {\n return new Interval({ invalid });\n }\n }\n\n /**\n * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.\n * @param {DateTime|Date|Object} start\n * @param {DateTime|Date|Object} end\n * @return {Interval}\n */\n static fromDateTimes(start, end) {\n const builtStart = friendlyDateTime(start),\n builtEnd = friendlyDateTime(end);\n\n const validateError = validateStartEnd(builtStart, builtEnd);\n\n if (validateError == null) {\n return new Interval({\n start: builtStart,\n end: builtEnd,\n });\n } else {\n return validateError;\n }\n }\n\n /**\n * Create an Interval from a start DateTime and a Duration to extend to.\n * @param {DateTime|Date|Object} start\n * @param {Duration|Object|number} duration - the length of the Interval.\n * @return {Interval}\n */\n static after(start, duration) {\n const dur = Duration.fromDurationLike(duration),\n dt = friendlyDateTime(start);\n return Interval.fromDateTimes(dt, dt.plus(dur));\n }\n\n /**\n * Create an Interval from an end DateTime and a Duration to extend backwards to.\n * @param {DateTime|Date|Object} end\n * @param {Duration|Object|number} duration - the length of the Interval.\n * @return {Interval}\n */\n static before(end, duration) {\n const dur = Duration.fromDurationLike(duration),\n dt = friendlyDateTime(end);\n return Interval.fromDateTimes(dt.minus(dur), dt);\n }\n\n /**\n * Create an Interval from an ISO 8601 string.\n * Accepts `/`, `/`, and `/` formats.\n * @param {string} text - the ISO string to parse\n * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO}\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @return {Interval}\n */\n static fromISO(text, opts) {\n const [s, e] = (text || \"\").split(\"/\", 2);\n if (s && e) {\n let start, startIsValid;\n try {\n start = DateTime.fromISO(s, opts);\n startIsValid = start.isValid;\n } catch (e) {\n startIsValid = false;\n }\n\n let end, endIsValid;\n try {\n end = DateTime.fromISO(e, opts);\n endIsValid = end.isValid;\n } catch (e) {\n endIsValid = false;\n }\n\n if (startIsValid && endIsValid) {\n return Interval.fromDateTimes(start, end);\n }\n\n if (startIsValid) {\n const dur = Duration.fromISO(e, opts);\n if (dur.isValid) {\n return Interval.after(start, dur);\n }\n } else if (endIsValid) {\n const dur = Duration.fromISO(s, opts);\n if (dur.isValid) {\n return Interval.before(end, dur);\n }\n }\n }\n return Interval.invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ISO 8601`);\n }\n\n /**\n * Check if an object is an Interval. Works across context boundaries\n * @param {object} o\n * @return {boolean}\n */\n static isInterval(o) {\n return (o && o.isLuxonInterval) || false;\n }\n\n /**\n * Returns the start of the Interval\n * @type {DateTime}\n */\n get start() {\n return this.isValid ? this.s : null;\n }\n\n /**\n * Returns the end of the Interval\n * @type {DateTime}\n */\n get end() {\n return this.isValid ? this.e : null;\n }\n\n /**\n * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.\n * @type {boolean}\n */\n get isValid() {\n return this.invalidReason === null;\n }\n\n /**\n * Returns an error code if this Interval is invalid, or null if the Interval is valid\n * @type {string}\n */\n get invalidReason() {\n return this.invalid ? this.invalid.reason : null;\n }\n\n /**\n * Returns an explanation of why this Interval became invalid, or null if the Interval is valid\n * @type {string}\n */\n get invalidExplanation() {\n return this.invalid ? this.invalid.explanation : null;\n }\n\n /**\n * Returns the length of the Interval in the specified unit.\n * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.\n * @return {number}\n */\n length(unit = \"milliseconds\") {\n return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN;\n }\n\n /**\n * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.\n * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'\n * asks 'what dates are included in this interval?', not 'how many days long is this interval?'\n * @param {string} [unit='milliseconds'] - the unit of time to count.\n * @return {number}\n */\n count(unit = \"milliseconds\") {\n if (!this.isValid) return NaN;\n const start = this.start.startOf(unit),\n end = this.end.startOf(unit);\n return Math.floor(end.diff(start, unit).get(unit)) + 1;\n }\n\n /**\n * Returns whether this Interval's start and end are both in the same unit of time\n * @param {string} unit - the unit of time to check sameness on\n * @return {boolean}\n */\n hasSame(unit) {\n return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;\n }\n\n /**\n * Return whether this Interval has the same start and end DateTimes.\n * @return {boolean}\n */\n isEmpty() {\n return this.s.valueOf() === this.e.valueOf();\n }\n\n /**\n * Return whether this Interval's start is after the specified DateTime.\n * @param {DateTime} dateTime\n * @return {boolean}\n */\n isAfter(dateTime) {\n if (!this.isValid) return false;\n return this.s > dateTime;\n }\n\n /**\n * Return whether this Interval's end is before the specified DateTime.\n * @param {DateTime} dateTime\n * @return {boolean}\n */\n isBefore(dateTime) {\n if (!this.isValid) return false;\n return this.e <= dateTime;\n }\n\n /**\n * Return whether this Interval contains the specified DateTime.\n * @param {DateTime} dateTime\n * @return {boolean}\n */\n contains(dateTime) {\n if (!this.isValid) return false;\n return this.s <= dateTime && this.e > dateTime;\n }\n\n /**\n * \"Sets\" the start and/or end dates. Returns a newly-constructed Interval.\n * @param {Object} values - the values to set\n * @param {DateTime} values.start - the starting DateTime\n * @param {DateTime} values.end - the ending DateTime\n * @return {Interval}\n */\n set({ start, end } = {}) {\n if (!this.isValid) return this;\n return Interval.fromDateTimes(start || this.s, end || this.e);\n }\n\n /**\n * Split this Interval at each of the specified DateTimes\n * @param {...DateTime} dateTimes - the unit of time to count.\n * @return {Array}\n */\n splitAt(...dateTimes) {\n if (!this.isValid) return [];\n const sorted = dateTimes\n .map(friendlyDateTime)\n .filter((d) => this.contains(d))\n .sort(),\n results = [];\n let { s } = this,\n i = 0;\n\n while (s < this.e) {\n const added = sorted[i] || this.e,\n next = +added > +this.e ? this.e : added;\n results.push(Interval.fromDateTimes(s, next));\n s = next;\n i += 1;\n }\n\n return results;\n }\n\n /**\n * Split this Interval into smaller Intervals, each of the specified length.\n * Left over time is grouped into a smaller interval\n * @param {Duration|Object|number} duration - The length of each resulting interval.\n * @return {Array}\n */\n splitBy(duration) {\n const dur = Duration.fromDurationLike(duration);\n\n if (!this.isValid || !dur.isValid || dur.as(\"milliseconds\") === 0) {\n return [];\n }\n\n let { s } = this,\n idx = 1,\n next;\n\n const results = [];\n while (s < this.e) {\n const added = this.start.plus(dur.mapUnits((x) => x * idx));\n next = +added > +this.e ? this.e : added;\n results.push(Interval.fromDateTimes(s, next));\n s = next;\n idx += 1;\n }\n\n return results;\n }\n\n /**\n * Split this Interval into the specified number of smaller intervals.\n * @param {number} numberOfParts - The number of Intervals to divide the Interval into.\n * @return {Array}\n */\n divideEqually(numberOfParts) {\n if (!this.isValid) return [];\n return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);\n }\n\n /**\n * Return whether this Interval overlaps with the specified Interval\n * @param {Interval} other\n * @return {boolean}\n */\n overlaps(other) {\n return this.e > other.s && this.s < other.e;\n }\n\n /**\n * Return whether this Interval's end is adjacent to the specified Interval's start.\n * @param {Interval} other\n * @return {boolean}\n */\n abutsStart(other) {\n if (!this.isValid) return false;\n return +this.e === +other.s;\n }\n\n /**\n * Return whether this Interval's start is adjacent to the specified Interval's end.\n * @param {Interval} other\n * @return {boolean}\n */\n abutsEnd(other) {\n if (!this.isValid) return false;\n return +other.e === +this.s;\n }\n\n /**\n * Return whether this Interval engulfs the start and end of the specified Interval.\n * @param {Interval} other\n * @return {boolean}\n */\n engulfs(other) {\n if (!this.isValid) return false;\n return this.s <= other.s && this.e >= other.e;\n }\n\n /**\n * Return whether this Interval has the same start and end as the specified Interval.\n * @param {Interval} other\n * @return {boolean}\n */\n equals(other) {\n if (!this.isValid || !other.isValid) {\n return false;\n }\n\n return this.s.equals(other.s) && this.e.equals(other.e);\n }\n\n /**\n * Return an Interval representing the intersection of this Interval and the specified Interval.\n * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.\n * Returns null if the intersection is empty, meaning, the intervals don't intersect.\n * @param {Interval} other\n * @return {Interval}\n */\n intersection(other) {\n if (!this.isValid) return this;\n const s = this.s > other.s ? this.s : other.s,\n e = this.e < other.e ? this.e : other.e;\n\n if (s >= e) {\n return null;\n } else {\n return Interval.fromDateTimes(s, e);\n }\n }\n\n /**\n * Return an Interval representing the union of this Interval and the specified Interval.\n * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.\n * @param {Interval} other\n * @return {Interval}\n */\n union(other) {\n if (!this.isValid) return this;\n const s = this.s < other.s ? this.s : other.s,\n e = this.e > other.e ? this.e : other.e;\n return Interval.fromDateTimes(s, e);\n }\n\n /**\n * Merge an array of Intervals into a equivalent minimal set of Intervals.\n * Combines overlapping and adjacent Intervals.\n * @param {Array} intervals\n * @return {Array}\n */\n static merge(intervals) {\n const [found, final] = intervals\n .sort((a, b) => a.s - b.s)\n .reduce(\n ([sofar, current], item) => {\n if (!current) {\n return [sofar, item];\n } else if (current.overlaps(item) || current.abutsStart(item)) {\n return [sofar, current.union(item)];\n } else {\n return [sofar.concat([current]), item];\n }\n },\n [[], null]\n );\n if (final) {\n found.push(final);\n }\n return found;\n }\n\n /**\n * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.\n * @param {Array} intervals\n * @return {Array}\n */\n static xor(intervals) {\n let start = null,\n currentCount = 0;\n const results = [],\n ends = intervals.map((i) => [\n { time: i.s, type: \"s\" },\n { time: i.e, type: \"e\" },\n ]),\n flattened = Array.prototype.concat(...ends),\n arr = flattened.sort((a, b) => a.time - b.time);\n\n for (const i of arr) {\n currentCount += i.type === \"s\" ? 1 : -1;\n\n if (currentCount === 1) {\n start = i.time;\n } else {\n if (start && +start !== +i.time) {\n results.push(Interval.fromDateTimes(start, i.time));\n }\n\n start = null;\n }\n }\n\n return Interval.merge(results);\n }\n\n /**\n * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.\n * @param {...Interval} intervals\n * @return {Array}\n */\n difference(...intervals) {\n return Interval.xor([this].concat(intervals))\n .map((i) => this.intersection(i))\n .filter((i) => i && !i.isEmpty());\n }\n\n /**\n * Returns a string representation of this Interval appropriate for debugging.\n * @return {string}\n */\n toString() {\n if (!this.isValid) return INVALID;\n return `[${this.s.toISO()} – ${this.e.toISO()})`;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this Interval.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @param {Object} opts - The same options as {@link DateTime#toISO}\n * @return {string}\n */\n toISO(opts) {\n if (!this.isValid) return INVALID;\n return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of date of this Interval.\n * The time components are ignored.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @return {string}\n */\n toISODate() {\n if (!this.isValid) return INVALID;\n return `${this.s.toISODate()}/${this.e.toISODate()}`;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of time of this Interval.\n * The date components are ignored.\n * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n * @param {Object} opts - The same options as {@link DateTime#toISO}\n * @return {string}\n */\n toISOTime(opts) {\n if (!this.isValid) return INVALID;\n return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;\n }\n\n /**\n * Returns a string representation of this Interval formatted according to the specified format string.\n * @param {string} dateFormat - the format string. This string formats the start and end time. See {@link DateTime#toFormat} for details.\n * @param {Object} opts - options\n * @param {string} [opts.separator = ' – '] - a separator to place between the start and end representations\n * @return {string}\n */\n toFormat(dateFormat, { separator = \" – \" } = {}) {\n if (!this.isValid) return INVALID;\n return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;\n }\n\n /**\n * Return a Duration representing the time spanned by this interval.\n * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.\n * @param {Object} opts - options that affect the creation of the Duration\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }\n * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }\n * @return {Duration}\n */\n toDuration(unit, opts) {\n if (!this.isValid) {\n return Duration.invalid(this.invalidReason);\n }\n return this.e.diff(this.s, unit, opts);\n }\n\n /**\n * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes\n * @param {function} mapFn\n * @return {Interval}\n * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())\n * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))\n */\n mapEndpoints(mapFn) {\n return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));\n }\n}\n","import DateTime from \"./datetime.js\";\nimport Settings from \"./settings.js\";\nimport Locale from \"./impl/locale.js\";\nimport IANAZone from \"./zones/IANAZone.js\";\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\n\nimport { hasRelative } from \"./impl/util.js\";\n\n/**\n * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment.\n */\nexport default class Info {\n /**\n * Return whether the specified zone contains a DST.\n * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.\n * @return {boolean}\n */\n static hasDST(zone = Settings.defaultZone) {\n const proto = DateTime.now().setZone(zone).set({ month: 12 });\n\n return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset;\n }\n\n /**\n * Return whether the specified zone is a valid IANA specifier.\n * @param {string} zone - Zone to check\n * @return {boolean}\n */\n static isValidIANAZone(zone) {\n return IANAZone.isValidZone(zone);\n }\n\n /**\n * Converts the input into a {@link Zone} instance.\n *\n * * If `input` is already a Zone instance, it is returned unchanged.\n * * If `input` is a string containing a valid time zone name, a Zone instance\n * with that name is returned.\n * * If `input` is a string that doesn't refer to a known time zone, a Zone\n * instance with {@link Zone#isValid} == false is returned.\n * * If `input is a number, a Zone instance with the specified fixed offset\n * in minutes is returned.\n * * If `input` is `null` or `undefined`, the default zone is returned.\n * @param {string|Zone|number} [input] - the value to be converted\n * @return {Zone}\n */\n static normalizeZone(input) {\n return normalizeZone(input, Settings.defaultZone);\n }\n\n /**\n * Return an array of standalone month names.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param {string} [length='long'] - the length of the month representation, such as \"numeric\", \"2-digit\", \"narrow\", \"short\", \"long\"\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @param {string} [opts.outputCalendar='gregory'] - the calendar\n * @example Info.months()[0] //=> 'January'\n * @example Info.months('short')[0] //=> 'Jan'\n * @example Info.months('numeric')[0] //=> '1'\n * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'\n * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'\n * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'\n * @return {Array}\n */\n static months(\n length = \"long\",\n { locale = null, numberingSystem = null, locObj = null, outputCalendar = \"gregory\" } = {}\n ) {\n return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);\n }\n\n /**\n * Return an array of format month names.\n * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that\n * changes the string.\n * See {@link Info#months}\n * @param {string} [length='long'] - the length of the month representation, such as \"numeric\", \"2-digit\", \"narrow\", \"short\", \"long\"\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @param {string} [opts.outputCalendar='gregory'] - the calendar\n * @return {Array}\n */\n static monthsFormat(\n length = \"long\",\n { locale = null, numberingSystem = null, locObj = null, outputCalendar = \"gregory\" } = {}\n ) {\n return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);\n }\n\n /**\n * Return an array of standalone week names.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param {string} [length='long'] - the length of the weekday representation, such as \"narrow\", \"short\", \"long\".\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @example Info.weekdays()[0] //=> 'Monday'\n * @example Info.weekdays('short')[0] //=> 'Mon'\n * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'\n * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'\n * @return {Array}\n */\n static weekdays(length = \"long\", { locale = null, numberingSystem = null, locObj = null } = {}) {\n return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);\n }\n\n /**\n * Return an array of format week names.\n * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that\n * changes the string.\n * See {@link Info#weekdays}\n * @param {string} [length='long'] - the length of the month representation, such as \"narrow\", \"short\", \"long\".\n * @param {Object} opts - options\n * @param {string} [opts.locale=null] - the locale code\n * @param {string} [opts.numberingSystem=null] - the numbering system\n * @param {string} [opts.locObj=null] - an existing locale object to use\n * @return {Array}\n */\n static weekdaysFormat(\n length = \"long\",\n { locale = null, numberingSystem = null, locObj = null } = {}\n ) {\n return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);\n }\n\n /**\n * Return an array of meridiems.\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @example Info.meridiems() //=> [ 'AM', 'PM' ]\n * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]\n * @return {Array}\n */\n static meridiems({ locale = null } = {}) {\n return Locale.create(locale).meridiems();\n }\n\n /**\n * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.\n * @param {string} [length='short'] - the length of the era representation, such as \"short\" or \"long\".\n * @param {Object} opts - options\n * @param {string} [opts.locale] - the locale code\n * @example Info.eras() //=> [ 'BC', 'AD' ]\n * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]\n * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]\n * @return {Array}\n */\n static eras(length = \"short\", { locale = null } = {}) {\n return Locale.create(locale, null, \"gregory\").eras(length);\n }\n\n /**\n * Return the set of available features in this environment.\n * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case.\n * Keys:\n * * `relative`: whether this environment supports relative time formatting\n * @example Info.features() //=> { relative: false }\n * @return {Object}\n */\n static features() {\n return { relative: hasRelative() };\n }\n}\n","import Duration from \"../duration.js\";\n\nfunction dayDiff(earlier, later) {\n const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf(\"day\").valueOf(),\n ms = utcDayStart(later) - utcDayStart(earlier);\n return Math.floor(Duration.fromMillis(ms).as(\"days\"));\n}\n\nfunction highOrderDiffs(cursor, later, units) {\n const differs = [\n [\"years\", (a, b) => b.year - a.year],\n [\"quarters\", (a, b) => b.quarter - a.quarter],\n [\"months\", (a, b) => b.month - a.month + (b.year - a.year) * 12],\n [\n \"weeks\",\n (a, b) => {\n const days = dayDiff(a, b);\n return (days - (days % 7)) / 7;\n },\n ],\n [\"days\", dayDiff],\n ];\n\n const results = {};\n let lowestOrder, highWater;\n\n for (const [unit, differ] of differs) {\n if (units.indexOf(unit) >= 0) {\n lowestOrder = unit;\n\n let delta = differ(cursor, later);\n highWater = cursor.plus({ [unit]: delta });\n\n if (highWater > later) {\n cursor = cursor.plus({ [unit]: delta - 1 });\n delta -= 1;\n } else {\n cursor = highWater;\n }\n\n results[unit] = delta;\n }\n }\n\n return [cursor, results, highWater, lowestOrder];\n}\n\nexport default function (earlier, later, units, opts) {\n let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units);\n\n const remainingMillis = later - cursor;\n\n const lowerOrderUnits = units.filter(\n (u) => [\"hours\", \"minutes\", \"seconds\", \"milliseconds\"].indexOf(u) >= 0\n );\n\n if (lowerOrderUnits.length === 0) {\n if (highWater < later) {\n highWater = cursor.plus({ [lowestOrder]: 1 });\n }\n\n if (highWater !== cursor) {\n results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);\n }\n }\n\n const duration = Duration.fromObject(results, opts);\n\n if (lowerOrderUnits.length > 0) {\n return Duration.fromMillis(remainingMillis, opts)\n .shiftTo(...lowerOrderUnits)\n .plus(duration);\n } else {\n return duration;\n }\n}\n","const numberingSystems = {\n arab: \"[\\u0660-\\u0669]\",\n arabext: \"[\\u06F0-\\u06F9]\",\n bali: \"[\\u1B50-\\u1B59]\",\n beng: \"[\\u09E6-\\u09EF]\",\n deva: \"[\\u0966-\\u096F]\",\n fullwide: \"[\\uFF10-\\uFF19]\",\n gujr: \"[\\u0AE6-\\u0AEF]\",\n hanidec: \"[〇|一|二|三|四|五|六|七|八|九]\",\n khmr: \"[\\u17E0-\\u17E9]\",\n knda: \"[\\u0CE6-\\u0CEF]\",\n laoo: \"[\\u0ED0-\\u0ED9]\",\n limb: \"[\\u1946-\\u194F]\",\n mlym: \"[\\u0D66-\\u0D6F]\",\n mong: \"[\\u1810-\\u1819]\",\n mymr: \"[\\u1040-\\u1049]\",\n orya: \"[\\u0B66-\\u0B6F]\",\n tamldec: \"[\\u0BE6-\\u0BEF]\",\n telu: \"[\\u0C66-\\u0C6F]\",\n thai: \"[\\u0E50-\\u0E59]\",\n tibt: \"[\\u0F20-\\u0F29]\",\n latn: \"\\\\d\",\n};\n\nconst numberingSystemsUTF16 = {\n arab: [1632, 1641],\n arabext: [1776, 1785],\n bali: [6992, 7001],\n beng: [2534, 2543],\n deva: [2406, 2415],\n fullwide: [65296, 65303],\n gujr: [2790, 2799],\n khmr: [6112, 6121],\n knda: [3302, 3311],\n laoo: [3792, 3801],\n limb: [6470, 6479],\n mlym: [3430, 3439],\n mong: [6160, 6169],\n mymr: [4160, 4169],\n orya: [2918, 2927],\n tamldec: [3046, 3055],\n telu: [3174, 3183],\n thai: [3664, 3673],\n tibt: [3872, 3881],\n};\n\nconst hanidecChars = numberingSystems.hanidec.replace(/[\\[|\\]]/g, \"\").split(\"\");\n\nexport function parseDigits(str) {\n let value = parseInt(str, 10);\n if (isNaN(value)) {\n value = \"\";\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n\n if (str[i].search(numberingSystems.hanidec) !== -1) {\n value += hanidecChars.indexOf(str[i]);\n } else {\n for (const key in numberingSystemsUTF16) {\n const [min, max] = numberingSystemsUTF16[key];\n if (code >= min && code <= max) {\n value += code - min;\n }\n }\n }\n }\n return parseInt(value, 10);\n } else {\n return value;\n }\n}\n\nexport function digitRegex({ numberingSystem }, append = \"\") {\n return new RegExp(`${numberingSystems[numberingSystem || \"latn\"]}${append}`);\n}\n","import { parseMillis, isUndefined, untruncateYear, signedOffset, hasOwnProperty } from \"./util.js\";\nimport Formatter from \"./formatter.js\";\nimport FixedOffsetZone from \"../zones/fixedOffsetZone.js\";\nimport IANAZone from \"../zones/IANAZone.js\";\nimport DateTime from \"../datetime.js\";\nimport { digitRegex, parseDigits } from \"./digits.js\";\nimport { ConflictingSpecificationError } from \"../errors.js\";\n\nconst MISSING_FTP = \"missing Intl.DateTimeFormat.formatToParts support\";\n\nfunction intUnit(regex, post = (i) => i) {\n return { regex, deser: ([s]) => post(parseDigits(s)) };\n}\n\nconst NBSP = String.fromCharCode(160);\nconst spaceOrNBSP = `[ ${NBSP}]`;\nconst spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, \"g\");\n\nfunction fixListRegex(s) {\n // make dots optional and also make them literal\n // make space and non breakable space characters interchangeable\n return s.replace(/\\./g, \"\\\\.?\").replace(spaceOrNBSPRegExp, spaceOrNBSP);\n}\n\nfunction stripInsensitivities(s) {\n return s\n .replace(/\\./g, \"\") // ignore dots that were made optional\n .replace(spaceOrNBSPRegExp, \" \") // interchange space and nbsp\n .toLowerCase();\n}\n\nfunction oneOf(strings, startIndex) {\n if (strings === null) {\n return null;\n } else {\n return {\n regex: RegExp(strings.map(fixListRegex).join(\"|\")),\n deser: ([s]) =>\n strings.findIndex((i) => stripInsensitivities(s) === stripInsensitivities(i)) + startIndex,\n };\n }\n}\n\nfunction offset(regex, groups) {\n return { regex, deser: ([, h, m]) => signedOffset(h, m), groups };\n}\n\nfunction simple(regex) {\n return { regex, deser: ([s]) => s };\n}\n\nfunction escapeToken(value) {\n return value.replace(/[\\-\\[\\]{}()*+?.,\\\\\\^$|#\\s]/g, \"\\\\$&\");\n}\n\nfunction unitForToken(token, loc) {\n const one = digitRegex(loc),\n two = digitRegex(loc, \"{2}\"),\n three = digitRegex(loc, \"{3}\"),\n four = digitRegex(loc, \"{4}\"),\n six = digitRegex(loc, \"{6}\"),\n oneOrTwo = digitRegex(loc, \"{1,2}\"),\n oneToThree = digitRegex(loc, \"{1,3}\"),\n oneToSix = digitRegex(loc, \"{1,6}\"),\n oneToNine = digitRegex(loc, \"{1,9}\"),\n twoToFour = digitRegex(loc, \"{2,4}\"),\n fourToSix = digitRegex(loc, \"{4,6}\"),\n literal = (t) => ({ regex: RegExp(escapeToken(t.val)), deser: ([s]) => s, literal: true }),\n unitate = (t) => {\n if (token.literal) {\n return literal(t);\n }\n switch (t.val) {\n // era\n case \"G\":\n return oneOf(loc.eras(\"short\", false), 0);\n case \"GG\":\n return oneOf(loc.eras(\"long\", false), 0);\n // years\n case \"y\":\n return intUnit(oneToSix);\n case \"yy\":\n return intUnit(twoToFour, untruncateYear);\n case \"yyyy\":\n return intUnit(four);\n case \"yyyyy\":\n return intUnit(fourToSix);\n case \"yyyyyy\":\n return intUnit(six);\n // months\n case \"M\":\n return intUnit(oneOrTwo);\n case \"MM\":\n return intUnit(two);\n case \"MMM\":\n return oneOf(loc.months(\"short\", true, false), 1);\n case \"MMMM\":\n return oneOf(loc.months(\"long\", true, false), 1);\n case \"L\":\n return intUnit(oneOrTwo);\n case \"LL\":\n return intUnit(two);\n case \"LLL\":\n return oneOf(loc.months(\"short\", false, false), 1);\n case \"LLLL\":\n return oneOf(loc.months(\"long\", false, false), 1);\n // dates\n case \"d\":\n return intUnit(oneOrTwo);\n case \"dd\":\n return intUnit(two);\n // ordinals\n case \"o\":\n return intUnit(oneToThree);\n case \"ooo\":\n return intUnit(three);\n // time\n case \"HH\":\n return intUnit(two);\n case \"H\":\n return intUnit(oneOrTwo);\n case \"hh\":\n return intUnit(two);\n case \"h\":\n return intUnit(oneOrTwo);\n case \"mm\":\n return intUnit(two);\n case \"m\":\n return intUnit(oneOrTwo);\n case \"q\":\n return intUnit(oneOrTwo);\n case \"qq\":\n return intUnit(two);\n case \"s\":\n return intUnit(oneOrTwo);\n case \"ss\":\n return intUnit(two);\n case \"S\":\n return intUnit(oneToThree);\n case \"SSS\":\n return intUnit(three);\n case \"u\":\n return simple(oneToNine);\n case \"uu\":\n return simple(oneOrTwo);\n case \"uuu\":\n return intUnit(one);\n // meridiem\n case \"a\":\n return oneOf(loc.meridiems(), 0);\n // weekYear (k)\n case \"kkkk\":\n return intUnit(four);\n case \"kk\":\n return intUnit(twoToFour, untruncateYear);\n // weekNumber (W)\n case \"W\":\n return intUnit(oneOrTwo);\n case \"WW\":\n return intUnit(two);\n // weekdays\n case \"E\":\n case \"c\":\n return intUnit(one);\n case \"EEE\":\n return oneOf(loc.weekdays(\"short\", false, false), 1);\n case \"EEEE\":\n return oneOf(loc.weekdays(\"long\", false, false), 1);\n case \"ccc\":\n return oneOf(loc.weekdays(\"short\", true, false), 1);\n case \"cccc\":\n return oneOf(loc.weekdays(\"long\", true, false), 1);\n // offset/zone\n case \"Z\":\n case \"ZZ\":\n return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2);\n case \"ZZZ\":\n return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2);\n // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing\n // because we don't have any way to figure out what they are\n case \"z\":\n return simple(/[a-z_+-/]{1,256}?/i);\n default:\n return literal(t);\n }\n };\n\n const unit = unitate(token) || {\n invalidReason: MISSING_FTP,\n };\n\n unit.token = token;\n\n return unit;\n}\n\nconst partTypeStyleToTokenVal = {\n year: {\n \"2-digit\": \"yy\",\n numeric: \"yyyyy\",\n },\n month: {\n numeric: \"M\",\n \"2-digit\": \"MM\",\n short: \"MMM\",\n long: \"MMMM\",\n },\n day: {\n numeric: \"d\",\n \"2-digit\": \"dd\",\n },\n weekday: {\n short: \"EEE\",\n long: \"EEEE\",\n },\n dayperiod: \"a\",\n dayPeriod: \"a\",\n hour: {\n numeric: \"h\",\n \"2-digit\": \"hh\",\n },\n minute: {\n numeric: \"m\",\n \"2-digit\": \"mm\",\n },\n second: {\n numeric: \"s\",\n \"2-digit\": \"ss\",\n },\n};\n\nfunction tokenForPart(part, locale, formatOpts) {\n const { type, value } = part;\n\n if (type === \"literal\") {\n return {\n literal: true,\n val: value,\n };\n }\n\n const style = formatOpts[type];\n\n let val = partTypeStyleToTokenVal[type];\n if (typeof val === \"object\") {\n val = val[style];\n }\n\n if (val) {\n return {\n literal: false,\n val,\n };\n }\n\n return undefined;\n}\n\nfunction buildRegex(units) {\n const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, \"\");\n return [`^${re}$`, units];\n}\n\nfunction match(input, regex, handlers) {\n const matches = input.match(regex);\n\n if (matches) {\n const all = {};\n let matchIndex = 1;\n for (const i in handlers) {\n if (hasOwnProperty(handlers, i)) {\n const h = handlers[i],\n groups = h.groups ? h.groups + 1 : 1;\n if (!h.literal && h.token) {\n all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));\n }\n matchIndex += groups;\n }\n }\n return [matches, all];\n } else {\n return [matches, {}];\n }\n}\n\nfunction dateTimeFromMatches(matches) {\n const toField = (token) => {\n switch (token) {\n case \"S\":\n return \"millisecond\";\n case \"s\":\n return \"second\";\n case \"m\":\n return \"minute\";\n case \"h\":\n case \"H\":\n return \"hour\";\n case \"d\":\n return \"day\";\n case \"o\":\n return \"ordinal\";\n case \"L\":\n case \"M\":\n return \"month\";\n case \"y\":\n return \"year\";\n case \"E\":\n case \"c\":\n return \"weekday\";\n case \"W\":\n return \"weekNumber\";\n case \"k\":\n return \"weekYear\";\n case \"q\":\n return \"quarter\";\n default:\n return null;\n }\n };\n\n let zone = null;\n let specificOffset;\n if (!isUndefined(matches.z)) {\n zone = IANAZone.create(matches.z);\n }\n\n if (!isUndefined(matches.Z)) {\n if (!zone) {\n zone = new FixedOffsetZone(matches.Z);\n }\n specificOffset = matches.Z;\n }\n\n if (!isUndefined(matches.q)) {\n matches.M = (matches.q - 1) * 3 + 1;\n }\n\n if (!isUndefined(matches.h)) {\n if (matches.h < 12 && matches.a === 1) {\n matches.h += 12;\n } else if (matches.h === 12 && matches.a === 0) {\n matches.h = 0;\n }\n }\n\n if (matches.G === 0 && matches.y) {\n matches.y = -matches.y;\n }\n\n if (!isUndefined(matches.u)) {\n matches.S = parseMillis(matches.u);\n }\n\n const vals = Object.keys(matches).reduce((r, k) => {\n const f = toField(k);\n if (f) {\n r[f] = matches[k];\n }\n\n return r;\n }, {});\n\n return [vals, zone, specificOffset];\n}\n\nlet dummyDateTimeCache = null;\n\nfunction getDummyDateTime() {\n if (!dummyDateTimeCache) {\n dummyDateTimeCache = DateTime.fromMillis(1555555555555);\n }\n\n return dummyDateTimeCache;\n}\n\nfunction maybeExpandMacroToken(token, locale) {\n if (token.literal) {\n return token;\n }\n\n const formatOpts = Formatter.macroTokenToFormatOpts(token.val);\n\n if (!formatOpts) {\n return token;\n }\n\n const formatter = Formatter.create(locale, formatOpts);\n const parts = formatter.formatDateTimeParts(getDummyDateTime());\n\n const tokens = parts.map((p) => tokenForPart(p, locale, formatOpts));\n\n if (tokens.includes(undefined)) {\n return token;\n }\n\n return tokens;\n}\n\nfunction expandMacroTokens(tokens, locale) {\n return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale)));\n}\n\n/**\n * @private\n */\n\nexport function explainFromTokens(locale, input, format) {\n const tokens = expandMacroTokens(Formatter.parseFormat(format), locale),\n units = tokens.map((t) => unitForToken(t, locale)),\n disqualifyingUnit = units.find((t) => t.invalidReason);\n\n if (disqualifyingUnit) {\n return { input, tokens, invalidReason: disqualifyingUnit.invalidReason };\n } else {\n const [regexString, handlers] = buildRegex(units),\n regex = RegExp(regexString, \"i\"),\n [rawMatches, matches] = match(input, regex, handlers),\n [result, zone, specificOffset] = matches\n ? dateTimeFromMatches(matches)\n : [null, null, undefined];\n if (hasOwnProperty(matches, \"a\") && hasOwnProperty(matches, \"H\")) {\n throw new ConflictingSpecificationError(\n \"Can't include meridiem when specifying 24-hour format\"\n );\n }\n return { input, tokens, regex, rawMatches, matches, result, zone, specificOffset };\n }\n}\n\nexport function parseFromTokens(locale, input, format) {\n const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format);\n return [result, zone, specificOffset, invalidReason];\n}\n","import {\n integerBetween,\n isLeapYear,\n timeObject,\n daysInYear,\n daysInMonth,\n weeksInWeekYear,\n isInteger,\n} from \"./util.js\";\nimport Invalid from \"./invalid.js\";\n\nconst nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],\n leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];\n\nfunction unitOutOfRange(unit, value) {\n return new Invalid(\n \"unit out of range\",\n `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`\n );\n}\n\nfunction dayOfWeek(year, month, day) {\n const d = new Date(Date.UTC(year, month - 1, day));\n\n if (year < 100 && year >= 0) {\n d.setUTCFullYear(d.getUTCFullYear() - 1900);\n }\n\n const js = d.getUTCDay();\n\n return js === 0 ? 7 : js;\n}\n\nfunction computeOrdinal(year, month, day) {\n return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];\n}\n\nfunction uncomputeOrdinal(year, ordinal) {\n const table = isLeapYear(year) ? leapLadder : nonLeapLadder,\n month0 = table.findIndex((i) => i < ordinal),\n day = ordinal - table[month0];\n return { month: month0 + 1, day };\n}\n\n/**\n * @private\n */\n\nexport function gregorianToWeek(gregObj) {\n const { year, month, day } = gregObj,\n ordinal = computeOrdinal(year, month, day),\n weekday = dayOfWeek(year, month, day);\n\n let weekNumber = Math.floor((ordinal - weekday + 10) / 7),\n weekYear;\n\n if (weekNumber < 1) {\n weekYear = year - 1;\n weekNumber = weeksInWeekYear(weekYear);\n } else if (weekNumber > weeksInWeekYear(year)) {\n weekYear = year + 1;\n weekNumber = 1;\n } else {\n weekYear = year;\n }\n\n return { weekYear, weekNumber, weekday, ...timeObject(gregObj) };\n}\n\nexport function weekToGregorian(weekData) {\n const { weekYear, weekNumber, weekday } = weekData,\n weekdayOfJan4 = dayOfWeek(weekYear, 1, 4),\n yearInDays = daysInYear(weekYear);\n\n let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3,\n year;\n\n if (ordinal < 1) {\n year = weekYear - 1;\n ordinal += daysInYear(year);\n } else if (ordinal > yearInDays) {\n year = weekYear + 1;\n ordinal -= daysInYear(weekYear);\n } else {\n year = weekYear;\n }\n\n const { month, day } = uncomputeOrdinal(year, ordinal);\n return { year, month, day, ...timeObject(weekData) };\n}\n\nexport function gregorianToOrdinal(gregData) {\n const { year, month, day } = gregData;\n const ordinal = computeOrdinal(year, month, day);\n return { year, ordinal, ...timeObject(gregData) };\n}\n\nexport function ordinalToGregorian(ordinalData) {\n const { year, ordinal } = ordinalData;\n const { month, day } = uncomputeOrdinal(year, ordinal);\n return { year, month, day, ...timeObject(ordinalData) };\n}\n\nexport function hasInvalidWeekData(obj) {\n const validYear = isInteger(obj.weekYear),\n validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)),\n validWeekday = integerBetween(obj.weekday, 1, 7);\n\n if (!validYear) {\n return unitOutOfRange(\"weekYear\", obj.weekYear);\n } else if (!validWeek) {\n return unitOutOfRange(\"week\", obj.week);\n } else if (!validWeekday) {\n return unitOutOfRange(\"weekday\", obj.weekday);\n } else return false;\n}\n\nexport function hasInvalidOrdinalData(obj) {\n const validYear = isInteger(obj.year),\n validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));\n\n if (!validYear) {\n return unitOutOfRange(\"year\", obj.year);\n } else if (!validOrdinal) {\n return unitOutOfRange(\"ordinal\", obj.ordinal);\n } else return false;\n}\n\nexport function hasInvalidGregorianData(obj) {\n const validYear = isInteger(obj.year),\n validMonth = integerBetween(obj.month, 1, 12),\n validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));\n\n if (!validYear) {\n return unitOutOfRange(\"year\", obj.year);\n } else if (!validMonth) {\n return unitOutOfRange(\"month\", obj.month);\n } else if (!validDay) {\n return unitOutOfRange(\"day\", obj.day);\n } else return false;\n}\n\nexport function hasInvalidTimeData(obj) {\n const { hour, minute, second, millisecond } = obj;\n const validHour =\n integerBetween(hour, 0, 23) ||\n (hour === 24 && minute === 0 && second === 0 && millisecond === 0),\n validMinute = integerBetween(minute, 0, 59),\n validSecond = integerBetween(second, 0, 59),\n validMillisecond = integerBetween(millisecond, 0, 999);\n\n if (!validHour) {\n return unitOutOfRange(\"hour\", hour);\n } else if (!validMinute) {\n return unitOutOfRange(\"minute\", minute);\n } else if (!validSecond) {\n return unitOutOfRange(\"second\", second);\n } else if (!validMillisecond) {\n return unitOutOfRange(\"millisecond\", millisecond);\n } else return false;\n}\n","import Duration from \"./duration.js\";\nimport Interval from \"./interval.js\";\nimport Settings from \"./settings.js\";\nimport Info from \"./info.js\";\nimport Formatter from \"./impl/formatter.js\";\nimport FixedOffsetZone from \"./zones/fixedOffsetZone.js\";\nimport Locale from \"./impl/locale.js\";\nimport {\n isUndefined,\n maybeArray,\n isDate,\n isNumber,\n bestBy,\n daysInMonth,\n daysInYear,\n isLeapYear,\n weeksInWeekYear,\n normalizeObject,\n roundTo,\n objToLocalTS,\n padStart,\n} from \"./impl/util.js\";\nimport { normalizeZone } from \"./impl/zoneUtil.js\";\nimport diff from \"./impl/diff.js\";\nimport { parseRFC2822Date, parseISODate, parseHTTPDate, parseSQL } from \"./impl/regexParser.js\";\nimport { parseFromTokens, explainFromTokens } from \"./impl/tokenParser.js\";\nimport {\n gregorianToWeek,\n weekToGregorian,\n gregorianToOrdinal,\n ordinalToGregorian,\n hasInvalidGregorianData,\n hasInvalidWeekData,\n hasInvalidOrdinalData,\n hasInvalidTimeData,\n} from \"./impl/conversions.js\";\nimport * as Formats from \"./impl/formats.js\";\nimport {\n InvalidArgumentError,\n ConflictingSpecificationError,\n InvalidUnitError,\n InvalidDateTimeError,\n} from \"./errors.js\";\nimport Invalid from \"./impl/invalid.js\";\n\nconst INVALID = \"Invalid DateTime\";\nconst MAX_DATE = 8.64e15;\n\nfunction unsupportedZone(zone) {\n return new Invalid(\"unsupported zone\", `the zone \"${zone.name}\" is not supported`);\n}\n\n// we cache week data on the DT object and this intermediates the cache\nfunction possiblyCachedWeekData(dt) {\n if (dt.weekData === null) {\n dt.weekData = gregorianToWeek(dt.c);\n }\n return dt.weekData;\n}\n\n// clone really means, \"make a new object with these modifications\". all \"setters\" really use this\n// to create a new object while only changing some of the properties\nfunction clone(inst, alts) {\n const current = {\n ts: inst.ts,\n zone: inst.zone,\n c: inst.c,\n o: inst.o,\n loc: inst.loc,\n invalid: inst.invalid,\n };\n return new DateTime({ ...current, ...alts, old: current });\n}\n\n// find the right offset a given local time. The o input is our guess, which determines which\n// offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)\nfunction fixOffset(localTS, o, tz) {\n // Our UTC time is just a guess because our offset is just a guess\n let utcGuess = localTS - o * 60 * 1000;\n\n // Test whether the zone matches the offset for this ts\n const o2 = tz.offset(utcGuess);\n\n // If so, offset didn't change and we're done\n if (o === o2) {\n return [utcGuess, o];\n }\n\n // If not, change the ts by the difference in the offset\n utcGuess -= (o2 - o) * 60 * 1000;\n\n // If that gives us the local time we want, we're done\n const o3 = tz.offset(utcGuess);\n if (o2 === o3) {\n return [utcGuess, o2];\n }\n\n // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time\n return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];\n}\n\n// convert an epoch timestamp into a calendar object with the given offset\nfunction tsToObj(ts, offset) {\n ts += offset * 60 * 1000;\n\n const d = new Date(ts);\n\n return {\n year: d.getUTCFullYear(),\n month: d.getUTCMonth() + 1,\n day: d.getUTCDate(),\n hour: d.getUTCHours(),\n minute: d.getUTCMinutes(),\n second: d.getUTCSeconds(),\n millisecond: d.getUTCMilliseconds(),\n };\n}\n\n// convert a calendar object to a epoch timestamp\nfunction objToTS(obj, offset, zone) {\n return fixOffset(objToLocalTS(obj), offset, zone);\n}\n\n// create a new DT instance by adding a duration, adjusting for DSTs\nfunction adjustTime(inst, dur) {\n const oPre = inst.o,\n year = inst.c.year + Math.trunc(dur.years),\n month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3,\n c = {\n ...inst.c,\n year,\n month,\n day:\n Math.min(inst.c.day, daysInMonth(year, month)) +\n Math.trunc(dur.days) +\n Math.trunc(dur.weeks) * 7,\n },\n millisToAdd = Duration.fromObject({\n years: dur.years - Math.trunc(dur.years),\n quarters: dur.quarters - Math.trunc(dur.quarters),\n months: dur.months - Math.trunc(dur.months),\n weeks: dur.weeks - Math.trunc(dur.weeks),\n days: dur.days - Math.trunc(dur.days),\n hours: dur.hours,\n minutes: dur.minutes,\n seconds: dur.seconds,\n milliseconds: dur.milliseconds,\n }).as(\"milliseconds\"),\n localTS = objToLocalTS(c);\n\n let [ts, o] = fixOffset(localTS, oPre, inst.zone);\n\n if (millisToAdd !== 0) {\n ts += millisToAdd;\n // that could have changed the offset by going over a DST, but we want to keep the ts the same\n o = inst.zone.offset(ts);\n }\n\n return { ts, o };\n}\n\n// helper useful in turning the results of parsing into real dates\n// by handling the zone options\nfunction parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) {\n const { setZone, zone } = opts;\n if (parsed && Object.keys(parsed).length !== 0) {\n const interpretationZone = parsedZone || zone,\n inst = DateTime.fromObject(parsed, {\n ...opts,\n zone: interpretationZone,\n specificOffset,\n });\n return setZone ? inst : inst.setZone(zone);\n } else {\n return DateTime.invalid(\n new Invalid(\"unparsable\", `the input \"${text}\" can't be parsed as ${format}`)\n );\n }\n}\n\n// if you want to output a technical format (e.g. RFC 2822), this helper\n// helps handle the details\nfunction toTechFormat(dt, format, allowZ = true) {\n return dt.isValid\n ? Formatter.create(Locale.create(\"en-US\"), {\n allowZ,\n forceSimple: true,\n }).formatDateTimeFromString(dt, format)\n : null;\n}\n\nfunction toISODate(o, extended) {\n const longFormat = o.c.year > 9999 || o.c.year < 0;\n let c = \"\";\n if (longFormat && o.c.year >= 0) c += \"+\";\n c += padStart(o.c.year, longFormat ? 6 : 4);\n\n if (extended) {\n c += \"-\";\n c += padStart(o.c.month);\n c += \"-\";\n c += padStart(o.c.day);\n } else {\n c += padStart(o.c.month);\n c += padStart(o.c.day);\n }\n return c;\n}\n\nfunction toISOTime(\n o,\n extended,\n suppressSeconds,\n suppressMilliseconds,\n includeOffset,\n extendedZone\n) {\n let c = padStart(o.c.hour);\n if (extended) {\n c += \":\";\n c += padStart(o.c.minute);\n if (o.c.second !== 0 || !suppressSeconds) {\n c += \":\";\n }\n } else {\n c += padStart(o.c.minute);\n }\n\n if (o.c.second !== 0 || !suppressSeconds) {\n c += padStart(o.c.second);\n\n if (o.c.millisecond !== 0 || !suppressMilliseconds) {\n c += \".\";\n c += padStart(o.c.millisecond, 3);\n }\n }\n\n if (includeOffset) {\n if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {\n c += \"Z\";\n } else if (o.o < 0) {\n c += \"-\";\n c += padStart(Math.trunc(-o.o / 60));\n c += \":\";\n c += padStart(Math.trunc(-o.o % 60));\n } else {\n c += \"+\";\n c += padStart(Math.trunc(o.o / 60));\n c += \":\";\n c += padStart(Math.trunc(o.o % 60));\n }\n }\n\n if (extendedZone) {\n c += \"[\" + o.zone.ianaName + \"]\";\n }\n return c;\n}\n\n// defaults for unspecified units in the supported calendars\nconst defaultUnitValues = {\n month: 1,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n },\n defaultWeekUnitValues = {\n weekNumber: 1,\n weekday: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n },\n defaultOrdinalUnitValues = {\n ordinal: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n };\n\n// Units in the supported calendars, sorted by bigness\nconst orderedUnits = [\"year\", \"month\", \"day\", \"hour\", \"minute\", \"second\", \"millisecond\"],\n orderedWeekUnits = [\n \"weekYear\",\n \"weekNumber\",\n \"weekday\",\n \"hour\",\n \"minute\",\n \"second\",\n \"millisecond\",\n ],\n orderedOrdinalUnits = [\"year\", \"ordinal\", \"hour\", \"minute\", \"second\", \"millisecond\"];\n\n// standardize case and plurality in units\nfunction normalizeUnit(unit) {\n const normalized = {\n year: \"year\",\n years: \"year\",\n month: \"month\",\n months: \"month\",\n day: \"day\",\n days: \"day\",\n hour: \"hour\",\n hours: \"hour\",\n minute: \"minute\",\n minutes: \"minute\",\n quarter: \"quarter\",\n quarters: \"quarter\",\n second: \"second\",\n seconds: \"second\",\n millisecond: \"millisecond\",\n milliseconds: \"millisecond\",\n weekday: \"weekday\",\n weekdays: \"weekday\",\n weeknumber: \"weekNumber\",\n weeksnumber: \"weekNumber\",\n weeknumbers: \"weekNumber\",\n weekyear: \"weekYear\",\n weekyears: \"weekYear\",\n ordinal: \"ordinal\",\n }[unit.toLowerCase()];\n\n if (!normalized) throw new InvalidUnitError(unit);\n\n return normalized;\n}\n\n// this is a dumbed down version of fromObject() that runs about 60% faster\n// but doesn't do any validation, makes a bunch of assumptions about what units\n// are present, and so on.\nfunction quickDT(obj, opts) {\n const zone = normalizeZone(opts.zone, Settings.defaultZone),\n loc = Locale.fromObject(opts),\n tsNow = Settings.now();\n\n let ts, o;\n\n // assume we have the higher-order units\n if (!isUndefined(obj.year)) {\n for (const u of orderedUnits) {\n if (isUndefined(obj[u])) {\n obj[u] = defaultUnitValues[u];\n }\n }\n\n const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);\n if (invalid) {\n return DateTime.invalid(invalid);\n }\n\n const offsetProvis = zone.offset(tsNow);\n [ts, o] = objToTS(obj, offsetProvis, zone);\n } else {\n ts = tsNow;\n }\n\n return new DateTime({ ts, zone, loc, o });\n}\n\nfunction diffRelative(start, end, opts) {\n const round = isUndefined(opts.round) ? true : opts.round,\n format = (c, unit) => {\n c = roundTo(c, round || opts.calendary ? 0 : 2, true);\n const formatter = end.loc.clone(opts).relFormatter(opts);\n return formatter.format(c, unit);\n },\n differ = (unit) => {\n if (opts.calendary) {\n if (!end.hasSame(start, unit)) {\n return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);\n } else return 0;\n } else {\n return end.diff(start, unit).get(unit);\n }\n };\n\n if (opts.unit) {\n return format(differ(opts.unit), opts.unit);\n }\n\n for (const unit of opts.units) {\n const count = differ(unit);\n if (Math.abs(count) >= 1) {\n return format(count, unit);\n }\n }\n return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);\n}\n\nfunction lastOpts(argList) {\n let opts = {},\n args;\n if (argList.length > 0 && typeof argList[argList.length - 1] === \"object\") {\n opts = argList[argList.length - 1];\n args = Array.from(argList).slice(0, argList.length - 1);\n } else {\n args = Array.from(argList);\n }\n return [opts, args];\n}\n\n/**\n * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.\n *\n * A DateTime comprises of:\n * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.\n * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).\n * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.\n *\n * Here is a brief overview of the most commonly used functionality it provides:\n *\n * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link DateTime#local}, {@link DateTime#utc}, and (most flexibly) {@link DateTime#fromObject}. To create one from a standard string format, use {@link DateTime#fromISO}, {@link DateTime#fromHTTP}, and {@link DateTime#fromRFC2822}. To create one from a custom string format, use {@link DateTime#fromFormat}. To create one from a native JS date, use {@link DateTime#fromJSDate}.\n * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link DateTime#toObject}), use the {@link DateTime#year}, {@link DateTime#month},\n * {@link DateTime#day}, {@link DateTime#hour}, {@link DateTime#minute}, {@link DateTime#second}, {@link DateTime#millisecond} accessors.\n * * **Week calendar**: For ISO week calendar attributes, see the {@link DateTime#weekYear}, {@link DateTime#weekNumber}, and {@link DateTime#weekday} accessors.\n * * **Configuration** See the {@link DateTime#locale} and {@link DateTime#numberingSystem} accessors.\n * * **Transformation**: To transform the DateTime into other DateTimes, use {@link DateTime#set}, {@link DateTime#reconfigure}, {@link DateTime#setZone}, {@link DateTime#setLocale}, {@link DateTime.plus}, {@link DateTime#minus}, {@link DateTime#endOf}, {@link DateTime#startOf}, {@link DateTime#toUTC}, and {@link DateTime#toLocal}.\n * * **Output**: To convert the DateTime to other representations, use the {@link DateTime#toRelative}, {@link DateTime#toRelativeCalendar}, {@link DateTime#toJSON}, {@link DateTime#toISO}, {@link DateTime#toHTTP}, {@link DateTime#toObject}, {@link DateTime#toRFC2822}, {@link DateTime#toString}, {@link DateTime#toLocaleString}, {@link DateTime#toFormat}, {@link DateTime#toMillis} and {@link DateTime#toJSDate}.\n *\n * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation.\n */\nexport default class DateTime {\n /**\n * @access private\n */\n constructor(config) {\n const zone = config.zone || Settings.defaultZone;\n\n let invalid =\n config.invalid ||\n (Number.isNaN(config.ts) ? new Invalid(\"invalid input\") : null) ||\n (!zone.isValid ? unsupportedZone(zone) : null);\n /**\n * @access private\n */\n this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;\n\n let c = null,\n o = null;\n if (!invalid) {\n const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);\n\n if (unchanged) {\n [c, o] = [config.old.c, config.old.o];\n } else {\n const ot = zone.offset(this.ts);\n c = tsToObj(this.ts, ot);\n invalid = Number.isNaN(c.year) ? new Invalid(\"invalid input\") : null;\n c = invalid ? null : c;\n o = invalid ? null : ot;\n }\n }\n\n /**\n * @access private\n */\n this._zone = zone;\n /**\n * @access private\n */\n this.loc = config.loc || Locale.create();\n /**\n * @access private\n */\n this.invalid = invalid;\n /**\n * @access private\n */\n this.weekData = null;\n /**\n * @access private\n */\n this.c = c;\n /**\n * @access private\n */\n this.o = o;\n /**\n * @access private\n */\n this.isLuxonDateTime = true;\n }\n\n // CONSTRUCT\n\n /**\n * Create a DateTime for the current instant, in the system's time zone.\n *\n * Use Settings to override these default values if needed.\n * @example DateTime.now().toISO() //~> now in the ISO format\n * @return {DateTime}\n */\n static now() {\n return new DateTime({});\n }\n\n /**\n * Create a local DateTime\n * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used\n * @param {number} [month=1] - The month, 1-indexed\n * @param {number} [day=1] - The day of the month, 1-indexed\n * @param {number} [hour=0] - The hour of the day, in 24-hour time\n * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59\n * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59\n * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999\n * @example DateTime.local() //~> now\n * @example DateTime.local({ zone: \"America/New_York\" }) //~> now, in US east coast time\n * @example DateTime.local(2017) //~> 2017-01-01T00:00:00\n * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00\n * @example DateTime.local(2017, 3, 12, { locale: \"fr\" }) //~> 2017-03-12T00:00:00, with a French locale\n * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00\n * @example DateTime.local(2017, 3, 12, 5, { zone: \"utc\" }) //~> 2017-03-12T05:00:00, in UTC\n * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00\n * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10\n * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765\n * @return {DateTime}\n */\n static local() {\n const [opts, args] = lastOpts(arguments),\n [year, month, day, hour, minute, second, millisecond] = args;\n return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);\n }\n\n /**\n * Create a DateTime in UTC\n * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used\n * @param {number} [month=1] - The month, 1-indexed\n * @param {number} [day=1] - The day of the month\n * @param {number} [hour=0] - The hour of the day, in 24-hour time\n * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59\n * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59\n * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999\n * @param {Object} options - configuration options for the DateTime\n * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance\n * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance\n * @example DateTime.utc() //~> now\n * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z\n * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z\n * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z\n * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z\n * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z\n * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: \"fr\" }) //~> 2017-03-12T05:45:00Z with a French locale\n * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z\n * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: \"fr\" }) //~> 2017-03-12T05:45:10.765Z with a French locale\n * @return {DateTime}\n */\n static utc() {\n const [opts, args] = lastOpts(arguments),\n [year, month, day, hour, minute, second, millisecond] = args;\n\n opts.zone = FixedOffsetZone.utcInstance;\n return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);\n }\n\n /**\n * Create a DateTime from a JavaScript Date object. Uses the default zone.\n * @param {Date} date - a JavaScript Date object\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @return {DateTime}\n */\n static fromJSDate(date, options = {}) {\n const ts = isDate(date) ? date.valueOf() : NaN;\n if (Number.isNaN(ts)) {\n return DateTime.invalid(\"invalid input\");\n }\n\n const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);\n if (!zoneToUse.isValid) {\n return DateTime.invalid(unsupportedZone(zoneToUse));\n }\n\n return new DateTime({\n ts: ts,\n zone: zoneToUse,\n loc: Locale.fromObject(options),\n });\n }\n\n /**\n * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.\n * @param {number} milliseconds - a number of milliseconds since 1970 UTC\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromMillis(milliseconds, options = {}) {\n if (!isNumber(milliseconds)) {\n throw new InvalidArgumentError(\n `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`\n );\n } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {\n // this isn't perfect because because we can still end up out of range because of additional shifting, but it's a start\n return DateTime.invalid(\"Timestamp out of range\");\n } else {\n return new DateTime({\n ts: milliseconds,\n zone: normalizeZone(options.zone, Settings.defaultZone),\n loc: Locale.fromObject(options),\n });\n }\n }\n\n /**\n * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.\n * @param {number} seconds - a number of seconds since 1970 UTC\n * @param {Object} options - configuration options for the DateTime\n * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into\n * @param {string} [options.locale] - a locale to set on the resulting DateTime instance\n * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromSeconds(seconds, options = {}) {\n if (!isNumber(seconds)) {\n throw new InvalidArgumentError(\"fromSeconds requires a numerical input\");\n } else {\n return new DateTime({\n ts: seconds * 1000,\n zone: normalizeZone(options.zone, Settings.defaultZone),\n loc: Locale.fromObject(options),\n });\n }\n }\n\n /**\n * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.\n * @param {Object} obj - the object to create the DateTime from\n * @param {number} obj.year - a year, such as 1987\n * @param {number} obj.month - a month, 1-12\n * @param {number} obj.day - a day of the month, 1-31, depending on the month\n * @param {number} obj.ordinal - day of the year, 1-365 or 366\n * @param {number} obj.weekYear - an ISO week year\n * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year\n * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday\n * @param {number} obj.hour - hour of the day, 0-23\n * @param {number} obj.minute - minute of the hour, 0-59\n * @param {number} obj.second - second of the minute, 0-59\n * @param {number} obj.millisecond - millisecond of the second, 0-999\n * @param {Object} opts - options for creating this DateTime\n * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'\n * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })\n * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })\n * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'\n * @return {DateTime}\n */\n static fromObject(obj, opts = {}) {\n obj = obj || {};\n const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);\n if (!zoneToUse.isValid) {\n return DateTime.invalid(unsupportedZone(zoneToUse));\n }\n\n const tsNow = Settings.now(),\n offsetProvis = !isUndefined(opts.specificOffset)\n ? opts.specificOffset\n : zoneToUse.offset(tsNow),\n normalized = normalizeObject(obj, normalizeUnit),\n containsOrdinal = !isUndefined(normalized.ordinal),\n containsGregorYear = !isUndefined(normalized.year),\n containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),\n containsGregor = containsGregorYear || containsGregorMD,\n definiteWeekDef = normalized.weekYear || normalized.weekNumber,\n loc = Locale.fromObject(opts);\n\n // cases:\n // just a weekday -> this week's instance of that weekday, no worries\n // (gregorian data or ordinal) + (weekYear or weekNumber) -> error\n // (gregorian month or day) + ordinal -> error\n // otherwise just use weeks or ordinals or gregorian, depending on what's specified\n\n if ((containsGregor || containsOrdinal) && definiteWeekDef) {\n throw new ConflictingSpecificationError(\n \"Can't mix weekYear/weekNumber units with year/month/day or ordinals\"\n );\n }\n\n if (containsGregorMD && containsOrdinal) {\n throw new ConflictingSpecificationError(\"Can't mix ordinal dates with month/day\");\n }\n\n const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor);\n\n // configure ourselves to deal with gregorian dates or week stuff\n let units,\n defaultValues,\n objNow = tsToObj(tsNow, offsetProvis);\n if (useWeekData) {\n units = orderedWeekUnits;\n defaultValues = defaultWeekUnitValues;\n objNow = gregorianToWeek(objNow);\n } else if (containsOrdinal) {\n units = orderedOrdinalUnits;\n defaultValues = defaultOrdinalUnitValues;\n objNow = gregorianToOrdinal(objNow);\n } else {\n units = orderedUnits;\n defaultValues = defaultUnitValues;\n }\n\n // set default values for missing stuff\n let foundFirst = false;\n for (const u of units) {\n const v = normalized[u];\n if (!isUndefined(v)) {\n foundFirst = true;\n } else if (foundFirst) {\n normalized[u] = defaultValues[u];\n } else {\n normalized[u] = objNow[u];\n }\n }\n\n // make sure the values we have are in range\n const higherOrderInvalid = useWeekData\n ? hasInvalidWeekData(normalized)\n : containsOrdinal\n ? hasInvalidOrdinalData(normalized)\n : hasInvalidGregorianData(normalized),\n invalid = higherOrderInvalid || hasInvalidTimeData(normalized);\n\n if (invalid) {\n return DateTime.invalid(invalid);\n }\n\n // compute the actual time\n const gregorian = useWeekData\n ? weekToGregorian(normalized)\n : containsOrdinal\n ? ordinalToGregorian(normalized)\n : normalized,\n [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse),\n inst = new DateTime({\n ts: tsFinal,\n zone: zoneToUse,\n o: offsetFinal,\n loc,\n });\n\n // gregorian data + weekday serves only to validate\n if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {\n return DateTime.invalid(\n \"mismatched weekday\",\n `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`\n );\n }\n\n return inst;\n }\n\n /**\n * Create a DateTime from an ISO 8601 string\n * @param {string} text - the ISO string\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone\n * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance\n * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromISO('2016-05-25T09:08:34.123')\n * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')\n * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})\n * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})\n * @example DateTime.fromISO('2016-W05-4')\n * @return {DateTime}\n */\n static fromISO(text, opts = {}) {\n const [vals, parsedZone] = parseISODate(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"ISO 8601\", text);\n }\n\n /**\n * Create a DateTime from an RFC 2822 string\n * @param {string} text - the RFC 2822 string\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.\n * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')\n * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')\n * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')\n * @return {DateTime}\n */\n static fromRFC2822(text, opts = {}) {\n const [vals, parsedZone] = parseRFC2822Date(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"RFC 2822\", text);\n }\n\n /**\n * Create a DateTime from an HTTP header date\n * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n * @param {string} text - the HTTP header date\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.\n * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.\n * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance\n * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')\n * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')\n * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994')\n * @return {DateTime}\n */\n static fromHTTP(text, opts = {}) {\n const [vals, parsedZone] = parseHTTPDate(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"HTTP\", opts);\n }\n\n /**\n * Create a DateTime from an input string and format string.\n * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).\n * @param {string} text - the string to parse\n * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone\n * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale\n * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @return {DateTime}\n */\n static fromFormat(text, fmt, opts = {}) {\n if (isUndefined(text) || isUndefined(fmt)) {\n throw new InvalidArgumentError(\"fromFormat requires an input string and a format\");\n }\n\n const { locale = null, numberingSystem = null } = opts,\n localeToUse = Locale.fromOpts({\n locale,\n numberingSystem,\n defaultToEN: true,\n }),\n [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt);\n if (invalid) {\n return DateTime.invalid(invalid);\n } else {\n return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset);\n }\n }\n\n /**\n * @deprecated use fromFormat instead\n */\n static fromString(text, fmt, opts = {}) {\n return DateTime.fromFormat(text, fmt, opts);\n }\n\n /**\n * Create a DateTime from a SQL date, time, or datetime\n * Defaults to en-US if no locale has been specified, regardless of the system's locale\n * @param {string} text - the string to parse\n * @param {Object} opts - options to affect the creation\n * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone\n * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one\n * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale\n * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system\n * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance\n * @example DateTime.fromSQL('2017-05-15')\n * @example DateTime.fromSQL('2017-05-15 09:12:34')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })\n * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })\n * @example DateTime.fromSQL('09:12:34.342')\n * @return {DateTime}\n */\n static fromSQL(text, opts = {}) {\n const [vals, parsedZone] = parseSQL(text);\n return parseDataToDateTime(vals, parsedZone, opts, \"SQL\", text);\n }\n\n /**\n * Create an invalid DateTime.\n * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent\n * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information\n * @return {DateTime}\n */\n static invalid(reason, explanation = null) {\n if (!reason) {\n throw new InvalidArgumentError(\"need to specify a reason the DateTime is invalid\");\n }\n\n const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);\n\n if (Settings.throwOnInvalid) {\n throw new InvalidDateTimeError(invalid);\n } else {\n return new DateTime({ invalid });\n }\n }\n\n /**\n * Check if an object is an instance of DateTime. Works across context boundaries\n * @param {object} o\n * @return {boolean}\n */\n static isDateTime(o) {\n return (o && o.isLuxonDateTime) || false;\n }\n\n // INFO\n\n /**\n * Get the value of unit.\n * @param {string} unit - a unit such as 'minute' or 'day'\n * @example DateTime.local(2017, 7, 4).get('month'); //=> 7\n * @example DateTime.local(2017, 7, 4).get('day'); //=> 4\n * @return {number}\n */\n get(unit) {\n return this[unit];\n }\n\n /**\n * Returns whether the DateTime is valid. Invalid DateTimes occur when:\n * * The DateTime was created from invalid calendar information, such as the 13th month or February 30\n * * The DateTime was created by an operation on another invalid date\n * @type {boolean}\n */\n get isValid() {\n return this.invalid === null;\n }\n\n /**\n * Returns an error code if this DateTime is invalid, or null if the DateTime is valid\n * @type {string}\n */\n get invalidReason() {\n return this.invalid ? this.invalid.reason : null;\n }\n\n /**\n * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid\n * @type {string}\n */\n get invalidExplanation() {\n return this.invalid ? this.invalid.explanation : null;\n }\n\n /**\n * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime\n *\n * @type {string}\n */\n get locale() {\n return this.isValid ? this.loc.locale : null;\n }\n\n /**\n * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime\n *\n * @type {string}\n */\n get numberingSystem() {\n return this.isValid ? this.loc.numberingSystem : null;\n }\n\n /**\n * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime\n *\n * @type {string}\n */\n get outputCalendar() {\n return this.isValid ? this.loc.outputCalendar : null;\n }\n\n /**\n * Get the time zone associated with this DateTime.\n * @type {Zone}\n */\n get zone() {\n return this._zone;\n }\n\n /**\n * Get the name of the time zone.\n * @type {string}\n */\n get zoneName() {\n return this.isValid ? this.zone.name : null;\n }\n\n /**\n * Get the year\n * @example DateTime.local(2017, 5, 25).year //=> 2017\n * @type {number}\n */\n get year() {\n return this.isValid ? this.c.year : NaN;\n }\n\n /**\n * Get the quarter\n * @example DateTime.local(2017, 5, 25).quarter //=> 2\n * @type {number}\n */\n get quarter() {\n return this.isValid ? Math.ceil(this.c.month / 3) : NaN;\n }\n\n /**\n * Get the month (1-12).\n * @example DateTime.local(2017, 5, 25).month //=> 5\n * @type {number}\n */\n get month() {\n return this.isValid ? this.c.month : NaN;\n }\n\n /**\n * Get the day of the month (1-30ish).\n * @example DateTime.local(2017, 5, 25).day //=> 25\n * @type {number}\n */\n get day() {\n return this.isValid ? this.c.day : NaN;\n }\n\n /**\n * Get the hour of the day (0-23).\n * @example DateTime.local(2017, 5, 25, 9).hour //=> 9\n * @type {number}\n */\n get hour() {\n return this.isValid ? this.c.hour : NaN;\n }\n\n /**\n * Get the minute of the hour (0-59).\n * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30\n * @type {number}\n */\n get minute() {\n return this.isValid ? this.c.minute : NaN;\n }\n\n /**\n * Get the second of the minute (0-59).\n * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52\n * @type {number}\n */\n get second() {\n return this.isValid ? this.c.second : NaN;\n }\n\n /**\n * Get the millisecond of the second (0-999).\n * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654\n * @type {number}\n */\n get millisecond() {\n return this.isValid ? this.c.millisecond : NaN;\n }\n\n /**\n * Get the week year\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2014, 12, 31).weekYear //=> 2015\n * @type {number}\n */\n get weekYear() {\n return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;\n }\n\n /**\n * Get the week number of the week year (1-52ish).\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2017, 5, 25).weekNumber //=> 21\n * @type {number}\n */\n get weekNumber() {\n return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;\n }\n\n /**\n * Get the day of the week.\n * 1 is Monday and 7 is Sunday\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2014, 11, 31).weekday //=> 4\n * @type {number}\n */\n get weekday() {\n return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;\n }\n\n /**\n * Get the ordinal (meaning the day of the year)\n * @example DateTime.local(2017, 5, 25).ordinal //=> 145\n * @type {number|DateTime}\n */\n get ordinal() {\n return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;\n }\n\n /**\n * Get the human readable short month name, such as 'Oct'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).monthShort //=> Oct\n * @type {string}\n */\n get monthShort() {\n return this.isValid ? Info.months(\"short\", { locObj: this.loc })[this.month - 1] : null;\n }\n\n /**\n * Get the human readable long month name, such as 'October'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).monthLong //=> October\n * @type {string}\n */\n get monthLong() {\n return this.isValid ? Info.months(\"long\", { locObj: this.loc })[this.month - 1] : null;\n }\n\n /**\n * Get the human readable short weekday, such as 'Mon'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon\n * @type {string}\n */\n get weekdayShort() {\n return this.isValid ? Info.weekdays(\"short\", { locObj: this.loc })[this.weekday - 1] : null;\n }\n\n /**\n * Get the human readable long weekday, such as 'Monday'.\n * Defaults to the system's locale if no locale has been specified\n * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday\n * @type {string}\n */\n get weekdayLong() {\n return this.isValid ? Info.weekdays(\"long\", { locObj: this.loc })[this.weekday - 1] : null;\n }\n\n /**\n * Get the UTC offset of this DateTime in minutes\n * @example DateTime.now().offset //=> -240\n * @example DateTime.utc().offset //=> 0\n * @type {number}\n */\n get offset() {\n return this.isValid ? +this.o : NaN;\n }\n\n /**\n * Get the short human name for the zone's current offset, for example \"EST\" or \"EDT\".\n * Defaults to the system's locale if no locale has been specified\n * @type {string}\n */\n get offsetNameShort() {\n if (this.isValid) {\n return this.zone.offsetName(this.ts, {\n format: \"short\",\n locale: this.locale,\n });\n } else {\n return null;\n }\n }\n\n /**\n * Get the long human name for the zone's current offset, for example \"Eastern Standard Time\" or \"Eastern Daylight Time\".\n * Defaults to the system's locale if no locale has been specified\n * @type {string}\n */\n get offsetNameLong() {\n if (this.isValid) {\n return this.zone.offsetName(this.ts, {\n format: \"long\",\n locale: this.locale,\n });\n } else {\n return null;\n }\n }\n\n /**\n * Get whether this zone's offset ever changes, as in a DST.\n * @type {boolean}\n */\n get isOffsetFixed() {\n return this.isValid ? this.zone.isUniversal : null;\n }\n\n /**\n * Get whether the DateTime is in a DST.\n * @type {boolean}\n */\n get isInDST() {\n if (this.isOffsetFixed) {\n return false;\n } else {\n return (\n this.offset > this.set({ month: 1, day: 1 }).offset ||\n this.offset > this.set({ month: 5 }).offset\n );\n }\n }\n\n /**\n * Returns true if this DateTime is in a leap year, false otherwise\n * @example DateTime.local(2016).isInLeapYear //=> true\n * @example DateTime.local(2013).isInLeapYear //=> false\n * @type {boolean}\n */\n get isInLeapYear() {\n return isLeapYear(this.year);\n }\n\n /**\n * Returns the number of days in this DateTime's month\n * @example DateTime.local(2016, 2).daysInMonth //=> 29\n * @example DateTime.local(2016, 3).daysInMonth //=> 31\n * @type {number}\n */\n get daysInMonth() {\n return daysInMonth(this.year, this.month);\n }\n\n /**\n * Returns the number of days in this DateTime's year\n * @example DateTime.local(2016).daysInYear //=> 366\n * @example DateTime.local(2013).daysInYear //=> 365\n * @type {number}\n */\n get daysInYear() {\n return this.isValid ? daysInYear(this.year) : NaN;\n }\n\n /**\n * Returns the number of weeks in this DateTime's year\n * @see https://en.wikipedia.org/wiki/ISO_week_date\n * @example DateTime.local(2004).weeksInWeekYear //=> 53\n * @example DateTime.local(2013).weeksInWeekYear //=> 52\n * @type {number}\n */\n get weeksInWeekYear() {\n return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;\n }\n\n /**\n * Returns the resolved Intl options for this DateTime.\n * This is useful in understanding the behavior of formatting methods\n * @param {Object} opts - the same options as toLocaleString\n * @return {Object}\n */\n resolvedLocaleOptions(opts = {}) {\n const { locale, numberingSystem, calendar } = Formatter.create(\n this.loc.clone(opts),\n opts\n ).resolvedOptions(this);\n return { locale, numberingSystem, outputCalendar: calendar };\n }\n\n // TRANSFORM\n\n /**\n * \"Set\" the DateTime's zone to UTC. Returns a newly-constructed DateTime.\n *\n * Equivalent to {@link DateTime#setZone}('utc')\n * @param {number} [offset=0] - optionally, an offset from UTC in minutes\n * @param {Object} [opts={}] - options to pass to `setZone()`\n * @return {DateTime}\n */\n toUTC(offset = 0, opts = {}) {\n return this.setZone(FixedOffsetZone.instance(offset), opts);\n }\n\n /**\n * \"Set\" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.\n *\n * Equivalent to `setZone('local')`\n * @return {DateTime}\n */\n toLocal() {\n return this.setZone(Settings.defaultZone);\n }\n\n /**\n * \"Set\" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.\n *\n * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.\n * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.\n * @param {Object} opts - options\n * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.\n * @return {DateTime}\n */\n setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {\n zone = normalizeZone(zone, Settings.defaultZone);\n if (zone.equals(this.zone)) {\n return this;\n } else if (!zone.isValid) {\n return DateTime.invalid(unsupportedZone(zone));\n } else {\n let newTS = this.ts;\n if (keepLocalTime || keepCalendarTime) {\n const offsetGuess = zone.offset(this.ts);\n const asObj = this.toObject();\n [newTS] = objToTS(asObj, offsetGuess, zone);\n }\n return clone(this, { ts: newTS, zone });\n }\n }\n\n /**\n * \"Set\" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.\n * @param {Object} properties - the properties to set\n * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })\n * @return {DateTime}\n */\n reconfigure({ locale, numberingSystem, outputCalendar } = {}) {\n const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });\n return clone(this, { loc });\n }\n\n /**\n * \"Set\" the locale. Returns a newly-constructed DateTime.\n * Just a convenient alias for reconfigure({ locale })\n * @example DateTime.local(2017, 5, 25).setLocale('en-GB')\n * @return {DateTime}\n */\n setLocale(locale) {\n return this.reconfigure({ locale });\n }\n\n /**\n * \"Set\" the values of specified units. Returns a newly-constructed DateTime.\n * You can only set units with this method; for \"setting\" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.\n * @param {Object} values - a mapping of units to numbers\n * @example dt.set({ year: 2017 })\n * @example dt.set({ hour: 8, minute: 30 })\n * @example dt.set({ weekday: 5 })\n * @example dt.set({ year: 2005, ordinal: 234 })\n * @return {DateTime}\n */\n set(values) {\n if (!this.isValid) return this;\n\n const normalized = normalizeObject(values, normalizeUnit),\n settingWeekStuff =\n !isUndefined(normalized.weekYear) ||\n !isUndefined(normalized.weekNumber) ||\n !isUndefined(normalized.weekday),\n containsOrdinal = !isUndefined(normalized.ordinal),\n containsGregorYear = !isUndefined(normalized.year),\n containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),\n containsGregor = containsGregorYear || containsGregorMD,\n definiteWeekDef = normalized.weekYear || normalized.weekNumber;\n\n if ((containsGregor || containsOrdinal) && definiteWeekDef) {\n throw new ConflictingSpecificationError(\n \"Can't mix weekYear/weekNumber units with year/month/day or ordinals\"\n );\n }\n\n if (containsGregorMD && containsOrdinal) {\n throw new ConflictingSpecificationError(\"Can't mix ordinal dates with month/day\");\n }\n\n let mixed;\n if (settingWeekStuff) {\n mixed = weekToGregorian({ ...gregorianToWeek(this.c), ...normalized });\n } else if (!isUndefined(normalized.ordinal)) {\n mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized });\n } else {\n mixed = { ...this.toObject(), ...normalized };\n\n // if we didn't set the day but we ended up on an overflow date,\n // use the last day of the right month\n if (isUndefined(normalized.day)) {\n mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);\n }\n }\n\n const [ts, o] = objToTS(mixed, this.o, this.zone);\n return clone(this, { ts, o });\n }\n\n /**\n * Add a period of time to this DateTime and return the resulting DateTime\n *\n * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.\n * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n * @example DateTime.now().plus(123) //~> in 123 milliseconds\n * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes\n * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow\n * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday\n * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min\n * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min\n * @return {DateTime}\n */\n plus(duration) {\n if (!this.isValid) return this;\n const dur = Duration.fromDurationLike(duration);\n return clone(this, adjustTime(this, dur));\n }\n\n /**\n * Subtract a period of time to this DateTime and return the resulting DateTime\n * See {@link DateTime#plus}\n * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()\n @return {DateTime}\n */\n minus(duration) {\n if (!this.isValid) return this;\n const dur = Duration.fromDurationLike(duration).negate();\n return clone(this, adjustTime(this, dur));\n }\n\n /**\n * \"Set\" this DateTime to the beginning of a unit of time.\n * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'\n * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'\n * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays\n * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'\n * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'\n * @return {DateTime}\n */\n startOf(unit) {\n if (!this.isValid) return this;\n const o = {},\n normalizedUnit = Duration.normalizeUnit(unit);\n switch (normalizedUnit) {\n case \"years\":\n o.month = 1;\n // falls through\n case \"quarters\":\n case \"months\":\n o.day = 1;\n // falls through\n case \"weeks\":\n case \"days\":\n o.hour = 0;\n // falls through\n case \"hours\":\n o.minute = 0;\n // falls through\n case \"minutes\":\n o.second = 0;\n // falls through\n case \"seconds\":\n o.millisecond = 0;\n break;\n case \"milliseconds\":\n break;\n // no default, invalid units throw in normalizeUnit()\n }\n\n if (normalizedUnit === \"weeks\") {\n o.weekday = 1;\n }\n\n if (normalizedUnit === \"quarters\") {\n const q = Math.ceil(this.month / 3);\n o.month = (q - 1) * 3 + 1;\n }\n\n return this.set(o);\n }\n\n /**\n * \"Set\" this DateTime to the end (meaning the last millisecond) of a unit of time\n * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.\n * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays\n * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'\n * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'\n * @return {DateTime}\n */\n endOf(unit) {\n return this.isValid\n ? this.plus({ [unit]: 1 })\n .startOf(unit)\n .minus(1)\n : this;\n }\n\n // OUTPUT\n\n /**\n * Returns a string representation of this DateTime formatted according to the specified format string.\n * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).\n * Defaults to en-US if no locale has been specified, regardless of the system's locale.\n * @param {string} fmt - the format string\n * @param {Object} opts - opts to override the configuration options on this DateTime\n * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'\n * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'\n * @example DateTime.now().toFormat('yyyy LLL dd', { locale: \"fr\" }) //=> '2017 avr. 22'\n * @example DateTime.now().toFormat(\"HH 'hours and' mm 'minutes'\") //=> '20 hours and 55 minutes'\n * @return {string}\n */\n toFormat(fmt, opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt)\n : INVALID;\n }\n\n /**\n * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.\n * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation\n * of the DateTime in the assigned locale.\n * Defaults to the system's locale if no locale has been specified\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat\n * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options\n * @param {Object} opts - opts to override the configuration options on this DateTime\n * @example DateTime.now().toLocaleString(); //=> 4/20/2017\n * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'\n * @example DateTime.now().toLocaleString({ locale: 'en-gb' }); //=> '20/04/2017'\n * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'\n * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'\n * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'\n * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'\n * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'\n * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'\n * @return {string}\n */\n toLocaleString(formatOpts = Formats.DATE_SHORT, opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this)\n : INVALID;\n }\n\n /**\n * Returns an array of format \"parts\", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.\n * Defaults to the system's locale if no locale has been specified\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts\n * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.\n * @example DateTime.now().toLocaleParts(); //=> [\n * //=> { type: 'day', value: '25' },\n * //=> { type: 'literal', value: '/' },\n * //=> { type: 'month', value: '05' },\n * //=> { type: 'literal', value: '/' },\n * //=> { type: 'year', value: '1982' }\n * //=> ]\n */\n toLocaleParts(opts = {}) {\n return this.isValid\n ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this)\n : [];\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime\n * @param {Object} opts - options\n * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.extendedZone=true] - add the time zone format extension\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'\n * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'\n * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'\n * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'\n * @return {string}\n */\n toISO({\n format = \"extended\",\n suppressSeconds = false,\n suppressMilliseconds = false,\n includeOffset = true,\n extendedZone = false,\n } = {}) {\n if (!this.isValid) {\n return null;\n }\n\n const ext = format === \"extended\";\n\n let c = toISODate(this, ext);\n c += \"T\";\n c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);\n return c;\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's date component\n * @param {Object} opts - options\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'\n * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'\n * @return {string}\n */\n toISODate({ format = \"extended\" } = {}) {\n if (!this.isValid) {\n return null;\n }\n\n return toISODate(this, format === \"extended\");\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's week date\n * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'\n * @return {string}\n */\n toISOWeekDate() {\n return toTechFormat(this, \"kkkk-'W'WW-c\");\n }\n\n /**\n * Returns an ISO 8601-compliant string representation of this DateTime's time component\n * @param {Object} opts - options\n * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0\n * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.extendedZone=true] - add the time zone format extension\n * @param {boolean} [opts.includePrefix=false] - include the `T` prefix\n * @param {string} [opts.format='extended'] - choose between the basic and extended format\n * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'\n * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'\n * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'\n * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'\n * @return {string}\n */\n toISOTime({\n suppressMilliseconds = false,\n suppressSeconds = false,\n includeOffset = true,\n includePrefix = false,\n extendedZone = false,\n format = \"extended\",\n } = {}) {\n if (!this.isValid) {\n return null;\n }\n\n let c = includePrefix ? \"T\" : \"\";\n return (\n c +\n toISOTime(\n this,\n format === \"extended\",\n suppressSeconds,\n suppressMilliseconds,\n includeOffset,\n extendedZone\n )\n );\n }\n\n /**\n * Returns an RFC 2822-compatible string representation of this DateTime\n * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'\n * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'\n * @return {string}\n */\n toRFC2822() {\n return toTechFormat(this, \"EEE, dd LLL yyyy HH:mm:ss ZZZ\", false);\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.\n * Specifically, the string conforms to RFC 1123.\n * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1\n * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'\n * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'\n * @return {string}\n */\n toHTTP() {\n return toTechFormat(this.toUTC(), \"EEE, dd LLL yyyy HH:mm:ss 'GMT'\");\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in SQL Date\n * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'\n * @return {string}\n */\n toSQLDate() {\n if (!this.isValid) {\n return null;\n }\n return toISODate(this, true);\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in SQL Time\n * @param {Object} opts - options\n * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'\n * @example DateTime.utc().toSQL() //=> '05:15:16.345'\n * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'\n * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'\n * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'\n * @return {string}\n */\n toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) {\n let fmt = \"HH:mm:ss.SSS\";\n\n if (includeZone || includeOffset) {\n if (includeOffsetSpace) {\n fmt += \" \";\n }\n if (includeZone) {\n fmt += \"z\";\n } else if (includeOffset) {\n fmt += \"ZZ\";\n }\n }\n\n return toTechFormat(this, fmt, true);\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for use in SQL DateTime\n * @param {Object} opts - options\n * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.\n * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'\n * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'\n * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'\n * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'\n * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'\n * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'\n * @return {string}\n */\n toSQL(opts = {}) {\n if (!this.isValid) {\n return null;\n }\n\n return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;\n }\n\n /**\n * Returns a string representation of this DateTime appropriate for debugging\n * @return {string}\n */\n toString() {\n return this.isValid ? this.toISO() : INVALID;\n }\n\n /**\n * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}\n * @return {number}\n */\n valueOf() {\n return this.toMillis();\n }\n\n /**\n * Returns the epoch milliseconds of this DateTime.\n * @return {number}\n */\n toMillis() {\n return this.isValid ? this.ts : NaN;\n }\n\n /**\n * Returns the epoch seconds of this DateTime.\n * @return {number}\n */\n toSeconds() {\n return this.isValid ? this.ts / 1000 : NaN;\n }\n\n /**\n * Returns the epoch seconds (as a whole number) of this DateTime.\n * @return {number}\n */\n toUnixInteger() {\n return this.isValid ? Math.floor(this.ts / 1000) : NaN;\n }\n\n /**\n * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.\n * @return {string}\n */\n toJSON() {\n return this.toISO();\n }\n\n /**\n * Returns a BSON serializable equivalent to this DateTime.\n * @return {Date}\n */\n toBSON() {\n return this.toJSDate();\n }\n\n /**\n * Returns a JavaScript object with this DateTime's year, month, day, and so on.\n * @param opts - options for generating the object\n * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output\n * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }\n * @return {Object}\n */\n toObject(opts = {}) {\n if (!this.isValid) return {};\n\n const base = { ...this.c };\n\n if (opts.includeConfig) {\n base.outputCalendar = this.outputCalendar;\n base.numberingSystem = this.loc.numberingSystem;\n base.locale = this.loc.locale;\n }\n return base;\n }\n\n /**\n * Returns a JavaScript Date equivalent to this DateTime.\n * @return {Date}\n */\n toJSDate() {\n return new Date(this.isValid ? this.ts : NaN);\n }\n\n // COMPARE\n\n /**\n * Return the difference between two DateTimes as a Duration.\n * @param {DateTime} otherDateTime - the DateTime to compare this one to\n * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.\n * @param {Object} opts - options that affect the creation of the Duration\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @example\n * var i1 = DateTime.fromISO('1982-05-25T09:45'),\n * i2 = DateTime.fromISO('1983-10-14T10:30');\n * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }\n * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }\n * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }\n * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }\n * @return {Duration}\n */\n diff(otherDateTime, unit = \"milliseconds\", opts = {}) {\n if (!this.isValid || !otherDateTime.isValid) {\n return Duration.invalid(\"created by diffing an invalid DateTime\");\n }\n\n const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts };\n\n const units = maybeArray(unit).map(Duration.normalizeUnit),\n otherIsLater = otherDateTime.valueOf() > this.valueOf(),\n earlier = otherIsLater ? this : otherDateTime,\n later = otherIsLater ? otherDateTime : this,\n diffed = diff(earlier, later, units, durOpts);\n\n return otherIsLater ? diffed.negate() : diffed;\n }\n\n /**\n * Return the difference between this DateTime and right now.\n * See {@link DateTime#diff}\n * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration\n * @param {Object} opts - options that affect the creation of the Duration\n * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use\n * @return {Duration}\n */\n diffNow(unit = \"milliseconds\", opts = {}) {\n return this.diff(DateTime.now(), unit, opts);\n }\n\n /**\n * Return an Interval spanning between this DateTime and another DateTime\n * @param {DateTime} otherDateTime - the other end point of the Interval\n * @return {Interval}\n */\n until(otherDateTime) {\n return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;\n }\n\n /**\n * Return whether this DateTime is in the same unit of time as another DateTime.\n * Higher-order units must also be identical for this function to return `true`.\n * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.\n * @param {DateTime} otherDateTime - the other DateTime\n * @param {string} unit - the unit of time to check sameness on\n * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day\n * @return {boolean}\n */\n hasSame(otherDateTime, unit) {\n if (!this.isValid) return false;\n\n const inputMs = otherDateTime.valueOf();\n const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true });\n return adjustedToZone.startOf(unit) <= inputMs && inputMs <= adjustedToZone.endOf(unit);\n }\n\n /**\n * Equality check\n * Two DateTimes are equal iff they represent the same millisecond, have the same zone and location, and are both valid.\n * To compare just the millisecond values, use `+dt1 === +dt2`.\n * @param {DateTime} other - the other DateTime\n * @return {boolean}\n */\n equals(other) {\n return (\n this.isValid &&\n other.isValid &&\n this.valueOf() === other.valueOf() &&\n this.zone.equals(other.zone) &&\n this.loc.equals(other.loc)\n );\n }\n\n /**\n * Returns a string representation of a this time relative to now, such as \"in two days\". Can only internationalize if your\n * platform supports Intl.RelativeTimeFormat. Rounds down by default.\n * @param {Object} options - options that affect the output\n * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.\n * @param {string} [options.style=\"long\"] - the style of units, must be \"long\", \"short\", or \"narrow\"\n * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of \"years\", \"quarters\", \"months\", \"weeks\", \"days\", \"hours\", \"minutes\", or \"seconds\"\n * @param {boolean} [options.round=true] - whether to round the numbers in the output.\n * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.\n * @param {string} options.locale - override the locale of this DateTime\n * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this\n * @example DateTime.now().plus({ days: 1 }).toRelative() //=> \"in 1 day\"\n * @example DateTime.now().setLocale(\"es\").toRelative({ days: 1 }) //=> \"dentro de 1 día\"\n * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: \"fr\" }) //=> \"dans 23 heures\"\n * @example DateTime.now().minus({ days: 2 }).toRelative() //=> \"2 days ago\"\n * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: \"hours\" }) //=> \"48 hours ago\"\n * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> \"1.5 days ago\"\n */\n toRelative(options = {}) {\n if (!this.isValid) return null;\n const base = options.base || DateTime.fromObject({}, { zone: this.zone }),\n padding = options.padding ? (this < base ? -options.padding : options.padding) : 0;\n let units = [\"years\", \"months\", \"days\", \"hours\", \"minutes\", \"seconds\"];\n let unit = options.unit;\n if (Array.isArray(options.unit)) {\n units = options.unit;\n unit = undefined;\n }\n return diffRelative(base, this.plus(padding), {\n ...options,\n numeric: \"always\",\n units,\n unit,\n });\n }\n\n /**\n * Returns a string representation of this date relative to today, such as \"yesterday\" or \"next month\".\n * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.\n * @param {Object} options - options that affect the output\n * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.\n * @param {string} options.locale - override the locale of this DateTime\n * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of \"years\", \"quarters\", \"months\", \"weeks\", or \"days\"\n * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this\n * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> \"tomorrow\"\n * @example DateTime.now().setLocale(\"es\").plus({ days: 1 }).toRelative() //=> \"\"mañana\"\n * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: \"fr\" }) //=> \"demain\"\n * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> \"2 days ago\"\n */\n toRelativeCalendar(options = {}) {\n if (!this.isValid) return null;\n\n return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, {\n ...options,\n numeric: \"auto\",\n units: [\"years\", \"months\", \"days\"],\n calendary: true,\n });\n }\n\n /**\n * Return the min of several date times\n * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum\n * @return {DateTime} the min DateTime, or undefined if called with no argument\n */\n static min(...dateTimes) {\n if (!dateTimes.every(DateTime.isDateTime)) {\n throw new InvalidArgumentError(\"min requires all arguments be DateTimes\");\n }\n return bestBy(dateTimes, (i) => i.valueOf(), Math.min);\n }\n\n /**\n * Return the max of several date times\n * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum\n * @return {DateTime} the max DateTime, or undefined if called with no argument\n */\n static max(...dateTimes) {\n if (!dateTimes.every(DateTime.isDateTime)) {\n throw new InvalidArgumentError(\"max requires all arguments be DateTimes\");\n }\n return bestBy(dateTimes, (i) => i.valueOf(), Math.max);\n }\n\n // MISC\n\n /**\n * Explain how a string would be parsed by fromFormat()\n * @param {string} text - the string to parse\n * @param {string} fmt - the format the string is expected to be in (see description)\n * @param {Object} options - options taken by fromFormat()\n * @return {Object}\n */\n static fromFormatExplain(text, fmt, options = {}) {\n const { locale = null, numberingSystem = null } = options,\n localeToUse = Locale.fromOpts({\n locale,\n numberingSystem,\n defaultToEN: true,\n });\n return explainFromTokens(localeToUse, text, fmt);\n }\n\n /**\n * @deprecated use fromFormatExplain instead\n */\n static fromStringExplain(text, fmt, options = {}) {\n return DateTime.fromFormatExplain(text, fmt, options);\n }\n\n // FORMAT PRESETS\n\n /**\n * {@link DateTime#toLocaleString} format like 10/14/1983\n * @type {Object}\n */\n static get DATE_SHORT() {\n return Formats.DATE_SHORT;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'\n * @type {Object}\n */\n static get DATE_MED() {\n return Formats.DATE_MED;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'\n * @type {Object}\n */\n static get DATE_MED_WITH_WEEKDAY() {\n return Formats.DATE_MED_WITH_WEEKDAY;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'October 14, 1983'\n * @type {Object}\n */\n static get DATE_FULL() {\n return Formats.DATE_FULL;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'\n * @type {Object}\n */\n static get DATE_HUGE() {\n return Formats.DATE_HUGE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_SIMPLE() {\n return Formats.TIME_SIMPLE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_WITH_SECONDS() {\n return Formats.TIME_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_WITH_SHORT_OFFSET() {\n return Formats.TIME_WITH_SHORT_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get TIME_WITH_LONG_OFFSET() {\n return Formats.TIME_WITH_LONG_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_SIMPLE() {\n return Formats.TIME_24_SIMPLE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_WITH_SECONDS() {\n return Formats.TIME_24_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_WITH_SHORT_OFFSET() {\n return Formats.TIME_24_WITH_SHORT_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.\n * @type {Object}\n */\n static get TIME_24_WITH_LONG_OFFSET() {\n return Formats.TIME_24_WITH_LONG_OFFSET;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_SHORT() {\n return Formats.DATETIME_SHORT;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_SHORT_WITH_SECONDS() {\n return Formats.DATETIME_SHORT_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_MED() {\n return Formats.DATETIME_MED;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_MED_WITH_SECONDS() {\n return Formats.DATETIME_MED_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_MED_WITH_WEEKDAY() {\n return Formats.DATETIME_MED_WITH_WEEKDAY;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_FULL() {\n return Formats.DATETIME_FULL;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_FULL_WITH_SECONDS() {\n return Formats.DATETIME_FULL_WITH_SECONDS;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_HUGE() {\n return Formats.DATETIME_HUGE;\n }\n\n /**\n * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.\n * @type {Object}\n */\n static get DATETIME_HUGE_WITH_SECONDS() {\n return Formats.DATETIME_HUGE_WITH_SECONDS;\n }\n}\n\n/**\n * @private\n */\nexport function friendlyDateTime(dateTimeish) {\n if (DateTime.isDateTime(dateTimeish)) {\n return dateTimeish;\n } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {\n return DateTime.fromJSDate(dateTimeish);\n } else if (dateTimeish && typeof dateTimeish === \"object\") {\n return DateTime.fromObject(dateTimeish);\n } else {\n throw new InvalidArgumentError(\n `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`\n );\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n/**\n * Tag that allows expressions to be used in localized non-HTML template\n * strings.\n *\n * Example: msg(str`Hello ${this.user}!`);\n *\n * The Lit html tag can also be used for this purpose, but HTML will need to be\n * escaped, and there is a small overhead for HTML parsing.\n *\n * Untagged template strings with expressions aren't supported by lit-localize\n * because they don't allow for values to be captured at runtime.\n */\nconst _str = (strings, ...values) => ({\n strTag: true,\n strings,\n values,\n});\nexport const str = _str;\nexport const isStrTagged = (val) => typeof val !== 'string' && 'strTag' in val;\n/**\n * Render the result of a `str` tagged template to a string. Note we don't need\n * to do this for Lit templates, since Lit itself handles rendering.\n */\nexport const joinStringsAndValues = (strings, values, valueOrder) => {\n let concat = strings[0];\n for (let i = 1; i < strings.length; i++) {\n concat += values[valueOrder ? valueOrder[i - 1] : i - 1];\n concat += strings[i];\n }\n return concat;\n};\n//# sourceMappingURL=str-tag.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport { isStrTagged, joinStringsAndValues } from './str-tag.js';\n/**\n * Default identity msg implementation. Simply returns the input template with\n * no awareness of translations. If the template is str-tagged, returns it in\n * string form.\n */\nexport const defaultMsg = ((template) => isStrTagged(template)\n ? joinStringsAndValues(template.strings, template.values)\n : template);\n//# sourceMappingURL=default-msg.js.map","/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nexport class Deferred {\n constructor() {\n this.settled = false;\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n resolve(value) {\n this.settled = true;\n this._resolve(value);\n }\n reject(error) {\n this.settled = true;\n this._reject(error);\n }\n}\n//# sourceMappingURL=deferred.js.map","/**\n * @license\n * Copyright 2014 Travis Webb\n * SPDX-License-Identifier: MIT\n */\n// This module is derived from the file:\n// https://github.com/tjwebb/fnv-plus/blob/1e2ce68a07cb7dd4c3c85364f3d8d96c95919474/index.js#L309\n//\n// Changes:\n// - Only the _hash64_1a_fast function is included.\n// - Removed loop unrolling.\n// - Converted to TypeScript ES module.\n// - var -> let/const\n//\n// TODO(aomarks) Upstream improvements to https://github.com/tjwebb/fnv-plus/.\nconst hl = [];\nfor (let i = 0; i < 256; i++) {\n hl[i] = ((i >> 4) & 15).toString(16) + (i & 15).toString(16);\n}\n/**\n * Perform a FNV-1A 64-bit hash of the given string (as UTF-16 code units), and\n * return a hexadecimal digest (left zero padded to 16 characters).\n *\n * @see {@link http://tools.ietf.org/html/draft-eastlake-fnv-06}\n */\nexport function fnv1a64(str) {\n let t0 = 0, v0 = 0x2325, t1 = 0, v1 = 0x8422, t2 = 0, v2 = 0x9ce4, t3 = 0, v3 = 0xcbf2;\n for (let i = 0; i < str.length; i++) {\n v0 ^= str.charCodeAt(i);\n t0 = v0 * 435;\n t1 = v1 * 435;\n t2 = v2 * 435;\n t3 = v3 * 435;\n t2 += v0 << 8;\n t3 += v1 << 8;\n t1 += t0 >>> 16;\n v0 = t0 & 65535;\n t2 += t1 >>> 16;\n v1 = t1 & 65535;\n v3 = (t3 + (t2 >>> 16)) & 65535;\n v2 = t2 & 65535;\n }\n return (hl[v3 >> 8] +\n hl[v3 & 255] +\n hl[v2 >> 8] +\n hl[v2 & 255] +\n hl[v1 >> 8] +\n hl[v1 & 255] +\n hl[v0 >> 8] +\n hl[v0 & 255]);\n}\n//# sourceMappingURL=fnv1a64.js.map","/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport { fnv1a64 } from './fnv1a64.js';\n/**\n * Delimiter used between each template string component before hashing. Used to\n * prevent e.g. \"foobar\" and \"foo${baz}bar\" from sharing a hash.\n *\n * This is the \"record separator\" ASCII character.\n */\nexport const HASH_DELIMITER = '\\x1e';\n/**\n * Id prefix on html-tagged templates to distinguish e.g. `x` from\n * html`x`.\n */\nconst HTML_PREFIX = 'h';\n/**\n * Id prefix on plain string templates to distinguish e.g. `x` from\n * html`x`.\n */\nconst STRING_PREFIX = 's';\n/**\n * Generate a unique ID for a lit-localize message.\n *\n * Example:\n * Template: html`Hello ${who}!`\n * Params: [\"Hello \", \"!\"], true\n * Output: h82ccc38d4d46eaa9\n *\n * The ID is constructed as:\n *\n * [0] Kind of template: [h]tml or [s]tring.\n * [1,16] 64-bit FNV-1a hash hex digest of the template strings, as UTF-16\n * code points, delineated by an ASCII \"record separator\" character.\n *\n * We choose FNV-1a because:\n *\n * 1. It's pretty fast (e.g. much faster than SHA-1).\n * 2. It's pretty small (0.25 KiB minified + brotli).\n * 3. We don't require cryptographic security, and 64 bits should give\n * sufficient collision resistance for any one application. Worst\n * case, we will always detect collisions during analysis.\n * 4. We can't use Web Crypto API (e.g. SHA-1), because it's asynchronous.\n * 5. It's a well known non-cryptographic hash with implementations in many\n * languages.\n * 6. There was an existing JavaScript implementation that doesn't require\n * BigInt, for IE11 compatibility.\n */\nexport function generateMsgId(strings, isHtmlTagged) {\n return ((isHtmlTagged ? HTML_PREFIX : STRING_PREFIX) +\n fnv1a64(typeof strings === 'string' ? strings : strings.join(HASH_DELIMITER)));\n}\n//# sourceMappingURL=id-generation.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport { defaultMsg } from './default-msg.js';\nimport { joinStringsAndValues } from './str-tag.js';\nimport { generateMsgId } from './id-generation.js';\nconst expressionOrders = new WeakMap();\nconst hashCache = new Map();\nexport function runtimeMsg(templates, template, options) {\n if (templates) {\n const id = options?.id ?? generateId(template);\n const localized = templates[id];\n if (localized) {\n if (typeof localized === 'string') {\n // E.g. \"Hello World!\"\n return localized;\n }\n else if ('strTag' in localized) {\n // E.g. str`Hello ${name}!`\n //\n // Localized templates have ${number} in place of real template\n // expressions. They can't have real template values, because the\n // variable scope would be wrong. The number tells us the index of the\n // source value to substitute in its place, because expressions can be\n // moved to a different position during translation.\n return joinStringsAndValues(localized.strings, \n // Cast `template` because its type wasn't automatically narrowed (but\n // we know it must be the same type as `localized`).\n template.values, localized.values);\n }\n else {\n // E.g. html`Hello ${name}!`\n //\n // We have to keep our own mapping of expression ordering because we do\n // an in-place update of `values`, and otherwise we'd lose ordering for\n // subsequent renders.\n let order = expressionOrders.get(localized);\n if (order === undefined) {\n order = localized.values;\n expressionOrders.set(localized, order);\n }\n return {\n ...localized,\n values: order.map((i) => template.values[i]),\n };\n }\n }\n }\n return defaultMsg(template);\n}\nfunction generateId(template) {\n const strings = typeof template === 'string' ? template : template.strings;\n let id = hashCache.get(strings);\n if (id === undefined) {\n id = generateMsgId(strings, typeof template !== 'string' && !('strTag' in template));\n hashCache.set(strings, id);\n }\n return id;\n}\n//# sourceMappingURL=runtime-msg.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport { _installMsgImplementation } from '../lit-localize.js';\nimport { Deferred } from '../internal/deferred.js';\nimport { LOCALE_STATUS_EVENT } from '../internal/locale-status-event.js';\nimport { runtimeMsg } from '../internal/runtime-msg.js';\n/**\n * Dispatch a \"lit-localize-status\" event to `window` with the given detail.\n */\nfunction dispatchStatusEvent(detail) {\n window.dispatchEvent(new CustomEvent(LOCALE_STATUS_EVENT, { detail }));\n}\nlet activeLocale = '';\nlet loadingLocale;\nlet sourceLocale;\nlet validLocales;\nlet loadLocale;\nlet templates;\nlet loading = new Deferred();\n// The loading promise must be initially resolved, because that's what we should\n// return if the user immediately calls setLocale(sourceLocale).\nloading.resolve();\nlet requestId = 0;\n/**\n * Set configuration parameters for lit-localize when in runtime mode. Returns\n * an object with functions:\n *\n * - `getLocale`: Return the active locale code.\n * - `setLocale`: Set the active locale code.\n *\n * Throws if called more than once.\n */\nexport const configureLocalization = (config) => {\n _installMsgImplementation(((template, options) => runtimeMsg(templates, template, options)));\n activeLocale = sourceLocale = config.sourceLocale;\n validLocales = new Set(config.targetLocales);\n validLocales.add(config.sourceLocale);\n loadLocale = config.loadLocale;\n return { getLocale, setLocale };\n};\n/**\n * Return the active locale code.\n */\nconst getLocale = () => {\n return activeLocale;\n};\n/**\n * Set the active locale code, and begin loading templates for that locale using\n * the `loadLocale` function that was passed to `configureLocalization`. Returns\n * a promise that resolves when the next locale is ready to be rendered.\n *\n * Note that if a second call to `setLocale` is made while the first requested\n * locale is still loading, then the second call takes precedence, and the\n * promise returned from the first call will resolve when second locale is\n * ready. If you need to know whether a particular locale was loaded, check\n * `getLocale` after the promise resolves.\n *\n * Throws if the given locale is not contained by the configured `sourceLocale`\n * or `targetLocales`.\n */\nconst setLocale = (newLocale) => {\n if (newLocale === (loadingLocale ?? activeLocale)) {\n return loading.promise;\n }\n if (!validLocales || !loadLocale) {\n throw new Error('Internal error');\n }\n if (!validLocales.has(newLocale)) {\n throw new Error('Invalid locale code');\n }\n requestId++;\n const thisRequestId = requestId;\n loadingLocale = newLocale;\n if (loading.settled) {\n loading = new Deferred();\n }\n dispatchStatusEvent({ status: 'loading', loadingLocale: newLocale });\n const localePromise = newLocale === sourceLocale\n ? // We could switch to the source locale synchronously, but we prefer to\n // queue it on a microtask so that switching locales is consistently\n // asynchronous.\n Promise.resolve({ templates: undefined })\n : loadLocale(newLocale);\n localePromise.then((mod) => {\n if (requestId === thisRequestId) {\n activeLocale = newLocale;\n loadingLocale = undefined;\n templates = mod.templates;\n dispatchStatusEvent({ status: 'ready', readyLocale: newLocale });\n loading.resolve();\n }\n // Else another locale was requested in the meantime. Don't resolve or\n // reject, because the newer load call is going to use the same promise.\n // Note the user can call getLocale() after the promise resolves if they\n // need to check if the locale is still the one they expected to load.\n }, (err) => {\n if (requestId === thisRequestId) {\n dispatchStatusEvent({\n status: 'error',\n errorLocale: newLocale,\n errorMessage: err.toString(),\n });\n loading.reject(err);\n }\n });\n return loading.promise;\n};\n//# sourceMappingURL=runtime.js.map","/**\n * @license\n * Copyright 2021 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n/**\n * Name of the event dispatched to `window` whenever a locale change starts,\n * finishes successfully, or fails. Only relevant to runtime mode.\n *\n * The `detail` of this event is an object with a `status` string that can be:\n * \"loading\", \"ready\", or \"error\", along with the relevant locale code, and\n * error message if applicable.\n *\n * You can listen for this event to know when your application should be\n * re-rendered following a locale change. See also the Localized mixin, which\n * automatically re-renders LitElement classes using this event.\n */\nexport const LOCALE_STATUS_EVENT = 'lit-localize-status';\n//# sourceMappingURL=locale-status-event.js.map","/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport { defaultMsg } from './internal/default-msg.js';\nexport * from './internal/locale-status-event.js';\nexport * from './internal/str-tag.js';\nexport * from './internal/types.js';\n// TODO(aomarks) In a future breaking version, remove these imports so that the\n// bulk of the code isn't included in bundles by default. In particular imagine\n// the component library use-case where msg() calls are made, but there is no\n// need to actually initialize any of the localization runtime.\nexport * from './internal/localized-controller.js';\nexport * from './internal/localized-decorator.js';\nexport * from './init/runtime.js';\nexport * from './init/transform.js';\n/**\n * Make a string or lit-html template localizable.\n *\n * @param template A string, a lit-html template, or a function that returns\n * either a string or lit-html template.\n * @param options Optional configuration object with the following properties:\n * - id: Optional project-wide unique identifier for this template. If\n * omitted, an id will be automatically generated from the template strings.\n * - desc: Optional description\n */\nexport let msg = defaultMsg;\nlet installed = false;\n/**\n * Internal only. Do not use this function.\n *\n * Installs an implementation of the msg function to replace the default\n * identity function. Throws if called more than once.\n *\n * @internal\n */\nexport function _installMsgImplementation(impl) {\n if (installed) {\n throw new Error('lit-localize can only be configured once');\n }\n msg = impl;\n installed = true;\n}\n//# sourceMappingURL=lit-localize.js.map","// Do not modify this file by hand!\n// Re-generate this file by running lit-localize.\n\n/**\n * The locale code that templates in this source code are written in.\n */\nexport const sourceLocale = `en`;\n\n/**\n * The other locale codes that this application is localized into. Sorted\n * lexicographically.\n */\nexport const targetLocales = [`es`, `fr`, `pt`] as const;\n\n/**\n * All valid project locale codes. Sorted lexicographically.\n */\nexport const allLocales = [`en`, `es`, `fr`, `pt`] as const;\n","import { property } from 'lit/decorators.js';\nimport {\n fetchResults,\n getUrl,\n getAssets,\n Asset,\n WebResponse,\n postUrl,\n postJSON,\n postForm,\n getCookie,\n} from '../utils';\nimport {\n ContactField,\n ContactGroup,\n CompletionOption,\n CompletionSchema,\n KeyedAssets,\n CustomEventType,\n Workspace,\n User,\n} from '../interfaces';\nimport { RapidElement } from '../RapidElement';\nimport { lru } from 'tiny-lru';\nimport { DateTime } from 'luxon';\nimport { css, html } from 'lit';\nimport { configureLocalization } from '@lit/localize';\nimport { sourceLocale, targetLocales } from '../locales/locale-codes';\n\nconst { setLocale } = configureLocalization({\n sourceLocale,\n targetLocales,\n loadLocale: locale => import(`./locales/${locale}.js`),\n});\n\nexport class Store extends RapidElement {\n public static get styles() {\n return css`\n :host {\n position: fixed;\n z-index: 1000;\n text-align: center;\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n top: 0.5em;\n }\n `;\n }\n\n settings = {};\n\n @property({ type: Number })\n ttl = 60000;\n\n @property({ type: Number })\n max = 20;\n\n @property({ type: Boolean })\n ready = false;\n\n @property({ type: Boolean })\n loader = false;\n\n @property({ type: String, attribute: 'completion' })\n completionEndpoint: string;\n\n @property({ type: String, attribute: 'fields' })\n fieldsEndpoint: string;\n\n @property({ type: String, attribute: 'groups' })\n groupsEndpoint: string;\n\n @property({ type: String, attribute: 'globals' })\n globalsEndpoint: string;\n\n @property({ type: String, attribute: 'languages' })\n languagesEndpoint: string;\n\n @property({ type: String, attribute: 'workspace' })\n workspaceEndpoint: string;\n\n @property({ type: String, attribute: 'users' })\n usersEndpoint: string;\n\n @property({ type: Object, attribute: false })\n private schema: CompletionSchema;\n\n @property({ type: Object, attribute: false })\n private fnOptions: CompletionOption[];\n\n @property({ type: Object, attribute: false })\n private keyedAssets: KeyedAssets = {};\n\n private locale = [...navigator.languages];\n\n private fields: { [key: string]: ContactField } = {};\n private groups: { [uuid: string]: ContactGroup } = {};\n private languages: any = {};\n private users: User[];\n private workspace: Workspace;\n private featuredFields: ContactField[] = [];\n\n // http promise to monitor for completeness\n public initialHttpComplete: Promise;\n\n private cache: any;\n\n public getLocale() {\n return this.locale[0];\n }\n\n public clearCache() {\n this.cache = lru(this.max, this.ttl);\n }\n\n public reset() {\n this.ready = false;\n this.clearCache();\n this.settings = JSON.parse(getCookie('settings') || '{}');\n\n /* \n // This will create a shorthand unit\n this.humanizer.addLanguage(\"en\", {\n y: () => \"y\",\n mo: () => \"mo\",\n w: () => \"w\",\n d: () => \"d\",\n h: () => \"h\",\n m: () => \"m\",\n s: () => \"s\",\n ms: () => \"ms\",\n decimal: \".\",\n });\n */\n\n const fetches = [];\n if (this.completionEndpoint) {\n fetches.push(\n getUrl(this.completionEndpoint).then(response => {\n this.schema = response.json['context'] as CompletionSchema;\n this.fnOptions = response.json['functions'] as CompletionOption[];\n })\n );\n }\n\n if (this.fieldsEndpoint) {\n fetches.push(this.refreshFields());\n }\n\n if (this.globalsEndpoint) {\n fetches.push(\n getAssets(this.globalsEndpoint).then((assets: Asset[]) => {\n this.keyedAssets['globals'] = assets.map((asset: Asset) => asset.key);\n })\n );\n }\n\n if (this.languagesEndpoint) {\n fetches.push(\n getAssets(this.languagesEndpoint).then((results: any[]) => {\n // convert array of objects to lookup\n this.languages = results.reduce(function (\n languages: any,\n result: any\n ) {\n languages[result.value] = result.name;\n return languages;\n },\n {});\n })\n );\n }\n\n if (this.groupsEndpoint) {\n fetches.push(\n getAssets(this.groupsEndpoint).then((groups: any[]) => {\n groups.forEach((group: any) => {\n this.groups[group.uuid] = group;\n });\n })\n );\n }\n\n if (this.workspaceEndpoint) {\n fetches.push(\n getUrl(this.workspaceEndpoint).then((response: WebResponse) => {\n this.workspace = response.json;\n const lang = response.headers.get('content-language');\n if (lang) {\n this.locale = [lang, ...this.locale];\n }\n })\n );\n }\n\n if (this.usersEndpoint) {\n fetches.push(\n getAssets(this.usersEndpoint).then((users: any[]) => {\n this.users = users;\n })\n );\n }\n\n this.initialHttpComplete = Promise.all(fetches);\n\n this.initialHttpComplete.then(() => {\n this.ready = true;\n });\n }\n\n public getAssignableUsers() {\n return this.users.filter((user: User) =>\n ['administrator', 'editor', 'agent'].includes(user.role)\n );\n }\n\n public getUser(email: string) {\n return this.users.find((user: User) => user.email === email);\n }\n\n public firstUpdated() {\n this.reset();\n }\n\n public getLanguageCode() {\n if (this.locale.length > 0) {\n return this.locale[0].split('-')[0];\n }\n return 'en';\n }\n\n public refreshGlobals() {\n getAssets(this.globalsEndpoint).then((assets: Asset[]) => {\n this.keyedAssets['globals'] = assets.map((asset: Asset) => asset.key);\n });\n }\n\n public refreshFields() {\n return getAssets(this.fieldsEndpoint).then((assets: Asset[]) => {\n this.keyedAssets['fields'] = [];\n this.featuredFields = [];\n\n assets.forEach((field: ContactField) => {\n this.keyedAssets['fields'].push(field.key);\n this.fields[field.key] = field;\n if (field.featured) {\n this.featuredFields.push(field);\n }\n });\n\n this.featuredFields.sort((a, b) => {\n return b.priority - a.priority;\n });\n\n this.keyedAssets['fields'].sort();\n\n this.fireCustomEvent(CustomEventType.StoreUpdated, {\n url: this.fieldsEndpoint,\n data: this.keyedAssets['fields'],\n });\n });\n }\n\n public getShortDuration(scheduled: DateTime, compareDate: DateTime = null) {\n const now = compareDate || DateTime.now();\n return scheduled\n .setLocale(this.locale[0])\n .toRelative({ base: now, style: 'long' });\n }\n\n public getShortDurationFromIso(isoDateA: string, isoDateB: string = null) {\n const scheduled = DateTime.fromISO(isoDateA);\n const now = isoDateB ? DateTime.fromISO(isoDateB) : DateTime.now();\n return this.getShortDuration(scheduled, now);\n }\n\n public setKeyedAssets(name: string, values: string[]): void {\n this.keyedAssets[name] = values;\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n if (changedProperties.has('ready') && this.ready) {\n const locale = this.getLanguageCode();\n const target = targetLocales.find(\n targetLocale => targetLocale === locale\n );\n\n if (target) {\n setLocale(target);\n }\n }\n }\n\n public getCompletionSchema(): CompletionSchema {\n return this.schema;\n }\n\n public getFunctions(): CompletionOption[] {\n return this.fnOptions;\n }\n\n public getKeyedAssets(): KeyedAssets {\n return this.keyedAssets;\n }\n\n public getFieldKeys(): string[] {\n return this.keyedAssets['fields'] || [];\n }\n\n public getContactField(key: string): ContactField {\n return this.fields[key];\n }\n\n public getFeaturedFields(): ContactField[] {\n return this.featuredFields;\n }\n\n public getLanguageName(iso: string) {\n return this.languages[iso];\n }\n\n public isDynamicGroup(uuid: string): boolean {\n const group = this.groups[uuid];\n // we treat missing groups as dynamic since the\n // api excludes initializing groups\n if (!group) {\n console.warn('No group for ' + uuid);\n }\n\n if (!group || group.query) {\n return true;\n }\n return false;\n }\n\n public getWorkspace(): Workspace {\n return this.workspace;\n }\n\n public formatDate(dateString: string) {\n return DateTime.fromISO(dateString)\n .setLocale(this.getLocale())\n .toLocaleString(DateTime.DATETIME_SHORT);\n }\n\n public postJSON(url: string, payload: any = '') {\n return postJSON(url, payload);\n }\n\n public postForm(url: string, payload: any | FormData) {\n return postForm(url, payload);\n }\n\n public postUrl(\n url: string,\n payload: any = '',\n headers: any = {},\n contentType = null\n ) {\n return postUrl(url, payload, headers, contentType);\n }\n\n public getUrl(\n url: string,\n options?: {\n force?: boolean;\n controller?: AbortController;\n headers?: { [key: string]: string };\n }\n ): Promise {\n options = options || {};\n if (!options.force && this.cache.has(url)) {\n return new Promise(resolve => {\n resolve(this.cache.get(url));\n });\n }\n\n return getUrl(url, options.controller, options.headers || {}).then(\n (response: WebResponse) => {\n return new Promise((resolve, reject) => {\n if (response.status >= 200 && response.status <= 300) {\n this.cache.set(url, response);\n resolve(response);\n } else {\n reject('Status: ' + response.status);\n }\n });\n }\n );\n }\n\n private pendingResolves = {};\n\n /**\n * Fetches all of the results for a given API endpoint with caching\n * @param url\n */\n public getResults(\n url: string,\n options?: { force?: boolean }\n ): Promise {\n options = options || {};\n const key = 'results_' + url;\n const results = this.cache.get(key);\n\n if (!options.force && results) {\n return new Promise(resolve => {\n resolve(results);\n });\n }\n\n return new Promise(resolve => {\n const pending = this.pendingResolves[url] || [];\n pending.push(resolve);\n this.pendingResolves[url] = pending;\n if (pending.length <= 1) {\n fetchResults(url).then((results: any[]) => {\n this.cache.set(key, results);\n const pending = this.pendingResolves[url] || [];\n while (pending.length > 0) {\n const resolve = pending.pop();\n resolve(results);\n }\n });\n }\n });\n }\n\n public fetching: { [url: string]: number } = {};\n\n public updateCache(url: string, data: any) {\n this.cache.set(url, data);\n this.fireCustomEvent(CustomEventType.StoreUpdated, { url, data });\n }\n\n public makeRequest(\n url: string,\n options?: { force?: boolean; prepareData?: (data: any) => any }\n ) {\n const previousRequest = this.fetching[url];\n const now = new Date().getTime();\n // if the request was recently made, don't do anything\n if (previousRequest && now - previousRequest < 500) {\n return;\n }\n\n this.fetching[url] = now;\n options = options || {};\n const cached = this.cache.get(url);\n if (cached && !options.force) {\n this.fireCustomEvent(CustomEventType.StoreUpdated, { url, data: cached });\n } else {\n fetchResults(url).then(data => {\n if (!data) {\n delete this.fetching[url];\n return;\n }\n\n data = options.prepareData ? options.prepareData(data) : data;\n this.cache.set(url, data);\n this.fireCustomEvent(CustomEventType.StoreUpdated, { url, data });\n delete this.fetching[url];\n });\n }\n }\n\n public get(key: string, defaultValue: any = null) {\n return this.settings[key] || defaultValue;\n }\n\n public set(key: string, value: string) {\n this.settings[key] = value;\n // not sure yet if we really want to perist these\n // setCookie(COOKIE_KEYS.SETTINGS, JSON.stringify(this.settings), '/');\n }\n\n public render() {\n if (!this.ready && this.loader) {\n return html``;\n }\n }\n}\n","import { TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { RapidElement, EventHandler } from '../RapidElement';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport {\n getClasses,\n getScrollParent,\n isElementVisible,\n throttle,\n} from '../utils';\n\nexport class Options extends RapidElement {\n static get styles() {\n return css`\n .options-container {\n background: var(--color-options-bg);\n user-select: none;\n border-radius: var(--curvature-widget);\n overflow: hidden;\n margin-top: var(--options-margin-top);\n display: flex;\n flex-direction: column;\n transform: scaleY(0.5) translateY(-5em);\n transition: transform var(--transition-speed)\n cubic-bezier(0.71, 0.18, 0.61, 1.33),\n opacity var(--transition-speed) cubic-bezier(0.71, 0.18, 0.61, 1.33);\n opacity: 0;\n border: 1px transparent;\n }\n\n .shadow {\n box-shadow: var(--options-shadow);\n }\n\n .anchored {\n position: fixed;\n }\n\n :host([block]) .options-container {\n flex-grow: 1;\n height: 100%;\n border: none;\n }\n\n :host([block]) .options-scroll {\n height: 100%;\n visibility: visible;\n overflow-y: auto;\n flex-grow: 1;\n -webkit-mask-image: -webkit-radial-gradient(white, black);\n }\n\n :host([block]) {\n border-radius: var(--curvature);\n display: block;\n height: 100%;\n }\n\n :host([block]) .shadow {\n box-shadow: var(--options-block-shadow);\n }\n\n .bordered {\n border: 1px solid var(--color-widget-border) !important;\n }\n\n :host([block]) .options {\n margin-bottom: 1.5em;\n }\n\n .options-scroll {\n display: flex;\n flex-direction: column;\n }\n\n :host([collapsed]) temba-icon {\n flex-grow: 1;\n margin-right: 0px !important;\n padding-top: 0.25em;\n padding-bottom: 0.25em;\n }\n\n :host([collapsed]) .name {\n display: none;\n }\n\n :host([collapsed]) .count {\n display: none;\n }\n\n .options {\n border-radius: var(--curvature-widget);\n overflow-y: auto;\n max-height: 225px;\n border: none;\n }\n\n .show {\n transform: scaleY(1) translateY(0);\n border: 1px solid var(--color-widget-border);\n opacity: 1;\n z-index: 1;\n }\n\n .option {\n font-size: var(--temba-options-font-size);\n padding: 5px 10px;\n border-radius: 4px;\n margin: 0.3em;\n cursor: pointer;\n color: var(--color-text-dark);\n }\n\n .option * {\n user-select: none;\n -webkit-user-select: none;\n -ms-user-select: none;\n overflow-wrap: break-word;\n word-wrap: break-word;\n -ms-word-break: break-all;\n word-break: break-word;\n -ms-hyphens: auto;\n -moz-hyphens: auto;\n -webkit-hyphens: auto;\n hyphens: auto;\n }\n\n .option .detail {\n font-size: 85%;\n color: rgba(0, 0, 0, 0.4);\n }\n\n code {\n background: rgba(0, 0, 0, 0.05);\n padding: 1px 5px;\n border-radius: var(--curvature-widget);\n }\n\n :host([block]) {\n position: relative;\n }\n\n :host([block]) .options {\n overflow-y: initial;\n }\n\n temba-loading {\n align-self: center;\n margin-top: 0.025em;\n }\n\n .loader-bar {\n pointer-events: none;\n align-items: center;\n background: #eee;\n max-height: 0;\n transition: max-height var(--transition-speed) ease-in-out;\n border-bottom-left-radius: var(--curvature-widget);\n border-bottom-right-radius: var(--curvature-widget);\n display: flex;\n overflow: hidden;\n }\n\n .loading .loader-bar {\n max-height: 1.1em;\n }\n\n .option:hover {\n background: var(--option-hover-bg);\n color: var(--option-hover-text);\n }\n\n .option.focused {\n background: var(--color-selection);\n color: var(--color-text-dark);\n }\n `;\n }\n\n @property({ type: Number })\n top: number;\n\n @property({ type: Number })\n left: number;\n\n @property({ type: Number })\n width: number;\n\n @property({ type: Number, attribute: 'static-width' })\n staticWidth: number;\n\n @property({ type: Boolean, attribute: 'anchor-right' })\n anchorRight: boolean;\n\n @property({ type: Number })\n marginHorizontal = 0;\n\n @property({ type: Number })\n marginVertical = 7;\n\n @property({ type: Object })\n anchorTo: HTMLElement;\n\n @property({ type: Boolean })\n visible: boolean;\n\n @property({ type: Boolean })\n block: boolean;\n\n @property({ type: Number })\n scrollPct = 75;\n\n @property({ type: Number })\n cursorIndex = -1;\n\n @property({ type: Boolean })\n internalFocusDisabled = false;\n\n @property({ type: Array })\n options: any[];\n\n @property({ type: Array })\n tempOptions: any[];\n\n @property({ type: Boolean })\n poppedTop: boolean;\n\n @property({ type: Boolean })\n spaceSelect: boolean;\n\n @property({ type: String })\n nameKey = 'name';\n\n @property({ type: Boolean })\n loading = false;\n\n @property({ type: Boolean })\n collapsed: boolean;\n\n @property({ type: Boolean })\n hideShadow = false;\n\n @property({ attribute: false })\n getName: { (option: any): string } = function (option: any) {\n return option[this.nameKey || 'name'];\n };\n\n @property({ attribute: false })\n renderInputOption: { (): TemplateResult } = function () {\n return null;\n };\n\n @property({ attribute: false })\n renderOption: { (option: any, selected: boolean): TemplateResult };\n\n @property({ attribute: false })\n renderOptionName: { (option: any, selected: boolean): TemplateResult };\n\n @property({ attribute: false })\n renderOptionDetail: { (option: any, selected: boolean): TemplateResult };\n\n @property({ type: Number })\n scrollHeight = 0;\n\n @property({ type: Boolean })\n triggerScroll = false;\n\n scrollParent: HTMLElement = null;\n\n resolvedRenderOption: { (option: any, selected: boolean): TemplateResult };\n\n public firstUpdated() {\n if (!this.block) {\n this.scrollParent = getScrollParent(this);\n this.calculatePosition = this.calculatePosition.bind(this);\n if (this.scrollParent) {\n this.scrollParent.addEventListener('scroll', this.calculatePosition);\n }\n this.calculatePosition();\n }\n\n this.resolvedRenderOption = (\n this.renderOption || this.renderOptionDefault\n ).bind(this);\n }\n\n public disconnectedCallback() {\n if (!this.block) {\n if (this.scrollParent) {\n this.scrollParent.removeEventListener('scroll', this.calculatePosition);\n }\n }\n }\n\n private isFocused() {\n const focused =\n this.closestElement(document.activeElement.tagName) ===\n document.activeElement;\n\n return focused;\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n // if our cursor changed, lets make sure our scrollbox is showing it\n if (!this.internalFocusDisabled && changedProperties.has('cursorIndex')) {\n const focusedOption = this.shadowRoot.querySelector(\n `div[data-option-index=\"${this.cursorIndex}\"]`\n ) as HTMLDivElement;\n\n if (focusedOption) {\n const scrollBox = this.shadowRoot.querySelector('.options-container');\n const scrollBoxRect = scrollBox.getBoundingClientRect();\n const scrollBoxHeight = scrollBoxRect.height;\n const focusedEleHeight = focusedOption.getBoundingClientRect().height;\n\n if (\n focusedOption.offsetTop + focusedEleHeight >\n scrollBox.scrollTop + scrollBoxHeight - 5\n ) {\n const scrollTo =\n focusedOption.offsetTop - scrollBoxHeight + focusedEleHeight + 5;\n scrollBox.scrollTop = scrollTo;\n } else if (focusedOption.offsetTop < scrollBox.scrollTop) {\n const scrollTo = focusedOption.offsetTop - 5;\n scrollBox.scrollTop = scrollTo;\n }\n }\n\n this.fireCustomEvent(CustomEventType.CursorChanged, {\n index: this.cursorIndex,\n });\n }\n\n if (changedProperties.has('visible') && changedProperties.has('options')) {\n if (!this.visible && this.options.length == 0) {\n this.tempOptions = changedProperties.get('options');\n window.setTimeout(() => {\n this.tempOptions = [];\n }, 300);\n }\n }\n\n if (changedProperties.has('options')) {\n this.calculatePosition();\n\n // allow scrolls to trigger again\n this.triggerScroll = true;\n\n const prevOptions = changedProperties.get('options');\n const previousCount = prevOptions ? prevOptions.length : 0;\n const newCount = this.options ? this.options.length : 0;\n\n if (\n this.cursorIndex === -1 ||\n newCount < previousCount ||\n (previousCount === 0 &&\n newCount > 0 &&\n !changedProperties.has('cursorIndex'))\n ) {\n if (!this.internalFocusDisabled) {\n if (!this.block) {\n this.cursorIndex = 0;\n } else {\n if (this.cursorIndex >= newCount) {\n this.cursorIndex = newCount - 1;\n }\n }\n\n if (this.block) {\n this.handleSelection(false);\n }\n }\n }\n\n // if on initial load we don't have enough options to load, trigger a scroll\n // threshold event in case the page size is smaller than our control height\n const scrollBox = this.shadowRoot.querySelector('.options');\n if (scrollBox.scrollHeight == scrollBox.clientHeight) {\n this.fireCustomEvent(CustomEventType.ScrollThreshold);\n }\n }\n\n if (changedProperties.has('visible')) {\n window.setTimeout(() => {\n this.calculatePosition();\n }, 100);\n }\n }\n\n private renderOptionDefault(option: any, selected: boolean): TemplateResult {\n const renderOptionName = (\n this.renderOptionName || this.renderOptionNameDefault\n ).bind(this);\n const renderOptionDetail = (\n this.renderOptionDetail || this.renderOptionDetailDefault\n ).bind(this);\n\n if (selected) {\n return html`\n
    ${renderOptionName(option, selected)}
    \n
    ${renderOptionDetail(option, selected)}
    \n `;\n } else {\n return html`\n
    ${renderOptionName(option, selected)}
    \n `;\n }\n }\n\n private renderOptionNameDefault(option: any): TemplateResult {\n return html`
    \n ${option.icon\n ? html``\n : null}\n
    ${option.prefix}${this.getName(option)}
    \n
    `;\n }\n\n private renderOptionDetailDefault(option: any): TemplateResult {\n return html` ${option.detail} `;\n }\n\n private handleSelection(tabbed = false, index = -1) {\n if (!this.internalFocusDisabled) {\n if (index === -1) {\n index = this.cursorIndex;\n }\n }\n\n const selected = this.options[index];\n this.fireCustomEvent(CustomEventType.Selection, {\n selected,\n tabbed,\n index,\n });\n }\n\n private moveCursor(direction: number): void {\n if (!this.internalFocusDisabled) {\n const newIndex = Math.max(\n Math.min(this.cursorIndex + direction, this.options.length - 1),\n 0\n );\n this.setCursor(newIndex);\n }\n }\n\n private setCursor: (index: number) => void = throttle(function (\n index: number\n ) {\n if (!this.internalFocusDisabled) {\n if (index !== this.cursorIndex) {\n this.cursorIndex = index;\n }\n }\n },\n 50);\n\n public scrollToTop() {\n const scrollBox = this.shadowRoot.querySelector('.options-scroll');\n scrollBox.scrollTop = 0;\n }\n\n private handleKeyDown(evt: KeyboardEvent) {\n if (this.internalFocusDisabled || (this.block && !this.isFocused())) {\n return;\n }\n\n if (this.options && this.options.length > 0) {\n if ((evt.ctrlKey && evt.key === 'n') || evt.key === 'ArrowDown') {\n this.moveCursor(1);\n evt.preventDefault();\n evt.stopPropagation();\n if (this.block) {\n this.handleSelection(false);\n }\n } else if ((evt.ctrlKey && evt.key === 'p') || evt.key === 'ArrowUp') {\n this.moveCursor(-1);\n evt.preventDefault();\n if (this.block) {\n this.handleSelection(false);\n }\n } else if (\n evt.key === 'Enter' ||\n evt.key === 'Tab' ||\n (this.spaceSelect && evt.key === ' ')\n ) {\n evt.preventDefault();\n evt.stopPropagation();\n this.handleSelection(evt.key === 'Tab');\n }\n\n if (evt.key === 'Escape') {\n this.fireCustomEvent(CustomEventType.Canceled);\n }\n }\n }\n\n private handleInnerScroll(evt: Event) {\n const scrollbox = evt.target as HTMLDivElement;\n\n // scroll height has changed, enable scroll trigger\n if (scrollbox.scrollHeight > this.scrollHeight) {\n this.scrollHeight = scrollbox.scrollHeight;\n this.triggerScroll = true;\n }\n\n if (this.triggerScroll) {\n const scrollPct =\n scrollbox.scrollTop / (scrollbox.scrollHeight - scrollbox.clientHeight);\n if (scrollPct * 100 > this.scrollPct) {\n this.fireCustomEvent(CustomEventType.ScrollThreshold);\n this.triggerScroll = false;\n }\n }\n }\n\n private calculatePosition() {\n if (this.visible && !this.block) {\n const optionsBounds = this.shadowRoot\n .querySelector('.options-container')\n .getBoundingClientRect();\n\n if (this.anchorTo) {\n const anchorBounds = this.anchorTo.getBoundingClientRect();\n const topTop = anchorBounds.top - optionsBounds.height;\n\n if (this.anchorTo && this.scrollParent) {\n if (!isElementVisible(this.anchorTo, this.scrollParent)) {\n // this.fireCustomEvent(CustomEventType.Canceled);\n }\n }\n\n if (\n topTop > 0 &&\n anchorBounds.bottom + optionsBounds.height > window.innerHeight\n ) {\n this.top = topTop; // + window.pageYOffset;\n this.poppedTop = true;\n } else {\n this.top = anchorBounds.bottom; // + window.pageYOffset;\n this.poppedTop = false;\n }\n\n this.left = anchorBounds.left;\n this.width =\n this.staticWidth > 0\n ? this.staticWidth\n : anchorBounds.width - 2 - this.marginHorizontal * 2;\n\n if (this.anchorRight) {\n this.left = anchorBounds.right - this.width;\n }\n }\n }\n }\n\n public getEventHandlers(): EventHandler[] {\n return [\n {\n event: 'keydown',\n method: this.handleKeyDown,\n isDocument: true,\n },\n {\n event: 'scroll',\n method: this.calculatePosition,\n isDocument: true,\n },\n ];\n }\n\n private handleMouseMove(evt: MouseEvent) {\n if (!this.block) {\n if (Math.abs(evt.movementX) + Math.abs(evt.movementY) > 0) {\n const index = (evt.currentTarget as HTMLElement).getAttribute(\n 'data-option-index'\n );\n this.setCursor(parseInt(index));\n }\n }\n }\n\n // we need to swallow mouse down so we don't grab focus\n private handleMouseDown(evt: MouseEvent) {\n evt.preventDefault();\n evt.stopPropagation();\n }\n\n private handleOptionClick(evt: MouseEvent) {\n evt.preventDefault();\n evt.stopPropagation();\n\n const index = (evt.currentTarget as HTMLElement).getAttribute(\n 'data-option-index'\n );\n\n if (index) {\n const newIndex = parseInt(index);\n this.setCursor(newIndex);\n this.handleSelection(false, newIndex);\n }\n }\n\n public render(): TemplateResult {\n let vertical = this.block ? 0 : this.marginVertical;\n if (this.poppedTop) {\n vertical *= -1;\n }\n\n const containerStyle = {\n 'margin-left': `${this.marginHorizontal}px`,\n 'margin-top': `${vertical}px`,\n };\n\n if (this.top) {\n containerStyle['top'] = `${this.top}px`;\n }\n\n if (this.left) {\n containerStyle['left'] = `${this.left}px`;\n }\n\n const optionsStyle = {};\n if (this.width) {\n optionsStyle['width'] = `${this.width}px`;\n }\n\n const classes = getClasses({\n 'options-container': true,\n show: this.visible,\n top: this.poppedTop,\n anchored: !this.block,\n loading: this.loading,\n shadow: !this.hideShadow,\n bordered: this.hideShadow,\n });\n\n const classesInner = getClasses({\n options: true,\n });\n\n let options = this.options || [];\n if (\n options.length == 0 &&\n this.tempOptions &&\n this.tempOptions.length > 0\n ) {\n options = this.tempOptions;\n }\n\n return html`\n
    \n \n
    \n ${options.map((option, index) => {\n return html`\n ${this.resolvedRenderOption(option, index === this.cursorIndex)}\n
    `;\n })}\n ${this.block ? html`
    ` : null}\n
    \n \n \n\n
    \n \n
    \n \n `;\n }\n}\n","import{nothing as t,noChange as i}from\"../lit-html.js\";import{Directive as r,PartType as s,directive as n}from\"../directive.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */class e extends r{constructor(i){if(super(i),this.it=t,i.type!==s.CHILD)throw Error(this.constructor.directiveName+\"() can only be used in child bindings\")}render(r){if(r===t||null==r)return this._t=void 0,this.it=r;if(r===i)return r;if(\"string\"!=typeof r)throw Error(this.constructor.directiveName+\"() called with a non-string value\");if(r===this.it)return this._t;this.it=r;const s=[r];return s.raw=s,this._t={_$litType$:this.constructor.resultType,strings:s,values:[]}}}e.directiveName=\"unsafeHTML\",e.resultType=1;const o=n(e);export{e as UnsafeHTMLDirective,o as unsafeHTML};\n//# sourceMappingURL=unsafe-html.js.map\n","const STATE_BODY = 0; // not in a expression\nconst STATE_PREFIX = 1; // '@' prefix that denotes the start of an expression\nconst STATE_IDENTIFIER = 2; // the identifier part, e.g. 'contact.age' in '@contact.age'\nconst STATE_BALANCED = 3; // the balanced parentheses delimited part, e.g. '(1 + 2)' in '@(1 + 2)'\nconst STATE_STRING_LITERAL = 4; // a string literal which could contain )\nconst STATE_ESCAPED_PREFIX = 5; // a '@' prefix preceded by another '@'\nconst STATE_IGNORE = 6;\n\nexport interface Expression {\n start: number;\n end: number;\n text: string;\n closed: boolean;\n}\n\n/**\n * Determines whether the given string starts with the given text\n */\nconst startsWith = (str: string, start: string): boolean => {\n return str.indexOf(start, 0) === 0;\n};\n\n/**\n * Checks the parsed (possibly partial) expression to determine if it's valid based on how it starts\n */\nconst isValidStart = (\n partialExpression: string,\n allowedTopLevels: string[],\n allowIncomplete: boolean\n): boolean => {\n const body = partialExpression.substring(1); // strip prefix\n\n if (body[0] === '(') {\n return true;\n } else {\n // if expression doesn't start with ( then check it's an allowed top level context reference\n const topLevel = body.split('.')[0].toLowerCase();\n\n if (allowIncomplete) {\n for (const allowed of allowedTopLevels) {\n if (startsWith(allowed, topLevel)) {\n return true;\n }\n }\n } else {\n return allowedTopLevels.indexOf(topLevel) >= 0;\n }\n return false;\n }\n};\n\n/**\n * Determines whether the given character is a word character, i.e. \\w in a regex\n */\nexport const isWordChar = (ch: string | 0): boolean => {\n return (\n (ch >= 'a' && ch <= 'z') ||\n (ch >= 'A' && ch <= 'Z') ||\n (ch >= '0' && ch <= '9') ||\n ch === '_'\n );\n};\n\n/**\n * Determines whether we are in a string literal\n */\nconst isInStringLiteral = (partialExpression: string): boolean => {\n // count number quotation marks\n let numQuotes = 0;\n for (const pos of partialExpression) {\n if (pos === '\"') {\n numQuotes++;\n }\n }\n return numQuotes % 2 !== 0; // odd means last string literal is open\n};\n\nexport default class ExcellentParser {\n private expressionPrefix: string;\n private allowedTopLevels: string[];\n\n /**\n * Creates a new parser\n * @param expressionPrefix the prefix for expressions, e.g. '@'\n * @param allowedTopLevels the context names that are allowed without parentheses, e.g. [\"contact\", \"flow\", ...]\n */\n constructor(expressionPrefix: string, allowedTopLevels: string[]) {\n this.expressionPrefix = expressionPrefix;\n this.allowedTopLevels = allowedTopLevels;\n }\n\n /**\n * Given the text up to the caret position, returns the expression currently being edited, without its prefix\n */\n public expressionContext(textToCaret: string): string {\n const expressions = this.findExpressions(textToCaret);\n if (expressions.length === 0) {\n // no expressions found\n return null;\n }\n\n const lastExpression = expressions[expressions.length - 1];\n\n // has last expression already ended or is it closed (i.e. has balanced parentheses)\n if (lastExpression.end < textToCaret.length || lastExpression.closed) {\n return null;\n }\n\n return lastExpression.text.substring(1); // return without prefix\n }\n\n /**\n * Given the partial expression currently being edited, returns the current auto-completable identifier\n * which may be a function name or a context reference.\n */\n public autoCompleteContext(partialExpression: string): string {\n if (isInStringLiteral(partialExpression)) {\n return null;\n }\n\n const neededParentheses = [];\n let fragment = '';\n let skipChar = false;\n let inQuotes = false;\n let prependFlag = '';\n\n for (let pos = partialExpression.length - 1; pos >= 0; pos--) {\n const ch = partialExpression[pos];\n\n if (ch === ' ') {\n skipChar = true;\n }\n\n if (ch === ',') {\n skipChar = true;\n if (neededParentheses[neededParentheses.length - 1] !== '(') {\n neededParentheses.push('(');\n }\n }\n\n if (ch === ')' && !inQuotes) {\n skipChar = true;\n neededParentheses.push('(');\n neededParentheses.push('(');\n }\n\n if (ch === '\"') {\n inQuotes = !inQuotes;\n }\n\n if (skipChar) {\n if (ch === '(' && !inQuotes) {\n if (neededParentheses[neededParentheses.length - 1] === '(') {\n neededParentheses.pop();\n }\n\n if (neededParentheses.length === 0) {\n skipChar = false;\n }\n }\n }\n\n if (ch === '(' && fragment === '') {\n prependFlag = '#';\n }\n\n if (skipChar || inQuotes || (ch === '(' && fragment === '')) {\n continue;\n }\n\n if (isWordChar(ch) || ch === '.') {\n fragment = ch + fragment;\n } else {\n break;\n }\n }\n\n if (fragment.match(/[A-Za-z][\\w]*(\\.[\\w]+)*/)) {\n return prependFlag + fragment;\n } else {\n return null;\n }\n }\n\n /**\n * TODO find the function context\n */\n public functionContext(partialExpression: string): string {\n const inString = isInStringLiteral(partialExpression);\n\n // initial state is string literal if number of quotes is odd\n let state = inString ? STATE_STRING_LITERAL : STATE_IGNORE;\n let identifier = '';\n let parenthesesLevel = partialExpression[-1] === '(' ? 0 : 1;\n\n for (let pos = partialExpression.length - 1; pos >= 0; pos--) {\n const ch = partialExpression[pos];\n\n if (ch === '@') {\n return '';\n }\n\n if (state === STATE_IGNORE) {\n if (parenthesesLevel === 0 && (isWordChar(ch) || ch === '.')) {\n state = STATE_IDENTIFIER;\n identifier = ch + identifier;\n } else if (ch === '\"') {\n state = STATE_STRING_LITERAL;\n } else if (ch === '(') {\n parenthesesLevel--;\n } else if (ch === ')') {\n parenthesesLevel++;\n }\n } else if (state === STATE_IDENTIFIER) {\n if (isWordChar(ch) || ch === '.') {\n identifier = ch + identifier;\n } else {\n return identifier;\n }\n } else if (state === STATE_STRING_LITERAL) {\n if (ch === '\"') {\n state = STATE_IGNORE;\n }\n }\n }\n return '';\n }\n\n public getContactFields(text: string): string[] {\n const fields = {};\n const re = /((parent|child\\.)*contact\\.)*fields\\.([a-z0-9_]+)/g;\n const expressions = this.findExpressions(text);\n for (const expression of expressions) {\n let match;\n // tslint:disable-next-line:no-conditional-assignment\n while ((match = re.exec(expression.text))) {\n (fields as any)[match[3]] = true;\n }\n }\n return Object.keys(fields);\n }\n\n /**\n * Finds all expressions in the given text, including any partially complete expression at the end of the input\n */\n public findExpressions(text: string): Expression[] {\n const expressions: Expression[] = [];\n let state = STATE_BODY;\n let currentExpression: Expression = null;\n let parenthesesLevel = 0;\n\n for (let pos = 0; pos < text.length; pos++) {\n const ch = text[pos];\n // in order to determine if the b in a.b terminates an identifier, we have to peek two characters ahead as\n // it could be a.b. (b terminates) or a.b.c (b doesn't terminate)\n const nextCh = pos < text.length - 1 ? text[pos + 1] : 0;\n const nextNextCh = pos < text.length - 2 ? text[pos + 2] : 0;\n\n if (state === STATE_BODY) {\n if (\n ch === this.expressionPrefix &&\n (isWordChar(nextCh) || nextCh === '(')\n ) {\n state = STATE_PREFIX;\n currentExpression = {\n start: pos,\n end: null,\n text: ch,\n closed: false,\n };\n } else if (\n ch === this.expressionPrefix &&\n nextCh === this.expressionPrefix\n ) {\n state = STATE_ESCAPED_PREFIX;\n }\n } else if (state === STATE_PREFIX) {\n if (isWordChar(ch)) {\n state = STATE_IDENTIFIER; // we're parsing an expression like @XXX\n } else if (ch === '(') {\n // we're parsing an expression like @(1 + 2)\n state = STATE_BALANCED;\n parenthesesLevel += 1;\n }\n currentExpression.text += ch;\n } else if (state === STATE_IDENTIFIER) {\n currentExpression.text += ch;\n } else if (state === STATE_BALANCED) {\n if (ch === '(') {\n parenthesesLevel += 1;\n } else if (ch === ')') {\n parenthesesLevel -= 1;\n } else if (ch === '\"') {\n state = STATE_STRING_LITERAL;\n }\n\n currentExpression.text += ch;\n\n // expression terminates if parentheses balance\n if (parenthesesLevel === 0) {\n currentExpression.end = pos + 1;\n }\n } else if (state === STATE_STRING_LITERAL) {\n if (ch === '\"') {\n state = STATE_BALANCED;\n }\n currentExpression.text += ch;\n } else if (state === STATE_ESCAPED_PREFIX) {\n state = STATE_BODY;\n }\n\n // identifier can terminate expression in 3 ways:\n // 1. next char is null (i.e. end of the input)\n // 2. next char is not a word character or period\n // 3. next char is a period, but it's not followed by a word character\n if (state === STATE_IDENTIFIER) {\n if (\n (!isWordChar(nextCh) && nextCh !== '.') ||\n (nextCh === '.' && !isWordChar(nextNextCh))\n ) {\n currentExpression.end = pos + 1;\n }\n }\n\n if (\n currentExpression != null &&\n (currentExpression.end != null || nextCh === 0)\n ) {\n const allowIncomplete = nextCh === 0; // if we're at the end of the input, allow incomplete expressions\n if (\n isValidStart(\n currentExpression.text,\n this.allowedTopLevels,\n allowIncomplete\n )\n ) {\n currentExpression.closed =\n currentExpression.text[1] === '(' && parenthesesLevel === 0;\n currentExpression.end = pos + 1;\n expressions.push(currentExpression);\n }\n\n currentExpression = null;\n state = STATE_BODY;\n }\n }\n\n return expressions;\n }\n}\n","// List of valid entities\n//\n// Generate with ./support/entities.js script\n//\n\n/*eslint quotes:0*/\nvar entities = {\n \"Aacute\":\"\\u00C1\",\n \"aacute\":\"\\u00E1\",\n \"Abreve\":\"\\u0102\",\n \"abreve\":\"\\u0103\",\n \"ac\":\"\\u223E\",\n \"acd\":\"\\u223F\",\n \"acE\":\"\\u223E\\u0333\",\n \"Acirc\":\"\\u00C2\",\n \"acirc\":\"\\u00E2\",\n \"acute\":\"\\u00B4\",\n \"Acy\":\"\\u0410\",\n \"acy\":\"\\u0430\",\n \"AElig\":\"\\u00C6\",\n \"aelig\":\"\\u00E6\",\n \"af\":\"\\u2061\",\n \"Afr\":\"\\uD835\\uDD04\",\n \"afr\":\"\\uD835\\uDD1E\",\n \"Agrave\":\"\\u00C0\",\n \"agrave\":\"\\u00E0\",\n \"alefsym\":\"\\u2135\",\n \"aleph\":\"\\u2135\",\n \"Alpha\":\"\\u0391\",\n \"alpha\":\"\\u03B1\",\n \"Amacr\":\"\\u0100\",\n \"amacr\":\"\\u0101\",\n \"amalg\":\"\\u2A3F\",\n \"AMP\":\"\\u0026\",\n \"amp\":\"\\u0026\",\n \"And\":\"\\u2A53\",\n \"and\":\"\\u2227\",\n \"andand\":\"\\u2A55\",\n \"andd\":\"\\u2A5C\",\n \"andslope\":\"\\u2A58\",\n \"andv\":\"\\u2A5A\",\n \"ang\":\"\\u2220\",\n \"ange\":\"\\u29A4\",\n \"angle\":\"\\u2220\",\n \"angmsd\":\"\\u2221\",\n \"angmsdaa\":\"\\u29A8\",\n \"angmsdab\":\"\\u29A9\",\n \"angmsdac\":\"\\u29AA\",\n \"angmsdad\":\"\\u29AB\",\n \"angmsdae\":\"\\u29AC\",\n \"angmsdaf\":\"\\u29AD\",\n \"angmsdag\":\"\\u29AE\",\n \"angmsdah\":\"\\u29AF\",\n \"angrt\":\"\\u221F\",\n \"angrtvb\":\"\\u22BE\",\n \"angrtvbd\":\"\\u299D\",\n \"angsph\":\"\\u2222\",\n \"angst\":\"\\u00C5\",\n \"angzarr\":\"\\u237C\",\n \"Aogon\":\"\\u0104\",\n \"aogon\":\"\\u0105\",\n \"Aopf\":\"\\uD835\\uDD38\",\n \"aopf\":\"\\uD835\\uDD52\",\n \"ap\":\"\\u2248\",\n \"apacir\":\"\\u2A6F\",\n \"apE\":\"\\u2A70\",\n \"ape\":\"\\u224A\",\n \"apid\":\"\\u224B\",\n \"apos\":\"\\u0027\",\n \"ApplyFunction\":\"\\u2061\",\n \"approx\":\"\\u2248\",\n \"approxeq\":\"\\u224A\",\n \"Aring\":\"\\u00C5\",\n \"aring\":\"\\u00E5\",\n \"Ascr\":\"\\uD835\\uDC9C\",\n \"ascr\":\"\\uD835\\uDCB6\",\n \"Assign\":\"\\u2254\",\n \"ast\":\"\\u002A\",\n \"asymp\":\"\\u2248\",\n \"asympeq\":\"\\u224D\",\n \"Atilde\":\"\\u00C3\",\n \"atilde\":\"\\u00E3\",\n \"Auml\":\"\\u00C4\",\n \"auml\":\"\\u00E4\",\n \"awconint\":\"\\u2233\",\n \"awint\":\"\\u2A11\",\n \"backcong\":\"\\u224C\",\n \"backepsilon\":\"\\u03F6\",\n \"backprime\":\"\\u2035\",\n \"backsim\":\"\\u223D\",\n \"backsimeq\":\"\\u22CD\",\n \"Backslash\":\"\\u2216\",\n \"Barv\":\"\\u2AE7\",\n \"barvee\":\"\\u22BD\",\n \"Barwed\":\"\\u2306\",\n \"barwed\":\"\\u2305\",\n \"barwedge\":\"\\u2305\",\n \"bbrk\":\"\\u23B5\",\n \"bbrktbrk\":\"\\u23B6\",\n \"bcong\":\"\\u224C\",\n \"Bcy\":\"\\u0411\",\n \"bcy\":\"\\u0431\",\n \"bdquo\":\"\\u201E\",\n \"becaus\":\"\\u2235\",\n \"Because\":\"\\u2235\",\n \"because\":\"\\u2235\",\n \"bemptyv\":\"\\u29B0\",\n \"bepsi\":\"\\u03F6\",\n \"bernou\":\"\\u212C\",\n \"Bernoullis\":\"\\u212C\",\n \"Beta\":\"\\u0392\",\n \"beta\":\"\\u03B2\",\n \"beth\":\"\\u2136\",\n \"between\":\"\\u226C\",\n \"Bfr\":\"\\uD835\\uDD05\",\n \"bfr\":\"\\uD835\\uDD1F\",\n \"bigcap\":\"\\u22C2\",\n \"bigcirc\":\"\\u25EF\",\n \"bigcup\":\"\\u22C3\",\n \"bigodot\":\"\\u2A00\",\n \"bigoplus\":\"\\u2A01\",\n \"bigotimes\":\"\\u2A02\",\n \"bigsqcup\":\"\\u2A06\",\n \"bigstar\":\"\\u2605\",\n \"bigtriangledown\":\"\\u25BD\",\n \"bigtriangleup\":\"\\u25B3\",\n \"biguplus\":\"\\u2A04\",\n \"bigvee\":\"\\u22C1\",\n \"bigwedge\":\"\\u22C0\",\n \"bkarow\":\"\\u290D\",\n \"blacklozenge\":\"\\u29EB\",\n \"blacksquare\":\"\\u25AA\",\n \"blacktriangle\":\"\\u25B4\",\n \"blacktriangledown\":\"\\u25BE\",\n \"blacktriangleleft\":\"\\u25C2\",\n \"blacktriangleright\":\"\\u25B8\",\n \"blank\":\"\\u2423\",\n \"blk12\":\"\\u2592\",\n \"blk14\":\"\\u2591\",\n \"blk34\":\"\\u2593\",\n \"block\":\"\\u2588\",\n \"bne\":\"\\u003D\\u20E5\",\n \"bnequiv\":\"\\u2261\\u20E5\",\n \"bNot\":\"\\u2AED\",\n \"bnot\":\"\\u2310\",\n \"Bopf\":\"\\uD835\\uDD39\",\n \"bopf\":\"\\uD835\\uDD53\",\n \"bot\":\"\\u22A5\",\n \"bottom\":\"\\u22A5\",\n \"bowtie\":\"\\u22C8\",\n \"boxbox\":\"\\u29C9\",\n \"boxDL\":\"\\u2557\",\n \"boxDl\":\"\\u2556\",\n \"boxdL\":\"\\u2555\",\n \"boxdl\":\"\\u2510\",\n \"boxDR\":\"\\u2554\",\n \"boxDr\":\"\\u2553\",\n \"boxdR\":\"\\u2552\",\n \"boxdr\":\"\\u250C\",\n \"boxH\":\"\\u2550\",\n \"boxh\":\"\\u2500\",\n \"boxHD\":\"\\u2566\",\n \"boxHd\":\"\\u2564\",\n \"boxhD\":\"\\u2565\",\n \"boxhd\":\"\\u252C\",\n \"boxHU\":\"\\u2569\",\n \"boxHu\":\"\\u2567\",\n \"boxhU\":\"\\u2568\",\n \"boxhu\":\"\\u2534\",\n \"boxminus\":\"\\u229F\",\n \"boxplus\":\"\\u229E\",\n \"boxtimes\":\"\\u22A0\",\n \"boxUL\":\"\\u255D\",\n \"boxUl\":\"\\u255C\",\n \"boxuL\":\"\\u255B\",\n \"boxul\":\"\\u2518\",\n \"boxUR\":\"\\u255A\",\n \"boxUr\":\"\\u2559\",\n \"boxuR\":\"\\u2558\",\n \"boxur\":\"\\u2514\",\n \"boxV\":\"\\u2551\",\n \"boxv\":\"\\u2502\",\n \"boxVH\":\"\\u256C\",\n \"boxVh\":\"\\u256B\",\n \"boxvH\":\"\\u256A\",\n \"boxvh\":\"\\u253C\",\n \"boxVL\":\"\\u2563\",\n \"boxVl\":\"\\u2562\",\n \"boxvL\":\"\\u2561\",\n \"boxvl\":\"\\u2524\",\n \"boxVR\":\"\\u2560\",\n \"boxVr\":\"\\u255F\",\n \"boxvR\":\"\\u255E\",\n \"boxvr\":\"\\u251C\",\n \"bprime\":\"\\u2035\",\n \"Breve\":\"\\u02D8\",\n \"breve\":\"\\u02D8\",\n \"brvbar\":\"\\u00A6\",\n \"Bscr\":\"\\u212C\",\n \"bscr\":\"\\uD835\\uDCB7\",\n \"bsemi\":\"\\u204F\",\n \"bsim\":\"\\u223D\",\n \"bsime\":\"\\u22CD\",\n \"bsol\":\"\\u005C\",\n \"bsolb\":\"\\u29C5\",\n \"bsolhsub\":\"\\u27C8\",\n \"bull\":\"\\u2022\",\n \"bullet\":\"\\u2022\",\n \"bump\":\"\\u224E\",\n \"bumpE\":\"\\u2AAE\",\n \"bumpe\":\"\\u224F\",\n \"Bumpeq\":\"\\u224E\",\n \"bumpeq\":\"\\u224F\",\n \"Cacute\":\"\\u0106\",\n \"cacute\":\"\\u0107\",\n \"Cap\":\"\\u22D2\",\n \"cap\":\"\\u2229\",\n \"capand\":\"\\u2A44\",\n \"capbrcup\":\"\\u2A49\",\n \"capcap\":\"\\u2A4B\",\n \"capcup\":\"\\u2A47\",\n \"capdot\":\"\\u2A40\",\n \"CapitalDifferentialD\":\"\\u2145\",\n \"caps\":\"\\u2229\\uFE00\",\n \"caret\":\"\\u2041\",\n \"caron\":\"\\u02C7\",\n \"Cayleys\":\"\\u212D\",\n \"ccaps\":\"\\u2A4D\",\n \"Ccaron\":\"\\u010C\",\n \"ccaron\":\"\\u010D\",\n \"Ccedil\":\"\\u00C7\",\n \"ccedil\":\"\\u00E7\",\n \"Ccirc\":\"\\u0108\",\n \"ccirc\":\"\\u0109\",\n \"Cconint\":\"\\u2230\",\n \"ccups\":\"\\u2A4C\",\n \"ccupssm\":\"\\u2A50\",\n \"Cdot\":\"\\u010A\",\n \"cdot\":\"\\u010B\",\n \"cedil\":\"\\u00B8\",\n \"Cedilla\":\"\\u00B8\",\n \"cemptyv\":\"\\u29B2\",\n \"cent\":\"\\u00A2\",\n \"CenterDot\":\"\\u00B7\",\n \"centerdot\":\"\\u00B7\",\n \"Cfr\":\"\\u212D\",\n \"cfr\":\"\\uD835\\uDD20\",\n \"CHcy\":\"\\u0427\",\n \"chcy\":\"\\u0447\",\n \"check\":\"\\u2713\",\n \"checkmark\":\"\\u2713\",\n \"Chi\":\"\\u03A7\",\n \"chi\":\"\\u03C7\",\n \"cir\":\"\\u25CB\",\n \"circ\":\"\\u02C6\",\n \"circeq\":\"\\u2257\",\n \"circlearrowleft\":\"\\u21BA\",\n \"circlearrowright\":\"\\u21BB\",\n \"circledast\":\"\\u229B\",\n \"circledcirc\":\"\\u229A\",\n \"circleddash\":\"\\u229D\",\n \"CircleDot\":\"\\u2299\",\n \"circledR\":\"\\u00AE\",\n \"circledS\":\"\\u24C8\",\n \"CircleMinus\":\"\\u2296\",\n \"CirclePlus\":\"\\u2295\",\n \"CircleTimes\":\"\\u2297\",\n \"cirE\":\"\\u29C3\",\n \"cire\":\"\\u2257\",\n \"cirfnint\":\"\\u2A10\",\n \"cirmid\":\"\\u2AEF\",\n \"cirscir\":\"\\u29C2\",\n \"ClockwiseContourIntegral\":\"\\u2232\",\n \"CloseCurlyDoubleQuote\":\"\\u201D\",\n \"CloseCurlyQuote\":\"\\u2019\",\n \"clubs\":\"\\u2663\",\n \"clubsuit\":\"\\u2663\",\n \"Colon\":\"\\u2237\",\n \"colon\":\"\\u003A\",\n \"Colone\":\"\\u2A74\",\n \"colone\":\"\\u2254\",\n \"coloneq\":\"\\u2254\",\n \"comma\":\"\\u002C\",\n \"commat\":\"\\u0040\",\n \"comp\":\"\\u2201\",\n \"compfn\":\"\\u2218\",\n \"complement\":\"\\u2201\",\n \"complexes\":\"\\u2102\",\n \"cong\":\"\\u2245\",\n \"congdot\":\"\\u2A6D\",\n \"Congruent\":\"\\u2261\",\n \"Conint\":\"\\u222F\",\n \"conint\":\"\\u222E\",\n \"ContourIntegral\":\"\\u222E\",\n \"Copf\":\"\\u2102\",\n \"copf\":\"\\uD835\\uDD54\",\n \"coprod\":\"\\u2210\",\n \"Coproduct\":\"\\u2210\",\n \"COPY\":\"\\u00A9\",\n \"copy\":\"\\u00A9\",\n \"copysr\":\"\\u2117\",\n \"CounterClockwiseContourIntegral\":\"\\u2233\",\n \"crarr\":\"\\u21B5\",\n \"Cross\":\"\\u2A2F\",\n \"cross\":\"\\u2717\",\n \"Cscr\":\"\\uD835\\uDC9E\",\n \"cscr\":\"\\uD835\\uDCB8\",\n \"csub\":\"\\u2ACF\",\n \"csube\":\"\\u2AD1\",\n \"csup\":\"\\u2AD0\",\n \"csupe\":\"\\u2AD2\",\n \"ctdot\":\"\\u22EF\",\n \"cudarrl\":\"\\u2938\",\n \"cudarrr\":\"\\u2935\",\n \"cuepr\":\"\\u22DE\",\n \"cuesc\":\"\\u22DF\",\n \"cularr\":\"\\u21B6\",\n \"cularrp\":\"\\u293D\",\n \"Cup\":\"\\u22D3\",\n \"cup\":\"\\u222A\",\n \"cupbrcap\":\"\\u2A48\",\n \"CupCap\":\"\\u224D\",\n \"cupcap\":\"\\u2A46\",\n \"cupcup\":\"\\u2A4A\",\n \"cupdot\":\"\\u228D\",\n \"cupor\":\"\\u2A45\",\n \"cups\":\"\\u222A\\uFE00\",\n \"curarr\":\"\\u21B7\",\n \"curarrm\":\"\\u293C\",\n \"curlyeqprec\":\"\\u22DE\",\n \"curlyeqsucc\":\"\\u22DF\",\n \"curlyvee\":\"\\u22CE\",\n \"curlywedge\":\"\\u22CF\",\n \"curren\":\"\\u00A4\",\n \"curvearrowleft\":\"\\u21B6\",\n \"curvearrowright\":\"\\u21B7\",\n \"cuvee\":\"\\u22CE\",\n \"cuwed\":\"\\u22CF\",\n \"cwconint\":\"\\u2232\",\n \"cwint\":\"\\u2231\",\n \"cylcty\":\"\\u232D\",\n \"Dagger\":\"\\u2021\",\n \"dagger\":\"\\u2020\",\n \"daleth\":\"\\u2138\",\n \"Darr\":\"\\u21A1\",\n \"dArr\":\"\\u21D3\",\n \"darr\":\"\\u2193\",\n \"dash\":\"\\u2010\",\n \"Dashv\":\"\\u2AE4\",\n \"dashv\":\"\\u22A3\",\n \"dbkarow\":\"\\u290F\",\n \"dblac\":\"\\u02DD\",\n \"Dcaron\":\"\\u010E\",\n \"dcaron\":\"\\u010F\",\n \"Dcy\":\"\\u0414\",\n \"dcy\":\"\\u0434\",\n \"DD\":\"\\u2145\",\n \"dd\":\"\\u2146\",\n \"ddagger\":\"\\u2021\",\n \"ddarr\":\"\\u21CA\",\n \"DDotrahd\":\"\\u2911\",\n \"ddotseq\":\"\\u2A77\",\n \"deg\":\"\\u00B0\",\n \"Del\":\"\\u2207\",\n \"Delta\":\"\\u0394\",\n \"delta\":\"\\u03B4\",\n \"demptyv\":\"\\u29B1\",\n \"dfisht\":\"\\u297F\",\n \"Dfr\":\"\\uD835\\uDD07\",\n \"dfr\":\"\\uD835\\uDD21\",\n \"dHar\":\"\\u2965\",\n \"dharl\":\"\\u21C3\",\n \"dharr\":\"\\u21C2\",\n \"DiacriticalAcute\":\"\\u00B4\",\n \"DiacriticalDot\":\"\\u02D9\",\n \"DiacriticalDoubleAcute\":\"\\u02DD\",\n \"DiacriticalGrave\":\"\\u0060\",\n \"DiacriticalTilde\":\"\\u02DC\",\n \"diam\":\"\\u22C4\",\n \"Diamond\":\"\\u22C4\",\n \"diamond\":\"\\u22C4\",\n \"diamondsuit\":\"\\u2666\",\n \"diams\":\"\\u2666\",\n \"die\":\"\\u00A8\",\n \"DifferentialD\":\"\\u2146\",\n \"digamma\":\"\\u03DD\",\n \"disin\":\"\\u22F2\",\n \"div\":\"\\u00F7\",\n \"divide\":\"\\u00F7\",\n \"divideontimes\":\"\\u22C7\",\n \"divonx\":\"\\u22C7\",\n \"DJcy\":\"\\u0402\",\n \"djcy\":\"\\u0452\",\n \"dlcorn\":\"\\u231E\",\n \"dlcrop\":\"\\u230D\",\n \"dollar\":\"\\u0024\",\n \"Dopf\":\"\\uD835\\uDD3B\",\n \"dopf\":\"\\uD835\\uDD55\",\n \"Dot\":\"\\u00A8\",\n \"dot\":\"\\u02D9\",\n \"DotDot\":\"\\u20DC\",\n \"doteq\":\"\\u2250\",\n \"doteqdot\":\"\\u2251\",\n \"DotEqual\":\"\\u2250\",\n \"dotminus\":\"\\u2238\",\n \"dotplus\":\"\\u2214\",\n \"dotsquare\":\"\\u22A1\",\n \"doublebarwedge\":\"\\u2306\",\n \"DoubleContourIntegral\":\"\\u222F\",\n \"DoubleDot\":\"\\u00A8\",\n \"DoubleDownArrow\":\"\\u21D3\",\n \"DoubleLeftArrow\":\"\\u21D0\",\n \"DoubleLeftRightArrow\":\"\\u21D4\",\n \"DoubleLeftTee\":\"\\u2AE4\",\n \"DoubleLongLeftArrow\":\"\\u27F8\",\n \"DoubleLongLeftRightArrow\":\"\\u27FA\",\n \"DoubleLongRightArrow\":\"\\u27F9\",\n \"DoubleRightArrow\":\"\\u21D2\",\n \"DoubleRightTee\":\"\\u22A8\",\n \"DoubleUpArrow\":\"\\u21D1\",\n \"DoubleUpDownArrow\":\"\\u21D5\",\n \"DoubleVerticalBar\":\"\\u2225\",\n \"DownArrow\":\"\\u2193\",\n \"Downarrow\":\"\\u21D3\",\n \"downarrow\":\"\\u2193\",\n \"DownArrowBar\":\"\\u2913\",\n \"DownArrowUpArrow\":\"\\u21F5\",\n \"DownBreve\":\"\\u0311\",\n \"downdownarrows\":\"\\u21CA\",\n \"downharpoonleft\":\"\\u21C3\",\n \"downharpoonright\":\"\\u21C2\",\n \"DownLeftRightVector\":\"\\u2950\",\n \"DownLeftTeeVector\":\"\\u295E\",\n \"DownLeftVector\":\"\\u21BD\",\n \"DownLeftVectorBar\":\"\\u2956\",\n \"DownRightTeeVector\":\"\\u295F\",\n \"DownRightVector\":\"\\u21C1\",\n \"DownRightVectorBar\":\"\\u2957\",\n \"DownTee\":\"\\u22A4\",\n \"DownTeeArrow\":\"\\u21A7\",\n \"drbkarow\":\"\\u2910\",\n \"drcorn\":\"\\u231F\",\n \"drcrop\":\"\\u230C\",\n \"Dscr\":\"\\uD835\\uDC9F\",\n \"dscr\":\"\\uD835\\uDCB9\",\n \"DScy\":\"\\u0405\",\n \"dscy\":\"\\u0455\",\n \"dsol\":\"\\u29F6\",\n \"Dstrok\":\"\\u0110\",\n \"dstrok\":\"\\u0111\",\n \"dtdot\":\"\\u22F1\",\n \"dtri\":\"\\u25BF\",\n \"dtrif\":\"\\u25BE\",\n \"duarr\":\"\\u21F5\",\n \"duhar\":\"\\u296F\",\n \"dwangle\":\"\\u29A6\",\n \"DZcy\":\"\\u040F\",\n \"dzcy\":\"\\u045F\",\n \"dzigrarr\":\"\\u27FF\",\n \"Eacute\":\"\\u00C9\",\n \"eacute\":\"\\u00E9\",\n \"easter\":\"\\u2A6E\",\n \"Ecaron\":\"\\u011A\",\n \"ecaron\":\"\\u011B\",\n \"ecir\":\"\\u2256\",\n \"Ecirc\":\"\\u00CA\",\n \"ecirc\":\"\\u00EA\",\n \"ecolon\":\"\\u2255\",\n \"Ecy\":\"\\u042D\",\n \"ecy\":\"\\u044D\",\n \"eDDot\":\"\\u2A77\",\n \"Edot\":\"\\u0116\",\n \"eDot\":\"\\u2251\",\n \"edot\":\"\\u0117\",\n \"ee\":\"\\u2147\",\n \"efDot\":\"\\u2252\",\n \"Efr\":\"\\uD835\\uDD08\",\n \"efr\":\"\\uD835\\uDD22\",\n \"eg\":\"\\u2A9A\",\n \"Egrave\":\"\\u00C8\",\n \"egrave\":\"\\u00E8\",\n \"egs\":\"\\u2A96\",\n \"egsdot\":\"\\u2A98\",\n \"el\":\"\\u2A99\",\n \"Element\":\"\\u2208\",\n \"elinters\":\"\\u23E7\",\n \"ell\":\"\\u2113\",\n \"els\":\"\\u2A95\",\n \"elsdot\":\"\\u2A97\",\n \"Emacr\":\"\\u0112\",\n \"emacr\":\"\\u0113\",\n \"empty\":\"\\u2205\",\n \"emptyset\":\"\\u2205\",\n \"EmptySmallSquare\":\"\\u25FB\",\n \"emptyv\":\"\\u2205\",\n \"EmptyVerySmallSquare\":\"\\u25AB\",\n \"emsp\":\"\\u2003\",\n \"emsp13\":\"\\u2004\",\n \"emsp14\":\"\\u2005\",\n \"ENG\":\"\\u014A\",\n \"eng\":\"\\u014B\",\n \"ensp\":\"\\u2002\",\n \"Eogon\":\"\\u0118\",\n \"eogon\":\"\\u0119\",\n \"Eopf\":\"\\uD835\\uDD3C\",\n \"eopf\":\"\\uD835\\uDD56\",\n \"epar\":\"\\u22D5\",\n \"eparsl\":\"\\u29E3\",\n \"eplus\":\"\\u2A71\",\n \"epsi\":\"\\u03B5\",\n \"Epsilon\":\"\\u0395\",\n \"epsilon\":\"\\u03B5\",\n \"epsiv\":\"\\u03F5\",\n \"eqcirc\":\"\\u2256\",\n \"eqcolon\":\"\\u2255\",\n \"eqsim\":\"\\u2242\",\n \"eqslantgtr\":\"\\u2A96\",\n \"eqslantless\":\"\\u2A95\",\n \"Equal\":\"\\u2A75\",\n \"equals\":\"\\u003D\",\n \"EqualTilde\":\"\\u2242\",\n \"equest\":\"\\u225F\",\n \"Equilibrium\":\"\\u21CC\",\n \"equiv\":\"\\u2261\",\n \"equivDD\":\"\\u2A78\",\n \"eqvparsl\":\"\\u29E5\",\n \"erarr\":\"\\u2971\",\n \"erDot\":\"\\u2253\",\n \"Escr\":\"\\u2130\",\n \"escr\":\"\\u212F\",\n \"esdot\":\"\\u2250\",\n \"Esim\":\"\\u2A73\",\n \"esim\":\"\\u2242\",\n \"Eta\":\"\\u0397\",\n \"eta\":\"\\u03B7\",\n \"ETH\":\"\\u00D0\",\n \"eth\":\"\\u00F0\",\n \"Euml\":\"\\u00CB\",\n \"euml\":\"\\u00EB\",\n \"euro\":\"\\u20AC\",\n \"excl\":\"\\u0021\",\n \"exist\":\"\\u2203\",\n \"Exists\":\"\\u2203\",\n \"expectation\":\"\\u2130\",\n \"ExponentialE\":\"\\u2147\",\n \"exponentiale\":\"\\u2147\",\n \"fallingdotseq\":\"\\u2252\",\n \"Fcy\":\"\\u0424\",\n \"fcy\":\"\\u0444\",\n \"female\":\"\\u2640\",\n \"ffilig\":\"\\uFB03\",\n \"fflig\":\"\\uFB00\",\n \"ffllig\":\"\\uFB04\",\n \"Ffr\":\"\\uD835\\uDD09\",\n \"ffr\":\"\\uD835\\uDD23\",\n \"filig\":\"\\uFB01\",\n \"FilledSmallSquare\":\"\\u25FC\",\n \"FilledVerySmallSquare\":\"\\u25AA\",\n \"fjlig\":\"\\u0066\\u006A\",\n \"flat\":\"\\u266D\",\n \"fllig\":\"\\uFB02\",\n \"fltns\":\"\\u25B1\",\n \"fnof\":\"\\u0192\",\n \"Fopf\":\"\\uD835\\uDD3D\",\n \"fopf\":\"\\uD835\\uDD57\",\n \"ForAll\":\"\\u2200\",\n \"forall\":\"\\u2200\",\n \"fork\":\"\\u22D4\",\n \"forkv\":\"\\u2AD9\",\n \"Fouriertrf\":\"\\u2131\",\n \"fpartint\":\"\\u2A0D\",\n \"frac12\":\"\\u00BD\",\n \"frac13\":\"\\u2153\",\n \"frac14\":\"\\u00BC\",\n \"frac15\":\"\\u2155\",\n \"frac16\":\"\\u2159\",\n \"frac18\":\"\\u215B\",\n \"frac23\":\"\\u2154\",\n \"frac25\":\"\\u2156\",\n \"frac34\":\"\\u00BE\",\n \"frac35\":\"\\u2157\",\n \"frac38\":\"\\u215C\",\n \"frac45\":\"\\u2158\",\n \"frac56\":\"\\u215A\",\n \"frac58\":\"\\u215D\",\n \"frac78\":\"\\u215E\",\n \"frasl\":\"\\u2044\",\n \"frown\":\"\\u2322\",\n \"Fscr\":\"\\u2131\",\n \"fscr\":\"\\uD835\\uDCBB\",\n \"gacute\":\"\\u01F5\",\n \"Gamma\":\"\\u0393\",\n \"gamma\":\"\\u03B3\",\n \"Gammad\":\"\\u03DC\",\n \"gammad\":\"\\u03DD\",\n \"gap\":\"\\u2A86\",\n \"Gbreve\":\"\\u011E\",\n \"gbreve\":\"\\u011F\",\n \"Gcedil\":\"\\u0122\",\n \"Gcirc\":\"\\u011C\",\n \"gcirc\":\"\\u011D\",\n \"Gcy\":\"\\u0413\",\n \"gcy\":\"\\u0433\",\n \"Gdot\":\"\\u0120\",\n \"gdot\":\"\\u0121\",\n \"gE\":\"\\u2267\",\n \"ge\":\"\\u2265\",\n \"gEl\":\"\\u2A8C\",\n \"gel\":\"\\u22DB\",\n \"geq\":\"\\u2265\",\n \"geqq\":\"\\u2267\",\n \"geqslant\":\"\\u2A7E\",\n \"ges\":\"\\u2A7E\",\n \"gescc\":\"\\u2AA9\",\n \"gesdot\":\"\\u2A80\",\n \"gesdoto\":\"\\u2A82\",\n \"gesdotol\":\"\\u2A84\",\n \"gesl\":\"\\u22DB\\uFE00\",\n \"gesles\":\"\\u2A94\",\n \"Gfr\":\"\\uD835\\uDD0A\",\n \"gfr\":\"\\uD835\\uDD24\",\n \"Gg\":\"\\u22D9\",\n \"gg\":\"\\u226B\",\n \"ggg\":\"\\u22D9\",\n \"gimel\":\"\\u2137\",\n \"GJcy\":\"\\u0403\",\n \"gjcy\":\"\\u0453\",\n \"gl\":\"\\u2277\",\n \"gla\":\"\\u2AA5\",\n \"glE\":\"\\u2A92\",\n \"glj\":\"\\u2AA4\",\n \"gnap\":\"\\u2A8A\",\n \"gnapprox\":\"\\u2A8A\",\n \"gnE\":\"\\u2269\",\n \"gne\":\"\\u2A88\",\n \"gneq\":\"\\u2A88\",\n \"gneqq\":\"\\u2269\",\n \"gnsim\":\"\\u22E7\",\n \"Gopf\":\"\\uD835\\uDD3E\",\n \"gopf\":\"\\uD835\\uDD58\",\n \"grave\":\"\\u0060\",\n \"GreaterEqual\":\"\\u2265\",\n \"GreaterEqualLess\":\"\\u22DB\",\n \"GreaterFullEqual\":\"\\u2267\",\n \"GreaterGreater\":\"\\u2AA2\",\n \"GreaterLess\":\"\\u2277\",\n \"GreaterSlantEqual\":\"\\u2A7E\",\n \"GreaterTilde\":\"\\u2273\",\n \"Gscr\":\"\\uD835\\uDCA2\",\n \"gscr\":\"\\u210A\",\n \"gsim\":\"\\u2273\",\n \"gsime\":\"\\u2A8E\",\n \"gsiml\":\"\\u2A90\",\n \"GT\":\"\\u003E\",\n \"Gt\":\"\\u226B\",\n \"gt\":\"\\u003E\",\n \"gtcc\":\"\\u2AA7\",\n \"gtcir\":\"\\u2A7A\",\n \"gtdot\":\"\\u22D7\",\n \"gtlPar\":\"\\u2995\",\n \"gtquest\":\"\\u2A7C\",\n \"gtrapprox\":\"\\u2A86\",\n \"gtrarr\":\"\\u2978\",\n \"gtrdot\":\"\\u22D7\",\n \"gtreqless\":\"\\u22DB\",\n \"gtreqqless\":\"\\u2A8C\",\n \"gtrless\":\"\\u2277\",\n \"gtrsim\":\"\\u2273\",\n \"gvertneqq\":\"\\u2269\\uFE00\",\n \"gvnE\":\"\\u2269\\uFE00\",\n \"Hacek\":\"\\u02C7\",\n \"hairsp\":\"\\u200A\",\n \"half\":\"\\u00BD\",\n \"hamilt\":\"\\u210B\",\n \"HARDcy\":\"\\u042A\",\n \"hardcy\":\"\\u044A\",\n \"hArr\":\"\\u21D4\",\n \"harr\":\"\\u2194\",\n \"harrcir\":\"\\u2948\",\n \"harrw\":\"\\u21AD\",\n \"Hat\":\"\\u005E\",\n \"hbar\":\"\\u210F\",\n \"Hcirc\":\"\\u0124\",\n \"hcirc\":\"\\u0125\",\n \"hearts\":\"\\u2665\",\n \"heartsuit\":\"\\u2665\",\n \"hellip\":\"\\u2026\",\n \"hercon\":\"\\u22B9\",\n \"Hfr\":\"\\u210C\",\n \"hfr\":\"\\uD835\\uDD25\",\n \"HilbertSpace\":\"\\u210B\",\n \"hksearow\":\"\\u2925\",\n \"hkswarow\":\"\\u2926\",\n \"hoarr\":\"\\u21FF\",\n \"homtht\":\"\\u223B\",\n \"hookleftarrow\":\"\\u21A9\",\n \"hookrightarrow\":\"\\u21AA\",\n \"Hopf\":\"\\u210D\",\n \"hopf\":\"\\uD835\\uDD59\",\n \"horbar\":\"\\u2015\",\n \"HorizontalLine\":\"\\u2500\",\n \"Hscr\":\"\\u210B\",\n \"hscr\":\"\\uD835\\uDCBD\",\n \"hslash\":\"\\u210F\",\n \"Hstrok\":\"\\u0126\",\n \"hstrok\":\"\\u0127\",\n \"HumpDownHump\":\"\\u224E\",\n \"HumpEqual\":\"\\u224F\",\n \"hybull\":\"\\u2043\",\n \"hyphen\":\"\\u2010\",\n \"Iacute\":\"\\u00CD\",\n \"iacute\":\"\\u00ED\",\n \"ic\":\"\\u2063\",\n \"Icirc\":\"\\u00CE\",\n \"icirc\":\"\\u00EE\",\n \"Icy\":\"\\u0418\",\n \"icy\":\"\\u0438\",\n \"Idot\":\"\\u0130\",\n \"IEcy\":\"\\u0415\",\n \"iecy\":\"\\u0435\",\n \"iexcl\":\"\\u00A1\",\n \"iff\":\"\\u21D4\",\n \"Ifr\":\"\\u2111\",\n \"ifr\":\"\\uD835\\uDD26\",\n \"Igrave\":\"\\u00CC\",\n \"igrave\":\"\\u00EC\",\n \"ii\":\"\\u2148\",\n \"iiiint\":\"\\u2A0C\",\n \"iiint\":\"\\u222D\",\n \"iinfin\":\"\\u29DC\",\n \"iiota\":\"\\u2129\",\n \"IJlig\":\"\\u0132\",\n \"ijlig\":\"\\u0133\",\n \"Im\":\"\\u2111\",\n \"Imacr\":\"\\u012A\",\n \"imacr\":\"\\u012B\",\n \"image\":\"\\u2111\",\n \"ImaginaryI\":\"\\u2148\",\n \"imagline\":\"\\u2110\",\n \"imagpart\":\"\\u2111\",\n \"imath\":\"\\u0131\",\n \"imof\":\"\\u22B7\",\n \"imped\":\"\\u01B5\",\n \"Implies\":\"\\u21D2\",\n \"in\":\"\\u2208\",\n \"incare\":\"\\u2105\",\n \"infin\":\"\\u221E\",\n \"infintie\":\"\\u29DD\",\n \"inodot\":\"\\u0131\",\n \"Int\":\"\\u222C\",\n \"int\":\"\\u222B\",\n \"intcal\":\"\\u22BA\",\n \"integers\":\"\\u2124\",\n \"Integral\":\"\\u222B\",\n \"intercal\":\"\\u22BA\",\n \"Intersection\":\"\\u22C2\",\n \"intlarhk\":\"\\u2A17\",\n \"intprod\":\"\\u2A3C\",\n \"InvisibleComma\":\"\\u2063\",\n \"InvisibleTimes\":\"\\u2062\",\n \"IOcy\":\"\\u0401\",\n \"iocy\":\"\\u0451\",\n \"Iogon\":\"\\u012E\",\n \"iogon\":\"\\u012F\",\n \"Iopf\":\"\\uD835\\uDD40\",\n \"iopf\":\"\\uD835\\uDD5A\",\n \"Iota\":\"\\u0399\",\n \"iota\":\"\\u03B9\",\n \"iprod\":\"\\u2A3C\",\n \"iquest\":\"\\u00BF\",\n \"Iscr\":\"\\u2110\",\n \"iscr\":\"\\uD835\\uDCBE\",\n \"isin\":\"\\u2208\",\n \"isindot\":\"\\u22F5\",\n \"isinE\":\"\\u22F9\",\n \"isins\":\"\\u22F4\",\n \"isinsv\":\"\\u22F3\",\n \"isinv\":\"\\u2208\",\n \"it\":\"\\u2062\",\n \"Itilde\":\"\\u0128\",\n \"itilde\":\"\\u0129\",\n \"Iukcy\":\"\\u0406\",\n \"iukcy\":\"\\u0456\",\n \"Iuml\":\"\\u00CF\",\n \"iuml\":\"\\u00EF\",\n \"Jcirc\":\"\\u0134\",\n \"jcirc\":\"\\u0135\",\n \"Jcy\":\"\\u0419\",\n \"jcy\":\"\\u0439\",\n \"Jfr\":\"\\uD835\\uDD0D\",\n \"jfr\":\"\\uD835\\uDD27\",\n \"jmath\":\"\\u0237\",\n \"Jopf\":\"\\uD835\\uDD41\",\n \"jopf\":\"\\uD835\\uDD5B\",\n \"Jscr\":\"\\uD835\\uDCA5\",\n \"jscr\":\"\\uD835\\uDCBF\",\n \"Jsercy\":\"\\u0408\",\n \"jsercy\":\"\\u0458\",\n \"Jukcy\":\"\\u0404\",\n \"jukcy\":\"\\u0454\",\n \"Kappa\":\"\\u039A\",\n \"kappa\":\"\\u03BA\",\n \"kappav\":\"\\u03F0\",\n \"Kcedil\":\"\\u0136\",\n \"kcedil\":\"\\u0137\",\n \"Kcy\":\"\\u041A\",\n \"kcy\":\"\\u043A\",\n \"Kfr\":\"\\uD835\\uDD0E\",\n \"kfr\":\"\\uD835\\uDD28\",\n \"kgreen\":\"\\u0138\",\n \"KHcy\":\"\\u0425\",\n \"khcy\":\"\\u0445\",\n \"KJcy\":\"\\u040C\",\n \"kjcy\":\"\\u045C\",\n \"Kopf\":\"\\uD835\\uDD42\",\n \"kopf\":\"\\uD835\\uDD5C\",\n \"Kscr\":\"\\uD835\\uDCA6\",\n \"kscr\":\"\\uD835\\uDCC0\",\n \"lAarr\":\"\\u21DA\",\n \"Lacute\":\"\\u0139\",\n \"lacute\":\"\\u013A\",\n \"laemptyv\":\"\\u29B4\",\n \"lagran\":\"\\u2112\",\n \"Lambda\":\"\\u039B\",\n \"lambda\":\"\\u03BB\",\n \"Lang\":\"\\u27EA\",\n \"lang\":\"\\u27E8\",\n \"langd\":\"\\u2991\",\n \"langle\":\"\\u27E8\",\n \"lap\":\"\\u2A85\",\n \"Laplacetrf\":\"\\u2112\",\n \"laquo\":\"\\u00AB\",\n \"Larr\":\"\\u219E\",\n \"lArr\":\"\\u21D0\",\n \"larr\":\"\\u2190\",\n \"larrb\":\"\\u21E4\",\n \"larrbfs\":\"\\u291F\",\n \"larrfs\":\"\\u291D\",\n \"larrhk\":\"\\u21A9\",\n \"larrlp\":\"\\u21AB\",\n \"larrpl\":\"\\u2939\",\n \"larrsim\":\"\\u2973\",\n \"larrtl\":\"\\u21A2\",\n \"lat\":\"\\u2AAB\",\n \"lAtail\":\"\\u291B\",\n \"latail\":\"\\u2919\",\n \"late\":\"\\u2AAD\",\n \"lates\":\"\\u2AAD\\uFE00\",\n \"lBarr\":\"\\u290E\",\n \"lbarr\":\"\\u290C\",\n \"lbbrk\":\"\\u2772\",\n \"lbrace\":\"\\u007B\",\n \"lbrack\":\"\\u005B\",\n \"lbrke\":\"\\u298B\",\n \"lbrksld\":\"\\u298F\",\n \"lbrkslu\":\"\\u298D\",\n \"Lcaron\":\"\\u013D\",\n \"lcaron\":\"\\u013E\",\n \"Lcedil\":\"\\u013B\",\n \"lcedil\":\"\\u013C\",\n \"lceil\":\"\\u2308\",\n \"lcub\":\"\\u007B\",\n \"Lcy\":\"\\u041B\",\n \"lcy\":\"\\u043B\",\n \"ldca\":\"\\u2936\",\n \"ldquo\":\"\\u201C\",\n \"ldquor\":\"\\u201E\",\n \"ldrdhar\":\"\\u2967\",\n \"ldrushar\":\"\\u294B\",\n \"ldsh\":\"\\u21B2\",\n \"lE\":\"\\u2266\",\n \"le\":\"\\u2264\",\n \"LeftAngleBracket\":\"\\u27E8\",\n \"LeftArrow\":\"\\u2190\",\n \"Leftarrow\":\"\\u21D0\",\n \"leftarrow\":\"\\u2190\",\n \"LeftArrowBar\":\"\\u21E4\",\n \"LeftArrowRightArrow\":\"\\u21C6\",\n \"leftarrowtail\":\"\\u21A2\",\n \"LeftCeiling\":\"\\u2308\",\n \"LeftDoubleBracket\":\"\\u27E6\",\n \"LeftDownTeeVector\":\"\\u2961\",\n \"LeftDownVector\":\"\\u21C3\",\n \"LeftDownVectorBar\":\"\\u2959\",\n \"LeftFloor\":\"\\u230A\",\n \"leftharpoondown\":\"\\u21BD\",\n \"leftharpoonup\":\"\\u21BC\",\n \"leftleftarrows\":\"\\u21C7\",\n \"LeftRightArrow\":\"\\u2194\",\n \"Leftrightarrow\":\"\\u21D4\",\n \"leftrightarrow\":\"\\u2194\",\n \"leftrightarrows\":\"\\u21C6\",\n \"leftrightharpoons\":\"\\u21CB\",\n \"leftrightsquigarrow\":\"\\u21AD\",\n \"LeftRightVector\":\"\\u294E\",\n \"LeftTee\":\"\\u22A3\",\n \"LeftTeeArrow\":\"\\u21A4\",\n \"LeftTeeVector\":\"\\u295A\",\n \"leftthreetimes\":\"\\u22CB\",\n \"LeftTriangle\":\"\\u22B2\",\n \"LeftTriangleBar\":\"\\u29CF\",\n \"LeftTriangleEqual\":\"\\u22B4\",\n \"LeftUpDownVector\":\"\\u2951\",\n \"LeftUpTeeVector\":\"\\u2960\",\n \"LeftUpVector\":\"\\u21BF\",\n \"LeftUpVectorBar\":\"\\u2958\",\n \"LeftVector\":\"\\u21BC\",\n \"LeftVectorBar\":\"\\u2952\",\n \"lEg\":\"\\u2A8B\",\n \"leg\":\"\\u22DA\",\n \"leq\":\"\\u2264\",\n \"leqq\":\"\\u2266\",\n \"leqslant\":\"\\u2A7D\",\n \"les\":\"\\u2A7D\",\n \"lescc\":\"\\u2AA8\",\n \"lesdot\":\"\\u2A7F\",\n \"lesdoto\":\"\\u2A81\",\n \"lesdotor\":\"\\u2A83\",\n \"lesg\":\"\\u22DA\\uFE00\",\n \"lesges\":\"\\u2A93\",\n \"lessapprox\":\"\\u2A85\",\n \"lessdot\":\"\\u22D6\",\n \"lesseqgtr\":\"\\u22DA\",\n \"lesseqqgtr\":\"\\u2A8B\",\n \"LessEqualGreater\":\"\\u22DA\",\n \"LessFullEqual\":\"\\u2266\",\n \"LessGreater\":\"\\u2276\",\n \"lessgtr\":\"\\u2276\",\n \"LessLess\":\"\\u2AA1\",\n \"lesssim\":\"\\u2272\",\n \"LessSlantEqual\":\"\\u2A7D\",\n \"LessTilde\":\"\\u2272\",\n \"lfisht\":\"\\u297C\",\n \"lfloor\":\"\\u230A\",\n \"Lfr\":\"\\uD835\\uDD0F\",\n \"lfr\":\"\\uD835\\uDD29\",\n \"lg\":\"\\u2276\",\n \"lgE\":\"\\u2A91\",\n \"lHar\":\"\\u2962\",\n \"lhard\":\"\\u21BD\",\n \"lharu\":\"\\u21BC\",\n \"lharul\":\"\\u296A\",\n \"lhblk\":\"\\u2584\",\n \"LJcy\":\"\\u0409\",\n \"ljcy\":\"\\u0459\",\n \"Ll\":\"\\u22D8\",\n \"ll\":\"\\u226A\",\n \"llarr\":\"\\u21C7\",\n \"llcorner\":\"\\u231E\",\n \"Lleftarrow\":\"\\u21DA\",\n \"llhard\":\"\\u296B\",\n \"lltri\":\"\\u25FA\",\n \"Lmidot\":\"\\u013F\",\n \"lmidot\":\"\\u0140\",\n \"lmoust\":\"\\u23B0\",\n \"lmoustache\":\"\\u23B0\",\n \"lnap\":\"\\u2A89\",\n \"lnapprox\":\"\\u2A89\",\n \"lnE\":\"\\u2268\",\n \"lne\":\"\\u2A87\",\n \"lneq\":\"\\u2A87\",\n \"lneqq\":\"\\u2268\",\n \"lnsim\":\"\\u22E6\",\n \"loang\":\"\\u27EC\",\n \"loarr\":\"\\u21FD\",\n \"lobrk\":\"\\u27E6\",\n \"LongLeftArrow\":\"\\u27F5\",\n \"Longleftarrow\":\"\\u27F8\",\n \"longleftarrow\":\"\\u27F5\",\n \"LongLeftRightArrow\":\"\\u27F7\",\n \"Longleftrightarrow\":\"\\u27FA\",\n \"longleftrightarrow\":\"\\u27F7\",\n \"longmapsto\":\"\\u27FC\",\n \"LongRightArrow\":\"\\u27F6\",\n \"Longrightarrow\":\"\\u27F9\",\n \"longrightarrow\":\"\\u27F6\",\n \"looparrowleft\":\"\\u21AB\",\n \"looparrowright\":\"\\u21AC\",\n \"lopar\":\"\\u2985\",\n \"Lopf\":\"\\uD835\\uDD43\",\n \"lopf\":\"\\uD835\\uDD5D\",\n \"loplus\":\"\\u2A2D\",\n \"lotimes\":\"\\u2A34\",\n \"lowast\":\"\\u2217\",\n \"lowbar\":\"\\u005F\",\n \"LowerLeftArrow\":\"\\u2199\",\n \"LowerRightArrow\":\"\\u2198\",\n \"loz\":\"\\u25CA\",\n \"lozenge\":\"\\u25CA\",\n \"lozf\":\"\\u29EB\",\n \"lpar\":\"\\u0028\",\n \"lparlt\":\"\\u2993\",\n \"lrarr\":\"\\u21C6\",\n \"lrcorner\":\"\\u231F\",\n \"lrhar\":\"\\u21CB\",\n \"lrhard\":\"\\u296D\",\n \"lrm\":\"\\u200E\",\n \"lrtri\":\"\\u22BF\",\n \"lsaquo\":\"\\u2039\",\n \"Lscr\":\"\\u2112\",\n \"lscr\":\"\\uD835\\uDCC1\",\n \"Lsh\":\"\\u21B0\",\n \"lsh\":\"\\u21B0\",\n \"lsim\":\"\\u2272\",\n \"lsime\":\"\\u2A8D\",\n \"lsimg\":\"\\u2A8F\",\n \"lsqb\":\"\\u005B\",\n \"lsquo\":\"\\u2018\",\n \"lsquor\":\"\\u201A\",\n \"Lstrok\":\"\\u0141\",\n \"lstrok\":\"\\u0142\",\n \"LT\":\"\\u003C\",\n \"Lt\":\"\\u226A\",\n \"lt\":\"\\u003C\",\n \"ltcc\":\"\\u2AA6\",\n \"ltcir\":\"\\u2A79\",\n \"ltdot\":\"\\u22D6\",\n \"lthree\":\"\\u22CB\",\n \"ltimes\":\"\\u22C9\",\n \"ltlarr\":\"\\u2976\",\n \"ltquest\":\"\\u2A7B\",\n \"ltri\":\"\\u25C3\",\n \"ltrie\":\"\\u22B4\",\n \"ltrif\":\"\\u25C2\",\n \"ltrPar\":\"\\u2996\",\n \"lurdshar\":\"\\u294A\",\n \"luruhar\":\"\\u2966\",\n \"lvertneqq\":\"\\u2268\\uFE00\",\n \"lvnE\":\"\\u2268\\uFE00\",\n \"macr\":\"\\u00AF\",\n \"male\":\"\\u2642\",\n \"malt\":\"\\u2720\",\n \"maltese\":\"\\u2720\",\n \"Map\":\"\\u2905\",\n \"map\":\"\\u21A6\",\n \"mapsto\":\"\\u21A6\",\n \"mapstodown\":\"\\u21A7\",\n \"mapstoleft\":\"\\u21A4\",\n \"mapstoup\":\"\\u21A5\",\n \"marker\":\"\\u25AE\",\n \"mcomma\":\"\\u2A29\",\n \"Mcy\":\"\\u041C\",\n \"mcy\":\"\\u043C\",\n \"mdash\":\"\\u2014\",\n \"mDDot\":\"\\u223A\",\n \"measuredangle\":\"\\u2221\",\n \"MediumSpace\":\"\\u205F\",\n \"Mellintrf\":\"\\u2133\",\n \"Mfr\":\"\\uD835\\uDD10\",\n \"mfr\":\"\\uD835\\uDD2A\",\n \"mho\":\"\\u2127\",\n \"micro\":\"\\u00B5\",\n \"mid\":\"\\u2223\",\n \"midast\":\"\\u002A\",\n \"midcir\":\"\\u2AF0\",\n \"middot\":\"\\u00B7\",\n \"minus\":\"\\u2212\",\n \"minusb\":\"\\u229F\",\n \"minusd\":\"\\u2238\",\n \"minusdu\":\"\\u2A2A\",\n \"MinusPlus\":\"\\u2213\",\n \"mlcp\":\"\\u2ADB\",\n \"mldr\":\"\\u2026\",\n \"mnplus\":\"\\u2213\",\n \"models\":\"\\u22A7\",\n \"Mopf\":\"\\uD835\\uDD44\",\n \"mopf\":\"\\uD835\\uDD5E\",\n \"mp\":\"\\u2213\",\n \"Mscr\":\"\\u2133\",\n \"mscr\":\"\\uD835\\uDCC2\",\n \"mstpos\":\"\\u223E\",\n \"Mu\":\"\\u039C\",\n \"mu\":\"\\u03BC\",\n \"multimap\":\"\\u22B8\",\n \"mumap\":\"\\u22B8\",\n \"nabla\":\"\\u2207\",\n \"Nacute\":\"\\u0143\",\n \"nacute\":\"\\u0144\",\n \"nang\":\"\\u2220\\u20D2\",\n \"nap\":\"\\u2249\",\n \"napE\":\"\\u2A70\\u0338\",\n \"napid\":\"\\u224B\\u0338\",\n \"napos\":\"\\u0149\",\n \"napprox\":\"\\u2249\",\n \"natur\":\"\\u266E\",\n \"natural\":\"\\u266E\",\n \"naturals\":\"\\u2115\",\n \"nbsp\":\"\\u00A0\",\n \"nbump\":\"\\u224E\\u0338\",\n \"nbumpe\":\"\\u224F\\u0338\",\n \"ncap\":\"\\u2A43\",\n \"Ncaron\":\"\\u0147\",\n \"ncaron\":\"\\u0148\",\n \"Ncedil\":\"\\u0145\",\n \"ncedil\":\"\\u0146\",\n \"ncong\":\"\\u2247\",\n \"ncongdot\":\"\\u2A6D\\u0338\",\n \"ncup\":\"\\u2A42\",\n \"Ncy\":\"\\u041D\",\n \"ncy\":\"\\u043D\",\n \"ndash\":\"\\u2013\",\n \"ne\":\"\\u2260\",\n \"nearhk\":\"\\u2924\",\n \"neArr\":\"\\u21D7\",\n \"nearr\":\"\\u2197\",\n \"nearrow\":\"\\u2197\",\n \"nedot\":\"\\u2250\\u0338\",\n \"NegativeMediumSpace\":\"\\u200B\",\n \"NegativeThickSpace\":\"\\u200B\",\n \"NegativeThinSpace\":\"\\u200B\",\n \"NegativeVeryThinSpace\":\"\\u200B\",\n \"nequiv\":\"\\u2262\",\n \"nesear\":\"\\u2928\",\n \"nesim\":\"\\u2242\\u0338\",\n \"NestedGreaterGreater\":\"\\u226B\",\n \"NestedLessLess\":\"\\u226A\",\n \"NewLine\":\"\\u000A\",\n \"nexist\":\"\\u2204\",\n \"nexists\":\"\\u2204\",\n \"Nfr\":\"\\uD835\\uDD11\",\n \"nfr\":\"\\uD835\\uDD2B\",\n \"ngE\":\"\\u2267\\u0338\",\n \"nge\":\"\\u2271\",\n \"ngeq\":\"\\u2271\",\n \"ngeqq\":\"\\u2267\\u0338\",\n \"ngeqslant\":\"\\u2A7E\\u0338\",\n \"nges\":\"\\u2A7E\\u0338\",\n \"nGg\":\"\\u22D9\\u0338\",\n \"ngsim\":\"\\u2275\",\n \"nGt\":\"\\u226B\\u20D2\",\n \"ngt\":\"\\u226F\",\n \"ngtr\":\"\\u226F\",\n \"nGtv\":\"\\u226B\\u0338\",\n \"nhArr\":\"\\u21CE\",\n \"nharr\":\"\\u21AE\",\n \"nhpar\":\"\\u2AF2\",\n \"ni\":\"\\u220B\",\n \"nis\":\"\\u22FC\",\n \"nisd\":\"\\u22FA\",\n \"niv\":\"\\u220B\",\n \"NJcy\":\"\\u040A\",\n \"njcy\":\"\\u045A\",\n \"nlArr\":\"\\u21CD\",\n \"nlarr\":\"\\u219A\",\n \"nldr\":\"\\u2025\",\n \"nlE\":\"\\u2266\\u0338\",\n \"nle\":\"\\u2270\",\n \"nLeftarrow\":\"\\u21CD\",\n \"nleftarrow\":\"\\u219A\",\n \"nLeftrightarrow\":\"\\u21CE\",\n \"nleftrightarrow\":\"\\u21AE\",\n \"nleq\":\"\\u2270\",\n \"nleqq\":\"\\u2266\\u0338\",\n \"nleqslant\":\"\\u2A7D\\u0338\",\n \"nles\":\"\\u2A7D\\u0338\",\n \"nless\":\"\\u226E\",\n \"nLl\":\"\\u22D8\\u0338\",\n \"nlsim\":\"\\u2274\",\n \"nLt\":\"\\u226A\\u20D2\",\n \"nlt\":\"\\u226E\",\n \"nltri\":\"\\u22EA\",\n \"nltrie\":\"\\u22EC\",\n \"nLtv\":\"\\u226A\\u0338\",\n \"nmid\":\"\\u2224\",\n \"NoBreak\":\"\\u2060\",\n \"NonBreakingSpace\":\"\\u00A0\",\n \"Nopf\":\"\\u2115\",\n \"nopf\":\"\\uD835\\uDD5F\",\n \"Not\":\"\\u2AEC\",\n \"not\":\"\\u00AC\",\n \"NotCongruent\":\"\\u2262\",\n \"NotCupCap\":\"\\u226D\",\n \"NotDoubleVerticalBar\":\"\\u2226\",\n \"NotElement\":\"\\u2209\",\n \"NotEqual\":\"\\u2260\",\n \"NotEqualTilde\":\"\\u2242\\u0338\",\n \"NotExists\":\"\\u2204\",\n \"NotGreater\":\"\\u226F\",\n \"NotGreaterEqual\":\"\\u2271\",\n \"NotGreaterFullEqual\":\"\\u2267\\u0338\",\n \"NotGreaterGreater\":\"\\u226B\\u0338\",\n \"NotGreaterLess\":\"\\u2279\",\n \"NotGreaterSlantEqual\":\"\\u2A7E\\u0338\",\n \"NotGreaterTilde\":\"\\u2275\",\n \"NotHumpDownHump\":\"\\u224E\\u0338\",\n \"NotHumpEqual\":\"\\u224F\\u0338\",\n \"notin\":\"\\u2209\",\n \"notindot\":\"\\u22F5\\u0338\",\n \"notinE\":\"\\u22F9\\u0338\",\n \"notinva\":\"\\u2209\",\n \"notinvb\":\"\\u22F7\",\n \"notinvc\":\"\\u22F6\",\n \"NotLeftTriangle\":\"\\u22EA\",\n \"NotLeftTriangleBar\":\"\\u29CF\\u0338\",\n \"NotLeftTriangleEqual\":\"\\u22EC\",\n \"NotLess\":\"\\u226E\",\n \"NotLessEqual\":\"\\u2270\",\n \"NotLessGreater\":\"\\u2278\",\n \"NotLessLess\":\"\\u226A\\u0338\",\n \"NotLessSlantEqual\":\"\\u2A7D\\u0338\",\n \"NotLessTilde\":\"\\u2274\",\n \"NotNestedGreaterGreater\":\"\\u2AA2\\u0338\",\n \"NotNestedLessLess\":\"\\u2AA1\\u0338\",\n \"notni\":\"\\u220C\",\n \"notniva\":\"\\u220C\",\n \"notnivb\":\"\\u22FE\",\n \"notnivc\":\"\\u22FD\",\n \"NotPrecedes\":\"\\u2280\",\n \"NotPrecedesEqual\":\"\\u2AAF\\u0338\",\n \"NotPrecedesSlantEqual\":\"\\u22E0\",\n \"NotReverseElement\":\"\\u220C\",\n \"NotRightTriangle\":\"\\u22EB\",\n \"NotRightTriangleBar\":\"\\u29D0\\u0338\",\n \"NotRightTriangleEqual\":\"\\u22ED\",\n \"NotSquareSubset\":\"\\u228F\\u0338\",\n \"NotSquareSubsetEqual\":\"\\u22E2\",\n \"NotSquareSuperset\":\"\\u2290\\u0338\",\n \"NotSquareSupersetEqual\":\"\\u22E3\",\n \"NotSubset\":\"\\u2282\\u20D2\",\n \"NotSubsetEqual\":\"\\u2288\",\n \"NotSucceeds\":\"\\u2281\",\n \"NotSucceedsEqual\":\"\\u2AB0\\u0338\",\n \"NotSucceedsSlantEqual\":\"\\u22E1\",\n \"NotSucceedsTilde\":\"\\u227F\\u0338\",\n \"NotSuperset\":\"\\u2283\\u20D2\",\n \"NotSupersetEqual\":\"\\u2289\",\n \"NotTilde\":\"\\u2241\",\n \"NotTildeEqual\":\"\\u2244\",\n \"NotTildeFullEqual\":\"\\u2247\",\n \"NotTildeTilde\":\"\\u2249\",\n \"NotVerticalBar\":\"\\u2224\",\n \"npar\":\"\\u2226\",\n \"nparallel\":\"\\u2226\",\n \"nparsl\":\"\\u2AFD\\u20E5\",\n \"npart\":\"\\u2202\\u0338\",\n \"npolint\":\"\\u2A14\",\n \"npr\":\"\\u2280\",\n \"nprcue\":\"\\u22E0\",\n \"npre\":\"\\u2AAF\\u0338\",\n \"nprec\":\"\\u2280\",\n \"npreceq\":\"\\u2AAF\\u0338\",\n \"nrArr\":\"\\u21CF\",\n \"nrarr\":\"\\u219B\",\n \"nrarrc\":\"\\u2933\\u0338\",\n \"nrarrw\":\"\\u219D\\u0338\",\n \"nRightarrow\":\"\\u21CF\",\n \"nrightarrow\":\"\\u219B\",\n \"nrtri\":\"\\u22EB\",\n \"nrtrie\":\"\\u22ED\",\n \"nsc\":\"\\u2281\",\n \"nsccue\":\"\\u22E1\",\n \"nsce\":\"\\u2AB0\\u0338\",\n \"Nscr\":\"\\uD835\\uDCA9\",\n \"nscr\":\"\\uD835\\uDCC3\",\n \"nshortmid\":\"\\u2224\",\n \"nshortparallel\":\"\\u2226\",\n \"nsim\":\"\\u2241\",\n \"nsime\":\"\\u2244\",\n \"nsimeq\":\"\\u2244\",\n \"nsmid\":\"\\u2224\",\n \"nspar\":\"\\u2226\",\n \"nsqsube\":\"\\u22E2\",\n \"nsqsupe\":\"\\u22E3\",\n \"nsub\":\"\\u2284\",\n \"nsubE\":\"\\u2AC5\\u0338\",\n \"nsube\":\"\\u2288\",\n \"nsubset\":\"\\u2282\\u20D2\",\n \"nsubseteq\":\"\\u2288\",\n \"nsubseteqq\":\"\\u2AC5\\u0338\",\n \"nsucc\":\"\\u2281\",\n \"nsucceq\":\"\\u2AB0\\u0338\",\n \"nsup\":\"\\u2285\",\n \"nsupE\":\"\\u2AC6\\u0338\",\n \"nsupe\":\"\\u2289\",\n \"nsupset\":\"\\u2283\\u20D2\",\n \"nsupseteq\":\"\\u2289\",\n \"nsupseteqq\":\"\\u2AC6\\u0338\",\n \"ntgl\":\"\\u2279\",\n \"Ntilde\":\"\\u00D1\",\n \"ntilde\":\"\\u00F1\",\n \"ntlg\":\"\\u2278\",\n \"ntriangleleft\":\"\\u22EA\",\n \"ntrianglelefteq\":\"\\u22EC\",\n \"ntriangleright\":\"\\u22EB\",\n \"ntrianglerighteq\":\"\\u22ED\",\n \"Nu\":\"\\u039D\",\n \"nu\":\"\\u03BD\",\n \"num\":\"\\u0023\",\n \"numero\":\"\\u2116\",\n \"numsp\":\"\\u2007\",\n \"nvap\":\"\\u224D\\u20D2\",\n \"nVDash\":\"\\u22AF\",\n \"nVdash\":\"\\u22AE\",\n \"nvDash\":\"\\u22AD\",\n \"nvdash\":\"\\u22AC\",\n \"nvge\":\"\\u2265\\u20D2\",\n \"nvgt\":\"\\u003E\\u20D2\",\n \"nvHarr\":\"\\u2904\",\n \"nvinfin\":\"\\u29DE\",\n \"nvlArr\":\"\\u2902\",\n \"nvle\":\"\\u2264\\u20D2\",\n \"nvlt\":\"\\u003C\\u20D2\",\n \"nvltrie\":\"\\u22B4\\u20D2\",\n \"nvrArr\":\"\\u2903\",\n \"nvrtrie\":\"\\u22B5\\u20D2\",\n \"nvsim\":\"\\u223C\\u20D2\",\n \"nwarhk\":\"\\u2923\",\n \"nwArr\":\"\\u21D6\",\n \"nwarr\":\"\\u2196\",\n \"nwarrow\":\"\\u2196\",\n \"nwnear\":\"\\u2927\",\n \"Oacute\":\"\\u00D3\",\n \"oacute\":\"\\u00F3\",\n \"oast\":\"\\u229B\",\n \"ocir\":\"\\u229A\",\n \"Ocirc\":\"\\u00D4\",\n \"ocirc\":\"\\u00F4\",\n \"Ocy\":\"\\u041E\",\n \"ocy\":\"\\u043E\",\n \"odash\":\"\\u229D\",\n \"Odblac\":\"\\u0150\",\n \"odblac\":\"\\u0151\",\n \"odiv\":\"\\u2A38\",\n \"odot\":\"\\u2299\",\n \"odsold\":\"\\u29BC\",\n \"OElig\":\"\\u0152\",\n \"oelig\":\"\\u0153\",\n \"ofcir\":\"\\u29BF\",\n \"Ofr\":\"\\uD835\\uDD12\",\n \"ofr\":\"\\uD835\\uDD2C\",\n \"ogon\":\"\\u02DB\",\n \"Ograve\":\"\\u00D2\",\n \"ograve\":\"\\u00F2\",\n \"ogt\":\"\\u29C1\",\n \"ohbar\":\"\\u29B5\",\n \"ohm\":\"\\u03A9\",\n \"oint\":\"\\u222E\",\n \"olarr\":\"\\u21BA\",\n \"olcir\":\"\\u29BE\",\n \"olcross\":\"\\u29BB\",\n \"oline\":\"\\u203E\",\n \"olt\":\"\\u29C0\",\n \"Omacr\":\"\\u014C\",\n \"omacr\":\"\\u014D\",\n \"Omega\":\"\\u03A9\",\n \"omega\":\"\\u03C9\",\n \"Omicron\":\"\\u039F\",\n \"omicron\":\"\\u03BF\",\n \"omid\":\"\\u29B6\",\n \"ominus\":\"\\u2296\",\n \"Oopf\":\"\\uD835\\uDD46\",\n \"oopf\":\"\\uD835\\uDD60\",\n \"opar\":\"\\u29B7\",\n \"OpenCurlyDoubleQuote\":\"\\u201C\",\n \"OpenCurlyQuote\":\"\\u2018\",\n \"operp\":\"\\u29B9\",\n \"oplus\":\"\\u2295\",\n \"Or\":\"\\u2A54\",\n \"or\":\"\\u2228\",\n \"orarr\":\"\\u21BB\",\n \"ord\":\"\\u2A5D\",\n \"order\":\"\\u2134\",\n \"orderof\":\"\\u2134\",\n \"ordf\":\"\\u00AA\",\n \"ordm\":\"\\u00BA\",\n \"origof\":\"\\u22B6\",\n \"oror\":\"\\u2A56\",\n \"orslope\":\"\\u2A57\",\n \"orv\":\"\\u2A5B\",\n \"oS\":\"\\u24C8\",\n \"Oscr\":\"\\uD835\\uDCAA\",\n \"oscr\":\"\\u2134\",\n \"Oslash\":\"\\u00D8\",\n \"oslash\":\"\\u00F8\",\n \"osol\":\"\\u2298\",\n \"Otilde\":\"\\u00D5\",\n \"otilde\":\"\\u00F5\",\n \"Otimes\":\"\\u2A37\",\n \"otimes\":\"\\u2297\",\n \"otimesas\":\"\\u2A36\",\n \"Ouml\":\"\\u00D6\",\n \"ouml\":\"\\u00F6\",\n \"ovbar\":\"\\u233D\",\n \"OverBar\":\"\\u203E\",\n \"OverBrace\":\"\\u23DE\",\n \"OverBracket\":\"\\u23B4\",\n \"OverParenthesis\":\"\\u23DC\",\n \"par\":\"\\u2225\",\n \"para\":\"\\u00B6\",\n \"parallel\":\"\\u2225\",\n \"parsim\":\"\\u2AF3\",\n \"parsl\":\"\\u2AFD\",\n \"part\":\"\\u2202\",\n \"PartialD\":\"\\u2202\",\n \"Pcy\":\"\\u041F\",\n \"pcy\":\"\\u043F\",\n \"percnt\":\"\\u0025\",\n \"period\":\"\\u002E\",\n \"permil\":\"\\u2030\",\n \"perp\":\"\\u22A5\",\n \"pertenk\":\"\\u2031\",\n \"Pfr\":\"\\uD835\\uDD13\",\n \"pfr\":\"\\uD835\\uDD2D\",\n \"Phi\":\"\\u03A6\",\n \"phi\":\"\\u03C6\",\n \"phiv\":\"\\u03D5\",\n \"phmmat\":\"\\u2133\",\n \"phone\":\"\\u260E\",\n \"Pi\":\"\\u03A0\",\n \"pi\":\"\\u03C0\",\n \"pitchfork\":\"\\u22D4\",\n \"piv\":\"\\u03D6\",\n \"planck\":\"\\u210F\",\n \"planckh\":\"\\u210E\",\n \"plankv\":\"\\u210F\",\n \"plus\":\"\\u002B\",\n \"plusacir\":\"\\u2A23\",\n \"plusb\":\"\\u229E\",\n \"pluscir\":\"\\u2A22\",\n \"plusdo\":\"\\u2214\",\n \"plusdu\":\"\\u2A25\",\n \"pluse\":\"\\u2A72\",\n \"PlusMinus\":\"\\u00B1\",\n \"plusmn\":\"\\u00B1\",\n \"plussim\":\"\\u2A26\",\n \"plustwo\":\"\\u2A27\",\n \"pm\":\"\\u00B1\",\n \"Poincareplane\":\"\\u210C\",\n \"pointint\":\"\\u2A15\",\n \"Popf\":\"\\u2119\",\n \"popf\":\"\\uD835\\uDD61\",\n \"pound\":\"\\u00A3\",\n \"Pr\":\"\\u2ABB\",\n \"pr\":\"\\u227A\",\n \"prap\":\"\\u2AB7\",\n \"prcue\":\"\\u227C\",\n \"prE\":\"\\u2AB3\",\n \"pre\":\"\\u2AAF\",\n \"prec\":\"\\u227A\",\n \"precapprox\":\"\\u2AB7\",\n \"preccurlyeq\":\"\\u227C\",\n \"Precedes\":\"\\u227A\",\n \"PrecedesEqual\":\"\\u2AAF\",\n \"PrecedesSlantEqual\":\"\\u227C\",\n \"PrecedesTilde\":\"\\u227E\",\n \"preceq\":\"\\u2AAF\",\n \"precnapprox\":\"\\u2AB9\",\n \"precneqq\":\"\\u2AB5\",\n \"precnsim\":\"\\u22E8\",\n \"precsim\":\"\\u227E\",\n \"Prime\":\"\\u2033\",\n \"prime\":\"\\u2032\",\n \"primes\":\"\\u2119\",\n \"prnap\":\"\\u2AB9\",\n \"prnE\":\"\\u2AB5\",\n \"prnsim\":\"\\u22E8\",\n \"prod\":\"\\u220F\",\n \"Product\":\"\\u220F\",\n \"profalar\":\"\\u232E\",\n \"profline\":\"\\u2312\",\n \"profsurf\":\"\\u2313\",\n \"prop\":\"\\u221D\",\n \"Proportion\":\"\\u2237\",\n \"Proportional\":\"\\u221D\",\n \"propto\":\"\\u221D\",\n \"prsim\":\"\\u227E\",\n \"prurel\":\"\\u22B0\",\n \"Pscr\":\"\\uD835\\uDCAB\",\n \"pscr\":\"\\uD835\\uDCC5\",\n \"Psi\":\"\\u03A8\",\n \"psi\":\"\\u03C8\",\n \"puncsp\":\"\\u2008\",\n \"Qfr\":\"\\uD835\\uDD14\",\n \"qfr\":\"\\uD835\\uDD2E\",\n \"qint\":\"\\u2A0C\",\n \"Qopf\":\"\\u211A\",\n \"qopf\":\"\\uD835\\uDD62\",\n \"qprime\":\"\\u2057\",\n \"Qscr\":\"\\uD835\\uDCAC\",\n \"qscr\":\"\\uD835\\uDCC6\",\n \"quaternions\":\"\\u210D\",\n \"quatint\":\"\\u2A16\",\n \"quest\":\"\\u003F\",\n \"questeq\":\"\\u225F\",\n \"QUOT\":\"\\u0022\",\n \"quot\":\"\\u0022\",\n \"rAarr\":\"\\u21DB\",\n \"race\":\"\\u223D\\u0331\",\n \"Racute\":\"\\u0154\",\n \"racute\":\"\\u0155\",\n \"radic\":\"\\u221A\",\n \"raemptyv\":\"\\u29B3\",\n \"Rang\":\"\\u27EB\",\n \"rang\":\"\\u27E9\",\n \"rangd\":\"\\u2992\",\n \"range\":\"\\u29A5\",\n \"rangle\":\"\\u27E9\",\n \"raquo\":\"\\u00BB\",\n \"Rarr\":\"\\u21A0\",\n \"rArr\":\"\\u21D2\",\n \"rarr\":\"\\u2192\",\n \"rarrap\":\"\\u2975\",\n \"rarrb\":\"\\u21E5\",\n \"rarrbfs\":\"\\u2920\",\n \"rarrc\":\"\\u2933\",\n \"rarrfs\":\"\\u291E\",\n \"rarrhk\":\"\\u21AA\",\n \"rarrlp\":\"\\u21AC\",\n \"rarrpl\":\"\\u2945\",\n \"rarrsim\":\"\\u2974\",\n \"Rarrtl\":\"\\u2916\",\n \"rarrtl\":\"\\u21A3\",\n \"rarrw\":\"\\u219D\",\n \"rAtail\":\"\\u291C\",\n \"ratail\":\"\\u291A\",\n \"ratio\":\"\\u2236\",\n \"rationals\":\"\\u211A\",\n \"RBarr\":\"\\u2910\",\n \"rBarr\":\"\\u290F\",\n \"rbarr\":\"\\u290D\",\n \"rbbrk\":\"\\u2773\",\n \"rbrace\":\"\\u007D\",\n \"rbrack\":\"\\u005D\",\n \"rbrke\":\"\\u298C\",\n \"rbrksld\":\"\\u298E\",\n \"rbrkslu\":\"\\u2990\",\n \"Rcaron\":\"\\u0158\",\n \"rcaron\":\"\\u0159\",\n \"Rcedil\":\"\\u0156\",\n \"rcedil\":\"\\u0157\",\n \"rceil\":\"\\u2309\",\n \"rcub\":\"\\u007D\",\n \"Rcy\":\"\\u0420\",\n \"rcy\":\"\\u0440\",\n \"rdca\":\"\\u2937\",\n \"rdldhar\":\"\\u2969\",\n \"rdquo\":\"\\u201D\",\n \"rdquor\":\"\\u201D\",\n \"rdsh\":\"\\u21B3\",\n \"Re\":\"\\u211C\",\n \"real\":\"\\u211C\",\n \"realine\":\"\\u211B\",\n \"realpart\":\"\\u211C\",\n \"reals\":\"\\u211D\",\n \"rect\":\"\\u25AD\",\n \"REG\":\"\\u00AE\",\n \"reg\":\"\\u00AE\",\n \"ReverseElement\":\"\\u220B\",\n \"ReverseEquilibrium\":\"\\u21CB\",\n \"ReverseUpEquilibrium\":\"\\u296F\",\n \"rfisht\":\"\\u297D\",\n \"rfloor\":\"\\u230B\",\n \"Rfr\":\"\\u211C\",\n \"rfr\":\"\\uD835\\uDD2F\",\n \"rHar\":\"\\u2964\",\n \"rhard\":\"\\u21C1\",\n \"rharu\":\"\\u21C0\",\n \"rharul\":\"\\u296C\",\n \"Rho\":\"\\u03A1\",\n \"rho\":\"\\u03C1\",\n \"rhov\":\"\\u03F1\",\n \"RightAngleBracket\":\"\\u27E9\",\n \"RightArrow\":\"\\u2192\",\n \"Rightarrow\":\"\\u21D2\",\n \"rightarrow\":\"\\u2192\",\n \"RightArrowBar\":\"\\u21E5\",\n \"RightArrowLeftArrow\":\"\\u21C4\",\n \"rightarrowtail\":\"\\u21A3\",\n \"RightCeiling\":\"\\u2309\",\n \"RightDoubleBracket\":\"\\u27E7\",\n \"RightDownTeeVector\":\"\\u295D\",\n \"RightDownVector\":\"\\u21C2\",\n \"RightDownVectorBar\":\"\\u2955\",\n \"RightFloor\":\"\\u230B\",\n \"rightharpoondown\":\"\\u21C1\",\n \"rightharpoonup\":\"\\u21C0\",\n \"rightleftarrows\":\"\\u21C4\",\n \"rightleftharpoons\":\"\\u21CC\",\n \"rightrightarrows\":\"\\u21C9\",\n \"rightsquigarrow\":\"\\u219D\",\n \"RightTee\":\"\\u22A2\",\n \"RightTeeArrow\":\"\\u21A6\",\n \"RightTeeVector\":\"\\u295B\",\n \"rightthreetimes\":\"\\u22CC\",\n \"RightTriangle\":\"\\u22B3\",\n \"RightTriangleBar\":\"\\u29D0\",\n \"RightTriangleEqual\":\"\\u22B5\",\n \"RightUpDownVector\":\"\\u294F\",\n \"RightUpTeeVector\":\"\\u295C\",\n \"RightUpVector\":\"\\u21BE\",\n \"RightUpVectorBar\":\"\\u2954\",\n \"RightVector\":\"\\u21C0\",\n \"RightVectorBar\":\"\\u2953\",\n \"ring\":\"\\u02DA\",\n \"risingdotseq\":\"\\u2253\",\n \"rlarr\":\"\\u21C4\",\n \"rlhar\":\"\\u21CC\",\n \"rlm\":\"\\u200F\",\n \"rmoust\":\"\\u23B1\",\n \"rmoustache\":\"\\u23B1\",\n \"rnmid\":\"\\u2AEE\",\n \"roang\":\"\\u27ED\",\n \"roarr\":\"\\u21FE\",\n \"robrk\":\"\\u27E7\",\n \"ropar\":\"\\u2986\",\n \"Ropf\":\"\\u211D\",\n \"ropf\":\"\\uD835\\uDD63\",\n \"roplus\":\"\\u2A2E\",\n \"rotimes\":\"\\u2A35\",\n \"RoundImplies\":\"\\u2970\",\n \"rpar\":\"\\u0029\",\n \"rpargt\":\"\\u2994\",\n \"rppolint\":\"\\u2A12\",\n \"rrarr\":\"\\u21C9\",\n \"Rrightarrow\":\"\\u21DB\",\n \"rsaquo\":\"\\u203A\",\n \"Rscr\":\"\\u211B\",\n \"rscr\":\"\\uD835\\uDCC7\",\n \"Rsh\":\"\\u21B1\",\n \"rsh\":\"\\u21B1\",\n \"rsqb\":\"\\u005D\",\n \"rsquo\":\"\\u2019\",\n \"rsquor\":\"\\u2019\",\n \"rthree\":\"\\u22CC\",\n \"rtimes\":\"\\u22CA\",\n \"rtri\":\"\\u25B9\",\n \"rtrie\":\"\\u22B5\",\n \"rtrif\":\"\\u25B8\",\n \"rtriltri\":\"\\u29CE\",\n \"RuleDelayed\":\"\\u29F4\",\n \"ruluhar\":\"\\u2968\",\n \"rx\":\"\\u211E\",\n \"Sacute\":\"\\u015A\",\n \"sacute\":\"\\u015B\",\n \"sbquo\":\"\\u201A\",\n \"Sc\":\"\\u2ABC\",\n \"sc\":\"\\u227B\",\n \"scap\":\"\\u2AB8\",\n \"Scaron\":\"\\u0160\",\n \"scaron\":\"\\u0161\",\n \"sccue\":\"\\u227D\",\n \"scE\":\"\\u2AB4\",\n \"sce\":\"\\u2AB0\",\n \"Scedil\":\"\\u015E\",\n \"scedil\":\"\\u015F\",\n \"Scirc\":\"\\u015C\",\n \"scirc\":\"\\u015D\",\n \"scnap\":\"\\u2ABA\",\n \"scnE\":\"\\u2AB6\",\n \"scnsim\":\"\\u22E9\",\n \"scpolint\":\"\\u2A13\",\n \"scsim\":\"\\u227F\",\n \"Scy\":\"\\u0421\",\n \"scy\":\"\\u0441\",\n \"sdot\":\"\\u22C5\",\n \"sdotb\":\"\\u22A1\",\n \"sdote\":\"\\u2A66\",\n \"searhk\":\"\\u2925\",\n \"seArr\":\"\\u21D8\",\n \"searr\":\"\\u2198\",\n \"searrow\":\"\\u2198\",\n \"sect\":\"\\u00A7\",\n \"semi\":\"\\u003B\",\n \"seswar\":\"\\u2929\",\n \"setminus\":\"\\u2216\",\n \"setmn\":\"\\u2216\",\n \"sext\":\"\\u2736\",\n \"Sfr\":\"\\uD835\\uDD16\",\n \"sfr\":\"\\uD835\\uDD30\",\n \"sfrown\":\"\\u2322\",\n \"sharp\":\"\\u266F\",\n \"SHCHcy\":\"\\u0429\",\n \"shchcy\":\"\\u0449\",\n \"SHcy\":\"\\u0428\",\n \"shcy\":\"\\u0448\",\n \"ShortDownArrow\":\"\\u2193\",\n \"ShortLeftArrow\":\"\\u2190\",\n \"shortmid\":\"\\u2223\",\n \"shortparallel\":\"\\u2225\",\n \"ShortRightArrow\":\"\\u2192\",\n \"ShortUpArrow\":\"\\u2191\",\n \"shy\":\"\\u00AD\",\n \"Sigma\":\"\\u03A3\",\n \"sigma\":\"\\u03C3\",\n \"sigmaf\":\"\\u03C2\",\n \"sigmav\":\"\\u03C2\",\n \"sim\":\"\\u223C\",\n \"simdot\":\"\\u2A6A\",\n \"sime\":\"\\u2243\",\n \"simeq\":\"\\u2243\",\n \"simg\":\"\\u2A9E\",\n \"simgE\":\"\\u2AA0\",\n \"siml\":\"\\u2A9D\",\n \"simlE\":\"\\u2A9F\",\n \"simne\":\"\\u2246\",\n \"simplus\":\"\\u2A24\",\n \"simrarr\":\"\\u2972\",\n \"slarr\":\"\\u2190\",\n \"SmallCircle\":\"\\u2218\",\n \"smallsetminus\":\"\\u2216\",\n \"smashp\":\"\\u2A33\",\n \"smeparsl\":\"\\u29E4\",\n \"smid\":\"\\u2223\",\n \"smile\":\"\\u2323\",\n \"smt\":\"\\u2AAA\",\n \"smte\":\"\\u2AAC\",\n \"smtes\":\"\\u2AAC\\uFE00\",\n \"SOFTcy\":\"\\u042C\",\n \"softcy\":\"\\u044C\",\n \"sol\":\"\\u002F\",\n \"solb\":\"\\u29C4\",\n \"solbar\":\"\\u233F\",\n \"Sopf\":\"\\uD835\\uDD4A\",\n \"sopf\":\"\\uD835\\uDD64\",\n \"spades\":\"\\u2660\",\n \"spadesuit\":\"\\u2660\",\n \"spar\":\"\\u2225\",\n \"sqcap\":\"\\u2293\",\n \"sqcaps\":\"\\u2293\\uFE00\",\n \"sqcup\":\"\\u2294\",\n \"sqcups\":\"\\u2294\\uFE00\",\n \"Sqrt\":\"\\u221A\",\n \"sqsub\":\"\\u228F\",\n \"sqsube\":\"\\u2291\",\n \"sqsubset\":\"\\u228F\",\n \"sqsubseteq\":\"\\u2291\",\n \"sqsup\":\"\\u2290\",\n \"sqsupe\":\"\\u2292\",\n \"sqsupset\":\"\\u2290\",\n \"sqsupseteq\":\"\\u2292\",\n \"squ\":\"\\u25A1\",\n \"Square\":\"\\u25A1\",\n \"square\":\"\\u25A1\",\n \"SquareIntersection\":\"\\u2293\",\n \"SquareSubset\":\"\\u228F\",\n \"SquareSubsetEqual\":\"\\u2291\",\n \"SquareSuperset\":\"\\u2290\",\n \"SquareSupersetEqual\":\"\\u2292\",\n \"SquareUnion\":\"\\u2294\",\n \"squarf\":\"\\u25AA\",\n \"squf\":\"\\u25AA\",\n \"srarr\":\"\\u2192\",\n \"Sscr\":\"\\uD835\\uDCAE\",\n \"sscr\":\"\\uD835\\uDCC8\",\n \"ssetmn\":\"\\u2216\",\n \"ssmile\":\"\\u2323\",\n \"sstarf\":\"\\u22C6\",\n \"Star\":\"\\u22C6\",\n \"star\":\"\\u2606\",\n \"starf\":\"\\u2605\",\n \"straightepsilon\":\"\\u03F5\",\n \"straightphi\":\"\\u03D5\",\n \"strns\":\"\\u00AF\",\n \"Sub\":\"\\u22D0\",\n \"sub\":\"\\u2282\",\n \"subdot\":\"\\u2ABD\",\n \"subE\":\"\\u2AC5\",\n \"sube\":\"\\u2286\",\n \"subedot\":\"\\u2AC3\",\n \"submult\":\"\\u2AC1\",\n \"subnE\":\"\\u2ACB\",\n \"subne\":\"\\u228A\",\n \"subplus\":\"\\u2ABF\",\n \"subrarr\":\"\\u2979\",\n \"Subset\":\"\\u22D0\",\n \"subset\":\"\\u2282\",\n \"subseteq\":\"\\u2286\",\n \"subseteqq\":\"\\u2AC5\",\n \"SubsetEqual\":\"\\u2286\",\n \"subsetneq\":\"\\u228A\",\n \"subsetneqq\":\"\\u2ACB\",\n \"subsim\":\"\\u2AC7\",\n \"subsub\":\"\\u2AD5\",\n \"subsup\":\"\\u2AD3\",\n \"succ\":\"\\u227B\",\n \"succapprox\":\"\\u2AB8\",\n \"succcurlyeq\":\"\\u227D\",\n \"Succeeds\":\"\\u227B\",\n \"SucceedsEqual\":\"\\u2AB0\",\n \"SucceedsSlantEqual\":\"\\u227D\",\n \"SucceedsTilde\":\"\\u227F\",\n \"succeq\":\"\\u2AB0\",\n \"succnapprox\":\"\\u2ABA\",\n \"succneqq\":\"\\u2AB6\",\n \"succnsim\":\"\\u22E9\",\n \"succsim\":\"\\u227F\",\n \"SuchThat\":\"\\u220B\",\n \"Sum\":\"\\u2211\",\n \"sum\":\"\\u2211\",\n \"sung\":\"\\u266A\",\n \"Sup\":\"\\u22D1\",\n \"sup\":\"\\u2283\",\n \"sup1\":\"\\u00B9\",\n \"sup2\":\"\\u00B2\",\n \"sup3\":\"\\u00B3\",\n \"supdot\":\"\\u2ABE\",\n \"supdsub\":\"\\u2AD8\",\n \"supE\":\"\\u2AC6\",\n \"supe\":\"\\u2287\",\n \"supedot\":\"\\u2AC4\",\n \"Superset\":\"\\u2283\",\n \"SupersetEqual\":\"\\u2287\",\n \"suphsol\":\"\\u27C9\",\n \"suphsub\":\"\\u2AD7\",\n \"suplarr\":\"\\u297B\",\n \"supmult\":\"\\u2AC2\",\n \"supnE\":\"\\u2ACC\",\n \"supne\":\"\\u228B\",\n \"supplus\":\"\\u2AC0\",\n \"Supset\":\"\\u22D1\",\n \"supset\":\"\\u2283\",\n \"supseteq\":\"\\u2287\",\n \"supseteqq\":\"\\u2AC6\",\n \"supsetneq\":\"\\u228B\",\n \"supsetneqq\":\"\\u2ACC\",\n \"supsim\":\"\\u2AC8\",\n \"supsub\":\"\\u2AD4\",\n \"supsup\":\"\\u2AD6\",\n \"swarhk\":\"\\u2926\",\n \"swArr\":\"\\u21D9\",\n \"swarr\":\"\\u2199\",\n \"swarrow\":\"\\u2199\",\n \"swnwar\":\"\\u292A\",\n \"szlig\":\"\\u00DF\",\n \"Tab\":\"\\u0009\",\n \"target\":\"\\u2316\",\n \"Tau\":\"\\u03A4\",\n \"tau\":\"\\u03C4\",\n \"tbrk\":\"\\u23B4\",\n \"Tcaron\":\"\\u0164\",\n \"tcaron\":\"\\u0165\",\n \"Tcedil\":\"\\u0162\",\n \"tcedil\":\"\\u0163\",\n \"Tcy\":\"\\u0422\",\n \"tcy\":\"\\u0442\",\n \"tdot\":\"\\u20DB\",\n \"telrec\":\"\\u2315\",\n \"Tfr\":\"\\uD835\\uDD17\",\n \"tfr\":\"\\uD835\\uDD31\",\n \"there4\":\"\\u2234\",\n \"Therefore\":\"\\u2234\",\n \"therefore\":\"\\u2234\",\n \"Theta\":\"\\u0398\",\n \"theta\":\"\\u03B8\",\n \"thetasym\":\"\\u03D1\",\n \"thetav\":\"\\u03D1\",\n \"thickapprox\":\"\\u2248\",\n \"thicksim\":\"\\u223C\",\n \"ThickSpace\":\"\\u205F\\u200A\",\n \"thinsp\":\"\\u2009\",\n \"ThinSpace\":\"\\u2009\",\n \"thkap\":\"\\u2248\",\n \"thksim\":\"\\u223C\",\n \"THORN\":\"\\u00DE\",\n \"thorn\":\"\\u00FE\",\n \"Tilde\":\"\\u223C\",\n \"tilde\":\"\\u02DC\",\n \"TildeEqual\":\"\\u2243\",\n \"TildeFullEqual\":\"\\u2245\",\n \"TildeTilde\":\"\\u2248\",\n \"times\":\"\\u00D7\",\n \"timesb\":\"\\u22A0\",\n \"timesbar\":\"\\u2A31\",\n \"timesd\":\"\\u2A30\",\n \"tint\":\"\\u222D\",\n \"toea\":\"\\u2928\",\n \"top\":\"\\u22A4\",\n \"topbot\":\"\\u2336\",\n \"topcir\":\"\\u2AF1\",\n \"Topf\":\"\\uD835\\uDD4B\",\n \"topf\":\"\\uD835\\uDD65\",\n \"topfork\":\"\\u2ADA\",\n \"tosa\":\"\\u2929\",\n \"tprime\":\"\\u2034\",\n \"TRADE\":\"\\u2122\",\n \"trade\":\"\\u2122\",\n \"triangle\":\"\\u25B5\",\n \"triangledown\":\"\\u25BF\",\n \"triangleleft\":\"\\u25C3\",\n \"trianglelefteq\":\"\\u22B4\",\n \"triangleq\":\"\\u225C\",\n \"triangleright\":\"\\u25B9\",\n \"trianglerighteq\":\"\\u22B5\",\n \"tridot\":\"\\u25EC\",\n \"trie\":\"\\u225C\",\n \"triminus\":\"\\u2A3A\",\n \"TripleDot\":\"\\u20DB\",\n \"triplus\":\"\\u2A39\",\n \"trisb\":\"\\u29CD\",\n \"tritime\":\"\\u2A3B\",\n \"trpezium\":\"\\u23E2\",\n \"Tscr\":\"\\uD835\\uDCAF\",\n \"tscr\":\"\\uD835\\uDCC9\",\n \"TScy\":\"\\u0426\",\n \"tscy\":\"\\u0446\",\n \"TSHcy\":\"\\u040B\",\n \"tshcy\":\"\\u045B\",\n \"Tstrok\":\"\\u0166\",\n \"tstrok\":\"\\u0167\",\n \"twixt\":\"\\u226C\",\n \"twoheadleftarrow\":\"\\u219E\",\n \"twoheadrightarrow\":\"\\u21A0\",\n \"Uacute\":\"\\u00DA\",\n \"uacute\":\"\\u00FA\",\n \"Uarr\":\"\\u219F\",\n \"uArr\":\"\\u21D1\",\n \"uarr\":\"\\u2191\",\n \"Uarrocir\":\"\\u2949\",\n \"Ubrcy\":\"\\u040E\",\n \"ubrcy\":\"\\u045E\",\n \"Ubreve\":\"\\u016C\",\n \"ubreve\":\"\\u016D\",\n \"Ucirc\":\"\\u00DB\",\n \"ucirc\":\"\\u00FB\",\n \"Ucy\":\"\\u0423\",\n \"ucy\":\"\\u0443\",\n \"udarr\":\"\\u21C5\",\n \"Udblac\":\"\\u0170\",\n \"udblac\":\"\\u0171\",\n \"udhar\":\"\\u296E\",\n \"ufisht\":\"\\u297E\",\n \"Ufr\":\"\\uD835\\uDD18\",\n \"ufr\":\"\\uD835\\uDD32\",\n \"Ugrave\":\"\\u00D9\",\n \"ugrave\":\"\\u00F9\",\n \"uHar\":\"\\u2963\",\n \"uharl\":\"\\u21BF\",\n \"uharr\":\"\\u21BE\",\n \"uhblk\":\"\\u2580\",\n \"ulcorn\":\"\\u231C\",\n \"ulcorner\":\"\\u231C\",\n \"ulcrop\":\"\\u230F\",\n \"ultri\":\"\\u25F8\",\n \"Umacr\":\"\\u016A\",\n \"umacr\":\"\\u016B\",\n \"uml\":\"\\u00A8\",\n \"UnderBar\":\"\\u005F\",\n \"UnderBrace\":\"\\u23DF\",\n \"UnderBracket\":\"\\u23B5\",\n \"UnderParenthesis\":\"\\u23DD\",\n \"Union\":\"\\u22C3\",\n \"UnionPlus\":\"\\u228E\",\n \"Uogon\":\"\\u0172\",\n \"uogon\":\"\\u0173\",\n \"Uopf\":\"\\uD835\\uDD4C\",\n \"uopf\":\"\\uD835\\uDD66\",\n \"UpArrow\":\"\\u2191\",\n \"Uparrow\":\"\\u21D1\",\n \"uparrow\":\"\\u2191\",\n \"UpArrowBar\":\"\\u2912\",\n \"UpArrowDownArrow\":\"\\u21C5\",\n \"UpDownArrow\":\"\\u2195\",\n \"Updownarrow\":\"\\u21D5\",\n \"updownarrow\":\"\\u2195\",\n \"UpEquilibrium\":\"\\u296E\",\n \"upharpoonleft\":\"\\u21BF\",\n \"upharpoonright\":\"\\u21BE\",\n \"uplus\":\"\\u228E\",\n \"UpperLeftArrow\":\"\\u2196\",\n \"UpperRightArrow\":\"\\u2197\",\n \"Upsi\":\"\\u03D2\",\n \"upsi\":\"\\u03C5\",\n \"upsih\":\"\\u03D2\",\n \"Upsilon\":\"\\u03A5\",\n \"upsilon\":\"\\u03C5\",\n \"UpTee\":\"\\u22A5\",\n \"UpTeeArrow\":\"\\u21A5\",\n \"upuparrows\":\"\\u21C8\",\n \"urcorn\":\"\\u231D\",\n \"urcorner\":\"\\u231D\",\n \"urcrop\":\"\\u230E\",\n \"Uring\":\"\\u016E\",\n \"uring\":\"\\u016F\",\n \"urtri\":\"\\u25F9\",\n \"Uscr\":\"\\uD835\\uDCB0\",\n \"uscr\":\"\\uD835\\uDCCA\",\n \"utdot\":\"\\u22F0\",\n \"Utilde\":\"\\u0168\",\n \"utilde\":\"\\u0169\",\n \"utri\":\"\\u25B5\",\n \"utrif\":\"\\u25B4\",\n \"uuarr\":\"\\u21C8\",\n \"Uuml\":\"\\u00DC\",\n \"uuml\":\"\\u00FC\",\n \"uwangle\":\"\\u29A7\",\n \"vangrt\":\"\\u299C\",\n \"varepsilon\":\"\\u03F5\",\n \"varkappa\":\"\\u03F0\",\n \"varnothing\":\"\\u2205\",\n \"varphi\":\"\\u03D5\",\n \"varpi\":\"\\u03D6\",\n \"varpropto\":\"\\u221D\",\n \"vArr\":\"\\u21D5\",\n \"varr\":\"\\u2195\",\n \"varrho\":\"\\u03F1\",\n \"varsigma\":\"\\u03C2\",\n \"varsubsetneq\":\"\\u228A\\uFE00\",\n \"varsubsetneqq\":\"\\u2ACB\\uFE00\",\n \"varsupsetneq\":\"\\u228B\\uFE00\",\n \"varsupsetneqq\":\"\\u2ACC\\uFE00\",\n \"vartheta\":\"\\u03D1\",\n \"vartriangleleft\":\"\\u22B2\",\n \"vartriangleright\":\"\\u22B3\",\n \"Vbar\":\"\\u2AEB\",\n \"vBar\":\"\\u2AE8\",\n \"vBarv\":\"\\u2AE9\",\n \"Vcy\":\"\\u0412\",\n \"vcy\":\"\\u0432\",\n \"VDash\":\"\\u22AB\",\n \"Vdash\":\"\\u22A9\",\n \"vDash\":\"\\u22A8\",\n \"vdash\":\"\\u22A2\",\n \"Vdashl\":\"\\u2AE6\",\n \"Vee\":\"\\u22C1\",\n \"vee\":\"\\u2228\",\n \"veebar\":\"\\u22BB\",\n \"veeeq\":\"\\u225A\",\n \"vellip\":\"\\u22EE\",\n \"Verbar\":\"\\u2016\",\n \"verbar\":\"\\u007C\",\n \"Vert\":\"\\u2016\",\n \"vert\":\"\\u007C\",\n \"VerticalBar\":\"\\u2223\",\n \"VerticalLine\":\"\\u007C\",\n \"VerticalSeparator\":\"\\u2758\",\n \"VerticalTilde\":\"\\u2240\",\n \"VeryThinSpace\":\"\\u200A\",\n \"Vfr\":\"\\uD835\\uDD19\",\n \"vfr\":\"\\uD835\\uDD33\",\n \"vltri\":\"\\u22B2\",\n \"vnsub\":\"\\u2282\\u20D2\",\n \"vnsup\":\"\\u2283\\u20D2\",\n \"Vopf\":\"\\uD835\\uDD4D\",\n \"vopf\":\"\\uD835\\uDD67\",\n \"vprop\":\"\\u221D\",\n \"vrtri\":\"\\u22B3\",\n \"Vscr\":\"\\uD835\\uDCB1\",\n \"vscr\":\"\\uD835\\uDCCB\",\n \"vsubnE\":\"\\u2ACB\\uFE00\",\n \"vsubne\":\"\\u228A\\uFE00\",\n \"vsupnE\":\"\\u2ACC\\uFE00\",\n \"vsupne\":\"\\u228B\\uFE00\",\n \"Vvdash\":\"\\u22AA\",\n \"vzigzag\":\"\\u299A\",\n \"Wcirc\":\"\\u0174\",\n \"wcirc\":\"\\u0175\",\n \"wedbar\":\"\\u2A5F\",\n \"Wedge\":\"\\u22C0\",\n \"wedge\":\"\\u2227\",\n \"wedgeq\":\"\\u2259\",\n \"weierp\":\"\\u2118\",\n \"Wfr\":\"\\uD835\\uDD1A\",\n \"wfr\":\"\\uD835\\uDD34\",\n \"Wopf\":\"\\uD835\\uDD4E\",\n \"wopf\":\"\\uD835\\uDD68\",\n \"wp\":\"\\u2118\",\n \"wr\":\"\\u2240\",\n \"wreath\":\"\\u2240\",\n \"Wscr\":\"\\uD835\\uDCB2\",\n \"wscr\":\"\\uD835\\uDCCC\",\n \"xcap\":\"\\u22C2\",\n \"xcirc\":\"\\u25EF\",\n \"xcup\":\"\\u22C3\",\n \"xdtri\":\"\\u25BD\",\n \"Xfr\":\"\\uD835\\uDD1B\",\n \"xfr\":\"\\uD835\\uDD35\",\n \"xhArr\":\"\\u27FA\",\n \"xharr\":\"\\u27F7\",\n \"Xi\":\"\\u039E\",\n \"xi\":\"\\u03BE\",\n \"xlArr\":\"\\u27F8\",\n \"xlarr\":\"\\u27F5\",\n \"xmap\":\"\\u27FC\",\n \"xnis\":\"\\u22FB\",\n \"xodot\":\"\\u2A00\",\n \"Xopf\":\"\\uD835\\uDD4F\",\n \"xopf\":\"\\uD835\\uDD69\",\n \"xoplus\":\"\\u2A01\",\n \"xotime\":\"\\u2A02\",\n \"xrArr\":\"\\u27F9\",\n \"xrarr\":\"\\u27F6\",\n \"Xscr\":\"\\uD835\\uDCB3\",\n \"xscr\":\"\\uD835\\uDCCD\",\n \"xsqcup\":\"\\u2A06\",\n \"xuplus\":\"\\u2A04\",\n \"xutri\":\"\\u25B3\",\n \"xvee\":\"\\u22C1\",\n \"xwedge\":\"\\u22C0\",\n \"Yacute\":\"\\u00DD\",\n \"yacute\":\"\\u00FD\",\n \"YAcy\":\"\\u042F\",\n \"yacy\":\"\\u044F\",\n \"Ycirc\":\"\\u0176\",\n \"ycirc\":\"\\u0177\",\n \"Ycy\":\"\\u042B\",\n \"ycy\":\"\\u044B\",\n \"yen\":\"\\u00A5\",\n \"Yfr\":\"\\uD835\\uDD1C\",\n \"yfr\":\"\\uD835\\uDD36\",\n \"YIcy\":\"\\u0407\",\n \"yicy\":\"\\u0457\",\n \"Yopf\":\"\\uD835\\uDD50\",\n \"yopf\":\"\\uD835\\uDD6A\",\n \"Yscr\":\"\\uD835\\uDCB4\",\n \"yscr\":\"\\uD835\\uDCCE\",\n \"YUcy\":\"\\u042E\",\n \"yucy\":\"\\u044E\",\n \"Yuml\":\"\\u0178\",\n \"yuml\":\"\\u00FF\",\n \"Zacute\":\"\\u0179\",\n \"zacute\":\"\\u017A\",\n \"Zcaron\":\"\\u017D\",\n \"zcaron\":\"\\u017E\",\n \"Zcy\":\"\\u0417\",\n \"zcy\":\"\\u0437\",\n \"Zdot\":\"\\u017B\",\n \"zdot\":\"\\u017C\",\n \"zeetrf\":\"\\u2128\",\n \"ZeroWidthSpace\":\"\\u200B\",\n \"Zeta\":\"\\u0396\",\n \"zeta\":\"\\u03B6\",\n \"Zfr\":\"\\u2128\",\n \"zfr\":\"\\uD835\\uDD37\",\n \"ZHcy\":\"\\u0416\",\n \"zhcy\":\"\\u0436\",\n \"zigrarr\":\"\\u21DD\",\n \"Zopf\":\"\\u2124\",\n \"zopf\":\"\\uD835\\uDD6B\",\n \"Zscr\":\"\\uD835\\uDCB5\",\n \"zscr\":\"\\uD835\\uDCCF\",\n \"zwj\":\"\\u200D\",\n \"zwnj\":\"\\u200C\"\n};\n\nvar hasOwn = Object.prototype.hasOwnProperty;\n\nfunction has(object, key) {\n return object\n ? hasOwn.call(object, key)\n : false;\n}\n\nfunction decodeEntity(name) {\n if (has(entities, name)) {\n return entities[name]\n } else {\n return name;\n }\n}\n\n/**\n * Utility functions\n */\n\nfunction typeOf(obj) {\n return Object.prototype.toString.call(obj);\n}\n\nfunction isString(obj) {\n return typeOf(obj) === '[object String]';\n}\n\nvar hasOwn$1 = Object.prototype.hasOwnProperty;\n\nfunction has$1(object, key) {\n return object\n ? hasOwn$1.call(object, key)\n : false;\n}\n\n// Extend objects\n//\nfunction assign(obj /*from1, from2, from3, ...*/) {\n var sources = [].slice.call(arguments, 1);\n\n sources.forEach(function (source) {\n if (!source) { return; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be object');\n }\n\n Object.keys(source).forEach(function (key) {\n obj[key] = source[key];\n });\n });\n\n return obj;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nvar UNESCAPE_MD_RE = /\\\\([\\\\!\"#$%&'()*+,.\\/:;<=>?@[\\]^_`{|}~-])/g;\n\nfunction unescapeMd(str) {\n if (str.indexOf('\\\\') < 0) { return str; }\n return str.replace(UNESCAPE_MD_RE, '$1');\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nfunction isValidEntityCode(c) {\n /*eslint no-bitwise:0*/\n // broken sequence\n if (c >= 0xD800 && c <= 0xDFFF) { return false; }\n // never used\n if (c >= 0xFDD0 && c <= 0xFDEF) { return false; }\n if ((c & 0xFFFF) === 0xFFFF || (c & 0xFFFF) === 0xFFFE) { return false; }\n // control codes\n if (c >= 0x00 && c <= 0x08) { return false; }\n if (c === 0x0B) { return false; }\n if (c >= 0x0E && c <= 0x1F) { return false; }\n if (c >= 0x7F && c <= 0x9F) { return false; }\n // out of range\n if (c > 0x10FFFF) { return false; }\n return true;\n}\n\nfunction fromCodePoint(c) {\n /*eslint no-bitwise:0*/\n if (c > 0xffff) {\n c -= 0x10000;\n var surrogate1 = 0xd800 + (c >> 10),\n surrogate2 = 0xdc00 + (c & 0x3ff);\n\n return String.fromCharCode(surrogate1, surrogate2);\n }\n return String.fromCharCode(c);\n}\n\nvar NAMED_ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi;\nvar DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i;\n\nfunction replaceEntityPattern(match, name) {\n var code = 0;\n var decoded = decodeEntity(name);\n\n if (name !== decoded) {\n return decoded;\n } else if (name.charCodeAt(0) === 0x23/* # */ && DIGITAL_ENTITY_TEST_RE.test(name)) {\n code = name[1].toLowerCase() === 'x' ?\n parseInt(name.slice(2), 16)\n :\n parseInt(name.slice(1), 10);\n if (isValidEntityCode(code)) {\n return fromCodePoint(code);\n }\n }\n return match;\n}\n\nfunction replaceEntities(str) {\n if (str.indexOf('&') < 0) { return str; }\n\n return str.replace(NAMED_ENTITY_RE, replaceEntityPattern);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nvar HTML_ESCAPE_TEST_RE = /[&<>\"]/;\nvar HTML_ESCAPE_REPLACE_RE = /[&<>\"]/g;\nvar HTML_REPLACEMENTS = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"'\n};\n\nfunction replaceUnsafeChar(ch) {\n return HTML_REPLACEMENTS[ch];\n}\n\nfunction escapeHtml(str) {\n if (HTML_ESCAPE_TEST_RE.test(str)) {\n return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar);\n }\n return str;\n}\n\nvar utils = /*#__PURE__*/Object.freeze({\n isString: isString,\n has: has$1,\n assign: assign,\n unescapeMd: unescapeMd,\n isValidEntityCode: isValidEntityCode,\n fromCodePoint: fromCodePoint,\n replaceEntities: replaceEntities,\n escapeHtml: escapeHtml\n});\n\n/**\n * Renderer rules cache\n */\n\nvar rules = {};\n\n/**\n * Blockquotes\n */\n\nrules.blockquote_open = function(/* tokens, idx, options, env */) {\n return '
    \\n';\n};\n\nrules.blockquote_close = function(tokens, idx /*, options, env */) {\n return '
    ' + getBreak(tokens, idx);\n};\n\n/**\n * Code\n */\n\nrules.code = function(tokens, idx /*, options, env */) {\n if (tokens[idx].block) {\n return '
    ' + escapeHtml(tokens[idx].content) + '
    ' + getBreak(tokens, idx);\n }\n return '' + escapeHtml(tokens[idx].content) + '';\n};\n\n/**\n * Fenced code blocks\n */\n\nrules.fence = function(tokens, idx, options, env, instance) {\n var token = tokens[idx];\n var langClass = '';\n var langPrefix = options.langPrefix;\n var langName = '', fences, fenceName;\n var highlighted;\n\n if (token.params) {\n\n //\n // ```foo bar\n //\n // Try custom renderer \"foo\" first. That will simplify overwrite\n // for diagrams, latex, and any other fenced block with custom look\n //\n\n fences = token.params.split(/\\s+/g);\n fenceName = fences.join(' ');\n\n if (has$1(instance.rules.fence_custom, fences[0])) {\n return instance.rules.fence_custom[fences[0]](tokens, idx, options, env, instance);\n }\n\n langName = escapeHtml(replaceEntities(unescapeMd(fenceName)));\n langClass = ' class=\"' + langPrefix + langName + '\"';\n }\n\n if (options.highlight) {\n highlighted = options.highlight.apply(options.highlight, [ token.content ].concat(fences))\n || escapeHtml(token.content);\n } else {\n highlighted = escapeHtml(token.content);\n }\n\n return '
    '\n        + highlighted\n        + '
    '\n + getBreak(tokens, idx);\n};\n\nrules.fence_custom = {};\n\n/**\n * Headings\n */\n\nrules.heading_open = function(tokens, idx /*, options, env */) {\n return '';\n};\nrules.heading_close = function(tokens, idx /*, options, env */) {\n return '\\n';\n};\n\n/**\n * Horizontal rules\n */\n\nrules.hr = function(tokens, idx, options /*, env */) {\n return (options.xhtmlOut ? '
    ' : '
    ') + getBreak(tokens, idx);\n};\n\n/**\n * Bullets\n */\n\nrules.bullet_list_open = function(/* tokens, idx, options, env */) {\n return '
      \\n';\n};\nrules.bullet_list_close = function(tokens, idx /*, options, env */) {\n return '
    ' + getBreak(tokens, idx);\n};\n\n/**\n * List items\n */\n\nrules.list_item_open = function(/* tokens, idx, options, env */) {\n return '
  • ';\n};\nrules.list_item_close = function(/* tokens, idx, options, env */) {\n return '
  • \\n';\n};\n\n/**\n * Ordered list items\n */\n\nrules.ordered_list_open = function(tokens, idx /*, options, env */) {\n var token = tokens[idx];\n var order = token.order > 1 ? ' start=\"' + token.order + '\"' : '';\n return '\\n';\n};\nrules.ordered_list_close = function(tokens, idx /*, options, env */) {\n return '' + getBreak(tokens, idx);\n};\n\n/**\n * Paragraphs\n */\n\nrules.paragraph_open = function(tokens, idx /*, options, env */) {\n return tokens[idx].tight ? '' : '

    ';\n};\nrules.paragraph_close = function(tokens, idx /*, options, env */) {\n var addBreak = !(tokens[idx].tight && idx && tokens[idx - 1].type === 'inline' && !tokens[idx - 1].content);\n return (tokens[idx].tight ? '' : '

    ') + (addBreak ? getBreak(tokens, idx) : '');\n};\n\n/**\n * Links\n */\n\nrules.link_open = function(tokens, idx, options /* env */) {\n var title = tokens[idx].title ? (' title=\"' + escapeHtml(replaceEntities(tokens[idx].title)) + '\"') : '';\n var target = options.linkTarget ? (' target=\"' + options.linkTarget + '\"') : '';\n return '';\n};\nrules.link_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Images\n */\n\nrules.image = function(tokens, idx, options /*, env */) {\n var src = ' src=\"' + escapeHtml(tokens[idx].src) + '\"';\n var title = tokens[idx].title ? (' title=\"' + escapeHtml(replaceEntities(tokens[idx].title)) + '\"') : '';\n var alt = ' alt=\"' + (tokens[idx].alt ? escapeHtml(replaceEntities(unescapeMd(tokens[idx].alt))) : '') + '\"';\n var suffix = options.xhtmlOut ? ' /' : '';\n return '';\n};\n\n/**\n * Tables\n */\n\nrules.table_open = function(/* tokens, idx, options, env */) {\n return '\\n';\n};\nrules.table_close = function(/* tokens, idx, options, env */) {\n return '
    \\n';\n};\nrules.thead_open = function(/* tokens, idx, options, env */) {\n return '\\n';\n};\nrules.thead_close = function(/* tokens, idx, options, env */) {\n return '\\n';\n};\nrules.tbody_open = function(/* tokens, idx, options, env */) {\n return '\\n';\n};\nrules.tbody_close = function(/* tokens, idx, options, env */) {\n return '\\n';\n};\nrules.tr_open = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.tr_close = function(/* tokens, idx, options, env */) {\n return '\\n';\n};\nrules.th_open = function(tokens, idx /*, options, env */) {\n var token = tokens[idx];\n return '';\n};\nrules.th_close = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.td_open = function(tokens, idx /*, options, env */) {\n var token = tokens[idx];\n return '';\n};\nrules.td_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Bold\n */\n\nrules.strong_open = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.strong_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Italicize\n */\n\nrules.em_open = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.em_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Strikethrough\n */\n\nrules.del_open = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.del_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Insert\n */\n\nrules.ins_open = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.ins_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Highlight\n */\n\nrules.mark_open = function(/* tokens, idx, options, env */) {\n return '';\n};\nrules.mark_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Super- and sub-script\n */\n\nrules.sub = function(tokens, idx /*, options, env */) {\n return '' + escapeHtml(tokens[idx].content) + '';\n};\nrules.sup = function(tokens, idx /*, options, env */) {\n return '' + escapeHtml(tokens[idx].content) + '';\n};\n\n/**\n * Breaks\n */\n\nrules.hardbreak = function(tokens, idx, options /*, env */) {\n return options.xhtmlOut ? '
    \\n' : '
    \\n';\n};\nrules.softbreak = function(tokens, idx, options /*, env */) {\n return options.breaks ? (options.xhtmlOut ? '
    \\n' : '
    \\n') : '\\n';\n};\n\n/**\n * Text\n */\n\nrules.text = function(tokens, idx /*, options, env */) {\n return escapeHtml(tokens[idx].content);\n};\n\n/**\n * Content\n */\n\nrules.htmlblock = function(tokens, idx /*, options, env */) {\n return tokens[idx].content;\n};\nrules.htmltag = function(tokens, idx /*, options, env */) {\n return tokens[idx].content;\n};\n\n/**\n * Abbreviations, initialism\n */\n\nrules.abbr_open = function(tokens, idx /*, options, env */) {\n return '';\n};\nrules.abbr_close = function(/* tokens, idx, options, env */) {\n return '';\n};\n\n/**\n * Footnotes\n */\n\nrules.footnote_ref = function(tokens, idx) {\n var n = Number(tokens[idx].id + 1).toString();\n var id = 'fnref' + n;\n if (tokens[idx].subId > 0) {\n id += ':' + tokens[idx].subId;\n }\n return '[' + n + ']';\n};\nrules.footnote_block_open = function(tokens, idx, options) {\n var hr = options.xhtmlOut\n ? '
    \\n'\n : '
    \\n';\n return hr + '
    \\n
      \\n';\n};\nrules.footnote_block_close = function() {\n return '
    \\n
    \\n';\n};\nrules.footnote_open = function(tokens, idx) {\n var id = Number(tokens[idx].id + 1).toString();\n return '
  • ';\n};\nrules.footnote_close = function() {\n return '
  • \\n';\n};\nrules.footnote_anchor = function(tokens, idx) {\n var n = Number(tokens[idx].id + 1).toString();\n var id = 'fnref' + n;\n if (tokens[idx].subId > 0) {\n id += ':' + tokens[idx].subId;\n }\n return ' ';\n};\n\n/**\n * Definition lists\n */\n\nrules.dl_open = function() {\n return '
    \\n';\n};\nrules.dt_open = function() {\n return '
    ';\n};\nrules.dd_open = function() {\n return '
    ';\n};\nrules.dl_close = function() {\n return '
    \\n';\n};\nrules.dt_close = function() {\n return '\\n';\n};\nrules.dd_close = function() {\n return '\\n';\n};\n\n/**\n * Helper functions\n */\n\nfunction nextToken(tokens, idx) {\n if (++idx >= tokens.length - 2) {\n return idx;\n }\n if ((tokens[idx].type === 'paragraph_open' && tokens[idx].tight) &&\n (tokens[idx + 1].type === 'inline' && tokens[idx + 1].content.length === 0) &&\n (tokens[idx + 2].type === 'paragraph_close' && tokens[idx + 2].tight)) {\n return nextToken(tokens, idx + 2);\n }\n return idx;\n}\n\n/**\n * Check to see if `\\n` is needed before the next token.\n *\n * @param {Array} `tokens`\n * @param {Number} `idx`\n * @return {String} Empty string or newline\n * @api private\n */\n\nvar getBreak = rules.getBreak = function getBreak(tokens, idx) {\n idx = nextToken(tokens, idx);\n if (idx < tokens.length && tokens[idx].type === 'list_item_close') {\n return '';\n }\n return '\\n';\n};\n\n/**\n * Renderer class. Renders HTML and exposes `rules` to allow\n * local modifications.\n */\n\nfunction Renderer() {\n this.rules = assign({}, rules);\n\n // exported helper, for custom rules only\n this.getBreak = rules.getBreak;\n}\n\n/**\n * Render a string of inline HTML with the given `tokens` and\n * `options`.\n *\n * @param {Array} `tokens`\n * @param {Object} `options`\n * @param {Object} `env`\n * @return {String}\n * @api public\n */\n\nRenderer.prototype.renderInline = function (tokens, options, env) {\n var _rules = this.rules;\n var len = tokens.length, i = 0;\n var result = '';\n\n while (len--) {\n result += _rules[tokens[i].type](tokens, i++, options, env, this);\n }\n\n return result;\n};\n\n/**\n * Render a string of HTML with the given `tokens` and\n * `options`.\n *\n * @param {Array} `tokens`\n * @param {Object} `options`\n * @param {Object} `env`\n * @return {String}\n * @api public\n */\n\nRenderer.prototype.render = function (tokens, options, env) {\n var _rules = this.rules;\n var len = tokens.length, i = -1;\n var result = '';\n\n while (++i < len) {\n if (tokens[i].type === 'inline') {\n result += this.renderInline(tokens[i].children, options, env);\n } else {\n result += _rules[tokens[i].type](tokens, i, options, env, this);\n }\n }\n return result;\n};\n\n/**\n * Ruler is a helper class for building responsibility chains from\n * parse rules. It allows:\n *\n * - easy stack rules chains\n * - getting main chain and named chains content (as arrays of functions)\n *\n * Helper methods, should not be used directly.\n * @api private\n */\n\nfunction Ruler() {\n // List of added rules. Each element is:\n //\n // { name: XXX,\n // enabled: Boolean,\n // fn: Function(),\n // alt: [ name2, name3 ] }\n //\n this.__rules__ = [];\n\n // Cached rule chains.\n //\n // First level - chain name, '' for default.\n // Second level - digital anchor for fast filtering by charcodes.\n //\n this.__cache__ = null;\n}\n\n/**\n * Find the index of a rule by `name`.\n *\n * @param {String} `name`\n * @return {Number} Index of the given `name`\n * @api private\n */\n\nRuler.prototype.__find__ = function (name) {\n var len = this.__rules__.length;\n var i = -1;\n\n while (len--) {\n if (this.__rules__[++i].name === name) {\n return i;\n }\n }\n return -1;\n};\n\n/**\n * Build the rules lookup cache\n *\n * @api private\n */\n\nRuler.prototype.__compile__ = function () {\n var self = this;\n var chains = [ '' ];\n\n // collect unique names\n self.__rules__.forEach(function (rule) {\n if (!rule.enabled) {\n return;\n }\n\n rule.alt.forEach(function (altName) {\n if (chains.indexOf(altName) < 0) {\n chains.push(altName);\n }\n });\n });\n\n self.__cache__ = {};\n\n chains.forEach(function (chain) {\n self.__cache__[chain] = [];\n self.__rules__.forEach(function (rule) {\n if (!rule.enabled) {\n return;\n }\n\n if (chain && rule.alt.indexOf(chain) < 0) {\n return;\n }\n self.__cache__[chain].push(rule.fn);\n });\n });\n};\n\n/**\n * Ruler public methods\n * ------------------------------------------------\n */\n\n/**\n * Replace rule function\n *\n * @param {String} `name` Rule name\n * @param {Function `fn`\n * @param {Object} `options`\n * @api private\n */\n\nRuler.prototype.at = function (name, fn, options) {\n var idx = this.__find__(name);\n var opt = options || {};\n\n if (idx === -1) {\n throw new Error('Parser rule not found: ' + name);\n }\n\n this.__rules__[idx].fn = fn;\n this.__rules__[idx].alt = opt.alt || [];\n this.__cache__ = null;\n};\n\n/**\n * Add a rule to the chain before given the `ruleName`.\n *\n * @param {String} `beforeName`\n * @param {String} `ruleName`\n * @param {Function} `fn`\n * @param {Object} `options`\n * @api private\n */\n\nRuler.prototype.before = function (beforeName, ruleName, fn, options) {\n var idx = this.__find__(beforeName);\n var opt = options || {};\n\n if (idx === -1) {\n throw new Error('Parser rule not found: ' + beforeName);\n }\n\n this.__rules__.splice(idx, 0, {\n name: ruleName,\n enabled: true,\n fn: fn,\n alt: opt.alt || []\n });\n\n this.__cache__ = null;\n};\n\n/**\n * Add a rule to the chain after the given `ruleName`.\n *\n * @param {String} `afterName`\n * @param {String} `ruleName`\n * @param {Function} `fn`\n * @param {Object} `options`\n * @api private\n */\n\nRuler.prototype.after = function (afterName, ruleName, fn, options) {\n var idx = this.__find__(afterName);\n var opt = options || {};\n\n if (idx === -1) {\n throw new Error('Parser rule not found: ' + afterName);\n }\n\n this.__rules__.splice(idx + 1, 0, {\n name: ruleName,\n enabled: true,\n fn: fn,\n alt: opt.alt || []\n });\n\n this.__cache__ = null;\n};\n\n/**\n * Add a rule to the end of chain.\n *\n * @param {String} `ruleName`\n * @param {Function} `fn`\n * @param {Object} `options`\n * @return {String}\n */\n\nRuler.prototype.push = function (ruleName, fn, options) {\n var opt = options || {};\n\n this.__rules__.push({\n name: ruleName,\n enabled: true,\n fn: fn,\n alt: opt.alt || []\n });\n\n this.__cache__ = null;\n};\n\n/**\n * Enable a rule or list of rules.\n *\n * @param {String|Array} `list` Name or array of rule names to enable\n * @param {Boolean} `strict` If `true`, all non listed rules will be disabled.\n * @api private\n */\n\nRuler.prototype.enable = function (list, strict) {\n list = !Array.isArray(list)\n ? [ list ]\n : list;\n\n // In strict mode disable all existing rules first\n if (strict) {\n this.__rules__.forEach(function (rule) {\n rule.enabled = false;\n });\n }\n\n // Search by name and enable\n list.forEach(function (name) {\n var idx = this.__find__(name);\n if (idx < 0) {\n throw new Error('Rules manager: invalid rule name ' + name);\n }\n this.__rules__[idx].enabled = true;\n }, this);\n\n this.__cache__ = null;\n};\n\n\n/**\n * Disable a rule or list of rules.\n *\n * @param {String|Array} `list` Name or array of rule names to disable\n * @api private\n */\n\nRuler.prototype.disable = function (list) {\n list = !Array.isArray(list)\n ? [ list ]\n : list;\n\n // Search by name and disable\n list.forEach(function (name) {\n var idx = this.__find__(name);\n if (idx < 0) {\n throw new Error('Rules manager: invalid rule name ' + name);\n }\n this.__rules__[idx].enabled = false;\n }, this);\n\n this.__cache__ = null;\n};\n\n/**\n * Get a rules list as an array of functions.\n *\n * @param {String} `chainName`\n * @return {Object}\n * @api private\n */\n\nRuler.prototype.getRules = function (chainName) {\n if (this.__cache__ === null) {\n this.__compile__();\n }\n return this.__cache__[chainName] || [];\n};\n\nfunction block(state) {\n\n if (state.inlineMode) {\n state.tokens.push({\n type: 'inline',\n content: state.src.replace(/\\n/g, ' ').trim(),\n level: 0,\n lines: [ 0, 1 ],\n children: []\n });\n\n } else {\n state.block.parse(state.src, state.options, state.env, state.tokens);\n }\n}\n\n// Inline parser state\n\nfunction StateInline(src, parserInline, options, env, outTokens) {\n this.src = src;\n this.env = env;\n this.options = options;\n this.parser = parserInline;\n this.tokens = outTokens;\n this.pos = 0;\n this.posMax = this.src.length;\n this.level = 0;\n this.pending = '';\n this.pendingLevel = 0;\n\n this.cache = []; // Stores { start: end } pairs. Useful for backtrack\n // optimization of pairs parse (emphasis, strikes).\n\n // Link parser state vars\n\n this.isInLabel = false; // Set true when seek link label - we should disable\n // \"paired\" rules (emphasis, strikes) to not skip\n // tailing `]`\n\n this.linkLevel = 0; // Increment for each nesting link. Used to prevent\n // nesting in definitions\n\n this.linkContent = ''; // Temporary storage for link url\n\n this.labelUnmatchedScopes = 0; // Track unpaired `[` for link labels\n // (backtrack optimization)\n}\n\n// Flush pending text\n//\nStateInline.prototype.pushPending = function () {\n this.tokens.push({\n type: 'text',\n content: this.pending,\n level: this.pendingLevel\n });\n this.pending = '';\n};\n\n// Push new token to \"stream\".\n// If pending text exists - flush it as text token\n//\nStateInline.prototype.push = function (token) {\n if (this.pending) {\n this.pushPending();\n }\n\n this.tokens.push(token);\n this.pendingLevel = this.level;\n};\n\n// Store value to cache.\n// !!! Implementation has parser-specific optimizations\n// !!! keys MUST be integer, >= 0; values MUST be integer, > 0\n//\nStateInline.prototype.cacheSet = function (key, val) {\n for (var i = this.cache.length; i <= key; i++) {\n this.cache.push(0);\n }\n\n this.cache[key] = val;\n};\n\n// Get cache value\n//\nStateInline.prototype.cacheGet = function (key) {\n return key < this.cache.length ? this.cache[key] : 0;\n};\n\n/**\n * Parse link labels\n *\n * This function assumes that first character (`[`) already matches;\n * returns the end of the label.\n *\n * @param {Object} state\n * @param {Number} start\n * @api private\n */\n\nfunction parseLinkLabel(state, start) {\n var level, found, marker,\n labelEnd = -1,\n max = state.posMax,\n oldPos = state.pos,\n oldFlag = state.isInLabel;\n\n if (state.isInLabel) { return -1; }\n\n if (state.labelUnmatchedScopes) {\n state.labelUnmatchedScopes--;\n return -1;\n }\n\n state.pos = start + 1;\n state.isInLabel = true;\n level = 1;\n\n while (state.pos < max) {\n marker = state.src.charCodeAt(state.pos);\n if (marker === 0x5B /* [ */) {\n level++;\n } else if (marker === 0x5D /* ] */) {\n level--;\n if (level === 0) {\n found = true;\n break;\n }\n }\n\n state.parser.skipToken(state);\n }\n\n if (found) {\n labelEnd = state.pos;\n state.labelUnmatchedScopes = 0;\n } else {\n state.labelUnmatchedScopes = level - 1;\n }\n\n // restore old state\n state.pos = oldPos;\n state.isInLabel = oldFlag;\n\n return labelEnd;\n}\n\n// Parse abbreviation definitions, i.e. `*[abbr]: description`\n\n\nfunction parseAbbr(str, parserInline, options, env) {\n var state, labelEnd, pos, max, label, title;\n\n if (str.charCodeAt(0) !== 0x2A/* * */) { return -1; }\n if (str.charCodeAt(1) !== 0x5B/* [ */) { return -1; }\n\n if (str.indexOf(']:') === -1) { return -1; }\n\n state = new StateInline(str, parserInline, options, env, []);\n labelEnd = parseLinkLabel(state, 1);\n\n if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 0x3A/* : */) { return -1; }\n\n max = state.posMax;\n\n // abbr title is always one line, so looking for ending \"\\n\" here\n for (pos = labelEnd + 2; pos < max; pos++) {\n if (state.src.charCodeAt(pos) === 0x0A) { break; }\n }\n\n label = str.slice(2, labelEnd);\n title = str.slice(labelEnd + 2, pos).trim();\n if (title.length === 0) { return -1; }\n if (!env.abbreviations) { env.abbreviations = {}; }\n // prepend ':' to avoid conflict with Object.prototype members\n if (typeof env.abbreviations[':' + label] === 'undefined') {\n env.abbreviations[':' + label] = title;\n }\n\n return pos;\n}\n\nfunction abbr(state) {\n var tokens = state.tokens, i, l, content, pos;\n\n if (state.inlineMode) {\n return;\n }\n\n // Parse inlines\n for (i = 1, l = tokens.length - 1; i < l; i++) {\n if (tokens[i - 1].type === 'paragraph_open' &&\n tokens[i].type === 'inline' &&\n tokens[i + 1].type === 'paragraph_close') {\n\n content = tokens[i].content;\n while (content.length) {\n pos = parseAbbr(content, state.inline, state.options, state.env);\n if (pos < 0) { break; }\n content = content.slice(pos).trim();\n }\n\n tokens[i].content = content;\n if (!content.length) {\n tokens[i - 1].tight = true;\n tokens[i + 1].tight = true;\n }\n }\n }\n}\n\nfunction normalizeLink(url) {\n var normalized = replaceEntities(url);\n // We shouldn't care about the result of malformed URIs,\n // and should not throw an exception.\n try {\n normalized = decodeURI(normalized);\n } catch (err) {}\n return encodeURI(normalized);\n}\n\n/**\n * Parse link destination\n *\n * - on success it returns a string and updates state.pos;\n * - on failure it returns null\n *\n * @param {Object} state\n * @param {Number} pos\n * @api private\n */\n\nfunction parseLinkDestination(state, pos) {\n var code, level, link,\n start = pos,\n max = state.posMax;\n\n if (state.src.charCodeAt(pos) === 0x3C /* < */) {\n pos++;\n while (pos < max) {\n code = state.src.charCodeAt(pos);\n if (code === 0x0A /* \\n */) { return false; }\n if (code === 0x3E /* > */) {\n link = normalizeLink(unescapeMd(state.src.slice(start + 1, pos)));\n if (!state.parser.validateLink(link)) { return false; }\n state.pos = pos + 1;\n state.linkContent = link;\n return true;\n }\n if (code === 0x5C /* \\ */ && pos + 1 < max) {\n pos += 2;\n continue;\n }\n\n pos++;\n }\n\n // no closing '>'\n return false;\n }\n\n // this should be ... } else { ... branch\n\n level = 0;\n while (pos < max) {\n code = state.src.charCodeAt(pos);\n\n if (code === 0x20) { break; }\n\n // ascii control chars\n if (code < 0x20 || code === 0x7F) { break; }\n\n if (code === 0x5C /* \\ */ && pos + 1 < max) {\n pos += 2;\n continue;\n }\n\n if (code === 0x28 /* ( */) {\n level++;\n if (level > 1) { break; }\n }\n\n if (code === 0x29 /* ) */) {\n level--;\n if (level < 0) { break; }\n }\n\n pos++;\n }\n\n if (start === pos) { return false; }\n\n link = unescapeMd(state.src.slice(start, pos));\n if (!state.parser.validateLink(link)) { return false; }\n\n state.linkContent = link;\n state.pos = pos;\n return true;\n}\n\n/**\n * Parse link title\n *\n * - on success it returns a string and updates state.pos;\n * - on failure it returns null\n *\n * @param {Object} state\n * @param {Number} pos\n * @api private\n */\n\nfunction parseLinkTitle(state, pos) {\n var code,\n start = pos,\n max = state.posMax,\n marker = state.src.charCodeAt(pos);\n\n if (marker !== 0x22 /* \" */ && marker !== 0x27 /* ' */ && marker !== 0x28 /* ( */) { return false; }\n\n pos++;\n\n // if opening marker is \"(\", switch it to closing marker \")\"\n if (marker === 0x28) { marker = 0x29; }\n\n while (pos < max) {\n code = state.src.charCodeAt(pos);\n if (code === marker) {\n state.pos = pos + 1;\n state.linkContent = unescapeMd(state.src.slice(start + 1, pos));\n return true;\n }\n if (code === 0x5C /* \\ */ && pos + 1 < max) {\n pos += 2;\n continue;\n }\n\n pos++;\n }\n\n return false;\n}\n\nfunction normalizeReference(str) {\n // use .toUpperCase() instead of .toLowerCase()\n // here to avoid a conflict with Object.prototype\n // members (most notably, `__proto__`)\n return str.trim().replace(/\\s+/g, ' ').toUpperCase();\n}\n\nfunction parseReference(str, parser, options, env) {\n var state, labelEnd, pos, max, code, start, href, title, label;\n\n if (str.charCodeAt(0) !== 0x5B/* [ */) { return -1; }\n\n if (str.indexOf(']:') === -1) { return -1; }\n\n state = new StateInline(str, parser, options, env, []);\n labelEnd = parseLinkLabel(state, 0);\n\n if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 0x3A/* : */) { return -1; }\n\n max = state.posMax;\n\n // [label]: destination 'title'\n // ^^^ skip optional whitespace here\n for (pos = labelEnd + 2; pos < max; pos++) {\n code = state.src.charCodeAt(pos);\n if (code !== 0x20 && code !== 0x0A) { break; }\n }\n\n // [label]: destination 'title'\n // ^^^^^^^^^^^ parse this\n if (!parseLinkDestination(state, pos)) { return -1; }\n href = state.linkContent;\n pos = state.pos;\n\n // [label]: destination 'title'\n // ^^^ skipping those spaces\n start = pos;\n for (pos = pos + 1; pos < max; pos++) {\n code = state.src.charCodeAt(pos);\n if (code !== 0x20 && code !== 0x0A) { break; }\n }\n\n // [label]: destination 'title'\n // ^^^^^^^ parse this\n if (pos < max && start !== pos && parseLinkTitle(state, pos)) {\n title = state.linkContent;\n pos = state.pos;\n } else {\n title = '';\n pos = start;\n }\n\n // ensure that the end of the line is empty\n while (pos < max && state.src.charCodeAt(pos) === 0x20/* space */) { pos++; }\n if (pos < max && state.src.charCodeAt(pos) !== 0x0A) { return -1; }\n\n label = normalizeReference(str.slice(1, labelEnd));\n if (typeof env.references[label] === 'undefined') {\n env.references[label] = { title: title, href: href };\n }\n\n return pos;\n}\n\n\nfunction references(state) {\n var tokens = state.tokens, i, l, content, pos;\n\n state.env.references = state.env.references || {};\n\n if (state.inlineMode) {\n return;\n }\n\n // Scan definitions in paragraph inlines\n for (i = 1, l = tokens.length - 1; i < l; i++) {\n if (tokens[i].type === 'inline' &&\n tokens[i - 1].type === 'paragraph_open' &&\n tokens[i + 1].type === 'paragraph_close') {\n\n content = tokens[i].content;\n while (content.length) {\n pos = parseReference(content, state.inline, state.options, state.env);\n if (pos < 0) { break; }\n content = content.slice(pos).trim();\n }\n\n tokens[i].content = content;\n if (!content.length) {\n tokens[i - 1].tight = true;\n tokens[i + 1].tight = true;\n }\n }\n }\n}\n\nfunction inline(state) {\n var tokens = state.tokens, tok, i, l;\n\n // Parse inlines\n for (i = 0, l = tokens.length; i < l; i++) {\n tok = tokens[i];\n if (tok.type === 'inline') {\n state.inline.parse(tok.content, state.options, state.env, tok.children);\n }\n }\n}\n\nfunction footnote_block(state) {\n var i, l, j, t, lastParagraph, list, tokens, current, currentLabel,\n level = 0,\n insideRef = false,\n refTokens = {};\n\n if (!state.env.footnotes) { return; }\n\n state.tokens = state.tokens.filter(function(tok) {\n if (tok.type === 'footnote_reference_open') {\n insideRef = true;\n current = [];\n currentLabel = tok.label;\n return false;\n }\n if (tok.type === 'footnote_reference_close') {\n insideRef = false;\n // prepend ':' to avoid conflict with Object.prototype members\n refTokens[':' + currentLabel] = current;\n return false;\n }\n if (insideRef) { current.push(tok); }\n return !insideRef;\n });\n\n if (!state.env.footnotes.list) { return; }\n list = state.env.footnotes.list;\n\n state.tokens.push({\n type: 'footnote_block_open',\n level: level++\n });\n for (i = 0, l = list.length; i < l; i++) {\n state.tokens.push({\n type: 'footnote_open',\n id: i,\n level: level++\n });\n\n if (list[i].tokens) {\n tokens = [];\n tokens.push({\n type: 'paragraph_open',\n tight: false,\n level: level++\n });\n tokens.push({\n type: 'inline',\n content: '',\n level: level,\n children: list[i].tokens\n });\n tokens.push({\n type: 'paragraph_close',\n tight: false,\n level: --level\n });\n } else if (list[i].label) {\n tokens = refTokens[':' + list[i].label];\n }\n\n state.tokens = state.tokens.concat(tokens);\n if (state.tokens[state.tokens.length - 1].type === 'paragraph_close') {\n lastParagraph = state.tokens.pop();\n } else {\n lastParagraph = null;\n }\n\n t = list[i].count > 0 ? list[i].count : 1;\n for (j = 0; j < t; j++) {\n state.tokens.push({\n type: 'footnote_anchor',\n id: i,\n subId: j,\n level: level\n });\n }\n\n if (lastParagraph) {\n state.tokens.push(lastParagraph);\n }\n\n state.tokens.push({\n type: 'footnote_close',\n level: --level\n });\n }\n state.tokens.push({\n type: 'footnote_block_close',\n level: --level\n });\n}\n\n// Enclose abbreviations in tags\n//\n\nvar PUNCT_CHARS = ' \\n()[]\\'\".,!?-';\n\n\n// from Google closure library\n// http://closure-library.googlecode.com/git-history/docs/local_closure_goog_string_string.js.source.html#line1021\nfunction regEscape(s) {\n return s.replace(/([-()\\[\\]{}+?*.$\\^|,:#= 0; i--) {\n token = tokens[i];\n if (token.type !== 'text') { continue; }\n\n pos = 0;\n text = token.content;\n reg.lastIndex = 0;\n level = token.level;\n nodes = [];\n\n while ((m = reg.exec(text))) {\n if (reg.lastIndex > pos) {\n nodes.push({\n type: 'text',\n content: text.slice(pos, m.index + m[1].length),\n level: level\n });\n }\n\n nodes.push({\n type: 'abbr_open',\n title: state.env.abbreviations[':' + m[2]],\n level: level++\n });\n nodes.push({\n type: 'text',\n content: m[2],\n level: level\n });\n nodes.push({\n type: 'abbr_close',\n level: --level\n });\n pos = reg.lastIndex - m[3].length;\n }\n\n if (!nodes.length) { continue; }\n\n if (pos < text.length) {\n nodes.push({\n type: 'text',\n content: text.slice(pos),\n level: level\n });\n }\n\n // replace current node\n blockTokens[j].children = tokens = [].concat(tokens.slice(0, i), nodes, tokens.slice(i + 1));\n }\n }\n}\n\n// Simple typographical replacements\n//\n// TODO:\n// - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾\n// - miltiplication 2 x 4 -> 2 × 4\n\nvar RARE_RE = /\\+-|\\.\\.|\\?\\?\\?\\?|!!!!|,,|--/;\n\nvar SCOPED_ABBR_RE = /\\((c|tm|r|p)\\)/ig;\nvar SCOPED_ABBR = {\n 'c': '©',\n 'r': '®',\n 'p': '§',\n 'tm': '™'\n};\n\nfunction replaceScopedAbbr(str) {\n if (str.indexOf('(') < 0) { return str; }\n\n return str.replace(SCOPED_ABBR_RE, function(match, name) {\n return SCOPED_ABBR[name.toLowerCase()];\n });\n}\n\n\nfunction replace(state) {\n var i, token, text, inlineTokens, blkIdx;\n\n if (!state.options.typographer) { return; }\n\n for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {\n\n if (state.tokens[blkIdx].type !== 'inline') { continue; }\n\n inlineTokens = state.tokens[blkIdx].children;\n\n for (i = inlineTokens.length - 1; i >= 0; i--) {\n token = inlineTokens[i];\n if (token.type === 'text') {\n text = token.content;\n\n text = replaceScopedAbbr(text);\n\n if (RARE_RE.test(text)) {\n text = text\n .replace(/\\+-/g, '±')\n // .., ..., ....... -> …\n // but ?..... & !..... -> ?.. & !..\n .replace(/\\.{2,}/g, '…').replace(/([?!])…/g, '$1..')\n .replace(/([?!]){4,}/g, '$1$1$1').replace(/,{2,}/g, ',')\n // em-dash\n .replace(/(^|[^-])---([^-]|$)/mg, '$1\\u2014$2')\n // en-dash\n .replace(/(^|\\s)--(\\s|$)/mg, '$1\\u2013$2')\n .replace(/(^|[^-\\s])--([^-\\s]|$)/mg, '$1\\u2013$2');\n }\n\n token.content = text;\n }\n }\n }\n}\n\n// Convert straight quotation marks to typographic ones\n//\n\nvar QUOTE_TEST_RE = /['\"]/;\nvar QUOTE_RE = /['\"]/g;\nvar PUNCT_RE = /[-\\s()\\[\\]]/;\nvar APOSTROPHE = '’';\n\n// This function returns true if the character at `pos`\n// could be inside a word.\nfunction isLetter(str, pos) {\n if (pos < 0 || pos >= str.length) { return false; }\n return !PUNCT_RE.test(str[pos]);\n}\n\n\nfunction replaceAt(str, index, ch) {\n return str.substr(0, index) + ch + str.substr(index + 1);\n}\n\n\nfunction smartquotes(state) {\n /*eslint max-depth:0*/\n var i, token, text, t, pos, max, thisLevel, lastSpace, nextSpace, item,\n canOpen, canClose, j, isSingle, blkIdx, tokens,\n stack;\n\n if (!state.options.typographer) { return; }\n\n stack = [];\n\n for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {\n\n if (state.tokens[blkIdx].type !== 'inline') { continue; }\n\n tokens = state.tokens[blkIdx].children;\n stack.length = 0;\n\n for (i = 0; i < tokens.length; i++) {\n token = tokens[i];\n\n if (token.type !== 'text' || QUOTE_TEST_RE.test(token.text)) { continue; }\n\n thisLevel = tokens[i].level;\n\n for (j = stack.length - 1; j >= 0; j--) {\n if (stack[j].level <= thisLevel) { break; }\n }\n stack.length = j + 1;\n\n text = token.content;\n pos = 0;\n max = text.length;\n\n /*eslint no-labels:0,block-scoped-var:0*/\n OUTER:\n while (pos < max) {\n QUOTE_RE.lastIndex = pos;\n t = QUOTE_RE.exec(text);\n if (!t) { break; }\n\n lastSpace = !isLetter(text, t.index - 1);\n pos = t.index + 1;\n isSingle = (t[0] === \"'\");\n nextSpace = !isLetter(text, pos);\n\n if (!nextSpace && !lastSpace) {\n // middle of word\n if (isSingle) {\n token.content = replaceAt(token.content, t.index, APOSTROPHE);\n }\n continue;\n }\n\n canOpen = !nextSpace;\n canClose = !lastSpace;\n\n if (canClose) {\n // this could be a closing quote, rewind the stack to get a match\n for (j = stack.length - 1; j >= 0; j--) {\n item = stack[j];\n if (stack[j].level < thisLevel) { break; }\n if (item.single === isSingle && stack[j].level === thisLevel) {\n item = stack[j];\n if (isSingle) {\n tokens[item.token].content = replaceAt(tokens[item.token].content, item.pos, state.options.quotes[2]);\n token.content = replaceAt(token.content, t.index, state.options.quotes[3]);\n } else {\n tokens[item.token].content = replaceAt(tokens[item.token].content, item.pos, state.options.quotes[0]);\n token.content = replaceAt(token.content, t.index, state.options.quotes[1]);\n }\n stack.length = j;\n continue OUTER;\n }\n }\n }\n\n if (canOpen) {\n stack.push({\n token: i,\n pos: t.index,\n single: isSingle,\n level: thisLevel\n });\n } else if (canClose && isSingle) {\n token.content = replaceAt(token.content, t.index, APOSTROPHE);\n }\n }\n }\n }\n}\n\n/**\n * Core parser `rules`\n */\n\nvar _rules = [\n [ 'block', block ],\n [ 'abbr', abbr ],\n [ 'references', references ],\n [ 'inline', inline ],\n [ 'footnote_tail', footnote_block ],\n [ 'abbr2', abbr2 ],\n [ 'replacements', replace ],\n [ 'smartquotes', smartquotes ],\n];\n\n/**\n * Class for top level (`core`) parser rules\n *\n * @api private\n */\n\nfunction Core() {\n this.options = {};\n this.ruler = new Ruler();\n for (var i = 0; i < _rules.length; i++) {\n this.ruler.push(_rules[i][0], _rules[i][1]);\n }\n}\n\n/**\n * Process rules with the given `state`\n *\n * @param {Object} `state`\n * @api private\n */\n\nCore.prototype.process = function (state) {\n var i, l, rules;\n rules = this.ruler.getRules('');\n for (i = 0, l = rules.length; i < l; i++) {\n rules[i](state);\n }\n};\n\n// Parser state class\n\nfunction StateBlock(src, parser, options, env, tokens) {\n var ch, s, start, pos, len, indent, indent_found;\n\n this.src = src;\n\n // Shortcuts to simplify nested calls\n this.parser = parser;\n\n this.options = options;\n\n this.env = env;\n\n //\n // Internal state vartiables\n //\n\n this.tokens = tokens;\n\n this.bMarks = []; // line begin offsets for fast jumps\n this.eMarks = []; // line end offsets for fast jumps\n this.tShift = []; // indent for each line\n\n // block parser variables\n this.blkIndent = 0; // required block content indent\n // (for example, if we are in list)\n this.line = 0; // line index in src\n this.lineMax = 0; // lines count\n this.tight = false; // loose/tight mode for lists\n this.parentType = 'root'; // if `list`, block parser stops on two newlines\n this.ddIndent = -1; // indent of the current dd block (-1 if there isn't any)\n\n this.level = 0;\n\n // renderer\n this.result = '';\n\n // Create caches\n // Generate markers.\n s = this.src;\n indent = 0;\n indent_found = false;\n\n for (start = pos = indent = 0, len = s.length; pos < len; pos++) {\n ch = s.charCodeAt(pos);\n\n if (!indent_found) {\n if (ch === 0x20/* space */) {\n indent++;\n continue;\n } else {\n indent_found = true;\n }\n }\n\n if (ch === 0x0A || pos === len - 1) {\n if (ch !== 0x0A) { pos++; }\n this.bMarks.push(start);\n this.eMarks.push(pos);\n this.tShift.push(indent);\n\n indent_found = false;\n indent = 0;\n start = pos + 1;\n }\n }\n\n // Push fake entry to simplify cache bounds checks\n this.bMarks.push(s.length);\n this.eMarks.push(s.length);\n this.tShift.push(0);\n\n this.lineMax = this.bMarks.length - 1; // don't count last fake line\n}\n\nStateBlock.prototype.isEmpty = function isEmpty(line) {\n return this.bMarks[line] + this.tShift[line] >= this.eMarks[line];\n};\n\nStateBlock.prototype.skipEmptyLines = function skipEmptyLines(from) {\n for (var max = this.lineMax; from < max; from++) {\n if (this.bMarks[from] + this.tShift[from] < this.eMarks[from]) {\n break;\n }\n }\n return from;\n};\n\n// Skip spaces from given position.\nStateBlock.prototype.skipSpaces = function skipSpaces(pos) {\n for (var max = this.src.length; pos < max; pos++) {\n if (this.src.charCodeAt(pos) !== 0x20/* space */) { break; }\n }\n return pos;\n};\n\n// Skip char codes from given position\nStateBlock.prototype.skipChars = function skipChars(pos, code) {\n for (var max = this.src.length; pos < max; pos++) {\n if (this.src.charCodeAt(pos) !== code) { break; }\n }\n return pos;\n};\n\n// Skip char codes reverse from given position - 1\nStateBlock.prototype.skipCharsBack = function skipCharsBack(pos, code, min) {\n if (pos <= min) { return pos; }\n\n while (pos > min) {\n if (code !== this.src.charCodeAt(--pos)) { return pos + 1; }\n }\n return pos;\n};\n\n// cut lines range from source.\nStateBlock.prototype.getLines = function getLines(begin, end, indent, keepLastLF) {\n var i, first, last, queue, shift,\n line = begin;\n\n if (begin >= end) {\n return '';\n }\n\n // Opt: don't use push queue for single line;\n if (line + 1 === end) {\n first = this.bMarks[line] + Math.min(this.tShift[line], indent);\n last = keepLastLF ? this.eMarks[line] + 1 : this.eMarks[line];\n return this.src.slice(first, last);\n }\n\n queue = new Array(end - begin);\n\n for (i = 0; line < end; line++, i++) {\n shift = this.tShift[line];\n if (shift > indent) { shift = indent; }\n if (shift < 0) { shift = 0; }\n\n first = this.bMarks[line] + shift;\n\n if (line + 1 < end || keepLastLF) {\n // No need for bounds check because we have fake entry on tail.\n last = this.eMarks[line] + 1;\n } else {\n last = this.eMarks[line];\n }\n\n queue[i] = this.src.slice(first, last);\n }\n\n return queue.join('');\n};\n\n// Code block (4 spaces padded)\n\nfunction code(state, startLine, endLine/*, silent*/) {\n var nextLine, last;\n\n if (state.tShift[startLine] - state.blkIndent < 4) { return false; }\n\n last = nextLine = startLine + 1;\n\n while (nextLine < endLine) {\n if (state.isEmpty(nextLine)) {\n nextLine++;\n continue;\n }\n if (state.tShift[nextLine] - state.blkIndent >= 4) {\n nextLine++;\n last = nextLine;\n continue;\n }\n break;\n }\n\n state.line = nextLine;\n state.tokens.push({\n type: 'code',\n content: state.getLines(startLine, last, 4 + state.blkIndent, true),\n block: true,\n lines: [ startLine, state.line ],\n level: state.level\n });\n\n return true;\n}\n\n// fences (``` lang, ~~~ lang)\n\nfunction fences(state, startLine, endLine, silent) {\n var marker, len, params, nextLine, mem,\n haveEndMarker = false,\n pos = state.bMarks[startLine] + state.tShift[startLine],\n max = state.eMarks[startLine];\n\n if (pos + 3 > max) { return false; }\n\n marker = state.src.charCodeAt(pos);\n\n if (marker !== 0x7E/* ~ */ && marker !== 0x60 /* ` */) {\n return false;\n }\n\n // scan marker length\n mem = pos;\n pos = state.skipChars(pos, marker);\n\n len = pos - mem;\n\n if (len < 3) { return false; }\n\n params = state.src.slice(pos, max).trim();\n\n if (params.indexOf('`') >= 0) { return false; }\n\n // Since start is found, we can report success here in validation mode\n if (silent) { return true; }\n\n // search end of block\n nextLine = startLine;\n\n for (;;) {\n nextLine++;\n if (nextLine >= endLine) {\n // unclosed block should be autoclosed by end of document.\n // also block seems to be autoclosed by end of parent\n break;\n }\n\n pos = mem = state.bMarks[nextLine] + state.tShift[nextLine];\n max = state.eMarks[nextLine];\n\n if (pos < max && state.tShift[nextLine] < state.blkIndent) {\n // non-empty line with negative indent should stop the list:\n // - ```\n // test\n break;\n }\n\n if (state.src.charCodeAt(pos) !== marker) { continue; }\n\n if (state.tShift[nextLine] - state.blkIndent >= 4) {\n // closing fence should be indented less than 4 spaces\n continue;\n }\n\n pos = state.skipChars(pos, marker);\n\n // closing code fence must be at least as long as the opening one\n if (pos - mem < len) { continue; }\n\n // make sure tail has spaces only\n pos = state.skipSpaces(pos);\n\n if (pos < max) { continue; }\n\n haveEndMarker = true;\n // found!\n break;\n }\n\n // If a fence has heading spaces, they should be removed from its inner block\n len = state.tShift[startLine];\n\n state.line = nextLine + (haveEndMarker ? 1 : 0);\n state.tokens.push({\n type: 'fence',\n params: params,\n content: state.getLines(startLine + 1, nextLine, len, true),\n lines: [ startLine, state.line ],\n level: state.level\n });\n\n return true;\n}\n\n// Block quotes\n\nfunction blockquote(state, startLine, endLine, silent) {\n var nextLine, lastLineEmpty, oldTShift, oldBMarks, oldIndent, oldParentType, lines,\n terminatorRules,\n i, l, terminate,\n pos = state.bMarks[startLine] + state.tShift[startLine],\n max = state.eMarks[startLine];\n\n if (pos > max) { return false; }\n\n // check the block quote marker\n if (state.src.charCodeAt(pos++) !== 0x3E/* > */) { return false; }\n\n if (state.level >= state.options.maxNesting) { return false; }\n\n // we know that it's going to be a valid blockquote,\n // so no point trying to find the end of it in silent mode\n if (silent) { return true; }\n\n // skip one optional space after '>'\n if (state.src.charCodeAt(pos) === 0x20) { pos++; }\n\n oldIndent = state.blkIndent;\n state.blkIndent = 0;\n\n oldBMarks = [ state.bMarks[startLine] ];\n state.bMarks[startLine] = pos;\n\n // check if we have an empty blockquote\n pos = pos < max ? state.skipSpaces(pos) : pos;\n lastLineEmpty = pos >= max;\n\n oldTShift = [ state.tShift[startLine] ];\n state.tShift[startLine] = pos - state.bMarks[startLine];\n\n terminatorRules = state.parser.ruler.getRules('blockquote');\n\n // Search the end of the block\n //\n // Block ends with either:\n // 1. an empty line outside:\n // ```\n // > test\n //\n // ```\n // 2. an empty line inside:\n // ```\n // >\n // test\n // ```\n // 3. another tag\n // ```\n // > test\n // - - -\n // ```\n for (nextLine = startLine + 1; nextLine < endLine; nextLine++) {\n pos = state.bMarks[nextLine] + state.tShift[nextLine];\n max = state.eMarks[nextLine];\n\n if (pos >= max) {\n // Case 1: line is not inside the blockquote, and this line is empty.\n break;\n }\n\n if (state.src.charCodeAt(pos++) === 0x3E/* > */) {\n // This line is inside the blockquote.\n\n // skip one optional space after '>'\n if (state.src.charCodeAt(pos) === 0x20) { pos++; }\n\n oldBMarks.push(state.bMarks[nextLine]);\n state.bMarks[nextLine] = pos;\n\n pos = pos < max ? state.skipSpaces(pos) : pos;\n lastLineEmpty = pos >= max;\n\n oldTShift.push(state.tShift[nextLine]);\n state.tShift[nextLine] = pos - state.bMarks[nextLine];\n continue;\n }\n\n // Case 2: line is not inside the blockquote, and the last line was empty.\n if (lastLineEmpty) { break; }\n\n // Case 3: another tag found.\n terminate = false;\n for (i = 0, l = terminatorRules.length; i < l; i++) {\n if (terminatorRules[i](state, nextLine, endLine, true)) {\n terminate = true;\n break;\n }\n }\n if (terminate) { break; }\n\n oldBMarks.push(state.bMarks[nextLine]);\n oldTShift.push(state.tShift[nextLine]);\n\n // A negative number means that this is a paragraph continuation;\n //\n // Any negative number will do the job here, but it's better for it\n // to be large enough to make any bugs obvious.\n state.tShift[nextLine] = -1337;\n }\n\n oldParentType = state.parentType;\n state.parentType = 'blockquote';\n state.tokens.push({\n type: 'blockquote_open',\n lines: lines = [ startLine, 0 ],\n level: state.level++\n });\n state.parser.tokenize(state, startLine, nextLine);\n state.tokens.push({\n type: 'blockquote_close',\n level: --state.level\n });\n state.parentType = oldParentType;\n lines[1] = state.line;\n\n // Restore original tShift; this might not be necessary since the parser\n // has already been here, but just to make sure we can do that.\n for (i = 0; i < oldTShift.length; i++) {\n state.bMarks[i + startLine] = oldBMarks[i];\n state.tShift[i + startLine] = oldTShift[i];\n }\n state.blkIndent = oldIndent;\n\n return true;\n}\n\n// Horizontal rule\n\nfunction hr(state, startLine, endLine, silent) {\n var marker, cnt, ch,\n pos = state.bMarks[startLine],\n max = state.eMarks[startLine];\n\n pos += state.tShift[startLine];\n\n if (pos > max) { return false; }\n\n marker = state.src.charCodeAt(pos++);\n\n // Check hr marker\n if (marker !== 0x2A/* * */ &&\n marker !== 0x2D/* - */ &&\n marker !== 0x5F/* _ */) {\n return false;\n }\n\n // markers can be mixed with spaces, but there should be at least 3 one\n\n cnt = 1;\n while (pos < max) {\n ch = state.src.charCodeAt(pos++);\n if (ch !== marker && ch !== 0x20/* space */) { return false; }\n if (ch === marker) { cnt++; }\n }\n\n if (cnt < 3) { return false; }\n\n if (silent) { return true; }\n\n state.line = startLine + 1;\n state.tokens.push({\n type: 'hr',\n lines: [ startLine, state.line ],\n level: state.level\n });\n\n return true;\n}\n\n// Lists\n\n// Search `[-+*][\\n ]`, returns next pos arter marker on success\n// or -1 on fail.\nfunction skipBulletListMarker(state, startLine) {\n var marker, pos, max;\n\n pos = state.bMarks[startLine] + state.tShift[startLine];\n max = state.eMarks[startLine];\n\n if (pos >= max) { return -1; }\n\n marker = state.src.charCodeAt(pos++);\n // Check bullet\n if (marker !== 0x2A/* * */ &&\n marker !== 0x2D/* - */ &&\n marker !== 0x2B/* + */) {\n return -1;\n }\n\n if (pos < max && state.src.charCodeAt(pos) !== 0x20) {\n // \" 1.test \" - is not a list item\n return -1;\n }\n\n return pos;\n}\n\n// Search `\\d+[.)][\\n ]`, returns next pos arter marker on success\n// or -1 on fail.\nfunction skipOrderedListMarker(state, startLine) {\n var ch,\n pos = state.bMarks[startLine] + state.tShift[startLine],\n max = state.eMarks[startLine];\n\n if (pos + 1 >= max) { return -1; }\n\n ch = state.src.charCodeAt(pos++);\n\n if (ch < 0x30/* 0 */ || ch > 0x39/* 9 */) { return -1; }\n\n for (;;) {\n // EOL -> fail\n if (pos >= max) { return -1; }\n\n ch = state.src.charCodeAt(pos++);\n\n if (ch >= 0x30/* 0 */ && ch <= 0x39/* 9 */) {\n continue;\n }\n\n // found valid marker\n if (ch === 0x29/* ) */ || ch === 0x2e/* . */) {\n break;\n }\n\n return -1;\n }\n\n\n if (pos < max && state.src.charCodeAt(pos) !== 0x20/* space */) {\n // \" 1.test \" - is not a list item\n return -1;\n }\n return pos;\n}\n\nfunction markTightParagraphs(state, idx) {\n var i, l,\n level = state.level + 2;\n\n for (i = idx + 2, l = state.tokens.length - 2; i < l; i++) {\n if (state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open') {\n state.tokens[i + 2].tight = true;\n state.tokens[i].tight = true;\n i += 2;\n }\n }\n}\n\n\nfunction list(state, startLine, endLine, silent) {\n var nextLine,\n indent,\n oldTShift,\n oldIndent,\n oldTight,\n oldParentType,\n start,\n posAfterMarker,\n max,\n indentAfterMarker,\n markerValue,\n markerCharCode,\n isOrdered,\n contentStart,\n listTokIdx,\n prevEmptyEnd,\n listLines,\n itemLines,\n tight = true,\n terminatorRules,\n i, l, terminate;\n\n // Detect list type and position after marker\n if ((posAfterMarker = skipOrderedListMarker(state, startLine)) >= 0) {\n isOrdered = true;\n } else if ((posAfterMarker = skipBulletListMarker(state, startLine)) >= 0) {\n isOrdered = false;\n } else {\n return false;\n }\n\n if (state.level >= state.options.maxNesting) { return false; }\n\n // We should terminate list on style change. Remember first one to compare.\n markerCharCode = state.src.charCodeAt(posAfterMarker - 1);\n\n // For validation mode we can terminate immediately\n if (silent) { return true; }\n\n // Start list\n listTokIdx = state.tokens.length;\n\n if (isOrdered) {\n start = state.bMarks[startLine] + state.tShift[startLine];\n markerValue = Number(state.src.substr(start, posAfterMarker - start - 1));\n\n state.tokens.push({\n type: 'ordered_list_open',\n order: markerValue,\n lines: listLines = [ startLine, 0 ],\n level: state.level++\n });\n\n } else {\n state.tokens.push({\n type: 'bullet_list_open',\n lines: listLines = [ startLine, 0 ],\n level: state.level++\n });\n }\n\n //\n // Iterate list items\n //\n\n nextLine = startLine;\n prevEmptyEnd = false;\n terminatorRules = state.parser.ruler.getRules('list');\n\n while (nextLine < endLine) {\n contentStart = state.skipSpaces(posAfterMarker);\n max = state.eMarks[nextLine];\n\n if (contentStart >= max) {\n // trimming space in \"- \\n 3\" case, indent is 1 here\n indentAfterMarker = 1;\n } else {\n indentAfterMarker = contentStart - posAfterMarker;\n }\n\n // If we have more than 4 spaces, the indent is 1\n // (the rest is just indented code block)\n if (indentAfterMarker > 4) { indentAfterMarker = 1; }\n\n // If indent is less than 1, assume that it's one, example:\n // \"-\\n test\"\n if (indentAfterMarker < 1) { indentAfterMarker = 1; }\n\n // \" - test\"\n // ^^^^^ - calculating total length of this thing\n indent = (posAfterMarker - state.bMarks[nextLine]) + indentAfterMarker;\n\n // Run subparser & write tokens\n state.tokens.push({\n type: 'list_item_open',\n lines: itemLines = [ startLine, 0 ],\n level: state.level++\n });\n\n oldIndent = state.blkIndent;\n oldTight = state.tight;\n oldTShift = state.tShift[startLine];\n oldParentType = state.parentType;\n state.tShift[startLine] = contentStart - state.bMarks[startLine];\n state.blkIndent = indent;\n state.tight = true;\n state.parentType = 'list';\n\n state.parser.tokenize(state, startLine, endLine, true);\n\n // If any of list item is tight, mark list as tight\n if (!state.tight || prevEmptyEnd) {\n tight = false;\n }\n // Item become loose if finish with empty line,\n // but we should filter last element, because it means list finish\n prevEmptyEnd = (state.line - startLine) > 1 && state.isEmpty(state.line - 1);\n\n state.blkIndent = oldIndent;\n state.tShift[startLine] = oldTShift;\n state.tight = oldTight;\n state.parentType = oldParentType;\n\n state.tokens.push({\n type: 'list_item_close',\n level: --state.level\n });\n\n nextLine = startLine = state.line;\n itemLines[1] = nextLine;\n contentStart = state.bMarks[startLine];\n\n if (nextLine >= endLine) { break; }\n\n if (state.isEmpty(nextLine)) {\n break;\n }\n\n //\n // Try to check if list is terminated or continued.\n //\n if (state.tShift[nextLine] < state.blkIndent) { break; }\n\n // fail if terminating block found\n terminate = false;\n for (i = 0, l = terminatorRules.length; i < l; i++) {\n if (terminatorRules[i](state, nextLine, endLine, true)) {\n terminate = true;\n break;\n }\n }\n if (terminate) { break; }\n\n // fail if list has another type\n if (isOrdered) {\n posAfterMarker = skipOrderedListMarker(state, nextLine);\n if (posAfterMarker < 0) { break; }\n } else {\n posAfterMarker = skipBulletListMarker(state, nextLine);\n if (posAfterMarker < 0) { break; }\n }\n\n if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) { break; }\n }\n\n // Finilize list\n state.tokens.push({\n type: isOrdered ? 'ordered_list_close' : 'bullet_list_close',\n level: --state.level\n });\n listLines[1] = nextLine;\n\n state.line = nextLine;\n\n // mark paragraphs tight if needed\n if (tight) {\n markTightParagraphs(state, listTokIdx);\n }\n\n return true;\n}\n\n// Process footnote reference list\n\nfunction footnote(state, startLine, endLine, silent) {\n var oldBMark, oldTShift, oldParentType, pos, label,\n start = state.bMarks[startLine] + state.tShift[startLine],\n max = state.eMarks[startLine];\n\n // line should be at least 5 chars - \"[^x]:\"\n if (start + 4 > max) { return false; }\n\n if (state.src.charCodeAt(start) !== 0x5B/* [ */) { return false; }\n if (state.src.charCodeAt(start + 1) !== 0x5E/* ^ */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n for (pos = start + 2; pos < max; pos++) {\n if (state.src.charCodeAt(pos) === 0x20) { return false; }\n if (state.src.charCodeAt(pos) === 0x5D /* ] */) {\n break;\n }\n }\n\n if (pos === start + 2) { return false; } // no empty footnote labels\n if (pos + 1 >= max || state.src.charCodeAt(++pos) !== 0x3A /* : */) { return false; }\n if (silent) { return true; }\n pos++;\n\n if (!state.env.footnotes) { state.env.footnotes = {}; }\n if (!state.env.footnotes.refs) { state.env.footnotes.refs = {}; }\n label = state.src.slice(start + 2, pos - 2);\n state.env.footnotes.refs[':' + label] = -1;\n\n state.tokens.push({\n type: 'footnote_reference_open',\n label: label,\n level: state.level++\n });\n\n oldBMark = state.bMarks[startLine];\n oldTShift = state.tShift[startLine];\n oldParentType = state.parentType;\n state.tShift[startLine] = state.skipSpaces(pos) - pos;\n state.bMarks[startLine] = pos;\n state.blkIndent += 4;\n state.parentType = 'footnote';\n\n if (state.tShift[startLine] < state.blkIndent) {\n state.tShift[startLine] += state.blkIndent;\n state.bMarks[startLine] -= state.blkIndent;\n }\n\n state.parser.tokenize(state, startLine, endLine, true);\n\n state.parentType = oldParentType;\n state.blkIndent -= 4;\n state.tShift[startLine] = oldTShift;\n state.bMarks[startLine] = oldBMark;\n\n state.tokens.push({\n type: 'footnote_reference_close',\n level: --state.level\n });\n\n return true;\n}\n\n// heading (#, ##, ...)\n\nfunction heading(state, startLine, endLine, silent) {\n var ch, level, tmp,\n pos = state.bMarks[startLine] + state.tShift[startLine],\n max = state.eMarks[startLine];\n\n if (pos >= max) { return false; }\n\n ch = state.src.charCodeAt(pos);\n\n if (ch !== 0x23/* # */ || pos >= max) { return false; }\n\n // count heading level\n level = 1;\n ch = state.src.charCodeAt(++pos);\n while (ch === 0x23/* # */ && pos < max && level <= 6) {\n level++;\n ch = state.src.charCodeAt(++pos);\n }\n\n if (level > 6 || (pos < max && ch !== 0x20/* space */)) { return false; }\n\n if (silent) { return true; }\n\n // Let's cut tails like ' ### ' from the end of string\n\n max = state.skipCharsBack(max, 0x20, pos); // space\n tmp = state.skipCharsBack(max, 0x23, pos); // #\n if (tmp > pos && state.src.charCodeAt(tmp - 1) === 0x20/* space */) {\n max = tmp;\n }\n\n state.line = startLine + 1;\n\n state.tokens.push({ type: 'heading_open',\n hLevel: level,\n lines: [ startLine, state.line ],\n level: state.level\n });\n\n // only if header is not empty\n if (pos < max) {\n state.tokens.push({\n type: 'inline',\n content: state.src.slice(pos, max).trim(),\n level: state.level + 1,\n lines: [ startLine, state.line ],\n children: []\n });\n }\n state.tokens.push({ type: 'heading_close', hLevel: level, level: state.level });\n\n return true;\n}\n\n// lheading (---, ===)\n\nfunction lheading(state, startLine, endLine/*, silent*/) {\n var marker, pos, max,\n next = startLine + 1;\n\n if (next >= endLine) { return false; }\n if (state.tShift[next] < state.blkIndent) { return false; }\n\n // Scan next line\n\n if (state.tShift[next] - state.blkIndent > 3) { return false; }\n\n pos = state.bMarks[next] + state.tShift[next];\n max = state.eMarks[next];\n\n if (pos >= max) { return false; }\n\n marker = state.src.charCodeAt(pos);\n\n if (marker !== 0x2D/* - */ && marker !== 0x3D/* = */) { return false; }\n\n pos = state.skipChars(pos, marker);\n\n pos = state.skipSpaces(pos);\n\n if (pos < max) { return false; }\n\n pos = state.bMarks[startLine] + state.tShift[startLine];\n\n state.line = next + 1;\n state.tokens.push({\n type: 'heading_open',\n hLevel: marker === 0x3D/* = */ ? 1 : 2,\n lines: [ startLine, state.line ],\n level: state.level\n });\n state.tokens.push({\n type: 'inline',\n content: state.src.slice(pos, state.eMarks[startLine]).trim(),\n level: state.level + 1,\n lines: [ startLine, state.line - 1 ],\n children: []\n });\n state.tokens.push({\n type: 'heading_close',\n hLevel: marker === 0x3D/* = */ ? 1 : 2,\n level: state.level\n });\n\n return true;\n}\n\n// List of valid html blocks names, accorting to commonmark spec\n// http://jgm.github.io/CommonMark/spec.html#html-blocks\n\nvar html_blocks = {};\n\n[\n 'article',\n 'aside',\n 'button',\n 'blockquote',\n 'body',\n 'canvas',\n 'caption',\n 'col',\n 'colgroup',\n 'dd',\n 'div',\n 'dl',\n 'dt',\n 'embed',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'hgroup',\n 'hr',\n 'iframe',\n 'li',\n 'map',\n 'object',\n 'ol',\n 'output',\n 'p',\n 'pre',\n 'progress',\n 'script',\n 'section',\n 'style',\n 'table',\n 'tbody',\n 'td',\n 'textarea',\n 'tfoot',\n 'th',\n 'tr',\n 'thead',\n 'ul',\n 'video'\n].forEach(function (name) { html_blocks[name] = true; });\n\n// HTML block\n\n\nvar HTML_TAG_OPEN_RE = /^<([a-zA-Z]{1,15})[\\s\\/>]/;\nvar HTML_TAG_CLOSE_RE = /^<\\/([a-zA-Z]{1,15})[\\s>]/;\n\nfunction isLetter$1(ch) {\n /*eslint no-bitwise:0*/\n var lc = ch | 0x20; // to lower case\n return (lc >= 0x61/* a */) && (lc <= 0x7a/* z */);\n}\n\nfunction htmlblock(state, startLine, endLine, silent) {\n var ch, match, nextLine,\n pos = state.bMarks[startLine],\n max = state.eMarks[startLine],\n shift = state.tShift[startLine];\n\n pos += shift;\n\n if (!state.options.html) { return false; }\n\n if (shift > 3 || pos + 2 >= max) { return false; }\n\n if (state.src.charCodeAt(pos) !== 0x3C/* < */) { return false; }\n\n ch = state.src.charCodeAt(pos + 1);\n\n if (ch === 0x21/* ! */ || ch === 0x3F/* ? */) {\n // Directive start / comment start / processing instruction start\n if (silent) { return true; }\n\n } else if (ch === 0x2F/* / */ || isLetter$1(ch)) {\n\n // Probably start or end of tag\n if (ch === 0x2F/* \\ */) {\n // closing tag\n match = state.src.slice(pos, max).match(HTML_TAG_CLOSE_RE);\n if (!match) { return false; }\n } else {\n // opening tag\n match = state.src.slice(pos, max).match(HTML_TAG_OPEN_RE);\n if (!match) { return false; }\n }\n // Make sure tag name is valid\n if (html_blocks[match[1].toLowerCase()] !== true) { return false; }\n if (silent) { return true; }\n\n } else {\n return false;\n }\n\n // If we are here - we detected HTML block.\n // Let's roll down till empty line (block end).\n nextLine = startLine + 1;\n while (nextLine < state.lineMax && !state.isEmpty(nextLine)) {\n nextLine++;\n }\n\n state.line = nextLine;\n state.tokens.push({\n type: 'htmlblock',\n level: state.level,\n lines: [ startLine, state.line ],\n content: state.getLines(startLine, nextLine, 0, true)\n });\n\n return true;\n}\n\n// GFM table, non-standard\n\nfunction getLine(state, line) {\n var pos = state.bMarks[line] + state.blkIndent,\n max = state.eMarks[line];\n\n return state.src.substr(pos, max - pos);\n}\n\nfunction table(state, startLine, endLine, silent) {\n var ch, lineText, pos, i, nextLine, rows, cell,\n aligns, t, tableLines, tbodyLines;\n\n // should have at least three lines\n if (startLine + 2 > endLine) { return false; }\n\n nextLine = startLine + 1;\n\n if (state.tShift[nextLine] < state.blkIndent) { return false; }\n\n // first character of the second line should be '|' or '-'\n\n pos = state.bMarks[nextLine] + state.tShift[nextLine];\n if (pos >= state.eMarks[nextLine]) { return false; }\n\n ch = state.src.charCodeAt(pos);\n if (ch !== 0x7C/* | */ && ch !== 0x2D/* - */ && ch !== 0x3A/* : */) { return false; }\n\n lineText = getLine(state, startLine + 1);\n if (!/^[-:| ]+$/.test(lineText)) { return false; }\n\n rows = lineText.split('|');\n if (rows <= 2) { return false; }\n aligns = [];\n for (i = 0; i < rows.length; i++) {\n t = rows[i].trim();\n if (!t) {\n // allow empty columns before and after table, but not in between columns;\n // e.g. allow ` |---| `, disallow ` ---||--- `\n if (i === 0 || i === rows.length - 1) {\n continue;\n } else {\n return false;\n }\n }\n\n if (!/^:?-+:?$/.test(t)) { return false; }\n if (t.charCodeAt(t.length - 1) === 0x3A/* : */) {\n aligns.push(t.charCodeAt(0) === 0x3A/* : */ ? 'center' : 'right');\n } else if (t.charCodeAt(0) === 0x3A/* : */) {\n aligns.push('left');\n } else {\n aligns.push('');\n }\n }\n\n lineText = getLine(state, startLine).trim();\n if (lineText.indexOf('|') === -1) { return false; }\n rows = lineText.replace(/^\\||\\|$/g, '').split('|');\n if (aligns.length !== rows.length) { return false; }\n if (silent) { return true; }\n\n state.tokens.push({\n type: 'table_open',\n lines: tableLines = [ startLine, 0 ],\n level: state.level++\n });\n state.tokens.push({\n type: 'thead_open',\n lines: [ startLine, startLine + 1 ],\n level: state.level++\n });\n\n state.tokens.push({\n type: 'tr_open',\n lines: [ startLine, startLine + 1 ],\n level: state.level++\n });\n for (i = 0; i < rows.length; i++) {\n state.tokens.push({\n type: 'th_open',\n align: aligns[i],\n lines: [ startLine, startLine + 1 ],\n level: state.level++\n });\n state.tokens.push({\n type: 'inline',\n content: rows[i].trim(),\n lines: [ startLine, startLine + 1 ],\n level: state.level,\n children: []\n });\n state.tokens.push({ type: 'th_close', level: --state.level });\n }\n state.tokens.push({ type: 'tr_close', level: --state.level });\n state.tokens.push({ type: 'thead_close', level: --state.level });\n\n state.tokens.push({\n type: 'tbody_open',\n lines: tbodyLines = [ startLine + 2, 0 ],\n level: state.level++\n });\n\n for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {\n if (state.tShift[nextLine] < state.blkIndent) { break; }\n\n lineText = getLine(state, nextLine).trim();\n if (lineText.indexOf('|') === -1) { break; }\n rows = lineText.replace(/^\\||\\|$/g, '').split('|');\n\n state.tokens.push({ type: 'tr_open', level: state.level++ });\n for (i = 0; i < rows.length; i++) {\n state.tokens.push({ type: 'td_open', align: aligns[i], level: state.level++ });\n // 0x7c === '|'\n cell = rows[i].substring(\n rows[i].charCodeAt(0) === 0x7c ? 1 : 0,\n rows[i].charCodeAt(rows[i].length - 1) === 0x7c ? rows[i].length - 1 : rows[i].length\n ).trim();\n state.tokens.push({\n type: 'inline',\n content: cell,\n level: state.level,\n children: []\n });\n state.tokens.push({ type: 'td_close', level: --state.level });\n }\n state.tokens.push({ type: 'tr_close', level: --state.level });\n }\n state.tokens.push({ type: 'tbody_close', level: --state.level });\n state.tokens.push({ type: 'table_close', level: --state.level });\n\n tableLines[1] = tbodyLines[1] = nextLine;\n state.line = nextLine;\n return true;\n}\n\n// Definition lists\n\n// Search `[:~][\\n ]`, returns next pos after marker on success\n// or -1 on fail.\nfunction skipMarker(state, line) {\n var pos, marker,\n start = state.bMarks[line] + state.tShift[line],\n max = state.eMarks[line];\n\n if (start >= max) { return -1; }\n\n // Check bullet\n marker = state.src.charCodeAt(start++);\n if (marker !== 0x7E/* ~ */ && marker !== 0x3A/* : */) { return -1; }\n\n pos = state.skipSpaces(start);\n\n // require space after \":\"\n if (start === pos) { return -1; }\n\n // no empty definitions, e.g. \" : \"\n if (pos >= max) { return -1; }\n\n return pos;\n}\n\nfunction markTightParagraphs$1(state, idx) {\n var i, l,\n level = state.level + 2;\n\n for (i = idx + 2, l = state.tokens.length - 2; i < l; i++) {\n if (state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open') {\n state.tokens[i + 2].tight = true;\n state.tokens[i].tight = true;\n i += 2;\n }\n }\n}\n\nfunction deflist(state, startLine, endLine, silent) {\n var contentStart,\n ddLine,\n dtLine,\n itemLines,\n listLines,\n listTokIdx,\n nextLine,\n oldIndent,\n oldDDIndent,\n oldParentType,\n oldTShift,\n oldTight,\n prevEmptyEnd,\n tight;\n\n if (silent) {\n // quirk: validation mode validates a dd block only, not a whole deflist\n if (state.ddIndent < 0) { return false; }\n return skipMarker(state, startLine) >= 0;\n }\n\n nextLine = startLine + 1;\n if (state.isEmpty(nextLine)) {\n if (++nextLine > endLine) { return false; }\n }\n\n if (state.tShift[nextLine] < state.blkIndent) { return false; }\n contentStart = skipMarker(state, nextLine);\n if (contentStart < 0) { return false; }\n\n if (state.level >= state.options.maxNesting) { return false; }\n\n // Start list\n listTokIdx = state.tokens.length;\n\n state.tokens.push({\n type: 'dl_open',\n lines: listLines = [ startLine, 0 ],\n level: state.level++\n });\n\n //\n // Iterate list items\n //\n\n dtLine = startLine;\n ddLine = nextLine;\n\n // One definition list can contain multiple DTs,\n // and one DT can be followed by multiple DDs.\n //\n // Thus, there is two loops here, and label is\n // needed to break out of the second one\n //\n /*eslint no-labels:0,block-scoped-var:0*/\n OUTER:\n for (;;) {\n tight = true;\n prevEmptyEnd = false;\n\n state.tokens.push({\n type: 'dt_open',\n lines: [ dtLine, dtLine ],\n level: state.level++\n });\n state.tokens.push({\n type: 'inline',\n content: state.getLines(dtLine, dtLine + 1, state.blkIndent, false).trim(),\n level: state.level + 1,\n lines: [ dtLine, dtLine ],\n children: []\n });\n state.tokens.push({\n type: 'dt_close',\n level: --state.level\n });\n\n for (;;) {\n state.tokens.push({\n type: 'dd_open',\n lines: itemLines = [ nextLine, 0 ],\n level: state.level++\n });\n\n oldTight = state.tight;\n oldDDIndent = state.ddIndent;\n oldIndent = state.blkIndent;\n oldTShift = state.tShift[ddLine];\n oldParentType = state.parentType;\n state.blkIndent = state.ddIndent = state.tShift[ddLine] + 2;\n state.tShift[ddLine] = contentStart - state.bMarks[ddLine];\n state.tight = true;\n state.parentType = 'deflist';\n\n state.parser.tokenize(state, ddLine, endLine, true);\n\n // If any of list item is tight, mark list as tight\n if (!state.tight || prevEmptyEnd) {\n tight = false;\n }\n // Item become loose if finish with empty line,\n // but we should filter last element, because it means list finish\n prevEmptyEnd = (state.line - ddLine) > 1 && state.isEmpty(state.line - 1);\n\n state.tShift[ddLine] = oldTShift;\n state.tight = oldTight;\n state.parentType = oldParentType;\n state.blkIndent = oldIndent;\n state.ddIndent = oldDDIndent;\n\n state.tokens.push({\n type: 'dd_close',\n level: --state.level\n });\n\n itemLines[1] = nextLine = state.line;\n\n if (nextLine >= endLine) { break OUTER; }\n\n if (state.tShift[nextLine] < state.blkIndent) { break OUTER; }\n contentStart = skipMarker(state, nextLine);\n if (contentStart < 0) { break; }\n\n ddLine = nextLine;\n\n // go to the next loop iteration:\n // insert DD tag and repeat checking\n }\n\n if (nextLine >= endLine) { break; }\n dtLine = nextLine;\n\n if (state.isEmpty(dtLine)) { break; }\n if (state.tShift[dtLine] < state.blkIndent) { break; }\n\n ddLine = dtLine + 1;\n if (ddLine >= endLine) { break; }\n if (state.isEmpty(ddLine)) { ddLine++; }\n if (ddLine >= endLine) { break; }\n\n if (state.tShift[ddLine] < state.blkIndent) { break; }\n contentStart = skipMarker(state, ddLine);\n if (contentStart < 0) { break; }\n\n // go to the next loop iteration:\n // insert DT and DD tags and repeat checking\n }\n\n // Finilize list\n state.tokens.push({\n type: 'dl_close',\n level: --state.level\n });\n listLines[1] = nextLine;\n\n state.line = nextLine;\n\n // mark paragraphs tight if needed\n if (tight) {\n markTightParagraphs$1(state, listTokIdx);\n }\n\n return true;\n}\n\n// Paragraph\n\nfunction paragraph(state, startLine/*, endLine*/) {\n var endLine, content, terminate, i, l,\n nextLine = startLine + 1,\n terminatorRules;\n\n endLine = state.lineMax;\n\n // jump line-by-line until empty one or EOF\n if (nextLine < endLine && !state.isEmpty(nextLine)) {\n terminatorRules = state.parser.ruler.getRules('paragraph');\n\n for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) {\n // this would be a code block normally, but after paragraph\n // it's considered a lazy continuation regardless of what's there\n if (state.tShift[nextLine] - state.blkIndent > 3) { continue; }\n\n // Some tags can terminate paragraph without empty line.\n terminate = false;\n for (i = 0, l = terminatorRules.length; i < l; i++) {\n if (terminatorRules[i](state, nextLine, endLine, true)) {\n terminate = true;\n break;\n }\n }\n if (terminate) { break; }\n }\n }\n\n content = state.getLines(startLine, nextLine, state.blkIndent, false).trim();\n\n state.line = nextLine;\n if (content.length) {\n state.tokens.push({\n type: 'paragraph_open',\n tight: false,\n lines: [ startLine, state.line ],\n level: state.level\n });\n state.tokens.push({\n type: 'inline',\n content: content,\n level: state.level + 1,\n lines: [ startLine, state.line ],\n children: []\n });\n state.tokens.push({\n type: 'paragraph_close',\n tight: false,\n level: state.level\n });\n }\n\n return true;\n}\n\n/**\n * Parser rules\n */\n\nvar _rules$1 = [\n [ 'code', code ],\n [ 'fences', fences, [ 'paragraph', 'blockquote', 'list' ] ],\n [ 'blockquote', blockquote, [ 'paragraph', 'blockquote', 'list' ] ],\n [ 'hr', hr, [ 'paragraph', 'blockquote', 'list' ] ],\n [ 'list', list, [ 'paragraph', 'blockquote' ] ],\n [ 'footnote', footnote, [ 'paragraph' ] ],\n [ 'heading', heading, [ 'paragraph', 'blockquote' ] ],\n [ 'lheading', lheading ],\n [ 'htmlblock', htmlblock, [ 'paragraph', 'blockquote' ] ],\n [ 'table', table, [ 'paragraph' ] ],\n [ 'deflist', deflist, [ 'paragraph' ] ],\n [ 'paragraph', paragraph ]\n];\n\n/**\n * Block Parser class\n *\n * @api private\n */\n\nfunction ParserBlock() {\n this.ruler = new Ruler();\n for (var i = 0; i < _rules$1.length; i++) {\n this.ruler.push(_rules$1[i][0], _rules$1[i][1], {\n alt: (_rules$1[i][2] || []).slice()\n });\n }\n}\n\n/**\n * Generate tokens for the given input range.\n *\n * @param {Object} `state` Has properties like `src`, `parser`, `options` etc\n * @param {Number} `startLine`\n * @param {Number} `endLine`\n * @api private\n */\n\nParserBlock.prototype.tokenize = function (state, startLine, endLine) {\n var rules = this.ruler.getRules('');\n var len = rules.length;\n var line = startLine;\n var hasEmptyLines = false;\n var ok, i;\n\n while (line < endLine) {\n state.line = line = state.skipEmptyLines(line);\n if (line >= endLine) {\n break;\n }\n\n // Termination condition for nested calls.\n // Nested calls currently used for blockquotes & lists\n if (state.tShift[line] < state.blkIndent) {\n break;\n }\n\n // Try all possible rules.\n // On success, rule should:\n //\n // - update `state.line`\n // - update `state.tokens`\n // - return true\n\n for (i = 0; i < len; i++) {\n ok = rules[i](state, line, endLine, false);\n if (ok) {\n break;\n }\n }\n\n // set state.tight iff we had an empty line before current tag\n // i.e. latest empty line should not count\n state.tight = !hasEmptyLines;\n\n // paragraph might \"eat\" one newline after it in nested lists\n if (state.isEmpty(state.line - 1)) {\n hasEmptyLines = true;\n }\n\n line = state.line;\n\n if (line < endLine && state.isEmpty(line)) {\n hasEmptyLines = true;\n line++;\n\n // two empty lines should stop the parser in list mode\n if (line < endLine && state.parentType === 'list' && state.isEmpty(line)) { break; }\n state.line = line;\n }\n }\n};\n\nvar TABS_SCAN_RE = /[\\n\\t]/g;\nvar NEWLINES_RE = /\\r[\\n\\u0085]|[\\u2424\\u2028\\u0085]/g;\nvar SPACES_RE = /\\u00a0/g;\n\n/**\n * Tokenize the given `str`.\n *\n * @param {String} `str` Source string\n * @param {Object} `options`\n * @param {Object} `env`\n * @param {Array} `outTokens`\n * @api private\n */\n\nParserBlock.prototype.parse = function (str, options, env, outTokens) {\n var state, lineStart = 0, lastTabPos = 0;\n if (!str) { return []; }\n\n // Normalize spaces\n str = str.replace(SPACES_RE, ' ');\n\n // Normalize newlines\n str = str.replace(NEWLINES_RE, '\\n');\n\n // Replace tabs with proper number of spaces (1..4)\n if (str.indexOf('\\t') >= 0) {\n str = str.replace(TABS_SCAN_RE, function (match, offset) {\n var result;\n if (str.charCodeAt(offset) === 0x0A) {\n lineStart = offset + 1;\n lastTabPos = 0;\n return match;\n }\n result = ' '.slice((offset - lineStart - lastTabPos) % 4);\n lastTabPos = offset - lineStart + 1;\n return result;\n });\n }\n\n state = new StateBlock(str, this, options, env, outTokens);\n this.tokenize(state, state.line, state.lineMax);\n};\n\n// Skip text characters for text token, place those to pending buffer\n// and increment current pos\n\n// Rule to skip pure text\n// '{}$%@~+=:' reserved for extentions\n\nfunction isTerminatorChar(ch) {\n switch (ch) {\n case 0x0A/* \\n */:\n case 0x5C/* \\ */:\n case 0x60/* ` */:\n case 0x2A/* * */:\n case 0x5F/* _ */:\n case 0x5E/* ^ */:\n case 0x5B/* [ */:\n case 0x5D/* ] */:\n case 0x21/* ! */:\n case 0x26/* & */:\n case 0x3C/* < */:\n case 0x3E/* > */:\n case 0x7B/* { */:\n case 0x7D/* } */:\n case 0x24/* $ */:\n case 0x25/* % */:\n case 0x40/* @ */:\n case 0x7E/* ~ */:\n case 0x2B/* + */:\n case 0x3D/* = */:\n case 0x3A/* : */:\n return true;\n default:\n return false;\n }\n}\n\nfunction text(state, silent) {\n var pos = state.pos;\n\n while (pos < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos))) {\n pos++;\n }\n\n if (pos === state.pos) { return false; }\n\n if (!silent) { state.pending += state.src.slice(state.pos, pos); }\n\n state.pos = pos;\n\n return true;\n}\n\n// Proceess '\\n'\n\nfunction newline(state, silent) {\n var pmax, max, pos = state.pos;\n\n if (state.src.charCodeAt(pos) !== 0x0A/* \\n */) { return false; }\n\n pmax = state.pending.length - 1;\n max = state.posMax;\n\n // ' \\n' -> hardbreak\n // Lookup in pending chars is bad practice! Don't copy to other rules!\n // Pending string is stored in concat mode, indexed lookups will cause\n // convertion to flat mode.\n if (!silent) {\n if (pmax >= 0 && state.pending.charCodeAt(pmax) === 0x20) {\n if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 0x20) {\n // Strip out all trailing spaces on this line.\n for (var i = pmax - 2; i >= 0; i--) {\n if (state.pending.charCodeAt(i) !== 0x20) {\n state.pending = state.pending.substring(0, i + 1);\n break;\n }\n }\n state.push({\n type: 'hardbreak',\n level: state.level\n });\n } else {\n state.pending = state.pending.slice(0, -1);\n state.push({\n type: 'softbreak',\n level: state.level\n });\n }\n\n } else {\n state.push({\n type: 'softbreak',\n level: state.level\n });\n }\n }\n\n pos++;\n\n // skip heading spaces for next line\n while (pos < max && state.src.charCodeAt(pos) === 0x20) { pos++; }\n\n state.pos = pos;\n return true;\n}\n\n// Proceess escaped chars and hardbreaks\n\nvar ESCAPED = [];\n\nfor (var i = 0; i < 256; i++) { ESCAPED.push(0); }\n\n'\\\\!\"#$%&\\'()*+,./:;<=>?@[]^_`{|}~-'\n .split('').forEach(function(ch) { ESCAPED[ch.charCodeAt(0)] = 1; });\n\n\nfunction escape(state, silent) {\n var ch, pos = state.pos, max = state.posMax;\n\n if (state.src.charCodeAt(pos) !== 0x5C/* \\ */) { return false; }\n\n pos++;\n\n if (pos < max) {\n ch = state.src.charCodeAt(pos);\n\n if (ch < 256 && ESCAPED[ch] !== 0) {\n if (!silent) { state.pending += state.src[pos]; }\n state.pos += 2;\n return true;\n }\n\n if (ch === 0x0A) {\n if (!silent) {\n state.push({\n type: 'hardbreak',\n level: state.level\n });\n }\n\n pos++;\n // skip leading whitespaces from next line\n while (pos < max && state.src.charCodeAt(pos) === 0x20) { pos++; }\n\n state.pos = pos;\n return true;\n }\n }\n\n if (!silent) { state.pending += '\\\\'; }\n state.pos++;\n return true;\n}\n\n// Parse backticks\n\nfunction backticks(state, silent) {\n var start, max, marker, matchStart, matchEnd,\n pos = state.pos,\n ch = state.src.charCodeAt(pos);\n\n if (ch !== 0x60/* ` */) { return false; }\n\n start = pos;\n pos++;\n max = state.posMax;\n\n while (pos < max && state.src.charCodeAt(pos) === 0x60/* ` */) { pos++; }\n\n marker = state.src.slice(start, pos);\n\n matchStart = matchEnd = pos;\n\n while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) {\n matchEnd = matchStart + 1;\n\n while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60/* ` */) { matchEnd++; }\n\n if (matchEnd - matchStart === marker.length) {\n if (!silent) {\n state.push({\n type: 'code',\n content: state.src.slice(pos, matchStart)\n .replace(/[ \\n]+/g, ' ')\n .trim(),\n block: false,\n level: state.level\n });\n }\n state.pos = matchEnd;\n return true;\n }\n }\n\n if (!silent) { state.pending += marker; }\n state.pos += marker.length;\n return true;\n}\n\n// Process ~~deleted text~~\n\nfunction del(state, silent) {\n var found,\n pos,\n stack,\n max = state.posMax,\n start = state.pos,\n lastChar,\n nextChar;\n\n if (state.src.charCodeAt(start) !== 0x7E/* ~ */) { return false; }\n if (silent) { return false; } // don't run any pairs in validation mode\n if (start + 4 >= max) { return false; }\n if (state.src.charCodeAt(start + 1) !== 0x7E/* ~ */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n lastChar = start > 0 ? state.src.charCodeAt(start - 1) : -1;\n nextChar = state.src.charCodeAt(start + 2);\n\n if (lastChar === 0x7E/* ~ */) { return false; }\n if (nextChar === 0x7E/* ~ */) { return false; }\n if (nextChar === 0x20 || nextChar === 0x0A) { return false; }\n\n pos = start + 2;\n while (pos < max && state.src.charCodeAt(pos) === 0x7E/* ~ */) { pos++; }\n if (pos > start + 3) {\n // sequence of 4+ markers taking as literal, same as in a emphasis\n state.pos += pos - start;\n if (!silent) { state.pending += state.src.slice(start, pos); }\n return true;\n }\n\n state.pos = start + 2;\n stack = 1;\n\n while (state.pos + 1 < max) {\n if (state.src.charCodeAt(state.pos) === 0x7E/* ~ */) {\n if (state.src.charCodeAt(state.pos + 1) === 0x7E/* ~ */) {\n lastChar = state.src.charCodeAt(state.pos - 1);\n nextChar = state.pos + 2 < max ? state.src.charCodeAt(state.pos + 2) : -1;\n if (nextChar !== 0x7E/* ~ */ && lastChar !== 0x7E/* ~ */) {\n if (lastChar !== 0x20 && lastChar !== 0x0A) {\n // closing '~~'\n stack--;\n } else if (nextChar !== 0x20 && nextChar !== 0x0A) {\n // opening '~~'\n stack++;\n } // else {\n // // standalone ' ~~ ' indented with spaces\n // }\n if (stack <= 0) {\n found = true;\n break;\n }\n }\n }\n }\n\n state.parser.skipToken(state);\n }\n\n if (!found) {\n // parser failed to find ending tag, so it's not valid emphasis\n state.pos = start;\n return false;\n }\n\n // found!\n state.posMax = state.pos;\n state.pos = start + 2;\n\n if (!silent) {\n state.push({ type: 'del_open', level: state.level++ });\n state.parser.tokenize(state);\n state.push({ type: 'del_close', level: --state.level });\n }\n\n state.pos = state.posMax + 2;\n state.posMax = max;\n return true;\n}\n\n// Process ++inserted text++\n\nfunction ins(state, silent) {\n var found,\n pos,\n stack,\n max = state.posMax,\n start = state.pos,\n lastChar,\n nextChar;\n\n if (state.src.charCodeAt(start) !== 0x2B/* + */) { return false; }\n if (silent) { return false; } // don't run any pairs in validation mode\n if (start + 4 >= max) { return false; }\n if (state.src.charCodeAt(start + 1) !== 0x2B/* + */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n lastChar = start > 0 ? state.src.charCodeAt(start - 1) : -1;\n nextChar = state.src.charCodeAt(start + 2);\n\n if (lastChar === 0x2B/* + */) { return false; }\n if (nextChar === 0x2B/* + */) { return false; }\n if (nextChar === 0x20 || nextChar === 0x0A) { return false; }\n\n pos = start + 2;\n while (pos < max && state.src.charCodeAt(pos) === 0x2B/* + */) { pos++; }\n if (pos !== start + 2) {\n // sequence of 3+ markers taking as literal, same as in a emphasis\n state.pos += pos - start;\n if (!silent) { state.pending += state.src.slice(start, pos); }\n return true;\n }\n\n state.pos = start + 2;\n stack = 1;\n\n while (state.pos + 1 < max) {\n if (state.src.charCodeAt(state.pos) === 0x2B/* + */) {\n if (state.src.charCodeAt(state.pos + 1) === 0x2B/* + */) {\n lastChar = state.src.charCodeAt(state.pos - 1);\n nextChar = state.pos + 2 < max ? state.src.charCodeAt(state.pos + 2) : -1;\n if (nextChar !== 0x2B/* + */ && lastChar !== 0x2B/* + */) {\n if (lastChar !== 0x20 && lastChar !== 0x0A) {\n // closing '++'\n stack--;\n } else if (nextChar !== 0x20 && nextChar !== 0x0A) {\n // opening '++'\n stack++;\n } // else {\n // // standalone ' ++ ' indented with spaces\n // }\n if (stack <= 0) {\n found = true;\n break;\n }\n }\n }\n }\n\n state.parser.skipToken(state);\n }\n\n if (!found) {\n // parser failed to find ending tag, so it's not valid emphasis\n state.pos = start;\n return false;\n }\n\n // found!\n state.posMax = state.pos;\n state.pos = start + 2;\n\n if (!silent) {\n state.push({ type: 'ins_open', level: state.level++ });\n state.parser.tokenize(state);\n state.push({ type: 'ins_close', level: --state.level });\n }\n\n state.pos = state.posMax + 2;\n state.posMax = max;\n return true;\n}\n\n// Process ==highlighted text==\n\nfunction mark(state, silent) {\n var found,\n pos,\n stack,\n max = state.posMax,\n start = state.pos,\n lastChar,\n nextChar;\n\n if (state.src.charCodeAt(start) !== 0x3D/* = */) { return false; }\n if (silent) { return false; } // don't run any pairs in validation mode\n if (start + 4 >= max) { return false; }\n if (state.src.charCodeAt(start + 1) !== 0x3D/* = */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n lastChar = start > 0 ? state.src.charCodeAt(start - 1) : -1;\n nextChar = state.src.charCodeAt(start + 2);\n\n if (lastChar === 0x3D/* = */) { return false; }\n if (nextChar === 0x3D/* = */) { return false; }\n if (nextChar === 0x20 || nextChar === 0x0A) { return false; }\n\n pos = start + 2;\n while (pos < max && state.src.charCodeAt(pos) === 0x3D/* = */) { pos++; }\n if (pos !== start + 2) {\n // sequence of 3+ markers taking as literal, same as in a emphasis\n state.pos += pos - start;\n if (!silent) { state.pending += state.src.slice(start, pos); }\n return true;\n }\n\n state.pos = start + 2;\n stack = 1;\n\n while (state.pos + 1 < max) {\n if (state.src.charCodeAt(state.pos) === 0x3D/* = */) {\n if (state.src.charCodeAt(state.pos + 1) === 0x3D/* = */) {\n lastChar = state.src.charCodeAt(state.pos - 1);\n nextChar = state.pos + 2 < max ? state.src.charCodeAt(state.pos + 2) : -1;\n if (nextChar !== 0x3D/* = */ && lastChar !== 0x3D/* = */) {\n if (lastChar !== 0x20 && lastChar !== 0x0A) {\n // closing '=='\n stack--;\n } else if (nextChar !== 0x20 && nextChar !== 0x0A) {\n // opening '=='\n stack++;\n } // else {\n // // standalone ' == ' indented with spaces\n // }\n if (stack <= 0) {\n found = true;\n break;\n }\n }\n }\n }\n\n state.parser.skipToken(state);\n }\n\n if (!found) {\n // parser failed to find ending tag, so it's not valid emphasis\n state.pos = start;\n return false;\n }\n\n // found!\n state.posMax = state.pos;\n state.pos = start + 2;\n\n if (!silent) {\n state.push({ type: 'mark_open', level: state.level++ });\n state.parser.tokenize(state);\n state.push({ type: 'mark_close', level: --state.level });\n }\n\n state.pos = state.posMax + 2;\n state.posMax = max;\n return true;\n}\n\n// Process *this* and _that_\n\nfunction isAlphaNum(code) {\n return (code >= 0x30 /* 0 */ && code <= 0x39 /* 9 */) ||\n (code >= 0x41 /* A */ && code <= 0x5A /* Z */) ||\n (code >= 0x61 /* a */ && code <= 0x7A /* z */);\n}\n\n// parse sequence of emphasis markers,\n// \"start\" should point at a valid marker\nfunction scanDelims(state, start) {\n var pos = start, lastChar, nextChar, count,\n can_open = true,\n can_close = true,\n max = state.posMax,\n marker = state.src.charCodeAt(start);\n\n lastChar = start > 0 ? state.src.charCodeAt(start - 1) : -1;\n\n while (pos < max && state.src.charCodeAt(pos) === marker) { pos++; }\n if (pos >= max) { can_open = false; }\n count = pos - start;\n\n if (count >= 4) {\n // sequence of four or more unescaped markers can't start/end an emphasis\n can_open = can_close = false;\n } else {\n nextChar = pos < max ? state.src.charCodeAt(pos) : -1;\n\n // check whitespace conditions\n if (nextChar === 0x20 || nextChar === 0x0A) { can_open = false; }\n if (lastChar === 0x20 || lastChar === 0x0A) { can_close = false; }\n\n if (marker === 0x5F /* _ */) {\n // check if we aren't inside the word\n if (isAlphaNum(lastChar)) { can_open = false; }\n if (isAlphaNum(nextChar)) { can_close = false; }\n }\n }\n\n return {\n can_open: can_open,\n can_close: can_close,\n delims: count\n };\n}\n\nfunction emphasis(state, silent) {\n var startCount,\n count,\n found,\n oldCount,\n newCount,\n stack,\n res,\n max = state.posMax,\n start = state.pos,\n marker = state.src.charCodeAt(start);\n\n if (marker !== 0x5F/* _ */ && marker !== 0x2A /* * */) { return false; }\n if (silent) { return false; } // don't run any pairs in validation mode\n\n res = scanDelims(state, start);\n startCount = res.delims;\n if (!res.can_open) {\n state.pos += startCount;\n if (!silent) { state.pending += state.src.slice(start, state.pos); }\n return true;\n }\n\n if (state.level >= state.options.maxNesting) { return false; }\n\n state.pos = start + startCount;\n stack = [ startCount ];\n\n while (state.pos < max) {\n if (state.src.charCodeAt(state.pos) === marker) {\n res = scanDelims(state, state.pos);\n count = res.delims;\n if (res.can_close) {\n oldCount = stack.pop();\n newCount = count;\n\n while (oldCount !== newCount) {\n if (newCount < oldCount) {\n stack.push(oldCount - newCount);\n break;\n }\n\n // assert(newCount > oldCount)\n newCount -= oldCount;\n\n if (stack.length === 0) { break; }\n state.pos += oldCount;\n oldCount = stack.pop();\n }\n\n if (stack.length === 0) {\n startCount = oldCount;\n found = true;\n break;\n }\n state.pos += count;\n continue;\n }\n\n if (res.can_open) { stack.push(count); }\n state.pos += count;\n continue;\n }\n\n state.parser.skipToken(state);\n }\n\n if (!found) {\n // parser failed to find ending tag, so it's not valid emphasis\n state.pos = start;\n return false;\n }\n\n // found!\n state.posMax = state.pos;\n state.pos = start + startCount;\n\n if (!silent) {\n if (startCount === 2 || startCount === 3) {\n state.push({ type: 'strong_open', level: state.level++ });\n }\n if (startCount === 1 || startCount === 3) {\n state.push({ type: 'em_open', level: state.level++ });\n }\n\n state.parser.tokenize(state);\n\n if (startCount === 1 || startCount === 3) {\n state.push({ type: 'em_close', level: --state.level });\n }\n if (startCount === 2 || startCount === 3) {\n state.push({ type: 'strong_close', level: --state.level });\n }\n }\n\n state.pos = state.posMax + startCount;\n state.posMax = max;\n return true;\n}\n\n// Process ~subscript~\n\n// same as UNESCAPE_MD_RE plus a space\nvar UNESCAPE_RE = /\\\\([ \\\\!\"#$%&'()*+,.\\/:;<=>?@[\\]^_`{|}~-])/g;\n\nfunction sub(state, silent) {\n var found,\n content,\n max = state.posMax,\n start = state.pos;\n\n if (state.src.charCodeAt(start) !== 0x7E/* ~ */) { return false; }\n if (silent) { return false; } // don't run any pairs in validation mode\n if (start + 2 >= max) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n state.pos = start + 1;\n\n while (state.pos < max) {\n if (state.src.charCodeAt(state.pos) === 0x7E/* ~ */) {\n found = true;\n break;\n }\n\n state.parser.skipToken(state);\n }\n\n if (!found || start + 1 === state.pos) {\n state.pos = start;\n return false;\n }\n\n content = state.src.slice(start + 1, state.pos);\n\n // don't allow unescaped spaces/newlines inside\n if (content.match(/(^|[^\\\\])(\\\\\\\\)*\\s/)) {\n state.pos = start;\n return false;\n }\n\n // found!\n state.posMax = state.pos;\n state.pos = start + 1;\n\n if (!silent) {\n state.push({\n type: 'sub',\n level: state.level,\n content: content.replace(UNESCAPE_RE, '$1')\n });\n }\n\n state.pos = state.posMax + 1;\n state.posMax = max;\n return true;\n}\n\n// Process ^superscript^\n\n// same as UNESCAPE_MD_RE plus a space\nvar UNESCAPE_RE$1 = /\\\\([ \\\\!\"#$%&'()*+,.\\/:;<=>?@[\\]^_`{|}~-])/g;\n\nfunction sup(state, silent) {\n var found,\n content,\n max = state.posMax,\n start = state.pos;\n\n if (state.src.charCodeAt(start) !== 0x5E/* ^ */) { return false; }\n if (silent) { return false; } // don't run any pairs in validation mode\n if (start + 2 >= max) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n state.pos = start + 1;\n\n while (state.pos < max) {\n if (state.src.charCodeAt(state.pos) === 0x5E/* ^ */) {\n found = true;\n break;\n }\n\n state.parser.skipToken(state);\n }\n\n if (!found || start + 1 === state.pos) {\n state.pos = start;\n return false;\n }\n\n content = state.src.slice(start + 1, state.pos);\n\n // don't allow unescaped spaces/newlines inside\n if (content.match(/(^|[^\\\\])(\\\\\\\\)*\\s/)) {\n state.pos = start;\n return false;\n }\n\n // found!\n state.posMax = state.pos;\n state.pos = start + 1;\n\n if (!silent) {\n state.push({\n type: 'sup',\n level: state.level,\n content: content.replace(UNESCAPE_RE$1, '$1')\n });\n }\n\n state.pos = state.posMax + 1;\n state.posMax = max;\n return true;\n}\n\n// Process [links]( \"stuff\")\n\n\nfunction links(state, silent) {\n var labelStart,\n labelEnd,\n label,\n href,\n title,\n pos,\n ref,\n code,\n isImage = false,\n oldPos = state.pos,\n max = state.posMax,\n start = state.pos,\n marker = state.src.charCodeAt(start);\n\n if (marker === 0x21/* ! */) {\n isImage = true;\n marker = state.src.charCodeAt(++start);\n }\n\n if (marker !== 0x5B/* [ */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n labelStart = start + 1;\n labelEnd = parseLinkLabel(state, start);\n\n // parser failed to find ']', so it's not a valid link\n if (labelEnd < 0) { return false; }\n\n pos = labelEnd + 1;\n if (pos < max && state.src.charCodeAt(pos) === 0x28/* ( */) {\n //\n // Inline link\n //\n\n // [link]( \"title\" )\n // ^^ skipping these spaces\n pos++;\n for (; pos < max; pos++) {\n code = state.src.charCodeAt(pos);\n if (code !== 0x20 && code !== 0x0A) { break; }\n }\n if (pos >= max) { return false; }\n\n // [link]( \"title\" )\n // ^^^^^^ parsing link destination\n start = pos;\n if (parseLinkDestination(state, pos)) {\n href = state.linkContent;\n pos = state.pos;\n } else {\n href = '';\n }\n\n // [link]( \"title\" )\n // ^^ skipping these spaces\n start = pos;\n for (; pos < max; pos++) {\n code = state.src.charCodeAt(pos);\n if (code !== 0x20 && code !== 0x0A) { break; }\n }\n\n // [link]( \"title\" )\n // ^^^^^^^ parsing link title\n if (pos < max && start !== pos && parseLinkTitle(state, pos)) {\n title = state.linkContent;\n pos = state.pos;\n\n // [link]( \"title\" )\n // ^^ skipping these spaces\n for (; pos < max; pos++) {\n code = state.src.charCodeAt(pos);\n if (code !== 0x20 && code !== 0x0A) { break; }\n }\n } else {\n title = '';\n }\n\n if (pos >= max || state.src.charCodeAt(pos) !== 0x29/* ) */) {\n state.pos = oldPos;\n return false;\n }\n pos++;\n } else {\n //\n // Link reference\n //\n\n // do not allow nested reference links\n if (state.linkLevel > 0) { return false; }\n\n // [foo] [bar]\n // ^^ optional whitespace (can include newlines)\n for (; pos < max; pos++) {\n code = state.src.charCodeAt(pos);\n if (code !== 0x20 && code !== 0x0A) { break; }\n }\n\n if (pos < max && state.src.charCodeAt(pos) === 0x5B/* [ */) {\n start = pos + 1;\n pos = parseLinkLabel(state, pos);\n if (pos >= 0) {\n label = state.src.slice(start, pos++);\n } else {\n pos = start - 1;\n }\n }\n\n // covers label === '' and label === undefined\n // (collapsed reference link and shortcut reference link respectively)\n if (!label) {\n if (typeof label === 'undefined') {\n pos = labelEnd + 1;\n }\n label = state.src.slice(labelStart, labelEnd);\n }\n\n ref = state.env.references[normalizeReference(label)];\n if (!ref) {\n state.pos = oldPos;\n return false;\n }\n href = ref.href;\n title = ref.title;\n }\n\n //\n // We found the end of the link, and know for a fact it's a valid link;\n // so all that's left to do is to call tokenizer.\n //\n if (!silent) {\n state.pos = labelStart;\n state.posMax = labelEnd;\n\n if (isImage) {\n state.push({\n type: 'image',\n src: href,\n title: title,\n alt: state.src.substr(labelStart, labelEnd - labelStart),\n level: state.level\n });\n } else {\n state.push({\n type: 'link_open',\n href: href,\n title: title,\n level: state.level++\n });\n state.linkLevel++;\n state.parser.tokenize(state);\n state.linkLevel--;\n state.push({ type: 'link_close', level: --state.level });\n }\n }\n\n state.pos = pos;\n state.posMax = max;\n return true;\n}\n\n// Process inline footnotes (^[...])\n\n\nfunction footnote_inline(state, silent) {\n var labelStart,\n labelEnd,\n footnoteId,\n oldLength,\n max = state.posMax,\n start = state.pos;\n\n if (start + 2 >= max) { return false; }\n if (state.src.charCodeAt(start) !== 0x5E/* ^ */) { return false; }\n if (state.src.charCodeAt(start + 1) !== 0x5B/* [ */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n labelStart = start + 2;\n labelEnd = parseLinkLabel(state, start + 1);\n\n // parser failed to find ']', so it's not a valid note\n if (labelEnd < 0) { return false; }\n\n // We found the end of the link, and know for a fact it's a valid link;\n // so all that's left to do is to call tokenizer.\n //\n if (!silent) {\n if (!state.env.footnotes) { state.env.footnotes = {}; }\n if (!state.env.footnotes.list) { state.env.footnotes.list = []; }\n footnoteId = state.env.footnotes.list.length;\n\n state.pos = labelStart;\n state.posMax = labelEnd;\n\n state.push({\n type: 'footnote_ref',\n id: footnoteId,\n level: state.level\n });\n state.linkLevel++;\n oldLength = state.tokens.length;\n state.parser.tokenize(state);\n state.env.footnotes.list[footnoteId] = { tokens: state.tokens.splice(oldLength) };\n state.linkLevel--;\n }\n\n state.pos = labelEnd + 1;\n state.posMax = max;\n return true;\n}\n\n// Process footnote references ([^...])\n\nfunction footnote_ref(state, silent) {\n var label,\n pos,\n footnoteId,\n footnoteSubId,\n max = state.posMax,\n start = state.pos;\n\n // should be at least 4 chars - \"[^x]\"\n if (start + 3 > max) { return false; }\n\n if (!state.env.footnotes || !state.env.footnotes.refs) { return false; }\n if (state.src.charCodeAt(start) !== 0x5B/* [ */) { return false; }\n if (state.src.charCodeAt(start + 1) !== 0x5E/* ^ */) { return false; }\n if (state.level >= state.options.maxNesting) { return false; }\n\n for (pos = start + 2; pos < max; pos++) {\n if (state.src.charCodeAt(pos) === 0x20) { return false; }\n if (state.src.charCodeAt(pos) === 0x0A) { return false; }\n if (state.src.charCodeAt(pos) === 0x5D /* ] */) {\n break;\n }\n }\n\n if (pos === start + 2) { return false; } // no empty footnote labels\n if (pos >= max) { return false; }\n pos++;\n\n label = state.src.slice(start + 2, pos - 1);\n if (typeof state.env.footnotes.refs[':' + label] === 'undefined') { return false; }\n\n if (!silent) {\n if (!state.env.footnotes.list) { state.env.footnotes.list = []; }\n\n if (state.env.footnotes.refs[':' + label] < 0) {\n footnoteId = state.env.footnotes.list.length;\n state.env.footnotes.list[footnoteId] = { label: label, count: 0 };\n state.env.footnotes.refs[':' + label] = footnoteId;\n } else {\n footnoteId = state.env.footnotes.refs[':' + label];\n }\n\n footnoteSubId = state.env.footnotes.list[footnoteId].count;\n state.env.footnotes.list[footnoteId].count++;\n\n state.push({\n type: 'footnote_ref',\n id: footnoteId,\n subId: footnoteSubId,\n level: state.level\n });\n }\n\n state.pos = pos;\n state.posMax = max;\n return true;\n}\n\n// List of valid url schemas, accorting to commonmark spec\n// http://jgm.github.io/CommonMark/spec.html#autolinks\n\nvar url_schemas = [\n 'coap',\n 'doi',\n 'javascript',\n 'aaa',\n 'aaas',\n 'about',\n 'acap',\n 'cap',\n 'cid',\n 'crid',\n 'data',\n 'dav',\n 'dict',\n 'dns',\n 'file',\n 'ftp',\n 'geo',\n 'go',\n 'gopher',\n 'h323',\n 'http',\n 'https',\n 'iax',\n 'icap',\n 'im',\n 'imap',\n 'info',\n 'ipp',\n 'iris',\n 'iris.beep',\n 'iris.xpc',\n 'iris.xpcs',\n 'iris.lwz',\n 'ldap',\n 'mailto',\n 'mid',\n 'msrp',\n 'msrps',\n 'mtqp',\n 'mupdate',\n 'news',\n 'nfs',\n 'ni',\n 'nih',\n 'nntp',\n 'opaquelocktoken',\n 'pop',\n 'pres',\n 'rtsp',\n 'service',\n 'session',\n 'shttp',\n 'sieve',\n 'sip',\n 'sips',\n 'sms',\n 'snmp',\n 'soap.beep',\n 'soap.beeps',\n 'tag',\n 'tel',\n 'telnet',\n 'tftp',\n 'thismessage',\n 'tn3270',\n 'tip',\n 'tv',\n 'urn',\n 'vemmi',\n 'ws',\n 'wss',\n 'xcon',\n 'xcon-userid',\n 'xmlrpc.beep',\n 'xmlrpc.beeps',\n 'xmpp',\n 'z39.50r',\n 'z39.50s',\n 'adiumxtra',\n 'afp',\n 'afs',\n 'aim',\n 'apt',\n 'attachment',\n 'aw',\n 'beshare',\n 'bitcoin',\n 'bolo',\n 'callto',\n 'chrome',\n 'chrome-extension',\n 'com-eventbrite-attendee',\n 'content',\n 'cvs',\n 'dlna-playsingle',\n 'dlna-playcontainer',\n 'dtn',\n 'dvb',\n 'ed2k',\n 'facetime',\n 'feed',\n 'finger',\n 'fish',\n 'gg',\n 'git',\n 'gizmoproject',\n 'gtalk',\n 'hcp',\n 'icon',\n 'ipn',\n 'irc',\n 'irc6',\n 'ircs',\n 'itms',\n 'jar',\n 'jms',\n 'keyparc',\n 'lastfm',\n 'ldaps',\n 'magnet',\n 'maps',\n 'market',\n 'message',\n 'mms',\n 'ms-help',\n 'msnim',\n 'mumble',\n 'mvn',\n 'notes',\n 'oid',\n 'palm',\n 'paparazzi',\n 'platform',\n 'proxy',\n 'psyc',\n 'query',\n 'res',\n 'resource',\n 'rmi',\n 'rsync',\n 'rtmp',\n 'secondlife',\n 'sftp',\n 'sgn',\n 'skype',\n 'smb',\n 'soldat',\n 'spotify',\n 'ssh',\n 'steam',\n 'svn',\n 'teamspeak',\n 'things',\n 'udp',\n 'unreal',\n 'ut2004',\n 'ventrilo',\n 'view-source',\n 'webcal',\n 'wtai',\n 'wyciwyg',\n 'xfire',\n 'xri',\n 'ymsgr'\n];\n\n// Process autolinks ''\n\n\n/*eslint max-len:0*/\nvar EMAIL_RE = /^<([a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/;\nvar AUTOLINK_RE = /^<([a-zA-Z.\\-]{1,25}):([^<>\\x00-\\x20]*)>/;\n\n\nfunction autolink(state, silent) {\n var tail, linkMatch, emailMatch, url, fullUrl, pos = state.pos;\n\n if (state.src.charCodeAt(pos) !== 0x3C/* < */) { return false; }\n\n tail = state.src.slice(pos);\n\n if (tail.indexOf('>') < 0) { return false; }\n\n linkMatch = tail.match(AUTOLINK_RE);\n\n if (linkMatch) {\n if (url_schemas.indexOf(linkMatch[1].toLowerCase()) < 0) { return false; }\n\n url = linkMatch[0].slice(1, -1);\n fullUrl = normalizeLink(url);\n if (!state.parser.validateLink(url)) { return false; }\n\n if (!silent) {\n state.push({\n type: 'link_open',\n href: fullUrl,\n level: state.level\n });\n state.push({\n type: 'text',\n content: url,\n level: state.level + 1\n });\n state.push({ type: 'link_close', level: state.level });\n }\n\n state.pos += linkMatch[0].length;\n return true;\n }\n\n emailMatch = tail.match(EMAIL_RE);\n\n if (emailMatch) {\n\n url = emailMatch[0].slice(1, -1);\n\n fullUrl = normalizeLink('mailto:' + url);\n if (!state.parser.validateLink(fullUrl)) { return false; }\n\n if (!silent) {\n state.push({\n type: 'link_open',\n href: fullUrl,\n level: state.level\n });\n state.push({\n type: 'text',\n content: url,\n level: state.level + 1\n });\n state.push({ type: 'link_close', level: state.level });\n }\n\n state.pos += emailMatch[0].length;\n return true;\n }\n\n return false;\n}\n\n// Regexps to match html elements\n\nfunction replace$1(regex, options) {\n regex = regex.source;\n options = options || '';\n\n return function self(name, val) {\n if (!name) {\n return new RegExp(regex, options);\n }\n val = val.source || val;\n regex = regex.replace(name, val);\n return self;\n };\n}\n\n\nvar attr_name = /[a-zA-Z_:][a-zA-Z0-9:._-]*/;\n\nvar unquoted = /[^\"'=<>`\\x00-\\x20]+/;\nvar single_quoted = /'[^']*'/;\nvar double_quoted = /\"[^\"]*\"/;\n\n/*eslint no-spaced-func:0*/\nvar attr_value = replace$1(/(?:unquoted|single_quoted|double_quoted)/)\n ('unquoted', unquoted)\n ('single_quoted', single_quoted)\n ('double_quoted', double_quoted)\n ();\n\nvar attribute = replace$1(/(?:\\s+attr_name(?:\\s*=\\s*attr_value)?)/)\n ('attr_name', attr_name)\n ('attr_value', attr_value)\n ();\n\nvar open_tag = replace$1(/<[A-Za-z][A-Za-z0-9]*attribute*\\s*\\/?>/)\n ('attribute', attribute)\n ();\n\nvar close_tag = /<\\/[A-Za-z][A-Za-z0-9]*\\s*>/;\nvar comment = /|/;\nvar processing = /<[?].*?[?]>/;\nvar declaration = /]*>/;\nvar cdata = //;\n\nvar HTML_TAG_RE = replace$1(/^(?:open_tag|close_tag|comment|processing|declaration|cdata)/)\n ('open_tag', open_tag)\n ('close_tag', close_tag)\n ('comment', comment)\n ('processing', processing)\n ('declaration', declaration)\n ('cdata', cdata)\n ();\n\n// Process html tags\n\n\nfunction isLetter$2(ch) {\n /*eslint no-bitwise:0*/\n var lc = ch | 0x20; // to lower case\n return (lc >= 0x61/* a */) && (lc <= 0x7a/* z */);\n}\n\n\nfunction htmltag(state, silent) {\n var ch, match, max, pos = state.pos;\n\n if (!state.options.html) { return false; }\n\n // Check start\n max = state.posMax;\n if (state.src.charCodeAt(pos) !== 0x3C/* < */ ||\n pos + 2 >= max) {\n return false;\n }\n\n // Quick fail on second char\n ch = state.src.charCodeAt(pos + 1);\n if (ch !== 0x21/* ! */ &&\n ch !== 0x3F/* ? */ &&\n ch !== 0x2F/* / */ &&\n !isLetter$2(ch)) {\n return false;\n }\n\n match = state.src.slice(pos).match(HTML_TAG_RE);\n if (!match) { return false; }\n\n if (!silent) {\n state.push({\n type: 'htmltag',\n content: state.src.slice(pos, pos + match[0].length),\n level: state.level\n });\n }\n state.pos += match[0].length;\n return true;\n}\n\n// Process html entity - {, ¯, ", ...\n\n\nvar DIGITAL_RE = /^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i;\nvar NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i;\n\n\nfunction entity(state, silent) {\n var ch, code, match, pos = state.pos, max = state.posMax;\n\n if (state.src.charCodeAt(pos) !== 0x26/* & */) { return false; }\n\n if (pos + 1 < max) {\n ch = state.src.charCodeAt(pos + 1);\n\n if (ch === 0x23 /* # */) {\n match = state.src.slice(pos).match(DIGITAL_RE);\n if (match) {\n if (!silent) {\n code = match[1][0].toLowerCase() === 'x' ? parseInt(match[1].slice(1), 16) : parseInt(match[1], 10);\n state.pending += isValidEntityCode(code) ? fromCodePoint(code) : fromCodePoint(0xFFFD);\n }\n state.pos += match[0].length;\n return true;\n }\n } else {\n match = state.src.slice(pos).match(NAMED_RE);\n if (match) {\n var decoded = decodeEntity(match[1]);\n if (match[1] !== decoded) {\n if (!silent) { state.pending += decoded; }\n state.pos += match[0].length;\n return true;\n }\n }\n }\n }\n\n if (!silent) { state.pending += '&'; }\n state.pos++;\n return true;\n}\n\n/**\n * Inline Parser `rules`\n */\n\nvar _rules$2 = [\n [ 'text', text ],\n [ 'newline', newline ],\n [ 'escape', escape ],\n [ 'backticks', backticks ],\n [ 'del', del ],\n [ 'ins', ins ],\n [ 'mark', mark ],\n [ 'emphasis', emphasis ],\n [ 'sub', sub ],\n [ 'sup', sup ],\n [ 'links', links ],\n [ 'footnote_inline', footnote_inline ],\n [ 'footnote_ref', footnote_ref ],\n [ 'autolink', autolink ],\n [ 'htmltag', htmltag ],\n [ 'entity', entity ]\n];\n\n/**\n * Inline Parser class. Note that link validation is stricter\n * in Remarkable than what is specified by CommonMark. If you\n * want to change this you can use a custom validator.\n *\n * @api private\n */\n\nfunction ParserInline() {\n this.ruler = new Ruler();\n for (var i = 0; i < _rules$2.length; i++) {\n this.ruler.push(_rules$2[i][0], _rules$2[i][1]);\n }\n\n // Can be overridden with a custom validator\n this.validateLink = validateLink;\n}\n\n/**\n * Skip a single token by running all rules in validation mode.\n * Returns `true` if any rule reports success.\n *\n * @param {Object} `state`\n * @api privage\n */\n\nParserInline.prototype.skipToken = function (state) {\n var rules = this.ruler.getRules('');\n var len = rules.length;\n var pos = state.pos;\n var i, cached_pos;\n\n if ((cached_pos = state.cacheGet(pos)) > 0) {\n state.pos = cached_pos;\n return;\n }\n\n for (i = 0; i < len; i++) {\n if (rules[i](state, true)) {\n state.cacheSet(pos, state.pos);\n return;\n }\n }\n\n state.pos++;\n state.cacheSet(pos, state.pos);\n};\n\n/**\n * Generate tokens for the given input range.\n *\n * @param {Object} `state`\n * @api private\n */\n\nParserInline.prototype.tokenize = function (state) {\n var rules = this.ruler.getRules('');\n var len = rules.length;\n var end = state.posMax;\n var ok, i;\n\n while (state.pos < end) {\n\n // Try all possible rules.\n // On success, the rule should:\n //\n // - update `state.pos`\n // - update `state.tokens`\n // - return true\n for (i = 0; i < len; i++) {\n ok = rules[i](state, false);\n\n if (ok) {\n break;\n }\n }\n\n if (ok) {\n if (state.pos >= end) { break; }\n continue;\n }\n\n state.pending += state.src[state.pos++];\n }\n\n if (state.pending) {\n state.pushPending();\n }\n};\n\n/**\n * Parse the given input string.\n *\n * @param {String} `str`\n * @param {Object} `options`\n * @param {Object} `env`\n * @param {Array} `outTokens`\n * @api private\n */\n\nParserInline.prototype.parse = function (str, options, env, outTokens) {\n var state = new StateInline(str, this, options, env, outTokens);\n this.tokenize(state);\n};\n\n/**\n * Validate the given `url` by checking for bad protocols.\n *\n * @param {String} `url`\n * @return {Boolean}\n */\n\nfunction validateLink(url) {\n var BAD_PROTOCOLS = [ 'vbscript', 'javascript', 'file', 'data' ];\n var str = url.trim().toLowerCase();\n // Care about digital entities \"javascript:alert(1)\"\n str = replaceEntities(str);\n if (str.indexOf(':') !== -1 && BAD_PROTOCOLS.indexOf(str.split(':')[0]) !== -1) {\n return false;\n }\n return true;\n}\n\n// Remarkable default options\n\nvar defaultConfig = {\n options: {\n html: false, // Enable HTML tags in source\n xhtmlOut: false, // Use '/' to close single tags (
    )\n breaks: false, // Convert '\\n' in paragraphs into
    \n langPrefix: 'language-', // CSS language prefix for fenced blocks\n linkTarget: '', // set target to open link in\n\n // Enable some language-neutral replacements + quotes beautification\n typographer: false,\n\n // Double + single quotes replacement pairs, when typographer enabled,\n // and smartquotes on. Set doubles to '«»' for Russian, '„“' for German.\n quotes: '“”‘’',\n\n // Highlighter function. Should return escaped HTML,\n // or '' if input not changed\n //\n // function (/*str, lang*/) { return ''; }\n //\n highlight: null,\n\n maxNesting: 20 // Internal protection, recursion limit\n },\n\n components: {\n\n core: {\n rules: [\n 'block',\n 'inline',\n 'references',\n 'replacements',\n 'smartquotes',\n 'references',\n 'abbr2',\n 'footnote_tail'\n ]\n },\n\n block: {\n rules: [\n 'blockquote',\n 'code',\n 'fences',\n 'footnote',\n 'heading',\n 'hr',\n 'htmlblock',\n 'lheading',\n 'list',\n 'paragraph',\n 'table'\n ]\n },\n\n inline: {\n rules: [\n 'autolink',\n 'backticks',\n 'del',\n 'emphasis',\n 'entity',\n 'escape',\n 'footnote_ref',\n 'htmltag',\n 'links',\n 'newline',\n 'text'\n ]\n }\n }\n};\n\n// Remarkable default options\n\nvar fullConfig = {\n options: {\n html: false, // Enable HTML tags in source\n xhtmlOut: false, // Use '/' to close single tags (
    )\n breaks: false, // Convert '\\n' in paragraphs into
    \n langPrefix: 'language-', // CSS language prefix for fenced blocks\n linkTarget: '', // set target to open link in\n\n // Enable some language-neutral replacements + quotes beautification\n typographer: false,\n\n // Double + single quotes replacement pairs, when typographer enabled,\n // and smartquotes on. Set doubles to '«»' for Russian, '„“' for German.\n quotes: '“”‘’',\n\n // Highlighter function. Should return escaped HTML,\n // or '' if input not changed\n //\n // function (/*str, lang*/) { return ''; }\n //\n highlight: null,\n\n maxNesting: 20 // Internal protection, recursion limit\n },\n\n components: {\n // Don't restrict core/block/inline rules\n core: {},\n block: {},\n inline: {}\n }\n};\n\n// Commonmark default options\n\nvar commonmarkConfig = {\n options: {\n html: true, // Enable HTML tags in source\n xhtmlOut: true, // Use '/' to close single tags (
    )\n breaks: false, // Convert '\\n' in paragraphs into
    \n langPrefix: 'language-', // CSS language prefix for fenced blocks\n linkTarget: '', // set target to open link in\n\n // Enable some language-neutral replacements + quotes beautification\n typographer: false,\n\n // Double + single quotes replacement pairs, when typographer enabled,\n // and smartquotes on. Set doubles to '«»' for Russian, '„“' for German.\n quotes: '“”‘’',\n\n // Highlighter function. Should return escaped HTML,\n // or '' if input not changed\n //\n // function (/*str, lang*/) { return ''; }\n //\n highlight: null,\n\n maxNesting: 20 // Internal protection, recursion limit\n },\n\n components: {\n\n core: {\n rules: [\n 'block',\n 'inline',\n 'references',\n 'abbr2'\n ]\n },\n\n block: {\n rules: [\n 'blockquote',\n 'code',\n 'fences',\n 'heading',\n 'hr',\n 'htmlblock',\n 'lheading',\n 'list',\n 'paragraph'\n ]\n },\n\n inline: {\n rules: [\n 'autolink',\n 'backticks',\n 'emphasis',\n 'entity',\n 'escape',\n 'htmltag',\n 'links',\n 'newline',\n 'text'\n ]\n }\n }\n};\n\n/**\n * Preset configs\n */\n\nvar config = {\n 'default': defaultConfig,\n 'full': fullConfig,\n 'commonmark': commonmarkConfig\n};\n\n/**\n * The `StateCore` class manages state.\n *\n * @param {Object} `instance` Remarkable instance\n * @param {String} `str` Markdown string\n * @param {Object} `env`\n */\n\nfunction StateCore(instance, str, env) {\n this.src = str;\n this.env = env;\n this.options = instance.options;\n this.tokens = [];\n this.inlineMode = false;\n\n this.inline = instance.inline;\n this.block = instance.block;\n this.renderer = instance.renderer;\n this.typographer = instance.typographer;\n}\n\n/**\n * The main `Remarkable` class. Create an instance of\n * `Remarkable` with a `preset` and/or `options`.\n *\n * @param {String} `preset` If no preset is given, `default` is used.\n * @param {Object} `options`\n */\n\nfunction Remarkable(preset, options) {\n if (typeof preset !== 'string') {\n options = preset;\n preset = 'default';\n }\n\n if (options && options.linkify != null) {\n console.warn(\n 'linkify option is removed. Use linkify plugin instead:\\n\\n' +\n 'import Remarkable from \\'remarkable\\';\\n' +\n 'import linkify from \\'remarkable/linkify\\';\\n' +\n 'new Remarkable().use(linkify)\\n'\n );\n }\n\n this.inline = new ParserInline();\n this.block = new ParserBlock();\n this.core = new Core();\n this.renderer = new Renderer();\n this.ruler = new Ruler();\n\n this.options = {};\n this.configure(config[preset]);\n this.set(options || {});\n}\n\n/**\n * Set options as an alternative to passing them\n * to the constructor.\n *\n * ```js\n * md.set({typographer: true});\n * ```\n * @param {Object} `options`\n * @api public\n */\n\nRemarkable.prototype.set = function (options) {\n assign(this.options, options);\n};\n\n/**\n * Batch loader for components rules states, and options\n *\n * @param {Object} `presets`\n */\n\nRemarkable.prototype.configure = function (presets) {\n var self = this;\n\n if (!presets) { throw new Error('Wrong `remarkable` preset, check name/content'); }\n if (presets.options) { self.set(presets.options); }\n if (presets.components) {\n Object.keys(presets.components).forEach(function (name) {\n if (presets.components[name].rules) {\n self[name].ruler.enable(presets.components[name].rules, true);\n }\n });\n }\n};\n\n/**\n * Use a plugin.\n *\n * ```js\n * var md = new Remarkable();\n *\n * md.use(plugin1)\n * .use(plugin2, opts)\n * .use(plugin3);\n * ```\n *\n * @param {Function} `plugin`\n * @param {Object} `options`\n * @return {Object} `Remarkable` for chaining\n */\n\nRemarkable.prototype.use = function (plugin, options) {\n plugin(this, options);\n return this;\n};\n\n\n/**\n * Parse the input `string` and return a tokens array.\n * Modifies `env` with definitions data.\n *\n * @param {String} `string`\n * @param {Object} `env`\n * @return {Array} Array of tokens\n */\n\nRemarkable.prototype.parse = function (str, env) {\n var state = new StateCore(this, str, env);\n this.core.process(state);\n return state.tokens;\n};\n\n/**\n * The main `.render()` method that does all the magic :)\n *\n * @param {String} `string`\n * @param {Object} `env`\n * @return {String} Rendered HTML.\n */\n\nRemarkable.prototype.render = function (str, env) {\n env = env || {};\n return this.renderer.render(this.parse(str, env), this.options, env);\n};\n\n/**\n * Parse the given content `string` as a single string.\n *\n * @param {String} `string`\n * @param {Object} `env`\n * @return {Array} Array of tokens\n */\n\nRemarkable.prototype.parseInline = function (str, env) {\n var state = new StateCore(this, str, env);\n state.inlineMode = true;\n this.core.process(state);\n return state.tokens;\n};\n\n/**\n * Render a single content `string`, without wrapping it\n * to paragraphs\n *\n * @param {String} `str`\n * @param {Object} `env`\n * @return {String}\n */\n\nRemarkable.prototype.renderInline = function (str, env) {\n env = env || {};\n return this.renderer.render(this.parseInline(str, env), this.options, env);\n};\n\nexport { Remarkable, utils };\n","import { html, TemplateResult } from 'lit';\nimport { unsafeHTML } from 'lit-html/directives/unsafe-html.js';\nimport {\n directive,\n Directive,\n Part,\n PartInfo,\n PartType,\n} from 'lit/directive.js';\nimport ExcellentParser, { Expression } from './ExcellentParser';\nimport {\n CompletionOption,\n CompletionProperty,\n CompletionResult,\n CompletionSchema,\n CompletionType,\n KeyedAssets,\n} from '../interfaces';\nimport { Store } from '../store/Store';\nimport { Remarkable } from 'remarkable';\n\nconst md = new Remarkable();\n\nconst messageParser = new ExcellentParser('@', [\n 'contact',\n 'fields',\n 'globals',\n 'urns',\n]);\n\nconst sessionParser = new ExcellentParser('@', [\n 'contact',\n 'fields',\n 'globals',\n 'urns',\n 'results',\n 'input',\n 'run',\n 'child',\n 'parent',\n 'node',\n 'webhook',\n 'ticket',\n 'trigger',\n 'resume',\n]);\n\n// Class-based directive API\nexport class RenderMarkdown extends Directive {\n // State stored in class field\n value: string | undefined;\n constructor(partInfo: PartInfo) {\n super(partInfo);\n // When necessary, validate part in constructor using `part.type`\n if (partInfo.type !== PartType.CHILD) {\n throw new Error('renderMarkdown only supports child expressions');\n }\n }\n // Optional: override update to perform any direct DOM manipulation\n // DirectiveParameters\n update(part: Part, [initialValue]: any) {\n /* Any imperative updates to DOM/parts would go here */\n return this.render(initialValue);\n }\n // Do SSR-compatible rendering (arguments are passed from call site)\n render(initialValue: string) {\n // Previous state available on class field\n if (this.value === undefined) {\n this.value = initialValue;\n }\n return html`${unsafeHTML(md.render(this.value))}`;\n }\n}\n\nexport const renderMarkdown = directive(RenderMarkdown);\n\nexport const renderCompletionOption = (\n option: CompletionOption,\n selected: boolean\n): TemplateResult => {\n if (option.signature) {\n const argStart = option.signature.indexOf('(');\n const name = option.signature.substr(0, argStart);\n const args = option.signature.substr(argStart);\n\n return html`\n
    \n
    ƒ
    \n
    ${name}
    \n ${selected\n ? html`\n \n ${args}\n
    \n
    ${renderMarkdown(option.summary)}
    \n `\n : null}\n \n `;\n }\n\n return html`\n
    \n
    ${option.name}
    \n ${selected\n ? html`
    ${option.summary}
    `\n : null}\n
    \n `;\n};\n\nexport const getFunctions = (\n functions: CompletionOption[],\n query: string\n): CompletionOption[] => {\n if (!query) {\n return functions;\n }\n return functions.filter((option: CompletionOption) => {\n if (option.signature) {\n return option.signature.indexOf((query || '').toLowerCase()) === 0;\n }\n return false;\n });\n};\n\n/**\n * Takes a dot query and returns the completions options at the current level\n * @param dotQuery query such as \"contact.first_n\"\n */\nexport const getCompletions = (\n schema: CompletionSchema,\n dotQuery: string,\n keyedAssets: KeyedAssets = {},\n session: boolean\n): CompletionOption[] => {\n const parts = (dotQuery || '').split('.');\n let currentProps: CompletionProperty[] = session\n ? schema.root\n : schema.root_no_session;\n\n if (!currentProps) {\n return [];\n }\n\n let prefix = '';\n let part = '';\n while (parts.length > 0) {\n part = parts.shift();\n if (part) {\n // eslint-disable-next-line\n const nextProp = currentProps.find(\n (prop: CompletionProperty) => prop.key === part\n );\n if (nextProp) {\n // eslint-disable-next-line\n const nextType = schema.types.find(\n (type: CompletionType) => type.name === nextProp.type\n );\n if (nextType && nextType.properties) {\n currentProps = nextType.properties;\n prefix += part + '.';\n } else if (nextType && nextType.property_template) {\n prefix += part + '.';\n const template = nextType.property_template;\n if (keyedAssets[nextType.name]) {\n currentProps = keyedAssets[nextType.name].map((key: string) => ({\n key: template.key.replace('{key}', key),\n help: template.help.replace('{key}', key),\n type: template.type,\n }));\n } else {\n currentProps = [];\n }\n } else {\n // eslint-disable-next-line\n currentProps = currentProps.filter((prop: CompletionProperty) =>\n prop.key.startsWith(part.toLowerCase())\n );\n break;\n }\n } else {\n // eslint-disable-next-line\n currentProps = currentProps.filter((prop: CompletionProperty) =>\n prop.key.startsWith(part.toLowerCase())\n );\n break;\n }\n }\n }\n\n return currentProps.map((prop: CompletionProperty) => {\n const name =\n prop.key === '__default__'\n ? prefix.substr(0, prefix.length - 1)\n : prefix + prop.key;\n return { name, summary: prop.help };\n });\n};\n\nexport const getOffset = (el: HTMLElement) => {\n const rect = el.getBoundingClientRect(),\n scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,\n scrollTop = window.pageYOffset || document.documentElement.scrollTop;\n return { top: rect.top + scrollTop, left: rect.left + scrollLeft };\n};\n\nexport const getVerticalScroll = (ele: Node) => {\n let current = ele;\n const verticalScroll = 0;\n while (current) {\n current = current.parentNode;\n }\n return verticalScroll;\n};\n\nexport const getCompletionName = (option: CompletionOption): string => {\n return (\n option.name || option.signature.substr(0, option.signature.indexOf('('))\n );\n};\n\nexport const getCompletionSignature = (option: CompletionOption): string => {\n return option.signature.substr(option.signature.indexOf('('));\n};\n\n/**\n * Determines the pixel position of position inside a textarea or input\n * TODO: Explore somethign like contenteditable to avoid this madness\n * see: https://jh3y.medium.com/how-to-where-s-the-caret-getting-the-xy-position-of-the-caret-a24ba372990a\n */\nconst getCursorXY = (input, selectionPoint) => {\n const { offsetLeft: inputX, offsetTop: inputY } = input;\n const div = document.createElement('div');\n const copyStyle = getComputedStyle(input);\n for (const prop of copyStyle) {\n div.style[prop] = copyStyle[prop];\n }\n div.style.position = 'relative';\n const swap = '.';\n const inputValue =\n input.tagName === 'INPUT' ? input.value.replace(/ /g, swap) : input.value;\n const textContent = inputValue.substr(0, selectionPoint);\n div.textContent = textContent;\n if (input.tagName === 'TEXTAREA') div.style.height = 'auto';\n if (input.tagName === 'INPUT') div.style.width = 'auto';\n const span = document.createElement('span');\n span.textContent = inputValue.substr(selectionPoint) || '.';\n div.appendChild(span);\n document.body.appendChild(div);\n const { offsetLeft: spanX, offsetTop: spanY } = span;\n document.body.removeChild(div);\n return {\n left: inputX + spanX,\n top: inputY + spanY,\n };\n};\n\nexport const updateInputElementWithCompletion = (\n currentQuery: string,\n ele: HTMLInputElement,\n option: CompletionOption\n) => {\n let insertText = '';\n\n if (option.signature) {\n // they selected a function\n insertText = option.signature.substr(0, option.signature.indexOf('(') + 1);\n } else {\n insertText = option.name;\n }\n\n const queryLength = currentQuery.length;\n\n if (ele) {\n const value = ele.value;\n const insertionPoint = ele.selectionStart - queryLength;\n\n // strip out our query\n // const insertionPoint = value.lastIndexOf(value.substring(0, this.inputElement.selectionStart));\n const leftSide = value.substr(0, insertionPoint);\n const remaining = value.substr(insertionPoint + queryLength);\n const caret = leftSide.length + insertText.length;\n\n // set our value and our new caret\n ele.value = leftSide + insertText + remaining;\n ele.setSelectionRange(caret, caret);\n\n // now scroll our text box if necessary\n const position = getCursorXY(ele, caret);\n if (position.left > ele.width) {\n ele.scrollLeft = position.left;\n }\n\n ele.dispatchEvent(new Event('input'));\n }\n};\n\nexport const executeCompletionQuery = (\n ele: HTMLInputElement,\n store: Store,\n session: boolean\n): CompletionResult => {\n const result: CompletionResult = {\n currentFunction: null,\n options: [],\n anchorPosition: null,\n query: null,\n };\n\n if (!ele) {\n return;\n }\n\n // we need a store to do anything useful\n if (!store) {\n return result;\n }\n\n const cursor = ele.selectionStart;\n const input = ele.value.substring(0, cursor);\n\n const parser = session ? sessionParser : messageParser;\n const expressions = parser.findExpressions(input);\n const currentExpression = expressions.find(\n (expr: Expression) =>\n expr.start <= cursor &&\n (expr.end > cursor || (expr.end === cursor && !expr.closed))\n );\n\n if (currentExpression) {\n const includeFunctions = currentExpression.text.indexOf('(') > -1;\n if (includeFunctions) {\n const functionQuery = parser.functionContext(currentExpression.text);\n if (functionQuery) {\n const fns = getFunctions(store.getFunctions(), functionQuery);\n if (fns.length > 0) {\n result.currentFunction = fns[0];\n }\n }\n }\n\n for (let i = currentExpression.text.length; i >= 0; i--) {\n const curr = currentExpression.text[i];\n if (\n curr === '@' ||\n curr === '(' ||\n curr === ' ' ||\n curr === ',' ||\n curr === ')' ||\n i === 0\n ) {\n // don't include non-expression chars\n if (\n curr === '(' ||\n curr === ' ' ||\n curr === ',' ||\n curr === ')' ||\n curr === '@'\n ) {\n i++;\n }\n\n const caret = getCursorXY(ele, currentExpression.start + i);\n\n result.anchorPosition = {\n left: caret.left - 2 - ele.scrollLeft,\n top: caret.top - ele.scrollTop,\n };\n\n result.query = currentExpression.text.substr(\n i,\n currentExpression.text.length - i\n );\n\n result.options = [\n ...getCompletions(\n store.getCompletionSchema(),\n result.query,\n store.getKeyedAssets(),\n session\n ),\n ...(includeFunctions\n ? getFunctions(store.getFunctions(), result.query)\n : []),\n ];\n\n return result;\n }\n }\n } else {\n result.options = [];\n result.query = '';\n }\n return result;\n};\n","/* eslint-disable @typescript-eslint/no-empty-function */\nimport { TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport {\n getUrl,\n getClasses,\n fetchResults,\n WebResponse,\n postJSON,\n} from '../utils';\nimport '../options/Options';\nimport { EventHandler } from '../RapidElement';\nimport { FormElement } from '../FormElement';\n\nimport { lru } from 'tiny-lru';\nimport { CompletionOption, CustomEventType, Position } from '../interfaces';\nimport {\n renderCompletionOption,\n updateInputElementWithCompletion,\n executeCompletionQuery,\n} from '../completion/helpers';\nimport { Store } from '../store/Store';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { Icon } from '../vectoricon';\nimport { msg } from '@lit/localize';\n\nconst LOOK_AHEAD = 20;\n\nexport class Select extends FormElement {\n private hiddenInputs: HTMLInputElement[] = [];\n\n static get styles() {\n return css`\n :host {\n font-family: var(--font-family);\n transition: all ease-in-out var(--transition-speed);\n display: inline;\n line-height: normal;\n outline: none;\n position: relative;\n --icon-color: var(--color-text-dark-secondary);\n }\n\n temba-options {\n --temba-options-font-size: var(--temba-select-selected-font-size);\n --icon-color: var(--color-text-dark);\n }\n\n :host:focus {\n outline: none;\n }\n\n #anchor {\n position: absolute;\n visibility: hidden;\n width: 250px;\n height: 25px;\n }\n\n .remove-item {\n cursor: pointer;\n display: inline-block;\n padding: 3px 6px;\n border-right: 1px solid rgba(100, 100, 100, 0.2);\n margin: 0;\n background: rgba(100, 100, 100, 0.05);\n }\n\n .selected-item.multi .remove-item {\n display: none;\n }\n\n .remove-item:hover {\n background: rgba(100, 100, 100, 0.1);\n }\n\n input:focus {\n outline: none;\n box-shadow: none;\n cursor: text;\n }\n\n .wrapper-bg {\n background: #f3f3f3;\n box-shadow: inset 0px 0px 4px rgb(0 0 0 / 10%);\n border-radius: var(--curvature-widget);\n }\n\n .select-container {\n display: flex;\n flex-direction: row;\n flex-wrap: nowrap;\n align-items: center;\n border: 1px solid var(--color-widget-border);\n transition: all ease-in-out var(--transition-speed);\n cursor: pointer;\n border-radius: var(--curvature-widget);\n background: var(--color-widget-bg);\n padding-top: 1px;\n box-shadow: var(--widget-box-shadow);\n position: relative;\n }\n\n temba-icon.select-open:hover,\n .clear-button:hover {\n --icon-color: var(--color-text-dark);\n }\n\n .select-container:focus {\n outline: none;\n }\n\n .select-container.multi {\n /* background: var(--color-widget-bg); */\n }\n\n .select-container.focused {\n background: var(--color-widget-bg-focused);\n border-color: var(--color-focus);\n box-shadow: var(--widget-box-shadow-focused);\n }\n\n .left-side {\n flex: 1;\n overflow: hidden;\n }\n\n .empty .placeholder {\n display: block;\n }\n\n .selected {\n display: flex;\n flex-direction: row;\n align-items: stretch;\n user-select: none;\n padding: var(--temba-select-selected-padding);\n }\n\n .searchable .selected {\n padding: 4px !important;\n }\n\n .multi .selected {\n flex-wrap: wrap;\n padding: 4px;\n }\n\n .multi.empty .selected {\n padding: var(--temba-select-selected-padding);\n }\n\n .selected .selected-item {\n display: flex;\n overflow: hidden;\n color: var(--color-widget-text);\n line-height: var(--temba-select-selected-line-height);\n --icon-color: var(--color-text-dark);\n }\n\n .multi .selected .selected-item {\n vertical-align: middle;\n background: rgba(100, 100, 100, 0.1);\n user-select: none;\n border-radius: 2px;\n align-items: stretch;\n flex-direction: row;\n flex-wrap: nowrap;\n margin: 2px 2px;\n }\n\n .selected-item .option-name {\n padding: 0px;\n font-size: var(--temba-select-selected-font-size);\n align-self: center;\n }\n\n .multi .selected-item .option-name {\n flex: 1 1 auto;\n align-self: center;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n font-size: 12px;\n padding: 2px 8px;\n }\n\n .multi .selected .selected-item.focused {\n background: rgba(100, 100, 100, 0.3);\n }\n\n input {\n font-size: 13px;\n width: 0px;\n cursor: pointer;\n background: none;\n resize: none;\n border: none !important;\n visibility: visible;\n line-height: inherit !important;\n height: var(--search-input-height) !important;\n margin: 0px !important;\n padding: 0px !important;\n box-shadow: none !important;\n font-family: var(--font-family);\n caret-color: var(--input-caret);\n }\n\n input:focus {\n box-shadow: none !important;\n }\n\n .searchable.no-search-input .input-wrapper {\n flex-grow: inherit;\n min-width: 1px;\n }\n\n .searchable.no-search-input.empty .input-wrapper {\n flex-grow: 1;\n min-width: 1px;\n }\n\n .searchable.no-search-input .input-wrapper .searchbox {\n flex-grow: inherit;\n min-width: 1px;\n }\n\n .searchable .input-wrapper .searchbox {\n flex-grow: 1;\n min-width: 80%;\n height: 100%;\n }\n\n .searchable.single.search-input .selected .selected-item {\n display: none;\n }\n\n .searchable.single.no-search-input\n .selected\n .input-wrapper\n input.searchbox {\n padding: 6px 2px !important;\n }\n\n .searchable.single.no-search-input.empty\n .selected\n .input-wrapper\n input.searchbox {\n padding: 6px 6px !important;\n }\n\n .empty input {\n width: 100%;\n }\n\n .searchable input {\n padding: 6px 4px !important;\n }\n\n .searchable input {\n visibility: visible;\n cursor: pointer;\n background: none;\n color: var(--color-text);\n resize: none;\n box-shadow: none !important;\n flex-grow: 1;\n border: none;\n caret-color: var(--input-caret);\n }\n\n .searchable input:focus {\n box-shadow: none !important;\n }\n\n .input-wrapper {\n flex-grow: 1;\n }\n\n .input-wrapper .searchbox {\n }\n\n .searchbox {\n border: 0px;\n }\n\n .searchbox::placeholder {\n color: var(--color-placeholder);\n font-size: 1em;\n line-height: var(--temba-select-selected-line-height);\n padding-left: 1px;\n }\n\n .placeholder {\n font-size: var(--temba-select-selected-font-size);\n color: var(--color-placeholder);\n display: none;\n line-height: var(--temba-select-selected-line-height);\n }\n\n .footer {\n padding: 5px 10px;\n background: var(--color-primary-light);\n color: rgba(0, 0, 0, 0.5);\n font-size: 80%;\n border-bottom-left-radius: var(--curvature-widget);\n border-bottom-right-radius: var(--curvature-widget);\n }\n\n .small {\n --temba-select-selected-padding: 7px;\n --temba-select-selected-line-height: 13px;\n --temba-select-selected-font-size: 12px;\n --search-input-height: 7px !important;\n }\n\n .info-text {\n opacity: 1;\n transition: padding-top var(--transition-speed) ease-in-out,\n padding-bottom var(--transition-speed) ease-in-out;\n margin-bottom: 16px;\n padding: 0.5em 1em;\n border-radius: var(--curvature);\n font-size: 0.9em;\n color: rgba(0, 0, 0, 0.5);\n position: relative;\n }\n\n .info-text.focused {\n opacity: 1;\n }\n\n .info-text.hide {\n opacity: 0;\n max-height: 0;\n margin-bottom: 0px;\n pointer-events: none;\n padding: 0px;\n }\n `;\n }\n\n @property({ type: Boolean })\n multi = false;\n\n @property({ type: Boolean })\n searchOnFocus = false;\n\n @property({ type: String })\n placeholder = '';\n\n @property()\n name = '';\n\n @property()\n endpoint: string;\n\n @property({ type: String })\n nameKey = 'name';\n\n @property({ type: String })\n valueKey = 'value';\n\n @property({ attribute: false })\n currentFunction: CompletionOption;\n\n @property({ type: String })\n queryParam: string = null;\n\n @property({ type: String })\n input = '';\n\n @property({ type: Array })\n visibleOptions: any[] = [];\n\n @property({ type: Array })\n completionOptions: CompletionOption[] = [];\n\n @property({ type: Number })\n quietMillis = 0;\n\n @property({ type: Boolean })\n fetching: boolean;\n\n @property({ type: Boolean })\n searchable = false;\n\n @property({ type: String })\n expressions: string;\n\n @property({ type: Boolean })\n cache = true;\n\n @property({ type: String })\n cacheKey = '';\n\n @property({ type: Boolean })\n focused = false;\n\n @property({ type: Boolean })\n disabled = false;\n\n @property({ attribute: false })\n selectedIndex = -1;\n\n @property({ type: Number })\n cursorIndex: number;\n\n @property({ attribute: false })\n anchorElement: HTMLElement;\n\n @property({ attribute: false })\n anchorExpressions: HTMLElement;\n\n @property({ type: Object })\n anchorPosition: Position = { left: 0, top: 0 };\n\n @property({ type: Boolean })\n tags = false;\n\n @property({ type: Boolean, attribute: 'space_select' })\n spaceSelect: boolean;\n\n @property({ type: Boolean })\n jsonValue: boolean;\n\n @property({ type: Boolean })\n hideErrors: boolean;\n\n @property({ type: Boolean })\n clearable: boolean;\n\n @property({ type: String })\n flavor = 'default';\n\n @property({ type: String, attribute: 'info_text' })\n infoText = '';\n\n @property({ type: Array })\n values: any[] = [];\n\n @property({ type: Object })\n selection: any;\n\n @property({ attribute: false })\n getName: (option: any) => string = (option: any) =>\n option[this.nameKey || 'name'];\n\n @property({ attribute: false })\n isMatch: (option: any, q: string) => boolean = (option: any, q: string) => {\n const name = this.getName(option) || '';\n return name.toLowerCase().indexOf(q) > -1;\n };\n\n @property({ attribute: false })\n getValue: (option: any) => string = (option: any) =>\n option[this.valueKey || 'value'] || option.id;\n\n @property({ type: Number, attribute: 'option-width' })\n optionWidth: number;\n\n @property({ type: Boolean, attribute: 'anchor-right' })\n anchorRight: boolean;\n\n @property({ attribute: false })\n shouldExclude: (option: any) => boolean;\n\n @property({ attribute: false })\n sortFunction: (a: any, b: any) => number;\n\n @property({ attribute: false })\n renderOption: (option: any, selected: boolean) => TemplateResult;\n\n @property({ attribute: false })\n renderOptionName: (option: any, selected: boolean) => TemplateResult;\n\n @property({ attribute: false })\n renderOptionDetail: (option: any, selected: boolean) => TemplateResult = () =>\n html``;\n\n @property({ attribute: false })\n renderSelectedItem: (option: any) => TemplateResult =\n this.renderSelectedItemDefault;\n\n @property({ attribute: false })\n createArbitraryOption: (input: string, options: any[]) => any =\n this.createArbitraryOptionDefault;\n\n @property({ attribute: false })\n getOptions: (response: WebResponse) => any[] = this.getOptionsDefault;\n\n @property({ attribute: false })\n isComplete: (newestOptions: any[], response: WebResponse) => boolean =\n this.isCompleteDefault;\n\n @property({ type: Array, attribute: 'options' })\n private staticOptions: any[] = [];\n\n private lastQuery: number;\n\n // private cancelToken: CancelTokenSource;\n private complete: boolean;\n private page: number;\n private next: string = null;\n private query: string;\n\n private removingSelection: boolean;\n\n private lruCache = lru(20, 60000);\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n if (changedProperties.has('values')) {\n this.updateInputs();\n if (\n this.multi ||\n this.values.length === 1 ||\n // fire change if being cleared\n (this.values.length == 0 &&\n changedProperties.get('values') &&\n changedProperties.get('values').length > 0)\n ) {\n this.fireEvent('change');\n }\n }\n\n // if our cache key changes, clear it out\n if (changedProperties.has('cacheKey')) {\n this.lruCache.clear();\n }\n\n if (\n changedProperties.has('input') &&\n !changedProperties.has('values') &&\n !changedProperties.has('options') &&\n this.focused\n ) {\n if (this.lastQuery) {\n window.clearTimeout(this.lastQuery);\n }\n\n this.lastQuery = window.setTimeout(() => {\n if (this.expressions && this.input.indexOf('@') > -1) {\n this.fetchExpressions();\n } else {\n this.fetchOptions(this.input);\n }\n }, this.quietMillis);\n }\n\n if (this.endpoint && changedProperties.has('fetching')) {\n if (!this.fetching && !this.isPastFetchThreshold()) {\n this.fireCustomEvent(CustomEventType.FetchComplete);\n }\n }\n\n // if our cursor changed, lets make sure our scrollbox is showing it\n if (\n (changedProperties.has('cursorIndex') ||\n changedProperties.has('visibleOptions')) &&\n this.endpoint &&\n !this.fetching\n ) {\n if (this.isPastFetchThreshold()) {\n this.fetchOptions(this.query, this.page + 1);\n }\n }\n\n // if they set an inital value, look through our static options for it\n if (changedProperties.has('value') && this.value && !this.values.length) {\n if (this.staticOptions.length > 0) {\n const existing = this.staticOptions.find(option => {\n return this.getValue(option) === this.value;\n });\n\n if (existing) {\n this.setValues([existing]);\n }\n }\n }\n\n // default to the first option if we don't have a placeholder\n if (\n this.values.length === 0 &&\n !this.placeholder &&\n this.staticOptions.length > 0\n ) {\n this.setValues([this.staticOptions[0]]);\n }\n }\n\n private updateInputs(): void {\n for (let ele = null; (ele = this.hiddenInputs.pop()); ) {\n ele.remove();\n }\n\n if (this.values.length === 0) {\n this.value = null;\n } else {\n const name = this.getAttribute('name');\n\n if (name) {\n if (!this.multi && this.values.length === 1) {\n this.selection = this.values[0];\n this.value = this.serializeValue(this.values[0]);\n } else {\n if (this.inputRoot.parentElement) {\n this.values.forEach(value => {\n const ele = document.createElement('input');\n ele.setAttribute('type', 'hidden');\n ele.setAttribute('name', name);\n ele.setAttribute('value', this.serializeValue(value));\n this.hiddenInputs.push(ele);\n this.inputRoot.parentElement.appendChild(ele);\n });\n }\n }\n }\n }\n }\n\n private setSelectedOption(option: any) {\n if (this.multi) {\n this.addValue(option);\n } else {\n this.setValues([option]);\n }\n\n if (!this.multi || !this.searchable) {\n this.blur();\n this.focused = false;\n }\n\n this.visibleOptions = [];\n this.input = '';\n this.next = null;\n this.complete = true;\n this.selectedIndex = -1;\n }\n\n private isPastFetchThreshold() {\n return (\n (this.visibleOptions.length > 0 || this.next) &&\n !this.complete &&\n (this.cursorIndex || 0) > this.visibleOptions.length - LOOK_AHEAD\n );\n }\n\n public handleOptionSelection(event: CustomEvent) {\n const selected = event.detail.selected;\n // check if we should post it\n if (selected.post && this.endpoint) {\n postJSON(this.endpoint, selected).then(response => {\n if (response.status >= 200 && response.status < 300) {\n this.setSelectedOption(response.json);\n this.lruCache = lru(20, 60000);\n } else {\n // TODO: find a way to share inline errors\n this.blur();\n }\n });\n } else {\n this.setSelectedOption(selected);\n }\n }\n\n private handleExpressionSelection(evt: CustomEvent) {\n const option = evt.detail.selected as CompletionOption;\n const tabbed = evt.detail.tabbed;\n\n const ele = this.shadowRoot.querySelector('.searchbox') as HTMLInputElement;\n updateInputElementWithCompletion(this.query, ele, option);\n\n this.query = '';\n this.completionOptions = [];\n\n if (tabbed) {\n this.fetchExpressions();\n } else if (this.input.indexOf('(') === -1) {\n this.addInputAsValue();\n }\n }\n\n private getNameInternal: (option: any) => string = (option: any) => {\n return this.getName(option);\n };\n\n private getOptionsDefault(response: WebResponse): any[] {\n return response.json['results'];\n }\n\n private isCompleteDefault(\n newestOptions: any[],\n response: WebResponse\n ): boolean {\n const json = response.json;\n return !json['more'] && !json['next'];\n }\n\n public handleRemoveSelection(selectionToRemove: any): void {\n this.removeValue(selectionToRemove);\n this.visibleOptions = [];\n }\n\n private createArbitraryOptionDefault(): any {\n return null;\n }\n\n public open(): void {\n this.requestUpdate('input');\n }\n\n public isOpen(): boolean {\n return this.visibleOptions.length > 0;\n }\n\n public setOptions(options: any[]): void {\n this.staticOptions = options;\n }\n\n private setVisibleOptions(options: any[]) {\n // if we have an exclusion filter apply it\n options = options.filter(option => {\n // exclude unnamed\n if (!this.getNameInternal(option)) {\n return false;\n }\n\n if (this.shouldExclude) {\n return !this.shouldExclude(option);\n }\n return true;\n });\n\n if (this.input) {\n // if we are searching locally, filter for the query\n if (this.searchable && !this.queryParam) {\n const q = this.input.trim().toLowerCase();\n options = options.filter((option: any) => this.isMatch(option, q));\n }\n\n const arbitraryOption: any = this.createArbitraryOption(\n this.input,\n options\n );\n\n if (arbitraryOption) {\n // set our arbitrary flag so we never have more than one\n arbitraryOption.arbitrary = true;\n\n // make sure our id is not already present\n const exists = options.find(\n (option: any) =>\n this.getValue(option) === this.getValue(arbitraryOption)\n );\n\n if (!exists) {\n if (options.length > 0) {\n if (options[0].arbitrary) {\n options[0] = arbitraryOption;\n } else {\n options.unshift(arbitraryOption);\n }\n } else {\n options.unshift(arbitraryOption);\n }\n }\n }\n }\n\n // filter out any options already selected by id\n // TODO: should maybe be doing a deep equals here with option to optimize\n if (this.values.length > 0) {\n if (this.multi) {\n options = options.filter(\n option =>\n !this.values.find(\n selected => this.getValue(selected) === this.getValue(option)\n )\n );\n } else {\n // if no search, single select should set our cursor to the selected item\n if (!this.input) {\n this.cursorIndex = options.findIndex(\n option => this.getValue(option) === this.getValue(this.values[0])\n );\n } else {\n this.cursorIndex = 0;\n }\n this.requestUpdate('cursorIndex');\n }\n }\n\n // finally sort\n if (this.sortFunction) {\n options.sort(this.sortFunction);\n }\n\n this.visibleOptions = options;\n\n this.fireCustomEvent(CustomEventType.ContentChanged, {\n options: this.visibleOptions,\n });\n }\n\n public fetchExpressions() {\n const store: Store = document.querySelector('temba-store');\n if (this.expressions && store) {\n const ele = this.shadowRoot.querySelector(\n '.searchbox'\n ) as HTMLInputElement;\n\n const result = executeCompletionQuery(\n ele,\n store,\n this.expressions === 'session'\n );\n this.query = result.query;\n this.completionOptions = result.options;\n this.visibleOptions = [];\n this.anchorPosition = result.anchorPosition;\n this.fireCustomEvent(CustomEventType.FetchComplete);\n return;\n }\n }\n\n public fetchOptions(query: string, page = 0) {\n this.completionOptions = [];\n\n if (!this.fetching) {\n this.fetching = true;\n\n // make sure we cancel any previous request\n // if (this.cancelToken) {\n // this.cancelToken.cancel();\n // }\n\n const options: any = [...this.staticOptions];\n const q = (query || '').trim().toLowerCase();\n\n if (this.tags && q) {\n if (\n !options.find(\n (option: any) =>\n this.getValue(option) && this.getValue(option).toLowerCase() === q\n )\n ) {\n options.splice(0, 0, { name: query, value: query });\n }\n }\n\n if (this.endpoint) {\n let url = this.endpoint;\n\n if (query && this.queryParam) {\n if (url.indexOf('?') > -1) {\n url += '&';\n } else {\n url += '?';\n }\n\n url += this.queryParam + '=' + encodeURIComponent(query);\n }\n\n if (page) {\n if (url.indexOf('?') > -1) {\n url += '&';\n } else {\n url += '?';\n }\n url += 'page=' + page;\n }\n\n if (this.next) {\n url = this.next;\n }\n\n const cache = this.lruCache.get(url);\n if (this.cache && !this.tags && cache) {\n if (page === 0 && !this.next) {\n this.cursorIndex = 0;\n this.setVisibleOptions([...options, ...cache.options]);\n } else {\n this.setVisibleOptions([...this.visibleOptions, ...cache.options]);\n }\n\n this.complete = cache.complete;\n this.next = cache.next;\n this.fetching = false;\n return;\n }\n\n // if we are searchable, but doing it locally, fetch all the options\n if (this.searchable && !this.queryParam) {\n fetchResults(url).then((results: any) => {\n if (this.cache && !this.tags) {\n this.lruCache.set(url, {\n options: results,\n complete: true,\n next: null,\n });\n\n this.complete = true;\n this.next = null;\n this.setVisibleOptions([...options, ...results]);\n this.fetching = false;\n }\n });\n } else {\n getUrl(url)\n .then((response: WebResponse) => {\n const results = this.getOptions(response).filter(\n (option: any) => {\n return this.isMatch(option, q);\n }\n );\n\n const json = response.json;\n if (json['next']) {\n this.next = json['next'];\n }\n\n if (page === 0 && !this.next) {\n this.cursorIndex = 0;\n this.setVisibleOptions([...options, ...results]);\n this.query = query;\n this.complete = this.isComplete(this.visibleOptions, response);\n } else {\n if (results.length > 0) {\n this.setVisibleOptions([...this.visibleOptions, ...results]);\n }\n this.complete = this.isComplete(results, response);\n }\n\n if (this.cache && !this.tags) {\n this.lruCache.set(url, {\n options: results,\n complete: this.complete,\n next: this.next,\n });\n }\n\n // if (!this.next) {\n this.fetching = false;\n //}\n this.page = page;\n })\n .catch((reason: any) => {\n // cancelled\n this.fetching = false;\n console.error(reason);\n });\n }\n } else {\n this.fetching = false;\n this.setVisibleOptions(options);\n }\n }\n }\n\n private handleFocus(): void {\n if (!this.focused && this.visibleOptions.length === 0) {\n this.focused = true;\n if (this.searchOnFocus && !this.removingSelection) {\n this.requestUpdate('input');\n }\n }\n }\n\n private handleBlur() {\n this.focused = false;\n if (this.visibleOptions.length > 0) {\n this.input = '';\n this.next = null;\n this.complete = true;\n this.visibleOptions = [];\n this.cursorIndex = 0;\n }\n }\n\n private handleClick(): void {\n this.selectedIndex = -1;\n this.requestUpdate('input');\n }\n\n private addInputAsValue() {\n const ele = this.shadowRoot.querySelector('.searchbox') as HTMLInputElement;\n const expression = {\n name: ele.value,\n value: ele.value,\n expression: true,\n };\n\n if (this.multi) {\n if (\n !this.values.find(option => {\n return (\n option.expression &&\n option.value &&\n expression.value &&\n option.value.toLowerCase().trim() ==\n expression.value.toLowerCase().trim()\n );\n })\n ) {\n this.addValue(expression);\n }\n } else {\n this.setValues([expression]);\n }\n\n this.input = '';\n if (!this.multi) {\n this.blur();\n }\n }\n\n private handleKeyDown(evt: KeyboardEvent) {\n // if we are completing an expression, select it\n if (\n evt.key === 'Enter' &&\n this.expressions &&\n this.completionOptions.length === 0 &&\n this.input.indexOf('@') > -1\n ) {\n this.addInputAsValue();\n }\n\n // see if we should open our options on a key event\n if (\n evt.key === 'Enter' ||\n evt.key === 'ArrowDown' ||\n (evt.key === 'n' && evt.ctrlKey)\n ) {\n if (\n this.visibleOptions.length === 0 &&\n this.completionOptions.length === 0\n ) {\n this.requestUpdate('input');\n return;\n }\n }\n\n // focus our last item on delete\n if (this.multi && evt.key === 'Backspace' && !this.input) {\n if (this.visibleOptions.length > 0) {\n this.visibleOptions = [];\n return;\n }\n\n if (this.selectedIndex === -1) {\n this.selectedIndex = this.values.length - 1;\n this.visibleOptions = [];\n } else {\n this.popValue();\n this.selectedIndex = -1;\n }\n } else {\n this.selectedIndex = -1;\n }\n }\n\n public getStaticOptions() {\n return this.staticOptions;\n }\n\n private handleInput(evt: KeyboardEvent) {\n const ele = evt.currentTarget as HTMLInputElement;\n this.input = ele.value;\n }\n\n private handleCancel() {\n this.visibleOptions = [];\n }\n\n private handleCursorChanged(event: CustomEvent) {\n this.cursorIndex = event.detail.index;\n }\n\n private handleContainerClick(event: MouseEvent) {\n this.focused = true;\n\n if ((event.target as any).tagName !== 'INPUT') {\n const input = this.shadowRoot.querySelector('input');\n if (input) {\n input.click();\n input.focus();\n return;\n }\n\n if (this.visibleOptions.length > 0) {\n this.visibleOptions = [];\n event.preventDefault();\n event.stopPropagation();\n } else {\n this.requestUpdate('input');\n }\n }\n }\n\n public getEventHandlers(): EventHandler[] {\n return [\n { event: CustomEventType.Canceled, method: this.handleCancel },\n {\n event: CustomEventType.CursorChanged,\n method: this.handleCursorChanged,\n },\n { event: 'blur', method: this.handleBlur },\n { event: 'focus', method: this.handleFocus },\n ];\n }\n\n public firstUpdated(changedProperties: any) {\n super.firstUpdated(changedProperties);\n\n this.anchorElement = this.shadowRoot.querySelector('.select-container');\n this.anchorExpressions = this.shadowRoot.querySelector('#anchor');\n\n // wait until children are created before adding our static options\n const value = this.value;\n window.setTimeout(() => {\n for (const child of this.children) {\n if (child.tagName === 'TEMBA-OPTION') {\n const option: any = {};\n for (const attribute of child.attributes) {\n option[attribute.name] = attribute.value;\n }\n this.staticOptions.push(option);\n\n if (\n child.getAttribute('selected') !== null ||\n this.getValue(option) == this.value\n ) {\n if (this.getAttribute('multi') !== null) {\n this.addValue(option);\n } else {\n this.setValues([option]);\n }\n }\n }\n }\n\n if (this.values.length === 0 && (!this.placeholder || value)) {\n if (this.staticOptions.length == 0 && this.endpoint) {\n // see if we need to auto select the first item but need to fetch it\n fetchResults(this.endpoint).then((results: any) => {\n if (results && results.length > 0) {\n if (value) {\n // if we started with a value, see if we can find it in the results\n const existing = results.find(option => {\n return this.getValue(option) === value;\n });\n\n if (existing) {\n this.setValues([existing]);\n return;\n }\n }\n this.setValues([results[0]]);\n }\n });\n } else {\n if (this.getAttribute('multi') !== null) {\n this.addValue(this.staticOptions[0]);\n } else {\n this.setValues([this.staticOptions[0]]);\n }\n }\n }\n\n if (this.searchable && this.staticOptions.length === 0) {\n this.quietMillis = 200;\n }\n }, 100);\n }\n\n private handleArrowClick(event: MouseEvent): void {\n if (this.visibleOptions.length > 0) {\n this.visibleOptions = [];\n event.preventDefault();\n event.stopPropagation();\n }\n }\n\n private renderSelectedItemDefault(option: any): TemplateResult {\n if (!option) {\n return null;\n }\n\n return html`\n
    \n ${option.icon\n ? html``\n : null}${this.getName(option)}\n
    \n `;\n }\n\n public serializeValue(value: any): string {\n // static options just use their value\n if (!this.jsonValue && (this.staticOptions.length > 0 || this.tags)) {\n return value.value;\n }\n\n return super.serializeValue(value);\n }\n\n public setSelection(value: string): void {\n for (const option of this.staticOptions) {\n if (this.getValue(option.value) === value) {\n if (this.values.length === 0 || this.values[0].value !== '' + value) {\n this.setValues([option]);\n }\n return;\n }\n }\n }\n\n private handleClear(evt: MouseEvent): void {\n evt.preventDefault();\n evt.stopPropagation();\n this.setValues([]);\n }\n\n public setValues(values: any[]) {\n this.values = values;\n this.requestUpdate('values');\n }\n\n public addValue(value: any) {\n this.values.push(value);\n this.requestUpdate('values');\n }\n\n public removeValue(valueToRemove: any) {\n const idx = this.values.indexOf(valueToRemove);\n if (idx > -1) {\n this.values.splice(idx, 1);\n }\n this.requestUpdate('values');\n }\n\n public popValue() {\n this.values.pop();\n this.requestUpdate('values');\n }\n\n public clear() {\n this.values = [];\n this.requestUpdate('values');\n }\n\n public render(): TemplateResult {\n const placeholder = this.values.length === 0 ? this.placeholder : '';\n const placeholderDiv = html`\n
    ${placeholder}
    \n `;\n\n const clear =\n this.clearable && this.values.length > 0 && !this.multi\n ? html``\n : null;\n\n const classes = getClasses({\n multi: this.multi,\n single: !this.multi,\n searchable: this.searchable,\n empty: this.values.length === 0,\n options: this.visibleOptions.length > 0,\n focused: this.focused,\n 'search-input': this.input.length > 0,\n 'no-search-input': this.input.length === 0,\n [this.flavor]: this.flavor !== null,\n disabled: this.disabled,\n });\n\n const anchorStyles = this.anchorPosition\n ? {\n top: '0px',\n left: `${this.anchorPosition.left - 10}px`,\n }\n : {};\n\n const input = this.searchable\n ? html`\n
    \n \n
    \n
    \n `\n : placeholderDiv;\n\n return html`\n \n \n \n
    \n \n
    \n
    \n ${!this.multi ? input : null}\n ${this.values.map(\n (selected: any, index: number) => html`\n \n ${this.multi\n ? html`\n {\n this.removingSelection = true;\n }}\n @mouseup=${() => {\n this.removingSelection = false;\n }}\n @click=${(evt: MouseEvent) => {\n evt.preventDefault();\n evt.stopPropagation();\n this.handleRemoveSelection(selected);\n }}\n >\n \n
    \n `\n : null}\n ${this.renderSelectedItem(selected)}\n
    \n `\n )}\n ${this.multi ? input : null}\n
    \n\n \n\n ${clear}\n\n \n ${\n !this.tags\n ? html`\n 0\n ? 'open'\n : ''}\"\n >\n `\n : null\n }\n \n \n \n
    ${this.infoText}
    \n\n \n 0}\n >\n\n {}}\n .anchorTo=${this.anchorExpressions}\n .options=${this.completionOptions}\n .renderOption=${renderCompletionOption}\n ?visible=${this.completionOptions.length > 0}\n >\n ${\n this.currentFunction\n ? html`\n
    \n ${renderCompletionOption(this.currentFunction, true)}\n
    \n `\n : null\n }\n ${\n this.completionOptions.length > 0\n ? html`
    \n ${msg('Tab to complete, enter to select')}\n
    `\n : null\n }\n \n \n `;\n }\n}\n","import { TemplateResult, css, html } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { ifDefined } from 'lit-html/directives/if-defined.js';\nimport { TextInput } from '../textinput/TextInput';\nimport {\n renderCompletionOption,\n updateInputElementWithCompletion,\n executeCompletionQuery,\n} from './helpers';\n\nimport { FormElement } from '../FormElement';\nimport { CompletionOption, Position } from '../interfaces';\nimport { Store } from '../store/Store';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { msg } from '@lit/localize';\n\n/**\n * Completion is a text input that handles excellent completion options in a popup\n */\nexport class Completion extends FormElement {\n static get styles() {\n return css`\n :host {\n display: block;\n }\n\n temba-options {\n --widget-box-shadow-focused: 0 0 4px rgba(0, 0, 0, 0.15);\n --color-focus: #e6e6e6;\n }\n\n .comp-container {\n position: relative;\n height: 100%;\n }\n\n #anchor {\n /* background: rgba(132, 40, 158, .1); */\n position: absolute;\n visibility: hidden;\n width: 250px;\n height: 20px;\n }\n\n .fn-marker {\n font-weight: bold;\n font-size: 42px;\n }\n\n .option-slot {\n background: #fff;\n }\n\n .current-fn {\n padding: 10px;\n margin: 5px;\n background: var(--color-primary-light);\n color: rgba(0, 0, 0, 0.5);\n border-radius: var(--curvature-widget);\n font-size: 90%;\n }\n\n .footer {\n padding: 5px 10px;\n background: var(--color-primary-light);\n color: rgba(0, 0, 0, 0.5);\n font-size: 80%;\n border-bottom-left-radius: var(--curvature-widget);\n border-bottom-right-radius: var(--curvature-widget);\n }\n\n code {\n background: rgba(0, 0, 0, 0.1);\n padding: 1px 5px;\n border-radius: var(--curvature);\n }\n `;\n }\n\n @property({ type: Number })\n maxLength: number;\n\n @property({ type: Boolean })\n session: boolean;\n\n @property({ type: Boolean })\n submitOnEnter = false;\n\n @property({ type: Object })\n anchorPosition: Position = { left: 0, top: 0 };\n\n @property({ attribute: false })\n currentFunction: CompletionOption;\n\n @property({ type: String })\n placeholder = '';\n\n @property({ attribute: false })\n textInputElement: TextInput;\n\n @property({ attribute: false })\n anchorElement: HTMLDivElement;\n\n @property({ type: Array })\n options: any[] = [];\n\n @property({ type: String })\n name = '';\n\n @property({ type: String })\n value = '';\n\n @property({ type: Boolean })\n textarea: boolean;\n\n @property({ type: Boolean })\n gsm: boolean;\n\n @property({ type: String })\n counter: string;\n\n @property({ type: Boolean })\n autogrow = false;\n\n private hiddenElement: HTMLInputElement;\n private query: string;\n\n public firstUpdated() {\n this.textInputElement = this.shadowRoot.querySelector(\n 'temba-textinput'\n ) as TextInput;\n this.anchorElement = this.shadowRoot.querySelector('#anchor');\n\n // create our hidden container so it gets included in our host element's form\n this.hiddenElement = document.createElement('input');\n this.hiddenElement.setAttribute('type', 'hidden');\n this.hiddenElement.setAttribute('name', this.getAttribute('name'));\n this.hiddenElement.setAttribute('value', this.getAttribute('value') || '');\n this.appendChild(this.hiddenElement);\n }\n\n private handleKeyUp(evt: KeyboardEvent) {\n // if we have options, ignore keys that are meant for them\n if (this.options && this.options.length > 0) {\n if (evt.key === 'ArrowUp' || evt.key === 'ArrowDown') {\n return;\n }\n\n if (evt.ctrlKey) {\n if (evt.key === 'n' || evt.key === 'p') {\n return;\n }\n }\n\n if (\n evt.key === 'Enter' ||\n evt.key === 'Escape' ||\n evt.key === 'Tab' ||\n evt.key.startsWith('Control')\n ) {\n evt.stopPropagation();\n evt.preventDefault();\n return;\n }\n\n this.executeQuery(evt.currentTarget as TextInput);\n }\n }\n\n public hasVisibleOptions() {\n return this.options.length > 0;\n }\n\n private executeQuery(ele: TextInput) {\n const store: Store = document.querySelector('temba-store');\n if (!ele.inputElement) {\n return;\n }\n const result = executeCompletionQuery(\n ele.inputElement,\n store,\n this.session\n );\n\n this.query = result.query;\n this.options = result.options;\n this.anchorPosition = result.anchorPosition;\n }\n\n private handleClick(evt: MouseEvent) {\n this.executeQuery(evt.currentTarget as TextInput);\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n // if our cursor changed, lets make sure our scrollbox is showing it\n if (changedProperties.has('value')) {\n this.hiddenElement.setAttribute('value', this.value);\n }\n }\n\n private handleInput(evt: KeyboardEvent) {\n const ele = evt.currentTarget as TextInput;\n this.executeQuery(ele);\n this.value = ele.inputElement.value;\n this.fireEvent('change');\n }\n\n private handleOptionCanceled() {\n // delay in case we are actively selecting\n window.setTimeout(() => {\n this.options = [];\n this.query = '';\n }, 100);\n }\n\n private handleOptionSelection(evt: CustomEvent) {\n const option = evt.detail.selected as CompletionOption;\n const tabbed = evt.detail.tabbed;\n\n updateInputElementWithCompletion(\n this.query,\n this.textInputElement.inputElement,\n option\n );\n this.query = '';\n this.options = [];\n\n if (tabbed) {\n this.executeQuery(this.textInputElement);\n }\n }\n\n public click() {\n super.click();\n const input = this.shadowRoot.querySelector('temba-textinput') as TextInput;\n if (input) {\n input.click();\n }\n }\n\n public focus() {\n super.focus();\n const input = this.shadowRoot.querySelector('temba-textinput') as TextInput;\n if (input) {\n input.focus();\n }\n }\n\n public render(): TemplateResult {\n const anchorStyles = this.anchorPosition\n ? {\n top: `${this.anchorPosition.top}px`,\n left: `${this.anchorPosition.left}px`,\n }\n : {};\n\n const visible = this.options && this.options.length > 0;\n\n return html`\n \n
    \n
    \n \n \n \n ${this.currentFunction\n ? html`\n
    \n ${renderCompletionOption(this.currentFunction, true)}\n
    \n `\n : null}\n
    \n ${msg('Tab to complete, enter to select')}\n
    \n \n
    \n \n `;\n }\n}\n","import { RapidElement } from './RapidElement';\nimport { throttle } from './utils';\n\nexport class ResizeElement extends RapidElement {\n public handleResize() {\n this.requestUpdate();\n }\n\n public getEventHandlers() {\n return [\n {\n event: 'resize',\n method: throttle(this.handleResize, 50),\n isWindow: true,\n },\n ];\n }\n}\n","import { property } from 'lit/decorators.js';\nimport { TemplateResult, html, css, PropertyValueMap } from 'lit';\nimport { Button } from '../button/Button';\nimport { CustomEventType } from '../interfaces';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { getClasses } from '../utils';\nimport { ResizeElement } from '../ResizeElement';\n\nexport enum ButtonType {\n PRIMARY = 'primary',\n SECONDARY = 'secondary',\n DESTRUCTIVE = 'destructive',\n}\nexport class DialogButton {\n name?: string;\n id?: string;\n details?: any;\n type?: string;\n closes?: boolean;\n}\n\nexport class Dialog extends ResizeElement {\n static get widths(): { [size: string]: string } {\n return {\n small: '400px',\n medium: '600px',\n large: '655px',\n };\n }\n\n static get styles() {\n return css`\n :host {\n position: absolute;\n z-index: 10000;\n font-family: var(--font-family);\n background: white;\n }\n\n .flex-grow {\n flex-grow: 1;\n }\n\n .flex {\n display: flex;\n flex-direction: column;\n width: 100%;\n position: relative;\n left: 0px;\n top: 0px;\n align-items: center;\n height: 100vh;\n }\n\n .mobile .flex {\n height: 100%;\n position: fixed;\n }\n\n .mobile .grow-top {\n flex-grow: 0;\n }\n\n .mobile .grow-bottom {\n flex-grow: 0;\n }\n\n .grow-top {\n flex-grow: 1;\n }\n\n .grow-bottom {\n flex-grow: 3;\n }\n\n .bottom-padding {\n padding: 3rem;\n }\n\n .dialog-mask {\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.5);\n opacity: 0;\n position: fixed;\n top: 0px;\n left: 0px;\n transition: opacity linear calc(var(--transition-speed) / 2ms);\n pointer-events: none;\n }\n\n .mobile.dialog-mask .dialog-container {\n border-radius: 0px;\n }\n\n .dialog-mask .dialog-container {\n position: relative;\n transition: transform var(--transition-speed) var(--bounce),\n opacity ease-in-out calc(var(--transition-speed) - 50ms);\n border-radius: var(--curvature);\n box-shadow: 0px 0px 2px 4px rgba(0, 0, 0, 0.06);\n overflow: hidden;\n transform: scale(0.9) translatey(2em);\n background: white;\n margin: auto;\n display: flex;\n flex-direction: column;\n }\n\n .dialog-body {\n background: #fff;\n overflow-y: auto;\n flex-grow: 1;\n }\n\n .dialog-mask.dialog-open {\n opacity: 1;\n pointer-events: auto;\n }\n\n .dialog-mask.dialog-open .dialog-container {\n top: inherit;\n }\n\n .dialog-mask.dialog-animation-end .dialog-container {\n transform: scale(1) !important;\n }\n\n .dialog-mask.dialog-ready .dialog-container {\n transform: none;\n }\n\n .dialog-mask.dialog-loading .dialog-container {\n margin-top: -10000px;\n }\n\n .header-text {\n display: flex;\n flex-direction: row;\n align-items: center;\n font-size: 20px;\n padding: 12px 20px;\n color: var(--header-text);\n background: var(--header-bg);\n }\n\n .header-text .title {\n flex-grow: 1;\n }\n\n .header-text .status {\n font-size: 0.6em;\n font-weight: bold;\n }\n\n .dialog-footer {\n background: var(--color-primary-light);\n padding: 10px;\n display: flex;\n flex-flow: row;\n align-items: center;\n }\n\n temba-button {\n margin-left: 10px;\n }\n\n .dialog-body temba-loading {\n position: absolute;\n right: 12px;\n margin-top: -30px;\n padding-bottom: 9px;\n display: none;\n }\n\n #page-loader {\n text-align: center;\n display: block;\n position: relative;\n opacity: 0;\n margin: auto;\n margin-top: 30px;\n width: 154px;\n transition: opacity calc(var(--transition-speed) * 5ms) ease-in\n calc(var(--transition-speed * 2));\n visibility: hidden;\n }\n\n .dialog-mask.dialog-loading #page-loader {\n opacity: 1;\n visibility: visible;\n }\n\n #submit-loader {\n flex-grow: 1;\n text-align: right;\n }\n `;\n }\n\n @property({ type: Boolean })\n open: boolean;\n\n @property()\n header: string;\n\n @property()\n body: string;\n\n @property({ type: Boolean })\n submitting: boolean;\n\n @property({ type: Boolean })\n destructive: boolean;\n\n @property({ type: Boolean })\n disabled: boolean;\n\n @property({ type: Boolean })\n loading: boolean;\n\n @property({ type: Boolean })\n hideOnClick: boolean;\n\n @property({ type: Boolean })\n noFocus: boolean;\n\n @property()\n size = 'medium';\n\n @property({ type: String })\n primaryButtonName = 'Ok';\n\n @property({ type: String })\n cancelButtonName = 'Cancel';\n\n @property({ type: String })\n width = null;\n\n @property()\n submittingName = 'Saving';\n\n @property()\n animationEnd: boolean;\n\n @property()\n ready: boolean;\n\n @property({ type: Array })\n buttons: DialogButton[] = [];\n\n @property({ attribute: false })\n onButtonClicked: (button: Button) => void;\n\n scrollOffset: any = 0;\n\n public constructor() {\n super();\n }\n\n protected firstUpdated(\n changes: PropertyValueMap | Map\n ): void {\n if (changes.has('cancelButtonName') && this.cancelButtonName) {\n this.buttons.push({\n name: this.cancelButtonName,\n type: ButtonType.SECONDARY,\n closes: true,\n });\n }\n\n if (changes.has('primaryButtonName') && this.primaryButtonName) {\n this.buttons.push({\n name: this.primaryButtonName,\n type: ButtonType.PRIMARY,\n });\n }\n }\n\n public updated(changedProperties: Map) {\n if (changedProperties.has('open')) {\n const body = document.querySelector('body');\n\n if (this.open) {\n this.animationEnd = true;\n window.setTimeout(() => {\n this.ready = true;\n this.animationEnd = false;\n }, 400);\n\n this.scrollOffset = -document.documentElement.scrollTop;\n body.style.position = 'fixed';\n body.style.overflowY = 'scroll';\n body.style.top = this.scrollOffset + 'px';\n body.style.width = '100%';\n body.style.overflowY = 'hidden';\n } else {\n body.style.position = '';\n body.style.overflowY = '';\n body.style.width = '';\n body.style.marginRight = '';\n body.style.paddingRight = '0px';\n window.scrollTo(0, parseInt(this.scrollOffset || '0') * -1);\n }\n\n // make sure our buttons aren't in progress on show\n if (this.open && !changedProperties.get('open')) {\n this.shadowRoot\n .querySelectorAll('temba-button')\n .forEach((button: Button) => {\n if (button) button.submitting = false;\n });\n\n if (!this.noFocus) {\n this.focusFirstInput();\n }\n } else {\n window.setTimeout(() => {\n this.ready = false;\n }, 400);\n }\n }\n }\n\n public focusFirstInput(): void {\n window.setTimeout(() => {\n let input = this.querySelector(\n 'temba-textinput, temba-completion, input[type=\"text\"], textarea'\n ) as any;\n if (input) {\n input = input.textInputElement || input.inputElement || input;\n if (!input.readOnly) {\n input.focus();\n input.click();\n }\n }\n }, 100);\n }\n\n public handleClick(evt: MouseEvent) {\n const button = evt.currentTarget as Button;\n if (!button.disabled) {\n let detail: DialogButton = {};\n if (button.index >= 0 && button.index < this.buttons.length) {\n detail = this.buttons[button.index];\n }\n\n this.fireCustomEvent(CustomEventType.ButtonClicked, { button, detail });\n if (button.name === this.cancelButtonName || (detail && detail.closes)) {\n this.open = false;\n }\n }\n }\n\n private getDocumentHeight(): number {\n const body = document.body;\n const html = document.documentElement;\n return Math.max(\n body.scrollHeight,\n body.offsetHeight,\n html.clientHeight,\n html.scrollHeight,\n html.offsetHeight\n );\n }\n\n private clickCancel() {\n const cancel = this.getCancelButton();\n if (cancel) {\n cancel.click();\n }\n }\n\n public getCancelButton(): Button {\n return this.shadowRoot.querySelector(\n `temba-button[name='${this.cancelButtonName}']`\n );\n }\n\n public getPrimaryButton(): Button {\n return this.shadowRoot.querySelector(`temba-button[primary]`);\n }\n\n private handleKeyUp(event: KeyboardEvent) {\n if (event.key === 'Escape') {\n this.clickCancel();\n }\n }\n\n private handleClickMask(event: MouseEvent) {\n if (this.hideOnClick) {\n const id = (event.target as HTMLElement).id;\n if (id === 'dialog-mask' || id === 'dialog-bg') {\n this.fireCustomEvent(CustomEventType.DialogHidden);\n this.clickCancel();\n }\n }\n }\n\n public show(): void {\n this.open = true;\n }\n\n public hide(): void {\n this.open = false;\n }\n\n public render(): TemplateResult {\n const dialogStyle = {\n width: this.width,\n minWidth: '250px',\n maxWidth: '600px',\n };\n if (!this.width) {\n dialogStyle['width'] = Dialog.widths[this.size];\n }\n\n if (this.isMobile()) {\n dialogStyle['width'] = '100%';\n dialogStyle['height'] = '100%';\n delete dialogStyle['maxWidth'];\n }\n\n const header = this.header\n ? html`\n
    \n
    \n
    ${this.header}
    \n
    \n
    \n `\n : null;\n\n return html`\n \n
    \n \n
    \n\n
    \n
    \n \n ${header}\n
    \n ${this.body ? this.body : html``}\n \n
    \n\n
    \n
    \n \n
    \n ${this.buttons.map(\n (button: DialogButton, index) => html`\n \n `\n )}\n
    \n
    \n
    \n \n \n \n `;\n }\n}\n","import { TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { unsafeHTML } from 'lit-html/directives/unsafe-html.js';\n\nimport { RapidElement } from '../RapidElement';\nimport { getUrl, serialize, postUrl, WebResponse, getClasses } from '../utils';\nimport { CustomEventType } from '../interfaces';\nimport { ButtonType, Dialog, DialogButton } from './Dialog';\n\nexport class Modax extends RapidElement {\n static get styles() {\n return css`\n fieldset {\n border: none;\n margin: 0;\n padding: 0;\n }\n\n .control-group {\n margin-bottom: var(--control-margin-bottom);\n }\n\n .form-actions {\n display: none;\n }\n\n button[type='submit'],\n input[type='submit'] {\n display: none;\n }\n\n .modax-body {\n padding: 20px;\n display: block;\n position: relative;\n background: var(--body-bg);\n }\n\n .modax-body.submitting:before {\n display: inline-block;\n content: '';\n height: 100%;\n width: 100%;\n margin-left: -20px;\n margin-top: -20px;\n background: rgba(200, 200, 200, 0.1);\n position: absolute;\n z-index: 10000;\n }\n\n temba-loading {\n margin: 0 auto;\n display: block;\n width: 150px;\n }\n\n ul.errorlist {\n margin-top: 0px;\n list-style-type: none;\n padding-left: 0;\n padding-bottom: 7px;\n }\n\n ul.errorlist li {\n color: var(--color-error);\n background: rgba(255, 181, 181, 0.17);\n box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1),\n 0 1px 2px 0 rgba(0, 0, 0, 0.06);\n color: tomato;\n padding: 10px;\n margin-bottom: 10px;\n border-radius: 6px;\n }\n\n .step-ball {\n background: rgba(var(--primary-rgb), 0.2);\n width: 1.2em;\n height: 1.2em;\n border-radius: 100%;\n margin-right: 0.5em;\n border: 0.15em solid transparent;\n }\n\n .step-ball.complete {\n background: rgba(var(--primary-rgb), 0.7);\n cursor: pointer;\n }\n .step-ball.complete:hover {\n background: rgba(var(--primary-rgb), 0.8);\n }\n\n .step-ball.active {\n border: 0.15em solid var(--color-primary-dark);\n }\n\n .wizard-steps {\n display: flex;\n flex-direction: row;\n margin-left: 0.6em;\n }\n `;\n }\n\n @property({ type: String })\n header = '';\n\n @property({ type: String })\n endpoint: string;\n\n @property({ type: Boolean, reflect: true })\n open = false;\n\n @property({ type: Boolean })\n fetching = false;\n\n @property({ type: Boolean })\n submitting: boolean;\n\n @property({ type: String })\n primaryName: string;\n\n @property({ type: String })\n cancelName: string;\n\n @property({ type: String })\n onLoaded: string;\n\n @property({ type: Boolean })\n noSubmit: boolean;\n\n @property({ type: Object })\n headers: any = {};\n\n @property({ type: String })\n body: any = this.getLoading();\n\n @property({ type: Boolean })\n disabled = false;\n\n @property({ type: Array })\n buttons: DialogButton[] = [];\n\n @property({ type: Number })\n wizardStep = 0;\n\n @property({ type: Number })\n wizardStepCount = 0;\n\n @property({ type: Boolean })\n suspendSubmit = false;\n // private cancelToken: CancelTokenSource;\n\n private handleSlotClicked(): void {\n this.open = true;\n }\n\n public updated(changes: Map) {\n super.updated(changes);\n\n if (changes.has('open')) {\n if (this.open) {\n this.fetchForm();\n } else {\n // open can get reflected into undefined, make sure we've been open before\n if (changes.get('open') !== undefined) {\n // hide our body after our hiding animation is done\n if (this.open) {\n window.setTimeout(() => {\n this.body = this.getLoading();\n this.submitting = false;\n }, 500);\n } else {\n // clear the modal body out when closed, note that js functions declared on the\n // window will hang around\n this.setBody('');\n }\n }\n }\n }\n\n if (changes.has('body') && this.open && this.body && !this.fetching) {\n const dialog = this.shadowRoot.querySelector('temba-dialog') as Dialog;\n dialog.focusFirstInput();\n }\n }\n\n private getLoading() {\n return html``;\n }\n\n public updatePrimaryButton(): void {\n const wizard = this.shadowRoot.querySelector(\n '#wizard-form'\n ) as HTMLDivElement;\n if (wizard) {\n this.wizardStep = parseInt(wizard.dataset.step);\n this.wizardStepCount = parseInt(wizard.dataset.steps);\n }\n\n if (!this.noSubmit) {\n this.updateComplete.then(() => {\n const submitButton = this.shadowRoot.querySelector(\n \"input[type='submit'],button[type='submit']\"\n ) as any;\n\n if (submitButton) {\n this.buttons = [\n { type: ButtonType.SECONDARY, name: 'Cancel', closes: true },\n { type: ButtonType.PRIMARY, name: submitButton.value },\n ];\n } else {\n this.buttons = [\n { type: ButtonType.SECONDARY, name: 'Ok', closes: true },\n ];\n }\n this.submitting = false;\n });\n }\n }\n\n private setBody(body: string): boolean {\n // remove any existing on our previous body\n const scriptBlock = this.shadowRoot.querySelector('.scripts') as any;\n for (const child of scriptBlock.children) {\n child.remove();\n }\n\n // parse out any scripts in the body\n const div = this.ownerDocument.createElement('div');\n div.innerHTML = body;\n const scripts = div.getElementsByTagName('script');\n const toAdd: any = [];\n // now add them in\n for (let i = scripts.length - 1; i >= 0; i--) {\n // for (let i = 0; i < scripts.length; i++) {\n const script = this.ownerDocument.createElement('script');\n const code = scripts[i].innerText;\n\n if (scripts[i].src && scripts[i].src.indexOf('web-dev-server') === -1) {\n script.src = scripts[i].src;\n script.type = 'text/javascript';\n script.async = true;\n\n // TODO: track and fire event once all scripts are loaded\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n script.onload = function () {};\n toAdd.push(script);\n } else if (code) {\n script.appendChild(this.ownerDocument.createTextNode(code));\n toAdd.push(script);\n // remove it from our current body text\n }\n scripts[i].remove();\n }\n\n const scriptOnly = !!div.querySelector('.success-script');\n\n if (!scriptOnly) {\n this.body = unsafeHTML(div.innerHTML);\n }\n\n this.updateComplete.then(() => {\n for (const script of toAdd) {\n scriptBlock.appendChild(script);\n }\n });\n return !scriptOnly;\n }\n\n public getHeaders(): any {\n const headers = this.headers;\n headers['X-PJAX'] = 1;\n return headers;\n }\n\n private fetchForm() {\n // const CancelToken = axios.CancelToken;\n // this.cancelToken = CancelToken.source();\n this.fetching = true;\n this.body = this.getLoading();\n getUrl(this.endpoint, null, this.getHeaders()).then(\n (response: WebResponse) => {\n // if it's a full page, breakout of the modal\n if (response.body.indexOf('') == 0) {\n document.location = response.url;\n } else {\n this.setBody(response.body);\n this.fetching = false;\n this.updateComplete.then(() => {\n this.updatePrimaryButton();\n this.fireCustomEvent(CustomEventType.Loaded, {\n body: this.getBody(),\n });\n });\n }\n }\n );\n }\n\n public submit(extra = {}): void {\n this.submitting = true;\n const form = this.shadowRoot.querySelector('form');\n\n let postData = form ? serialize(form) : '';\n if (extra) {\n Object.keys(extra).forEach(key => {\n postData +=\n (postData.length > 1 ? '&' : '') +\n encodeURIComponent(key) +\n '=' +\n encodeURIComponent(extra[key]);\n });\n }\n\n postUrl(\n this.endpoint,\n postData,\n this.getHeaders(),\n 'application/x-www-form-urlencoded'\n )\n .then((response: WebResponse) => {\n window.setTimeout(() => {\n let redirect = response.headers.get('temba-success');\n if (\n !redirect &&\n response.url &&\n response.url.indexOf(this.endpoint) === -1\n ) {\n redirect = response.url;\n }\n\n if (redirect) {\n if (redirect === 'hide') {\n this.updateComplete.then(() => {\n this.open = false;\n this.fireCustomEvent(CustomEventType.Submitted);\n });\n } else {\n this.fireCustomEvent(CustomEventType.Redirected, {\n url: redirect,\n });\n this.open = false;\n }\n } else {\n // if we set the body, update our submit button\n if (this.setBody(response.body)) {\n this.updateComplete.then(() => {\n this.updatePrimaryButton();\n });\n }\n }\n }, 1000);\n })\n .catch(error => {\n console.error(error);\n });\n }\n\n private handleDialogClick(evt: CustomEvent) {\n const button = evt.detail.button;\n const detail = evt.detail.detail;\n if (!button.disabled && !button.submitting) {\n if (button.primary || button.destructive) {\n if (!this.suspendSubmit) {\n this.submit();\n }\n }\n }\n\n if (detail.closes) {\n this.open = false;\n this.fetching = false;\n this.cancelName = undefined;\n }\n }\n\n private handleDialogHidden() {\n // this.cancelToken.cancel();\n this.open = false;\n this.fetching = false;\n }\n\n private isDestructive(): boolean {\n return this.endpoint && this.endpoint.indexOf('delete') > -1;\n }\n\n private handleGotoStep(evt: MouseEvent) {\n const step = (evt.target as HTMLDivElement).dataset.gotoStep;\n if (step) {\n this.submit({ wizard_goto_step: step });\n }\n }\n\n public getBody() {\n return this.shadowRoot.querySelector('.modax-body');\n }\n\n public render(): TemplateResult {\n const wizardStepBalls = [];\n\n const wizard = this.shadowRoot.querySelector(\n '#wizard-form'\n ) as HTMLDivElement;\n if (wizard) {\n const completed = (wizard.getAttribute('data-completed') || '')\n .split(',')\n .filter(step => step.length > 0);\n\n for (let i = 0; i < this.wizardStepCount; i++) {\n wizardStepBalls.push(\n html``\n );\n }\n }\n\n return html`\n \n \n ${this.body}\n \n
    \n
    \n
    ${wizardStepBalls}
    \n
    \n \n
    \n \n
    \n `;\n }\n}\n","import { LitElement, TemplateResult, html, css } from 'lit';\nimport { getClasses } from '../utils';\n\nimport { property } from 'lit/decorators.js';\n\nexport class Button extends LitElement {\n static get styles() {\n return css`\n :host {\n display: inline-block;\n font-family: var(--font-family);\n font-weight: 400;\n }\n\n .small {\n font-size: 0.8em;\n --button-y: 0px;\n --button-x: 0.5em;\n }\n\n .v-2.button-container {\n background: var(--button-bg);\n background-image: var(--button-bg-img);\n color: var(--button-text);\n box-shadow: var(--button-shadow);\n transition: all calc(var(--transition-speed) / 2) ease-in;\n }\n\n .button-container {\n color: #fff;\n cursor: pointer;\n display: block;\n border-radius: var(--curvature);\n outline: none;\n transition: background ease-in var(--transition-speed);\n user-select: none;\n -webkit-user-select: none;\n text-align: center;\n }\n\n .button-name {\n white-space: nowrap;\n }\n\n .secondary-button:hover .button-mask {\n border: 1px solid var(--color-button-secondary);\n }\n\n .button-mask:hover {\n background: rgba(0, 0, 0, 0.05);\n }\n\n .button-container:focus {\n outline: none;\n margin: 0;\n }\n\n .button-container:focus {\n box-shadow: var(--widget-box-shadow-focused);\n }\n\n .button-container.secondary-button:focus .button-mask {\n background: transparent;\n }\n\n .button-mask {\n padding: var(--button-y) var(--button-x);\n border-radius: var(--curvature);\n border: 1px solid transparent;\n transition: var(--transition-speed);\n background: var(--button-mask);\n }\n\n .button-container.disabled-button {\n background: rgba(0, 0, 0, 0.05);\n color: rgba(255, 255, 255, 0.45);\n cursor: default;\n }\n\n .button-container.disabled-button .button-mask {\n box-shadow: 0 0 0px 1px var(--color-button-disabled);\n }\n\n .button-container.disabled-button:hover .button-mask {\n box-shadow: 0 0 0px 1px var(--color-button-disabled);\n background: rgba(0, 0, 0, 0.05);\n }\n\n .button-container.active-button .button-mask {\n }\n\n .secondary-button.active-button {\n background: transparent;\n color: var(--color-text);\n }\n\n .secondary-button.active-button .button-mask {\n border: none;\n }\n\n .button-container.secondary-button.active-button:focus .button-mask {\n background: transparent;\n box-shadow: none;\n }\n\n .primary-button {\n background: var(--color-button-primary);\n color: var(--color-button-primary-text);\n }\n\n .light-button {\n background: var(--color-button-light);\n color: var(--color-button-light-text);\n }\n\n .attention-button {\n background: var(--color-button-attention);\n color: var(--color-button-primary-text);\n }\n\n .secondary-button {\n background: transparent;\n color: var(--color-text);\n }\n\n .destructive-button {\n background: var(--color-button-destructive);\n color: var(--color-button-destructive-text);\n }\n\n .button-mask.disabled-button {\n background: rgba(0, 0, 0, 0.1);\n }\n\n .secondary-button .button-mask:hover {\n background: transparent;\n }\n\n .submit-animation {\n padding: 1px 4px;\n }\n\n .submit-animation temba-loading {\n margin-bottom: -3px;\n line-height: normal;\n }\n `;\n }\n\n @property({ type: Boolean })\n primary: boolean;\n\n @property({ type: Boolean })\n secondary: boolean;\n\n @property({ type: Boolean })\n attention: boolean;\n\n @property({ type: Number })\n v = 1;\n\n @property({ type: Boolean })\n destructive: boolean;\n\n @property({ type: Boolean })\n light: boolean;\n\n @property()\n name: string;\n\n @property({ type: Boolean })\n disabled: boolean;\n\n @property({ type: Boolean })\n submitting: boolean;\n\n @property({ type: Boolean })\n active: boolean;\n\n @property({ type: Boolean })\n small: boolean;\n\n @property({ type: String })\n href: string;\n\n @property({ type: Number })\n index?: number;\n\n private handleClick(evt: MouseEvent) {\n if (this.disabled) {\n evt.preventDefault();\n evt.stopPropagation();\n }\n\n if (this.href && !this.disabled) {\n this.ownerDocument.location.href = this.href;\n evt.preventDefault();\n evt.stopPropagation();\n }\n }\n\n private handleKeyUp(event: KeyboardEvent): void {\n this.active = false;\n if (event.key === 'Enter') {\n this.click();\n }\n }\n\n private handleMouseDown(): void {\n if (!this.disabled && !this.submitting) {\n this.active = true;\n this.classList.add('active');\n }\n }\n\n private handleMouseUp(): void {\n this.active = false;\n this.classList.remove('active');\n }\n\n public render(): TemplateResult {\n const buttonName = this.submitting\n ? html`
    \n \n
    `\n : this.name;\n\n return html`\n \n
    \n
    ${buttonName}
    \n
    \n \n `;\n }\n}\n","import { TemplateResult, html, css, LitElement } from 'lit';\nimport { property } from 'lit/decorators.js';\n\n/**\n * A small wrapper to display labels and help text in a smartmin style.\n * This exists so we can display things consistently before restyling.\n */\nexport class FormField extends LitElement {\n static get styles() {\n return css`\n :host {\n font-family: var(--font-family);\n }\n\n label {\n margin-bottom: 5px;\n margin-left: 4px;\n display: block;\n font-weight: 400;\n font-size: var(--label-size);\n letter-spacing: 0.05em;\n line-height: normal;\n color: #777;\n }\n\n .help-text {\n font-size: var(--help-text-size);\n line-height: normal;\n color: var(--color-text-help);\n margin-left: var(--help-text-margin-left);\n margin-top: -16px;\n opacity: 0;\n transition: opacity ease-in-out 100ms, margin-top ease-in-out 200ms;\n pointer-events: none;\n }\n\n .help-text.help-always {\n opacity: 1;\n margin-top: 6px;\n margin-left: var(--help-text-margin-left);\n }\n\n .field:focus-within .help-text {\n margin-top: 6px;\n opacity: 1;\n }\n\n .alert-error {\n background: rgba(255, 181, 181, 0.17);\n border: none;\n border-left: 0px solid var(--color-error);\n color: var(--color-error);\n padding: 10px;\n margin: 15px 0px;\n border-radius: var(--curvature);\n box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1),\n 0 1px 2px 0 rgba(0, 0, 0, 0.06);\n }\n\n .disabled {\n opacity: var(--disabled-opacity) !important;\n pointer-events: none !important;\n }\n `;\n }\n\n @property({ type: Boolean, attribute: 'hide_label' })\n hideLabel = false;\n\n @property({ type: Boolean, attribute: 'widget_only' })\n widgetOnly = false;\n\n @property({ type: Array, attribute: false })\n errors: string[] = [];\n\n @property({ type: Boolean })\n hideErrors = false;\n\n @property({ type: String, attribute: 'help_text' })\n helpText = '';\n\n @property({ type: Boolean, attribute: 'help_always' })\n helpAlways = true;\n\n @property({ type: String })\n label = '';\n\n @property({ type: String })\n name = '';\n\n @property({ type: Boolean })\n disabled = false;\n\n public render(): TemplateResult {\n const errors = !this.hideErrors\n ? (this.errors || []).map((error: string) => {\n return html`
    ${error}
    `;\n })\n : [];\n\n if (this.widgetOnly) {\n return html`\n
    \n ${errors}\n `;\n }\n\n return html`\n
    \n ${!!this.name && !this.hideLabel && !!this.label\n ? html`\n
    \n `;\n }\n}\n","import { html, TemplateResult, css, LitElement } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { range } from '../utils';\n\nexport class Loading extends LitElement {\n static get styles() {\n return css`\n :host {\n display: block;\n }\n\n .loading-unit {\n border: 1px inset rgba(0, 0, 0, 0.05);\n animation: loading-pulse 0.9s cubic-bezier(0.3, 0, 0.7, 1) infinite;\n }\n\n .loading-container {\n display: flex;\n }\n\n @keyframes loading-pulse {\n 0% {\n transform: scale(0.2);\n opacity: 0.1;\n }\n 20% {\n transform: scale(1);\n opacity: 1;\n }\n 100% {\n transform: scale(0.2);\n opacity: 0.1;\n }\n }\n `;\n }\n\n @property({ type: String })\n color = 'var(--color-primary-dark)';\n\n @property({ type: Number })\n size = 5;\n\n @property({ type: Number })\n units = 5;\n\n @property({ type: Boolean })\n square?: boolean;\n\n @property({ type: String })\n direction = 'row';\n\n public render(): TemplateResult {\n const margin = this.size / 2;\n\n return html`\n
    \n ${range(0, this.units).map((num: number) => {\n const ballStyle = {\n 'border-radius': this.square ? '0' : '50%',\n width: this.size + 'px',\n height: this.size + 'px',\n margin: margin + 'px',\n animationDelay: `-${1 - num * (1 / this.units)}s`,\n background: this.color,\n };\n return html`\n
    \n `;\n })}\n
    \n `;\n }\n}\n","// '@£$¥èéùìòÇ\\nØø\\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ\\x20!\"#¤%&\\'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà\\f^{}\\\\[~]|€'\nconst GSM_charCodes = [\n 10, 12, 13, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66,\n 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85,\n 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97, 98, 99, 100, 101, 102, 103, 104,\n 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,\n 120, 121, 122, 123, 124, 125, 126, 161, 163, 164, 165, 167, 191, 196, 197,\n 198, 199, 201, 209, 214, 216, 220, 223, 224, 228, 229, 230, 232, 233, 236,\n 241, 242, 246, 248, 249, 252, 915, 916, 920, 923, 926, 928, 931, 934, 936,\n 937, 8364,\n];\n\n// '\\f|^€{}[~]\\\\'\nconst GSMe_charCodes = [12, 91, 92, 93, 94, 123, 124, 125, 126, 8364];\n\nfunction existsInArray(code, array) {\n const len = array.length;\n let i = 0;\n while (i < len) {\n const e = array[i];\n if (code === e) return true;\n i++;\n }\n return false;\n}\n\nexport function validateCharacter(character) {\n const code = character.charCodeAt(0);\n return existsInArray(code, GSM_charCodes);\n}\n\nexport function validateMessage(message) {\n for (let i = 0; i < message.length; i++) {\n if (!validateCharacter(message.charAt(i))) return false;\n }\n return true;\n}\n\nexport function validateExtendedCharacter(character) {\n const code = character.charCodeAt(0);\n return existsInArray(code, GSMe_charCodes);\n}\n","import { validateCharacter, validateExtendedCharacter } from './gsmvalidator';\n\nfunction isHighSurrogate(code) {\n return code >= 0xd800 && code <= 0xdbff;\n}\n\nexport const gsmSplit = function (message, options) {\n options = options || { summary: false };\n\n if (message === '') {\n return {\n parts: [\n {\n content: options.summary ? undefined : '',\n length: 0,\n bytes: 0,\n },\n ],\n totalLength: 0,\n totalBytes: 0,\n };\n }\n\n const messages = [];\n let length = 0;\n let bytes = 0;\n let totalBytes = 0;\n let totalLength = 0;\n let messagePart = '';\n\n function bank() {\n const msg = {\n content: options.summary ? undefined : messagePart,\n length: length,\n bytes: bytes,\n };\n messages.push(msg);\n\n totalLength += length;\n length = 0;\n totalBytes += bytes;\n bytes = 0;\n messagePart = '';\n }\n\n for (let i = 0, count = message.length; i < count; i++) {\n let c = message.charAt(i);\n\n if (!validateCharacter(c)) {\n if (isHighSurrogate(c.charCodeAt(0))) {\n i++;\n }\n c = '\\u0020';\n } else if (validateExtendedCharacter(c)) {\n if (bytes === 152) bank();\n bytes++;\n }\n\n bytes++;\n length++;\n\n if (!options.summary) messagePart += c;\n\n if (bytes === 153) bank();\n }\n\n if (bytes > 0) bank();\n\n if (messages[1] && totalBytes <= 160) {\n return {\n parts: [\n {\n content: options.summary\n ? undefined\n : messages[0].content + messages[1].content,\n length: totalLength,\n bytes: totalBytes,\n },\n ],\n totalLength: totalLength,\n totalBytes: totalBytes,\n };\n }\n\n return {\n parts: messages,\n totalLength: totalLength,\n totalBytes: totalBytes,\n };\n};\n","function isHighSurrogate(code) {\n return code >= 0xd800 && code <= 0xdbff;\n}\n\nexport const unicodeSplit = function (message, options) {\n options = options || { summary: false };\n\n if (message === '') {\n return {\n parts: [\n {\n content: options.summary ? undefined : '',\n length: 0,\n bytes: 0,\n },\n ],\n totalLength: 0,\n totalBytes: 0,\n };\n }\n\n const messages = [];\n let length = 0;\n let bytes = 0;\n let totalBytes = 0;\n let totalLength = 0;\n let partStart = 0;\n\n function bank(partEnd = undefined) {\n const msg = {\n content: options.summary\n ? undefined\n : partEnd\n ? message.substring(partStart, partEnd + 1)\n : message.substring(partStart),\n length: length,\n bytes: bytes,\n };\n messages.push(msg);\n\n partStart = partEnd + 1;\n\n totalLength += length;\n length = 0;\n totalBytes += bytes;\n bytes = 0;\n }\n\n for (let i = 0, count = message.length; i < count; i++) {\n const code = message.charCodeAt(i);\n const highSurrogate = isHighSurrogate(code);\n\n if (highSurrogate) {\n if (bytes === 132) bank(i - 1);\n bytes += 2;\n i++;\n }\n\n bytes += 2;\n length++;\n\n if (bytes === 134) bank(i);\n }\n\n if (bytes > 0) bank();\n\n if (messages[1] && totalBytes <= 140) {\n return {\n parts: [\n {\n content: options.summary ? undefined : message,\n length: totalLength,\n bytes: totalBytes,\n },\n ],\n totalLength: totalLength,\n totalBytes: totalBytes,\n };\n }\n\n return {\n parts: messages,\n totalLength: totalLength,\n totalBytes: totalBytes,\n };\n};\n","/**\n * This is the same SMS splitter we've been using but we've\n * updated it here to use it with ESM imports\n * See https://github.com/Codesleuth/split-sms\n */\n\nimport { gsmSplit } from './gsmsplitter';\nimport { validateMessage } from './gsmvalidator';\nimport { unicodeSplit } from './unicodesplitter';\n\nexport const UNICODE = 'Unicode';\nexport const GSM = 'GSM';\n\nfunction calculateRemaining(parts, singleBytes, multiBytes, charBytes) {\n const max = parts.length === 1 ? singleBytes : multiBytes;\n return (max - parts[parts.length - 1].bytes) / charBytes;\n}\n\nexport const splitSMS = function (message: string, options: any = {}) {\n const characterset = options && options.characterset;\n\n options = {\n summary: options && options.summary,\n };\n\n const isGsm =\n (characterset === undefined && validateMessage(message)) ||\n characterset === GSM;\n let splitResult, singleBytes, multiBytes, charBytes;\n\n if (isGsm) {\n splitResult = gsmSplit(message, options);\n singleBytes = 160;\n multiBytes = 153;\n charBytes = 1;\n } else {\n splitResult = unicodeSplit(message, options);\n singleBytes = 140;\n multiBytes = 134;\n charBytes = 2;\n }\n\n const remainingInPart = calculateRemaining(\n splitResult.parts,\n singleBytes,\n multiBytes,\n charBytes\n );\n\n return {\n characterSet: isGsm ? GSM : UNICODE,\n parts: splitResult.parts,\n bytes: splitResult.totalBytes,\n length: splitResult.totalLength,\n remainingInPart: remainingInPart,\n };\n};\n","export const MAX_GSM_SINGLE = 160;\nexport const MAX_GSM_MULTI = 153;\nexport const MAX_UNICODE_SINGLE = 70;\nexport const MAX_UNICODE_MULTI = 67;\n\nexport const COMPLETION_HELP = 'Tab to complete, enter to select';\n\nexport const GSM: { [key: string]: number } = {\n // char: charCode\n 0: 48,\n 1: 49,\n 2: 50,\n 3: 51,\n 4: 52,\n 5: 53,\n 6: 54,\n 7: 55,\n 8: 56,\n 9: 57,\n '\\n': 10,\n '\\f': 12,\n '\\r': 13,\n ' ': 32,\n '!': 33,\n '\"': 34,\n '#': 35,\n $: 36,\n '%': 37,\n '&': 38,\n \"'\": 39,\n '(': 40,\n ')': 41,\n '*': 42,\n '+': 43,\n ',': 44,\n '-': 45,\n '.': 46,\n '/': 47,\n ':': 58,\n ';': 59,\n '<': 60,\n '=': 61,\n '>': 62,\n '?': 63,\n '@': 64,\n A: 65,\n B: 66,\n C: 67,\n D: 68,\n E: 69,\n F: 70,\n G: 71,\n H: 72,\n I: 73,\n J: 74,\n K: 75,\n L: 76,\n M: 77,\n N: 78,\n O: 79,\n P: 80,\n Q: 81,\n R: 82,\n S: 83,\n T: 84,\n U: 85,\n V: 86,\n W: 87,\n X: 88,\n Y: 89,\n Z: 90,\n '[': 91,\n '\\\\': 92,\n ']': 93,\n '^': 94,\n _: 95,\n a: 97,\n b: 98,\n c: 99,\n d: 100,\n e: 101,\n f: 102,\n g: 103,\n h: 104,\n i: 105,\n j: 106,\n k: 107,\n l: 108,\n m: 109,\n n: 110,\n o: 111,\n p: 112,\n q: 113,\n r: 114,\n s: 115,\n t: 116,\n u: 117,\n v: 118,\n w: 119,\n x: 120,\n y: 121,\n z: 122,\n '{': 123,\n '|': 124,\n '}': 125,\n '~': 126,\n '¡': 161,\n '£': 163,\n '¤': 164,\n '¥': 165,\n '§': 167,\n '¿': 191,\n Ä: 196,\n Å: 197,\n Æ: 198,\n Ç: 199,\n É: 201,\n Ñ: 209,\n Ö: 214,\n Ø: 216,\n Ü: 220,\n ß: 223,\n à: 224,\n ä: 228,\n å: 229,\n æ: 230,\n è: 232,\n é: 233,\n ì: 236,\n ñ: 241,\n ò: 242,\n ö: 246,\n ø: 248,\n ù: 249,\n ü: 252,\n Γ: 915,\n Δ: 916,\n Θ: 920,\n Λ: 923,\n Ξ: 926,\n Π: 928,\n Σ: 931,\n Φ: 934,\n Ψ: 936,\n Ω: 937,\n '€': 8364,\n};\n\nexport const isGSM = (char: string): boolean => {\n // eslint-disable-next-line no-prototype-builtins\n return GSM.hasOwnProperty(char);\n};\n\nexport const getExtendedCharacters = (text: string): string[] => {\n const extended: { [ch: string]: boolean } = {};\n for (const ch of text) {\n if (!isGSM(ch)) {\n extended[ch] = true;\n }\n }\n return Object.keys(extended);\n};\n","import { css, html, TemplateResult } from 'lit';\nimport { RapidElement } from '../RapidElement';\nimport { splitSMS } from '../sms';\nimport { getExtendedCharacters } from './helpers';\nimport { property } from 'lit/decorators.js';\n\nexport class CharCount extends RapidElement {\n static get styles() {\n return css`\n :host {\n overflow: auto;\n }\n\n :host::after {\n content: '';\n clear: both;\n display: table;\n }\n\n .counter {\n float: right;\n text-align: right;\n position: relative;\n }\n\n .extended {\n font-size: 14px;\n display: flex;\n margin-top: 4px;\n }\n\n .extended-char {\n border: 1px solid #e6e6e6;\n border-radius: var(--curvature-widget);\n padding: 4px;\n text-align: center;\n line-height: 20px;\n margin-right: 4px;\n }\n\n .summary {\n width: 180px;\n padding: 8px 12px;\n font-size: 12px;\n background: white;\n border-radius: var(--curvature-widget);\n overflow: hidden;\n opacity: 0.3;\n transform: scale(0.7);\n box-shadow: var(--shadow);\n transition: transform cubic-bezier(0.71, 0.18, 0.61, 1.33)\n var(--transition-speed);\n visibility: hidden;\n margin-top: var(--temba-charcount-summary-margin-top);\n right: var(--temba-charcount-summary-right);\n bottom: var(--temba-charcount-summary-bottom);\n text-align: left;\n position: var(--temba-charcount-summary-position);\n z-index: 1000;\n }\n\n .fine-print {\n margin-top: 8px;\n margin-left: -12px;\n margin-right: -12px;\n margin-bottom: -8px;\n padding: 8px 12px;\n color: #999;\n background: #f5f5f5;\n font-size: 10px;\n }\n\n .extended-warning {\n margin-top: 8px;\n }\n\n .note {\n font-weight: 600;\n display: inline-block;\n margin-right: 2px;\n }\n\n .counts {\n cursor: pointer;\n transition: all cubic-bezier(0.71, 0.18, 0.61, 1.33) 200ms;\n transform: scale(0.9);\n display: inline-block;\n padding: 2px 6px;\n border-radius: var(--curvature);\n margin-top: var(--temba-charcount-counts-margin-top);\n }\n\n .segments {\n font-size: 85%;\n display: inline-block;\n }\n\n .attention .counts {\n transform: scale(0.95);\n background: var(--color-overlay-light);\n color: var(--color-overlay-light-text);\n }\n\n .attention .segments {\n font-weight: 600;\n }\n\n .counter:hover .summary {\n opacity: 1;\n transform: scale(1);\n visibility: visible;\n }\n `;\n }\n\n @property({ type: String })\n text: string;\n\n @property({ type: Number })\n count: number;\n\n @property({ type: Number, attribute: false })\n segments: number;\n\n @property({ type: Object, attribute: false })\n extended: string[] = [];\n\n public updated(changes: Map) {\n super.updated(changes);\n if (changes.has('text')) {\n this.updateSegments();\n }\n }\n\n private updateSegments() {\n const sms = splitSMS(this.text);\n this.count = sms.length;\n this.segments = sms.parts.length;\n this.extended = getExtendedCharacters(this.text);\n this.count = this.text.length;\n }\n\n public render(): TemplateResult {\n const hasExpressions = this.text && this.text.indexOf('@') > -1;\n\n let segments = html`.`;\n if (this.segments > 1) {\n segments = html`and will use ${hasExpressions ? html`at least` : null}\n ${this.segments} messages to send over SMS.`;\n } else {\n segments = html`and will use ${hasExpressions ? html`at least` : null} one\n message to send over SMS.`;\n }\n\n let extended = null;\n if (this.extended.length > 0 && (this.segments > 1 || hasExpressions)) {\n extended = this.extended.map(\n (ch: string) => html`
    ${ch}
    `\n );\n extended = html`\n
    \n Some characters require more space over SMS. To save on fees, consider\n replacing them.\n
    ${extended}
    \n
    \n `;\n }\n\n const summary =\n this.count > 1\n ? html`
    \n This message is ${this.count} characters\n ${segments} ${extended}\n ${hasExpressions\n ? html`\n
    \n
    NOTE
    \n Using variables may result in more messages when sending\n over SMS than this estimate.\n
    \n `\n : null}\n
    `\n : null;\n\n return html`
    ${this.count}${\n this.segments > 1 || hasExpressions\n ? html`
    \n  / ${this.segments}${hasExpressions ? html`+` : null}\n
    \n
    `\n : null\n }
    ${summary}
    `;\n }\n}\n","import { html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { RapidElement } from '../RapidElement';\nimport { Store } from './Store';\n\n/**\n * StoreMonitorElement notifies when the store is updated and with what url\n */\nexport class StoreMonitorElement extends RapidElement {\n @property({ type: String })\n url: string;\n\n @property({ type: Boolean })\n showLoading = false;\n\n store: Store;\n\n private handleStoreUpdated(event: CustomEvent) {\n this.store.initialHttpComplete.then(() => {\n this.storeUpdated(event);\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function\n protected storeUpdated(event: CustomEvent) {}\n\n protected updated(\n properties: PropertyValueMap | Map\n ): void {\n super.updated(properties);\n }\n\n connectedCallback(): void {\n super.connectedCallback();\n this.store = document.querySelector('temba-store') as Store;\n this.handleStoreUpdated = this.handleStoreUpdated.bind(this);\n if (this.store) {\n this.store.addEventListener(\n CustomEventType.StoreUpdated,\n this.handleStoreUpdated\n );\n }\n }\n\n disconnectedCallback(): void {\n super.disconnectedCallback();\n if (this.store) {\n this.store.removeEventListener(\n CustomEventType.StoreUpdated,\n this.handleStoreUpdated\n );\n }\n }\n\n public render(): TemplateResult {\n if (!this.store.ready && this.showLoading) {\n return html``;\n }\n }\n}\n","import { PropertyValueMap } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\n\nimport { Store } from './Store';\nimport { StoreMonitorElement } from './StoreMonitorElement';\n\n/**\n * StoreElement is a listener for a given endpoint that re-renders\n * when the underlying store element changes\n */\nexport class StoreElement extends StoreMonitorElement {\n @property({ type: String })\n url: string;\n\n @property({ type: Boolean })\n showLoading = false;\n\n @property({ type: Object, attribute: false })\n data: any;\n\n store: Store;\n\n prepareData(data: any): any {\n return data;\n }\n\n public refresh() {\n this.store.makeRequest(this.url, {\n prepareData: this.prepareData,\n force: true,\n });\n }\n\n protected storeUpdated(event: CustomEvent) {\n if (event.detail.url === this.url) {\n const previous = this.data;\n this.data = event.detail.data;\n this.fireCustomEvent(CustomEventType.Refreshed, {\n data: event.detail.data,\n previous,\n });\n }\n }\n\n protected updated(\n properties: PropertyValueMap | Map\n ): void {\n super.updated(properties);\n if (properties.has('url')) {\n if (this.url) {\n this.store.makeRequest(this.url, { prepareData: this.prepareData });\n } else {\n this.data = null;\n }\n }\n }\n\n connectedCallback(): void {\n super.connectedCallback();\n this.prepareData = this.prepareData.bind(this);\n }\n}\n","import { PropertyValueMap } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { Contact, Group } from '../interfaces';\nimport { StoreElement } from '../store/StoreElement';\n\nexport class ContactStoreElement extends StoreElement {\n @property({ type: String })\n contact: string;\n\n @property({ type: Object, attribute: false })\n data: Contact;\n\n @property({ type: String })\n endpoint = '/api/v2/contacts.json?uuid=';\n\n prepareData(data: any) {\n if (data && data.length > 0) {\n data = data[0];\n data.groups.forEach((group: Group) => {\n group.is_dynamic = this.store.isDynamicGroup(group.uuid);\n });\n\n data.groups.sort((a: Group, b: Group) => {\n if (!a.is_dynamic || !b.is_dynamic) {\n if (a.is_dynamic) {\n return -1;\n }\n\n if (b.is_dynamic) {\n return 1;\n }\n }\n\n return a.name.localeCompare(b.name);\n });\n\n return data;\n }\n return null;\n }\n\n public setContact(contact: any) {\n // make sure contact data is properly prepped\n this.data = this.prepareData([contact]);\n this.store.updateCache(`${this.endpoint}${this.contact}`, this.data);\n }\n\n protected updated(\n changes: PropertyValueMap | Map\n ): void {\n super.updated(changes);\n if (changes.has('contact')) {\n if (this.contact) {\n this.url = `${this.endpoint}${this.contact}`;\n } else {\n this.url = null;\n }\n }\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { Contact, CustomEventType, Ticket } from '../interfaces';\nimport { postJSON } from '../utils';\nimport { ContactHistory } from './ContactHistory';\nimport { ContactStoreElement } from './ContactStoreElement';\nimport { Compose } from '../compose/Compose';\n\nconst DEFAULT_REFRESH = 10000;\n\nexport class ContactChat extends ContactStoreElement {\n public static get styles() {\n return css`\n :host {\n flex-grow: 1;\n display: flex;\n flex-direction: row;\n min-height: 0;\n --compose-shadow: none;\n --compose-border: none;\n --compose-padding: 3px;\n --compose-curvature: none;\n }\n\n .chat-wrapper {\n display: flex;\n flex-grow: 1;\n flex-direction: column;\n min-height: 0;\n }\n\n temba-contact-history {\n border-bottom: 1px solid #f6f6f6;\n flex-grow: 1;\n display: flex;\n flex-direction: column;\n min-height: 0;\n }\n\n .chatbox {\n box-shadow: 0px -5px 1rem 0rem rgba(0, 0, 0, 0.07);\n display: flex;\n flex-direction: column;\n --textarea-min-height: 1em;\n --textarea-height: 1.2em;\n --widget-box-shadow-focused: none;\n }\n\n .chatbox:focus-within {\n --textarea-height: 4em;\n }\n\n .chatbox.full {\n border-bottom-right-radius: 0 !important;\n }\n\n .closed-footer {\n padding: 1em;\n background: #f2f2f2;\n border-top: 3px solid #e1e1e1;\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n a {\n color: var(--color-link-primary);\n }\n\n a:hover {\n text-decoration: underline;\n color: var(--color-link-primary-hover);\n }\n\n temba-button#reopen-button {\n --button-y: 1px;\n --button-x: 12px;\n }\n\n temba-completion {\n --widget-box-shadow: none;\n --color-widget-border: transparent;\n --widget-box-shadow-focused: none;\n --color-focus: transparent;\n --color-widget-bg-focused: transparent;\n }\n `;\n }\n\n @property({ type: String, attribute: 'ticket' })\n ticketUUID: string;\n\n @property({ type: String })\n contactsEndpoint = '/api/v2/contacts.json';\n\n @property({ type: String })\n currentNote = '';\n\n @property({ type: Boolean })\n showDetails = true;\n\n @property({ type: Boolean })\n monitor = false;\n\n @property({ type: Object })\n currentTicket: Ticket = null;\n\n @property({ type: Object })\n currentContact: Contact = null;\n\n @property({ type: String })\n agent = '';\n\n // http promise to monitor for completeness\n public httpComplete: Promise;\n\n constructor() {\n super();\n }\n\n refreshInterval = null;\n\n public connectedCallback() {\n super.connectedCallback();\n if (this.monitor) {\n this.refreshInterval = setInterval(() => {\n if (this.currentTicket && this.currentTicket.closed_on) {\n return;\n }\n this.refresh();\n }, DEFAULT_REFRESH);\n }\n }\n\n public disconnectedCallback() {\n if (this.refreshInterval) {\n clearInterval(this.refreshInterval);\n }\n }\n\n public getContactHistory(): ContactHistory {\n return this.shadowRoot.querySelector(\n 'temba-contact-history'\n ) as ContactHistory;\n }\n\n public refresh(scrollToBottom = false): void {\n const contactHistory = this.getContactHistory();\n if (contactHistory) {\n if (scrollToBottom) {\n contactHistory.scrollToBottom();\n }\n contactHistory.refresh();\n // super.refresh();\n }\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n // if we don't have an endpoint infer one\n if (\n changedProperties.has('data') ||\n changedProperties.has('currentContact')\n ) {\n this.currentContact = this.data;\n }\n }\n\n private handleSend(evt: CustomEvent) {\n const buttonName = evt.detail.name;\n if (buttonName === 'Send') {\n const payload = {\n contact: this.currentContact.uuid,\n };\n const compose = evt.currentTarget as Compose;\n if (compose) {\n const text = compose.currentText;\n if (text && text.length > 0) {\n payload['text'] = text;\n }\n const attachments = compose.currentAttachments;\n if (attachments && attachments.length > 0) {\n const attachment_uuids = attachments.map(\n attachment => attachment.uuid\n );\n payload['attachments'] = attachment_uuids;\n }\n }\n if (this.currentTicket) {\n payload['ticket'] = this.currentTicket.uuid;\n }\n\n const genericError = buttonName + ' failed, please try again.';\n\n postJSON(`/api/v2/messages.json`, payload)\n .then(response => {\n if (response.status < 400) {\n compose.reset();\n this.refresh(true);\n this.fireCustomEvent(CustomEventType.MessageSent, { msg: payload });\n } else if (response.status < 500) {\n if (\n response.json.text &&\n response.json.text.length > 0 &&\n response.json.text[0].length > 0\n ) {\n let textError = response.json.text[0];\n textError = textError.replace(\n 'Ensure this field has no more than',\n 'Maximum allowed text is'\n );\n compose.buttonError = textError;\n } else if (\n response.json.attachments &&\n response.json.attachments.length > 0 &&\n response.json.attachments[0].length > 0\n ) {\n let attachmentError = response.json.attachments[0];\n attachmentError = attachmentError\n .replace(\n 'Ensure this field has no more than',\n 'Maximum allowed attachments is'\n )\n .replace('elements', 'files');\n compose.buttonError = attachmentError;\n } else {\n compose.buttonError = genericError;\n }\n } else {\n compose.buttonError = genericError;\n }\n })\n .catch(error => {\n console.error(error);\n compose.buttonError = genericError;\n });\n }\n }\n\n public render(): TemplateResult {\n const contactHistory = this.currentContact\n ? this.getTembaContactHistory()\n : null;\n const chatbox = this.currentContact ? this.getTembaChatbox() : null;\n\n const contactHistoryAndChatbox = html`\n
    ${contactHistory} ${chatbox}
    \n `;\n return html`${contactHistoryAndChatbox}`;\n }\n\n private getTembaContactHistory(): TemplateResult {\n return html` \n `;\n }\n\n private getTembaChatbox(): TemplateResult {\n if (this.currentTicket) {\n if (this.currentContact && this.currentContact.status !== 'active') {\n //no chatbox for archived, blocked, or stopped contacts\n return null;\n } else {\n if (!this.currentTicket.closed_on) {\n //chatbox for active contacts with an open ticket\n return this.getChatbox();\n } else {\n return null;\n }\n }\n }\n\n if (this.currentContact && this.currentContact.status !== 'active') {\n //no chatbox for archived, blocked, or stopped contacts\n return null;\n } else {\n //chatbox for active contacts\n return this.getChatbox();\n }\n }\n\n private getChatbox(): TemplateResult {\n return html`
    \n \n \n
    `;\n }\n}\n","import { Contact, User } from '../interfaces';\nimport { fetchResults, getUrl, postUrl, WebResponse } from '../utils';\nimport { ContactHistoryPage } from './events';\n\nexport const SCROLL_THRESHOLD = 100;\nexport const SIMULATED_WEB_SLOWNESS = 0;\nexport const MAX_CHAT_REFRESH = 10000;\nexport const MIN_CHAT_REFRESH = 500;\nexport const BODY_SNIPPET_LENGTH = 250;\n\nexport const closeTicket = (uuid: string): Promise => {\n const formData = new FormData();\n formData.append('status', 'C');\n return postUrl(`/ticket/update/${uuid}/?_format=json`, formData);\n};\n\nexport const fetchContact = (endpoint: string): Promise => {\n return new Promise((resolve, reject) => {\n fetchResults(endpoint).then((contacts: Contact[]) => {\n if (contacts && contacts.length === 1) {\n resolve(contacts[0]);\n } else {\n reject('No contact found');\n }\n });\n });\n};\n\nlet pendingRequests: AbortController[] = [];\n\nexport const fetchContactHistory = (\n reset: boolean,\n endpoint: string,\n ticket: string,\n before: number = undefined,\n after: number = undefined\n): Promise => {\n if (reset) {\n pendingRequests.forEach(controller => {\n controller.abort();\n });\n pendingRequests = [];\n }\n\n return new Promise(resolve => {\n const controller = new AbortController();\n pendingRequests.push(controller);\n\n let url = endpoint;\n if (before) {\n url += `&before=${before}`;\n }\n\n if (after) {\n url += `&after=${after}`;\n }\n\n if (ticket) {\n url += `&ticket=${ticket}`;\n }\n\n getUrl(url, controller)\n .then((response: WebResponse) => {\n // on success, remove our abort controller\n pendingRequests = pendingRequests.filter(\n (controller: AbortController) => {\n return response.controller === controller;\n }\n );\n resolve(response.json as ContactHistoryPage);\n })\n .catch(() => {\n // canceled\n });\n });\n};\n\nexport const getDisplayName = (user: User) => {\n if (!user) {\n return 'Somebody';\n }\n\n if (user.first_name && user.last_name) {\n return `${user.first_name} ${user.last_name}`;\n }\n\n if (user.first_name) {\n return user.first_name;\n }\n\n return user.email;\n};\n","import { css, html, TemplateResult } from 'lit';\nimport { Msg, ObjectReference, User } from '../interfaces';\nimport { getClasses, oxford, oxfordFn, oxfordNamed } from '../utils';\nimport { Icon } from '../vectoricon';\nimport { getDisplayName } from './helpers';\n\nexport const getEventStyles = () => {\n return css`\n .grouping {\n margin-top: 1em;\n }\n\n .grouping.verbose {\n background: #f9f9f9;\n color: var(--color-dark);\n --color-link-primary: rgba(38, 166, 230, 1);\n pointer-events: none;\n background: #fefefe;\n box-shadow: -8px 0px 8px 1px rgba(0, 0, 0, 0.05) inset;\n margin-right: -16px;\n padding-right: 16px;\n margin-bottom: 1.3em;\n max-width: 100%;\n }\n\n .grouping .items {\n display: block;\n }\n\n .grouping.verbose .items {\n opacity: 0;\n max-height: 0;\n display: flex;\n flex-direction: column;\n user-select: none;\n }\n\n .grouping.flows .items {\n padding: 0;\n }\n\n .grouping.messages .items {\n display: flex;\n flex-direction: column;\n margin: 0em 0.75em;\n }\n\n .grouping.verbose.expanded .items {\n transition: max-height var(--transition-speed) ease-in-out,\n opacity var(--transition-speed) ease-in-out;\n opacity: 1;\n max-height: 1000px;\n padding: 1em 1em;\n }\n\n .grouping.verbose.expanded {\n border-top: 1px solid #f3f3f3;\n border-bottom: 1px solid #f3f3f3;\n }\n\n .grouping.verbose.expanded,\n .grouping.verbose .event-count {\n pointer-events: auto;\n }\n\n .grouping.verbose temba-icon {\n }\n\n .grouping.verbose > .event,\n .grouping.verbose > pre {\n max-height: 0px;\n padding-top: 0;\n padding-bottom: 0;\n margin-top: 0;\n margin-bottom: 0;\n opacity: 0;\n }\n\n .grouping.verbose .attn {\n color: #666;\n }\n\n .event-count {\n position: relative;\n font-size: 0.8em;\n text-align: center;\n margin: 0 auto;\n display: table;\n padding: 3px 10px;\n font-weight: 400;\n color: #999;\n cursor: pointer;\n width: 100%;\n opacity: 1;\n }\n\n .event-count temba-icon {\n display: inline-block;\n position: absolute;\n right: 5px;\n top: 5px;\n }\n\n .event-count:hover {\n color: var(--color-link-primary-hover);\n }\n\n .expanded .event-count {\n padding: 0;\n pointer-events: none;\n }\n\n .grouping.flows {\n margin-left: 1em;\n margin-right: 1em;\n margin-bottom: 1.5em;\n\n border: 1px solid #f2f2f2;\n border-radius: var(--curvature);\n padding: 0.5em 1em;\n }\n\n .grouping.flows .event {\n margin: 0;\n padding: 0;\n }\n\n .grouping.tickets {\n margin-bottom: 2em;\n }\n\n pre {\n white-space: pre-wrap;\n word-wrap: break-word;\n }\n\n .grouping.verbose.expanded .event,\n .grouping.verbose.expanded pre {\n max-height: 500px;\n opacity: 1;\n }\n\n .grouping-close-button {\n position: relative;\n display: inline-block;\n opacity: 0;\n float: right;\n --icon-color: #666;\n }\n\n .grouping.verbose.expanded:hover .grouping-close-button {\n opacity: 1;\n }\n\n .grouping.messages,\n .grouping.tickets {\n display: flex;\n flex-direction: column;\n }\n\n .event {\n margin: 0.25em 0.5em;\n border-radius: var(--curvature);\n flex-grow: 1;\n }\n\n .msg {\n border-radius: calc(var(--curvature) * 2.5);\n border: 2px solid rgba(100, 100, 100, 0.1);\n max-width: 300px;\n word-break: break-word;\n overflow: hidden;\n }\n\n .msg.attachments-1.no-message {\n border: 2px solid transparent;\n background-color: transparent !important;\n }\n\n .msg .text {\n padding: var(--event-padding);\n }\n\n .event.msg_received .msg {\n background: rgba(200, 200, 200, 0.1);\n }\n\n .event.msg_created,\n .event.broadcast_created,\n .event.ivr_created,\n .event.ticket_note_added {\n align-self: flex-end;\n }\n\n .event.msg_created .msg,\n .event.broadcast_created .msg,\n .event.ivr_created .msg {\n background: var(--color-primary-dark);\n color: white;\n font-weight: 400;\n }\n\n .msg.automated {\n background: var(--color-automated) !important;\n }\n\n .queued {\n opacity: 0.3;\n }\n\n .optin_requested {\n --icon-color: var(--color-primary-dark);\n }\n\n .webhook_called {\n --icon-color: #e68628;\n word-break: break-all;\n }\n\n .webhook_called .failed {\n --icon-color: var(--color-error);\n color: var(--color-error);\n }\n\n .input_labels_added,\n .contact_name_changed,\n .contact_field_changed,\n .contact_urns_changed,\n .contact_language_changed,\n .run_result_changed {\n --icon-color: rgba(1, 193, 175, 1);\n }\n\n .email_sent {\n --icon-color: #8e5ea7;\n }\n\n .contact_groups_changed .added {\n --icon-color: #309c42;\n }\n .contact_groups_changed .removed {\n --icon-color: var(--color-error);\n }\n\n .event.error .description,\n .event.failure .description {\n color: var(--color-error);\n }\n\n .description.error {\n color: var(--color-error);\n }\n\n .info {\n border: 1px solid rgba(100, 100, 100, 0.2);\n background: rgba(10, 10, 10, 0.02);\n }\n\n .ticket_note_added {\n max-width: 300px;\n }\n\n .note-summary {\n display: flex;\n flex-direction: row;\n font-size: 85%;\n margin-top: -0.5em;\n color: rgba(0, 0, 0, 0.6);\n padding: 8px 3px;\n }\n\n .ticket_note_added .description {\n border: 2px solid rgba(100, 100, 100, 0.1);\n background: rgb(255, 249, 194);\n padding: var(--event-padding);\n font-weight: 400;\n color: rgba(0, 0, 0, 0.6);\n border-radius: calc(var(--curvature) * 2.5);\n }\n\n .channel_event {\n --icon-color: rgb(200, 200, 200);\n }\n\n .airtime_transferred,\n .flow_exited,\n .flow_entered,\n .ticket_opened,\n .ticket_reopened,\n .ticket_closed,\n .call_started,\n .campaign_fired {\n --icon-color: rgba(223, 65, 159, 1);\n }\n\n .active-ticket.ticket_opened {\n padding: 0em 1em;\n }\n\n .ticket_closed .inactive .subtext {\n display: none;\n }\n\n .attn {\n color: var(--color-text);\n }\n\n .flow_exited,\n .flow_entered {\n align-self: center;\n max-width: 80%;\n display: flex;\n flex-direction: row;\n }\n\n .flow_exited temba-icon,\n .flow_entered temba-icon {\n }\n\n .event {\n display: flex;\n align-items: center;\n }\n\n .event .description {\n flex-grow: 1;\n }\n\n .msg-summary {\n display: flex;\n font-size: 85%;\n color: rgba(0, 0, 0, 0.6);\n padding: 6px 3px;\n margin-bottom: 0.5em;\n margin-top: -0.5em;\n }\n\n .msg-summary temba-icon.log {\n --icon-color: rgba(0, 0, 0, 0.2);\n }\n\n .msg-summary temba-icon.log:hover {\n --icon-color: var(--color-link-primary-hover);\n cursor: pointer;\n }\n\n .msg-summary temba-icon.error {\n --icon-color: rgba(var(--error-rgb), 0.75);\n }\n\n .msg-summary temba-icon.error:hover {\n --icon-color: var(--color-error);\n cursor: pointer;\n }\n\n .msg-summary temba-icon.broadcast {\n --icon-color: rgba(90, 90, 90, 0.5);\n }\n\n .msg-summary * {\n display: flex;\n margin-right: 1px;\n margin-left: 1px;\n }\n\n .unsupported {\n border: 1px solid #f2f2f2;\n color: #999;\n padding: 0.5em 1em;\n border-radius: var(--curvature);\n }\n\n .optin {\n align-items: center;\n padding: 0 0.2em;\n }\n\n .time {\n padding: 0.3em 1px;\n }\n\n .subtext .time {\n padding: 0em;\n }\n\n .status {\n padding: 0.3em 3px;\n }\n\n .separator {\n padding: 0.3em 0px;\n }\n\n .recipients {\n padding: 0.3em 3px;\n }\n\n .verbose temba-icon,\n .flows temba-icon,\n .tickets temba-icon {\n margin-right: 0.75em;\n }\n\n .attn {\n display: inline-block;\n font-weight: 500;\n margin: 0px 2px;\n word-break: break-all;\n white-space: break-spaces;\n }\n\n .subtext {\n font-size: 80%;\n }\n\n .body-pre {\n white-space: pre-wrap;\n word-wrap: break-word;\n font-size: 90%;\n }\n\n a,\n .linked {\n color: var(--color-link-primary);\n cursor: pointer;\n }\n\n a:hover,\n .linked:hover {\n text-decoration: underline;\n color: var(--color-link-primary-hover);\n }\n\n temba-icon.error {\n --icon-color: var(--color-error);\n }\n\n .delivery-error {\n --icon-color: var(--color-error);\n margin-right: 0.25em;\n }\n\n .flow {\n --icon-color: #ddd;\n background: #fff;\n width: 18px;\n height: 18px;\n padding-top: 4px;\n padding-left: 9px;\n border: 0px solid #f3f3f3;\n }\n\n .assigned {\n color: #777;\n max-width: 300px;\n margin-left: auto;\n margin-right: auto;\n display: flex;\n flex-direction: column;\n align-items: center;\n margin-bottom: 10px;\n }\n\n .assigned .attn {\n color: #777;\n }\n\n .attachments {\n display: flex;\n flex-wrap: wrap;\n margin: -0.2em;\n }\n\n .attachment {\n flex: 1 0 45%;\n border-top: 0.05em solid transparent;\n border-left: 0.05em solid transparent;\n margin-top: 0.05em;\n margin-left: 0.05em;\n }\n `;\n};\n\nexport interface EventGroup {\n type: string;\n events: ContactEvent[];\n open: boolean;\n}\n\nexport enum Events {\n MESSAGE_CREATED = 'msg_created',\n MESSAGE_RECEIVED = 'msg_received',\n BROADCAST_CREATED = 'broadcast_created',\n IVR_CREATED = 'ivr_created',\n FLOW_ENTERED = 'flow_entered',\n FLOW_EXITED = 'flow_exited',\n RUN_RESULT_CHANGED = 'run_result_changed',\n CONTACT_FIELD_CHANGED = 'contact_field_changed',\n CONTACT_GROUPS_CHANGED = 'contact_groups_changed',\n CONTACT_NAME_CHANGED = 'contact_name_changed',\n CONTACT_URNS_CHANGED = 'contact_urns_changed',\n CAMPAIGN_FIRED = 'campaign_fired',\n CHANNEL_EVENT = 'channel_event',\n CONTACT_LANGUAGE_CHANGED = 'contact_language_changed',\n WEBHOOK_CALLED = 'webhook_called',\n AIRTIME_TRANSFERRED = 'airtime_transferred',\n CALL_STARTED = 'call_started',\n EMAIL_SENT = 'email_sent',\n INPUT_LABELS_ADDED = 'input_labels_added',\n NOTE_CREATED = 'note_created',\n TICKET_ASSIGNED = 'ticket_assigned',\n TICKET_NOTE_ADDED = 'ticket_note_added',\n TICKET_CLOSED = 'ticket_closed',\n TICKET_OPENED = 'ticket_opened',\n TICKET_REOPENED = 'ticket_reopened',\n OPTIN_REQUESTED = 'optin_requested',\n ERROR = 'error',\n FAILURE = 'failure',\n}\n\nexport interface ContactEvent {\n type: string;\n created_on: string;\n}\n\nexport interface ChannelEvent extends ContactEvent {\n channel_event_type: string;\n duration: number;\n\n event: {\n type: string;\n channel: { uuid: string; name: string };\n duration?: number;\n optin?: {\n uuid: string;\n name: string;\n };\n };\n}\n\nexport interface ContactLanguageChangedEvent extends ContactEvent {\n language: string;\n step_uuid: string;\n session_uuid: string;\n}\n\nexport interface OptinRequestedEvent extends ContactEvent {\n optin: {\n uuid: string;\n name: string;\n };\n}\n\nexport interface MsgEvent extends ContactEvent {\n msg: Msg;\n status: string;\n failed_reason?: string;\n failed_reason_display?: string;\n logs_url: string;\n msg_type: string;\n recipient_count?: number;\n created_by?: User;\n optin?: ObjectReference;\n}\n\nexport interface FlowEvent extends ContactEvent {\n flow: ObjectReference;\n status: string;\n}\n\nexport interface EmailSentEvent extends ContactEvent {\n to: string[];\n subject: string;\n body: string;\n}\n\nexport interface URNsChangedEvent extends ContactEvent {\n urns: string[];\n}\n\nexport interface TicketEvent extends ContactEvent {\n note?: string;\n assignee?: User;\n ticket: {\n uuid: string;\n body: string;\n topic?: ObjectReference;\n closed_on?: string;\n opened_on?: string;\n };\n created_by?: User;\n}\n\nexport interface LabelsAddedEvent extends ContactEvent {\n labels: ObjectReference[];\n}\n\nexport interface NameChangedEvent extends ContactEvent {\n name: string;\n}\n\nexport interface UpdateFieldEvent extends ContactEvent {\n field: { key: string; name: string };\n value: { text: string };\n}\n\nexport interface ErrorMessageEvent extends ContactEvent {\n text: string;\n}\n\nexport interface UpdateResultEvent extends ContactEvent {\n name: string;\n value: string;\n category: string;\n input: string;\n}\n\nexport interface ContactGroupsEvent extends ContactEvent {\n groups_added: ObjectReference[];\n groups_removed: ObjectReference[];\n}\n\nexport interface WebhookEvent extends ContactEvent {\n status: string;\n status_code: number;\n elapsed_ms: number;\n logs_url: string;\n url: string;\n}\n\nexport interface AirtimeTransferredEvent extends ContactEvent {\n sender: string;\n recipient: string;\n currency: string;\n desired_amount: string;\n actual_amount: string;\n logs_url: string;\n}\n\nexport type CallStartedEvent = ContactEvent;\nexport interface CampaignFiredEvent extends ContactEvent {\n campaign: { uuid: string; id: number; name: string };\n campaign_event: {\n id: number;\n offset_display: string;\n relative_to: { key: string; name: string };\n };\n fired_result: string;\n}\n\nexport interface ContactHistoryPage {\n has_older: boolean;\n recent_only: boolean;\n next_before: number;\n next_after: number;\n start_date: Date;\n events: ContactEvent[];\n}\n\nexport const getEventGroupType = (event: ContactEvent, ticket: string) => {\n if (!event) {\n return 'messages';\n }\n\n switch (event.type) {\n case Events.TICKET_ASSIGNED:\n case Events.TICKET_OPENED:\n case Events.TICKET_CLOSED:\n case Events.TICKET_REOPENED:\n if (!ticket) {\n return 'verbose';\n }\n\n if ((event as TicketEvent).ticket.uuid === ticket) {\n return 'tickets';\n }\n\n break;\n case Events.FLOW_ENTERED:\n case Events.FLOW_EXITED:\n return 'flows';\n case Events.BROADCAST_CREATED:\n case Events.MESSAGE_CREATED:\n case Events.MESSAGE_RECEIVED:\n case Events.IVR_CREATED:\n case Events.TICKET_NOTE_ADDED:\n case Events.NOTE_CREATED:\n return 'messages';\n }\n return 'verbose';\n};\n\nexport const renderAttachment = (attachment: string): TemplateResult => {\n const idx = attachment.indexOf(':');\n const attType = attachment.substr(0, idx);\n const url = attachment.substr(idx + 1);\n const [mediaType, ext] = attType.split('/', 2);\n\n let inner = null;\n if (mediaType === 'image') {\n inner = html`\n \n `;\n } else if (ext === 'pdf') {\n return html``;\n } else if (mediaType === 'video') {\n return html`\n \n `;\n } else if (mediaType === 'audio') {\n return html`\n ${url}\n `;\n } else if (attType === 'geo') {\n const [lat, long] = url.split(',');\n const latFloat = parseFloat(lat);\n const longFloat = parseFloat(long);\n const geo = `${lat}000000%2C${long}000000`;\n\n return html` `;\n } else {\n return html`
    \n \n
    Attachment ${ext}
    \n
    `;\n }\n\n return html`
    ${inner}
    `;\n};\n\nexport const renderMsgEvent = (event: MsgEvent): TemplateResult => {\n const isInbound = event.type === Events.MESSAGE_RECEIVED;\n const isError = event.status === 'E';\n const isFailure = event.status === 'F';\n\n // summary items which appear under the message bubble\n const summary: TemplateResult[] = [];\n\n if (event.logs_url) {\n summary.push(html`
    \n \n
    `);\n } else if (isError) {\n summary.push(\n html``\n );\n } else if (isFailure) {\n summary.push(\n html``\n );\n }\n\n if (event.type == 'broadcast_created') {\n summary.push(html``);\n\n if (event.recipient_count > 1) {\n summary.push(\n html`
    ${event.recipient_count} contacts
    `\n );\n }\n summary.push(html`
    `);\n }\n\n if (event.optin) {\n summary.push(\n html`
    ${event.optin.name}
    \n
    `\n );\n }\n\n if (event.status === 'Q') {\n summary.push(html`
    Queued
    `);\n }\n\n summary.push(\n html``\n );\n\n return html`\n
    \n \n ${event.msg.text\n ? html`
    ${event.msg.text}
    `\n : null}\n ${event.msg.attachments\n ? html`
    \n ${event.msg.attachments.map(\n attachment =>\n html`
    \n ${renderAttachment(attachment)}\n
    `\n )}\n
    `\n : null}\n
    \n\n ${!event.msg.text && !event.msg.attachments && !event.optin\n ? html`
    Unsupported Message
    `\n : null}\n\n \n
    \n ${summary}\n \n \n\n ${!isInbound && event.created_by\n ? html``\n : null}\n `;\n};\n\nexport const renderFlowEvent = (event: FlowEvent): TemplateResult => {\n let verb = 'Interrupted';\n let icon = Icon.flow_interrupted;\n\n if (event.status !== 'I') {\n if (event.type === Events.FLOW_ENTERED) {\n verb = 'Started';\n icon = Icon.flow;\n } else {\n verb = 'Completed';\n icon = Icon.flow;\n }\n }\n\n return html`\n \n
    \n ${verb}\n \n ${event.flow.name}\n \n
    \n `;\n};\n\nexport const renderResultEvent = (event: UpdateResultEvent): TemplateResult => {\n if (event.name.startsWith('_')) {\n return null;\n }\n return html`\n \n
    \n Updated\n
    ${event.name}
    \n to\n
    ${event.value}
    \n ${event.category\n ? html`with category\n
    ${event.category}
    `\n : null}\n
    \n `;\n};\n\nexport const renderUpdateEvent = (event: UpdateFieldEvent): TemplateResult => {\n return html`\n \n
    \n ${event.value\n ? html`Updated\n
    ${event.field.name}
    \n to\n
    ${event.value.text}
    `\n : html`Cleared\n
    ${event.field.name}
    `}\n
    \n `;\n};\n\nexport const renderNameChanged = (event: NameChangedEvent): TemplateResult => {\n return html`\n \n
    \n Updated\n
    Name
    \n to\n
    ${event.name}
    \n
    \n `;\n};\n\nexport const renderContactURNsChanged = (\n event: URNsChangedEvent\n): TemplateResult => {\n return html`\n \n
    \n Updated\n
    URNs
    \n to\n ${oxfordFn(\n event.urns,\n (urn: string) =>\n html`
    ${urn.split(':')[1].split('?')[0]}
    `\n )}\n
    \n \n `;\n};\n\nexport const renderEmailSent = (event: EmailSentEvent): TemplateResult => {\n return html`\n \n
    \n Email sent to\n
    ${oxford(event.to, 'and')}
    \n with subject\n
    ${event.subject}
    \n
    \n `;\n};\n\nexport const renderLabelsAdded = (event: LabelsAddedEvent): TemplateResult => {\n return html`\n \n
    \n Message labeled with\n
    ${oxfordNamed(event.labels, 'and')}
    \n
    \n `;\n};\n\nexport const renderNoteCreated = (event: TicketEvent): TemplateResult => {\n return html`
    \n
    \n
    ${event.note}
    \n
    \n
    \n \n
    \n
    \n \n
    `;\n};\n\nexport const renderTicketAction = (\n event: TicketEvent,\n action: string,\n grouped: boolean\n): TemplateResult => {\n if (grouped) {\n return html`
    \n \n
    \n ${getDisplayName(event.created_by)} ${action} a\n \n ticket\n \n
    \n
    `;\n }\n\n return html`\n
    \n
    \n ${event.created_by\n ? html` ${getDisplayName(event.created_by)} ${action} this ticket `\n : html` This ticket was ${action} `}\n
    \n
    \n \n
    \n
    \n `;\n};\n\nexport const renderTicketAssigned = (event: TicketEvent): TemplateResult => {\n return html`\n
    \n
    \n ${event.assignee\n ? event.assignee.id === event.created_by.id\n ? html`${getDisplayName(event.created_by)} took this ticket`\n : html`${getDisplayName(event.created_by)} assigned this ticket to\n
    ${getDisplayName(event.assignee)}
    `\n : html`${getDisplayName(event.created_by)} unassigned this ticket`}\n
    \n
    \n \n
    \n
    \n `;\n};\n\nexport const renderTicketOpened = (\n event: TicketEvent,\n handleClose: (uuid: string) => void,\n grouped: boolean\n): TemplateResult => {\n if (grouped) {\n return html`
    \n \n
    \n ${event.ticket.topic.name}\n ticket\n was opened\n
    \n
    `;\n } else {\n return html`\n
    \n
    \n ${getDisplayName(event.created_by)} opened this ticket\n
    \n
    \n \n
    \n
    \n `;\n }\n};\n\nexport const renderErrorMessage = (\n event: ErrorMessageEvent\n): TemplateResult => {\n return html`\n \n
    \n ${event.text}\n ${event.type === Events.FAILURE\n ? html`
    Run ended prematurely, check the flow design.
    `\n : null}\n
    \n `;\n};\n\nexport const renderWebhookEvent = (event: WebhookEvent): TemplateResult => {\n return html`\n \n \n
    \n ${event.status === 'success'\n ? html`Successfully called ${event.url}`\n : html`Failed to call ${event.url}`}\n
    \n \n `;\n};\n\nexport const renderAirtimeTransferredEvent = (\n event: AirtimeTransferredEvent\n): TemplateResult => {\n if (parseFloat(event.actual_amount) === 0) {\n return html`\n
    Airtime transfer failed
    `;\n }\n\n return html`\n
    \n Transferred\n
    ${event.actual_amount} ${event.currency}
    \n of airtime\n
    `;\n};\n\nexport const renderCallStartedEvent = (): TemplateResult => {\n return html`\n
    Call Started
    `;\n};\n\nexport const renderContactLanguageChangedEvent = (\n event: ContactLanguageChangedEvent\n): TemplateResult => {\n return html`\n
    \n Language updated to ${event.language}\n
    `;\n};\n\nexport const renderOptinRequested = (\n event: OptinRequestedEvent\n): TemplateResult => {\n return html`\n
    \n Requested opt-in for ${event.optin.name}\n
    `;\n};\n\nexport const renderChannelEvent = (event: ChannelEvent): TemplateResult => {\n let eventMessage: string | TemplateResult = '';\n let icon = Icon.call;\n\n if (event.event.type === 'mt_miss') {\n eventMessage = 'Missed outgoing call';\n icon = Icon.call_missed;\n } else if (event.event.type === 'mo_miss') {\n eventMessage = 'Missed incoming call';\n icon = Icon.call_missed;\n } else if (event.event.type === 'new_conversation') {\n eventMessage = 'Started Conversation';\n icon = Icon.event;\n } else if (event.channel_event_type === 'welcome_message') {\n eventMessage = 'Welcome Message Sent';\n icon = Icon.event;\n } else if (event.event.type === 'referral') {\n eventMessage = 'Referred';\n icon = Icon.event;\n } else if (event.event.type === 'follow') {\n eventMessage = 'Followed';\n icon = Icon.event;\n } else if (event.event.type === 'stop_contact') {\n eventMessage = 'Stopped';\n icon = Icon.contact_stopped;\n } else if (event.event.type === 'mt_call') {\n eventMessage = 'Outgoing Phone Call';\n } else if (event.event.type == 'mo_call') {\n eventMessage = 'Incoming Phone call';\n } else if (event.event.type == 'optin') {\n eventMessage = html`Opted in to\n ${event.event.optin?.name}`;\n icon = Icon.optin;\n } else if (event.event.type == 'optout') {\n eventMessage = html`Opted out of\n ${event.event.optin?.name}`;\n icon = Icon.optout;\n }\n\n return html`\n
    ${eventMessage}
    `;\n};\n\nexport const renderCampaignFiredEvent = (\n event: CampaignFiredEvent\n): TemplateResult => {\n return html`\n
    \n Campaign\n ${event.campaign.name}\n ${event.fired_result === 'S' ? 'skipped' : 'triggered'}\n \n ${event.campaign_event.offset_display}\n ${event.campaign_event.relative_to.name}\n
    `;\n};\n\nexport const renderContactGroupsEvent = (\n event: ContactGroupsEvent\n): TemplateResult => {\n const groups = event.groups_added || event.groups_removed;\n const added = !!event.groups_added;\n return html`\n \n
    \n ${added ? 'Added to' : 'Removed from'}\n ${oxfordFn(\n groups,\n (group: ObjectReference) =>\n html`${group.name}`\n )}\n ${event.type === Events.FAILURE\n ? html`
    Run ended prematurely, check the flow design.
    `\n : null}\n
    \n `;\n};\n","import { css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { html, TemplateResult } from 'lit-html';\nimport { Contact, CustomEventType, Msg, Ticket } from '../interfaces';\nimport { RapidElement } from '../RapidElement';\nimport { Asset, getAssets, getClasses, postJSON, throttle } from '../utils';\n\nimport {\n AirtimeTransferredEvent,\n CampaignFiredEvent,\n ChannelEvent,\n ContactEvent,\n ContactGroupsEvent,\n ContactHistoryPage,\n ContactLanguageChangedEvent,\n EmailSentEvent,\n ErrorMessageEvent,\n EventGroup,\n Events,\n FlowEvent,\n getEventGroupType,\n getEventStyles,\n LabelsAddedEvent,\n MsgEvent,\n NameChangedEvent,\n OptinRequestedEvent,\n renderAirtimeTransferredEvent,\n renderCallStartedEvent,\n renderCampaignFiredEvent,\n renderChannelEvent,\n renderContactGroupsEvent,\n renderContactLanguageChangedEvent,\n renderContactURNsChanged,\n renderEmailSent,\n renderErrorMessage,\n renderFlowEvent,\n renderLabelsAdded,\n renderMsgEvent,\n renderNameChanged,\n renderNoteCreated,\n renderOptinRequested,\n renderResultEvent,\n renderTicketAction,\n renderTicketAssigned,\n renderTicketOpened,\n renderUpdateEvent,\n renderWebhookEvent,\n TicketEvent,\n UpdateFieldEvent,\n UpdateResultEvent,\n URNsChangedEvent,\n WebhookEvent,\n} from './events';\nimport {\n fetchContactHistory,\n MAX_CHAT_REFRESH,\n MIN_CHAT_REFRESH,\n SCROLL_THRESHOLD,\n} from './helpers';\nimport { Lightbox } from '../lightbox/Lightbox';\nimport { Store } from '../store/Store';\n\n// when images load, make sure we are on the bottom of the scroll window if necessary\nexport const loadHandler = function (event) {\n const target = event.target as HTMLElement;\n const events = this.host.getEventsPane();\n if (target.tagName == 'IMG') {\n if (!this.host.showMessageAlert) {\n if (\n events.scrollTop > target.offsetTop - 1000 &&\n target.offsetTop > events.scrollHeight - 500\n ) {\n this.host.scrollToBottom();\n }\n }\n }\n};\n\nexport class ContactHistory extends RapidElement {\n public httpComplete: Promise;\n private store: Store;\n\n public constructor() {\n super();\n }\n\n connectedCallback() {\n super.connectedCallback();\n this.shadowRoot.addEventListener('load', loadHandler, true);\n this.store = document.querySelector('temba-store') as Store;\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this.shadowRoot.removeEventListener('load', loadHandler, true);\n }\n\n private getTicketForEvent(event: TicketEvent) {\n return this.getTicket((event as TicketEvent).ticket.uuid);\n }\n\n private getTicket(uuid: string) {\n return (this.tickets || []).find(ticket => ticket.uuid === uuid);\n }\n\n static get styles() {\n return css`\n ${getEventStyles()}\n\n .wrapper {\n border: 0px solid green;\n display: flex;\n flex-direction: column;\n align-items: items-stretch;\n flex-grow: 1;\n min-height: 0;\n }\n\n .events {\n overflow-y: scroll;\n overflow-x: hidden;\n background: #fff;\n display: flex;\n flex-direction: column;\n flex-grow: 1;\n min-height: 0;\n padding-top: 3em;\n padding-bottom: 1em;\n }\n\n temba-loading {\n align-self: center;\n margin-top: 0.025em;\n position: absolute;\n z-index: 250;\n padding-top: 1em;\n }\n\n .new-messages-container {\n display: flex;\n z-index: 1;\n background: pink;\n margin-bottom: 0px;\n }\n\n .new-messages {\n pointer-events: none;\n margin: 0 auto;\n margin-top: 0em;\n margin-bottom: -2.5em;\n padding: 0.25em 1em;\n border-radius: var(--curvature);\n background: var(--color-primary-dark);\n color: var(--color-text-light);\n opacity: 0;\n cursor: pointer;\n transition: all var(--transition-speed) ease-in-out;\n box-shadow: rgb(0 0 0 / 15%) 0px 3px 3px 0px;\n }\n\n .new-messages.expanded {\n margin-top: -2.5em;\n margin-bottom: 0.5em;\n pointer-events: auto;\n opacity: 1;\n pointer: cursor;\n }\n\n .scroll-title {\n display: flex;\n flex-direction: column;\n z-index: 2;\n border-top-left-radius: var(--curvature);\n overflow: hidden;\n box-shadow: 0px 3px 3px 0px rgba(0, 0, 0, 0.15);\n background: rgb(240, 240, 240);\n padding: 1em 1.2em;\n font-size: 1.2em;\n font-weight: 400;\n }\n\n .attachment img {\n cursor: pointer;\n }\n `;\n }\n\n @property({ type: Object })\n contact: Contact;\n\n @property({ type: String })\n uuid: string;\n\n @property({ type: String })\n agent: string;\n\n @property({ type: Array })\n eventGroups: EventGroup[] = [];\n\n @property({ type: Boolean })\n refreshing = false;\n\n @property({ type: Boolean })\n fetching = false;\n\n @property({ type: Boolean })\n complete = false;\n\n @property({ type: String })\n endpoint: string;\n\n @property({ type: Boolean })\n debug = false;\n\n @property({ type: Boolean })\n showMessageAlert = false;\n\n @property({ attribute: false, type: Object })\n mostRecentEvent: ContactEvent;\n\n @property({ type: String })\n ticket: string = null;\n\n @property({ type: String })\n endDate: string = null;\n\n @property({ type: Array })\n tickets: Ticket[] = null;\n\n ticketEvents: { [uuid: string]: TicketEvent } = {};\n\n nextBefore: number;\n nextAfter: number;\n lastHeight = 0;\n lastRefreshAdded: number;\n refreshTimeout: any = null;\n empty = false;\n\n public firstUpdated(changedProperties: Map) {\n super.firstUpdated(changedProperties);\n this.handleClose = this.handleClose.bind(this);\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n // fire an event if we get a new event\n if (\n changedProperties.has('mostRecentEvent') &&\n changedProperties.get('mostRecentEvent') &&\n this.mostRecentEvent\n ) {\n this.fireCustomEvent(CustomEventType.Refreshed);\n }\n\n if (changedProperties.has('endDate')) {\n if (this.refreshTimeout && this.endDate) {\n window.clearTimeout(this.refreshTimeout);\n }\n }\n\n // if we don't have an endpoint infer one\n if (changedProperties.has('uuid')) {\n if (this.uuid == null) {\n this.reset();\n } else {\n const endpoint = `/contact/history/${this.uuid}/?_format=json`;\n\n if (this.endpoint !== endpoint) {\n this.reset();\n\n if (this.endDate) {\n const before = new Date(this.endDate);\n this.nextBefore = before.getTime() * 1000 + 1000;\n }\n\n this.endpoint = endpoint;\n this.refreshTickets();\n }\n }\n }\n\n if (changedProperties.has('ticket')) {\n this.endpoint = null;\n this.requestUpdate('uuid');\n }\n\n if (\n changedProperties.has('refreshing') &&\n this.refreshing &&\n this.endpoint &&\n !this.endDate\n ) {\n const after = (this.getLastEventTime() - 1) * 1000;\n let forceOpen = false;\n\n fetchContactHistory(false, this.endpoint, this.ticket, null, after)\n .then((results: ContactHistoryPage) => {\n if (results.events && results.events.length > 0) {\n this.updateMostRecent(results.events[0]);\n }\n\n // keep track of any ticket events\n results.events.forEach((event: ContactEvent) => {\n if (event.type === Events.TICKET_OPENED) {\n const ticketEvent = event as TicketEvent;\n this.ticketEvents[ticketEvent.ticket.uuid] = ticketEvent;\n }\n });\n\n const fetchedEvents = results.events.reverse();\n\n // dedupe any events we get from the server\n // TODO: perhaps make this a little less crazy\n let removed = 0;\n this.eventGroups.forEach(g => {\n const before = g.events.length;\n g.events = g.events.filter(\n prev =>\n !fetchedEvents.find(fetched => {\n return (\n prev.created_on == fetched.created_on &&\n prev.type === fetched.type\n );\n })\n );\n removed += before - g.events.length;\n });\n\n this.lastRefreshAdded = fetchedEvents.length - removed;\n\n // reflow our most recent event group in case it merges with our new groups\n const previousGroups = [...this.eventGroups];\n\n if (this.eventGroups.length > 0) {\n const sliced = previousGroups.splice(\n previousGroups.length - 1,\n 1\n )[0];\n\n forceOpen = sliced.open;\n fetchedEvents.splice(0, 0, ...sliced.events);\n }\n\n const grouped = this.getEventGroups(fetchedEvents);\n if (grouped.length) {\n if (forceOpen) {\n grouped[grouped.length - 1].open = forceOpen;\n }\n this.eventGroups = [...previousGroups, ...grouped];\n }\n this.refreshing = false;\n this.scheduleRefresh();\n })\n .catch(() => {\n this.refreshing = false;\n this.scheduleRefresh();\n });\n }\n\n if (changedProperties.has('fetching') && this.fetching) {\n if (!this.nextBefore) {\n this.nextBefore = new Date().getTime() * 1000 - 1000;\n }\n\n this.httpComplete = fetchContactHistory(\n this.empty,\n this.endpoint,\n this.ticket,\n this.nextBefore,\n this.nextAfter\n ).then((results: ContactHistoryPage) => {\n // see if we have a new event\n if (results.events && results.events.length > 0) {\n this.updateMostRecent(results.events[0]);\n\n // keep track of any ticket events\n results.events.forEach((event: ContactEvent) => {\n if (event.type === Events.TICKET_OPENED) {\n const ticketEvent = event as TicketEvent;\n this.ticketEvents[ticketEvent.ticket.uuid] = ticketEvent;\n }\n });\n }\n\n let forceOpen = false;\n const fetchedEvents = results.events ? results.events.reverse() : [];\n\n // reflow our last event group in case it merges with our new groups\n if (this.eventGroups.length > 0) {\n const sliced = this.eventGroups.splice(0, 1)[0];\n forceOpen = sliced.open;\n fetchedEvents.push(...sliced.events);\n }\n\n const grouped = this.getEventGroups(fetchedEvents);\n if (grouped.length) {\n if (forceOpen) {\n grouped[grouped.length - 1].open = forceOpen;\n }\n\n this.eventGroups = [...grouped, ...this.eventGroups];\n }\n\n if (results.next_before === this.nextBefore) {\n this.complete = true;\n }\n\n this.nextBefore = results.next_before;\n this.nextAfter = results.next_after;\n this.fetching = false;\n this.empty = false;\n });\n }\n\n if (changedProperties.has('refreshing') && !this.refreshing) {\n if (this.lastRefreshAdded > 0) {\n const events = this.getEventsPane();\n\n // if we are near the bottom, push us to the bottom to show new stuff\n if (this.lastHeight > 0) {\n const addedHeight = events.scrollHeight - this.lastHeight;\n\n const distanceFromBottom =\n events.scrollHeight -\n events.scrollTop -\n addedHeight -\n events.clientHeight;\n\n if (distanceFromBottom < 500) {\n this.scrollToBottom();\n } else {\n this.showMessageAlert = true;\n }\n }\n\n if (this.eventGroups.length > 0) {\n this.lastHeight = events.scrollHeight;\n }\n }\n }\n\n if (\n changedProperties.has('fetching') &&\n !this.fetching &&\n changedProperties.get('fetching') !== undefined\n ) {\n const events = this.getEventsPane();\n\n if (this.lastHeight && events.scrollHeight > this.lastHeight) {\n const scrollTop =\n events.scrollTop + events.scrollHeight - this.lastHeight;\n events.scrollTop = scrollTop;\n }\n\n // scroll to the bottom if it's our first fetch\n if (!this.lastHeight) {\n this.scrollToBottom();\n }\n\n // don't record our scroll height until we have history\n if (this.eventGroups.length > 0) {\n this.lastHeight = events.scrollHeight;\n }\n }\n\n if (changedProperties.has('endpoint') && this.endpoint) {\n this.fetching = true;\n this.empty = true;\n }\n }\n\n private refreshTickets() {\n if (this.ticket) {\n let url = `/api/v2/tickets.json?contact=${this.uuid}`;\n if (this.ticket) {\n url = `${url}&ticket=${this.ticket}`;\n }\n\n getAssets(url).then((tickets: Ticket[]) => {\n this.tickets = tickets.reverse();\n });\n }\n }\n\n public getEventsPane() {\n return this.getDiv('.events');\n }\n\n public scrollToBottom(smooth = false) {\n const events = this.getEventsPane();\n events.scrollTo({\n top: events.scrollHeight,\n behavior: smooth ? 'smooth' : 'auto',\n });\n this.showMessageAlert = false;\n\n window.setTimeout(() => {\n events.scrollTo({\n top: events.scrollHeight,\n behavior: smooth ? 'smooth' : 'auto',\n });\n }, 0);\n }\n\n public refresh(): void {\n this.scheduleRefresh(500);\n }\n\n private getEventGroups(events: ContactEvent[]): EventGroup[] {\n const grouped: EventGroup[] = [];\n let eventGroup: EventGroup = undefined;\n for (const event of events) {\n const currentEventGroupType = getEventGroupType(event, this.ticket);\n // see if we need a new event group\n if (!eventGroup || eventGroup.type !== currentEventGroupType) {\n // we have a new type, save our last group\n if (eventGroup) {\n grouped.push(eventGroup);\n }\n eventGroup = {\n open: false,\n events: [event],\n type: currentEventGroupType,\n };\n } else {\n // our event matches the current group, stuff it in there\n eventGroup.events.push(event);\n }\n }\n\n if (eventGroup && eventGroup.events.length > 0) {\n grouped.push(eventGroup);\n }\n return grouped;\n }\n\n private scheduleRefresh(wait = -1) {\n if (this.endDate) {\n return;\n }\n\n let refreshWait = wait;\n\n if (wait === -1) {\n const lastEventTime = this.getLastEventTime();\n refreshWait = Math.max(\n Math.min((new Date().getTime() - lastEventTime) / 2, MAX_CHAT_REFRESH),\n MIN_CHAT_REFRESH\n );\n }\n\n // cancel any outstanding timeout\n if (wait > -1 && this.refreshTimeout) {\n window.clearTimeout(this.refreshTimeout);\n }\n\n this.refreshTimeout = window.setTimeout(() => {\n if (this.refreshing) {\n this.scheduleRefresh();\n this.refreshing = false;\n } else {\n this.refreshing = true;\n }\n }, refreshWait);\n }\n\n private reset() {\n this.endpoint = null;\n this.tickets = null;\n this.ticketEvents = {};\n this.eventGroups = [];\n this.fetching = false;\n this.complete = false;\n this.nextBefore = null;\n this.nextAfter = null;\n this.lastHeight = 0;\n }\n\n private handleEventGroupShow(event: MouseEvent) {\n const grouping = event.currentTarget as HTMLDivElement;\n const groupIndex = parseInt(grouping.getAttribute('data-group-index'));\n const eventGroup =\n this.eventGroups[this.eventGroups.length - groupIndex - 1];\n eventGroup.open = true;\n this.requestUpdate('eventGroups');\n }\n\n private handleEventGroupHide(event: MouseEvent) {\n event.preventDefault();\n event.stopPropagation();\n\n const grouping = event.currentTarget as HTMLDivElement;\n const groupIndex = parseInt(grouping.getAttribute('data-group-index'));\n const eventGroup =\n this.eventGroups[this.eventGroups.length - groupIndex - 1];\n\n eventGroup.open = false;\n\n this.requestUpdate('eventGroups');\n }\n\n private handleScroll() {\n const events = this.getEventsPane();\n if (events.scrollTop <= SCROLL_THRESHOLD) {\n if (this.eventGroups.length > 0 && !this.fetching && !this.complete) {\n this.fetching = true;\n }\n }\n }\n\n private updateMostRecent(newEvent: ContactEvent) {\n if (\n !this.mostRecentEvent ||\n this.mostRecentEvent.type !== newEvent.type ||\n this.mostRecentEvent.created_on !== newEvent.created_on\n ) {\n this.mostRecentEvent = newEvent;\n }\n }\n\n private getLastEventTime(): number {\n const mostRecentGroup = this.eventGroups[this.eventGroups.length - 1];\n if (mostRecentGroup) {\n const mostRecentEvent =\n mostRecentGroup.events[mostRecentGroup.events.length - 1];\n return new Date(mostRecentEvent.created_on).getTime();\n }\n return 0;\n }\n\n public renderEvent(event: ContactEvent): any {\n switch (event.type) {\n case Events.IVR_CREATED:\n case Events.MESSAGE_CREATED:\n case Events.MESSAGE_RECEIVED:\n case Events.BROADCAST_CREATED:\n if ((event as MsgEvent).created_by) {\n (event as MsgEvent).created_by = this.store.getUser(\n (event as MsgEvent).created_by.email\n );\n }\n\n return renderMsgEvent(event as MsgEvent);\n\n case Events.FLOW_ENTERED:\n case Events.FLOW_EXITED:\n return renderFlowEvent(event as FlowEvent);\n\n case Events.RUN_RESULT_CHANGED:\n return renderResultEvent(event as UpdateResultEvent);\n\n case Events.CONTACT_FIELD_CHANGED:\n return renderUpdateEvent(event as UpdateFieldEvent);\n\n case Events.CONTACT_NAME_CHANGED:\n return renderNameChanged(event as NameChangedEvent);\n\n case Events.CONTACT_URNS_CHANGED:\n return renderContactURNsChanged(event as URNsChangedEvent);\n\n case Events.EMAIL_SENT:\n return renderEmailSent(event as EmailSentEvent);\n\n case Events.INPUT_LABELS_ADDED:\n return renderLabelsAdded(event as LabelsAddedEvent);\n\n case Events.TICKET_OPENED: {\n return renderTicketAction(event as TicketEvent, 'opened', !this.ticket);\n }\n case Events.TICKET_NOTE_ADDED:\n return renderNoteCreated(event as TicketEvent);\n\n case Events.TICKET_ASSIGNED:\n return renderTicketAssigned(event as TicketEvent);\n case Events.TICKET_REOPENED: {\n return renderTicketAction(\n event as TicketEvent,\n 'reopened',\n !this.ticket\n );\n }\n case Events.TICKET_CLOSED:\n return renderTicketAction(event as TicketEvent, 'closed', !this.ticket);\n\n case Events.ERROR:\n case Events.FAILURE:\n return renderErrorMessage(event as ErrorMessageEvent);\n case Events.CONTACT_GROUPS_CHANGED:\n return renderContactGroupsEvent(event as ContactGroupsEvent);\n case Events.WEBHOOK_CALLED:\n return renderWebhookEvent(event as WebhookEvent);\n case Events.AIRTIME_TRANSFERRED:\n return renderAirtimeTransferredEvent(event as AirtimeTransferredEvent);\n case Events.CALL_STARTED:\n return renderCallStartedEvent();\n case Events.CAMPAIGN_FIRED:\n return renderCampaignFiredEvent(event as CampaignFiredEvent);\n case Events.CHANNEL_EVENT:\n return renderChannelEvent(event as ChannelEvent);\n case Events.CONTACT_LANGUAGE_CHANGED:\n return renderContactLanguageChangedEvent(\n event as ContactLanguageChangedEvent\n );\n case Events.OPTIN_REQUESTED:\n return renderOptinRequested(event as OptinRequestedEvent);\n }\n\n return html`\n
    ${event.type}
    `;\n }\n\n private handleClose(uuid: string) {\n this.httpComplete = postJSON(`/api/v2/ticket_actions.json`, {\n tickets: [uuid],\n action: 'close',\n })\n .then(() => {\n this.refreshTickets();\n this.refresh();\n this.fireCustomEvent(CustomEventType.ContentChanged, {\n ticket: { uuid, status: 'closed' },\n });\n })\n .catch((response: any) => {\n console.error(response);\n });\n }\n\n public checkForAgentAssignmentEvent(agent: string) {\n this.httpComplete = getAssets(\n `/api/v2/tickets.json?uuid=${this.ticket}`\n ).then((assets: Asset[]) => {\n if (assets.length === 1) {\n const ticket = assets[0] as Ticket;\n if (ticket.assignee && ticket.assignee.email === agent) {\n this.fireCustomEvent(CustomEventType.ContentChanged, {\n ticket: { uuid: this.ticket, assigned: 'self' },\n });\n } else {\n this.fireCustomEvent(CustomEventType.ContentChanged, {\n ticket: {\n uuid: this.ticket,\n assigned: ticket.assignee ? ticket.assignee : null,\n },\n });\n }\n }\n });\n }\n\n public getEventHandlers() {\n return [\n {\n event: 'scroll',\n method: throttle(this.handleScroll, 50),\n },\n ];\n }\n\n /** Check if a ticket event is no longer represented in a session */\n private isPurged(ticket: Ticket): boolean {\n return !this.ticketEvents[ticket.uuid];\n }\n\n private handleEventClicked(event) {\n const ele = event.target as HTMLDivElement;\n if (ele.tagName == 'IMG') {\n // if we have one, show in our lightbox\n const lightbox = document.querySelector('temba-lightbox') as Lightbox;\n if (lightbox) {\n lightbox.showElement(ele);\n }\n }\n }\n\n private renderEventContainer(event: ContactEvent) {\n const renderedEvent = html`\n \n ${this.renderEvent(event)}\n \n ${this.debug ? html`
    ${JSON.stringify(event, null, 2)}
    ` : null}\n `;\n return renderedEvent;\n }\n\n public render(): TemplateResult {\n return html`\n ${\n this.fetching\n ? html``\n : html`
    `\n }\n
    \n ${this.eventGroups.map((eventGroup: EventGroup, index: number) => {\n const grouping = getEventGroupType(eventGroup.events[0], this.ticket);\n const groupIndex = this.eventGroups.length - index - 1;\n\n const classes = getClasses({\n grouping: true,\n [grouping]: true,\n expanded: eventGroup.open,\n });\n return html`
    \n ${grouping === 'verbose'\n ? html`\n ${eventGroup.open\n ? html``\n : html`${eventGroup.events.length}\n ${eventGroup.events.length === 1\n ? html`event`\n : html`events`} `}\n
    `\n : null}\n\n
    \n ${eventGroup.events.map((event: ContactEvent) => {\n if (\n event.type === Events.TICKET_ASSIGNED &&\n (event as TicketEvent).note\n ) {\n const noteEvent = { ...event };\n noteEvent.type = Events.TICKET_NOTE_ADDED;\n\n return html`${this.renderEventContainer(\n noteEvent\n )}${this.renderEventContainer(event)}`;\n } else {\n return this.renderEventContainer(event);\n }\n })}\n
    \n
    `;\n })}\n \n\n ${\n this.contact && this.contact.status === 'active'\n ? html`
    \n {\n this.scrollToBottom(true);\n }}\n class=\"new-messages ${getClasses({\n expanded: this.showMessageAlert,\n })}\"\n >\n New Messages\n
    \n `\n : null\n }\n \n \n `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { RapidElement } from '../RapidElement';\nimport { Store } from '../store/Store';\nimport { fetchResultsPage, ResultsPage } from '../utils';\n\nconst DEFAULT_REFRESH = 10000;\n\nexport class TembaList extends RapidElement {\n @property({ type: Array, attribute: false })\n items: any[] = [];\n\n @property({ type: Object, attribute: false })\n selected: any;\n\n @property({ type: Number })\n cursorIndex = -1;\n\n @property({ type: String })\n endpoint: string;\n\n @property({ type: String })\n nextSelection: any;\n\n @property({ type: Number })\n tabIndex = 1;\n\n @property({ type: String })\n valueKey = 'id';\n\n @property({ type: String })\n value: string;\n\n @property({ type: Boolean })\n loading = false;\n\n @property({ type: Boolean })\n collapsed: boolean;\n\n @property({ type: Boolean })\n hideShadow: boolean;\n\n @property({ type: Boolean })\n paused = false;\n\n @property({ type: Boolean })\n internalFocusDisabled = false;\n\n @property({ attribute: false })\n getNextRefresh: (firstOption: any) => any;\n\n @property({ attribute: false })\n sanitizeOption: (option: any) => any;\n\n @property({ attribute: false })\n renderOption: (option: any, selected: boolean) => TemplateResult;\n\n @property({ attribute: false })\n renderOptionDetail: (option: any, selected: boolean) => TemplateResult;\n\n @property({ attribute: false, type: Object })\n mostRecentItem: any;\n\n // changes to the refresh key force a refresh\n @property({ type: String })\n refreshKey = '0';\n\n reverseRefresh = true;\n\n // our next page from our endpoint\n nextPage: string = null;\n\n pages = 0;\n clearRefreshTimeout: any;\n pending: AbortController[] = [];\n\n store: Store;\n\n // used for testing only\n preserve: boolean;\n\n static get styles() {\n return css`\n temba-options {\n display: block;\n width: 100%;\n flex-grow: 1;\n }\n `;\n }\n\n constructor() {\n super();\n this.store = document.querySelector('temba-store') as Store;\n this.handleSelection.bind(this);\n }\n\n private reset(): void {\n this.selected = null;\n this.nextPage = null;\n this.cursorIndex = -1;\n this.mostRecentItem = null;\n this.items = [];\n }\n\n refreshInterval = null;\n\n public connectedCallback() {\n super.connectedCallback();\n this.refreshInterval = setInterval(() => {\n if (!this.paused) {\n this.refreshKey = 'default_' + new Date().getTime();\n }\n }, DEFAULT_REFRESH);\n }\n\n public disconnectedCallback() {\n clearInterval(this.refreshInterval);\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n if (changedProperties.has('endpoint') && this.endpoint) {\n this.reset();\n this.loading = true;\n this.fetchItems();\n }\n\n if (changedProperties.has('loading')) {\n if (!this.loading) {\n this.fireCustomEvent(CustomEventType.FetchComplete);\n }\n }\n\n if (\n changedProperties.has('refreshKey') &&\n !changedProperties.has('endpoint')\n ) {\n this.refreshTop();\n }\n\n if (changedProperties.has('mostRecentItem') && this.mostRecentItem) {\n this.fireCustomEvent(CustomEventType.Refreshed);\n }\n\n if (changedProperties.has('cursorIndex')) {\n if (this.cursorIndex > -1) {\n this.selected = this.items[this.cursorIndex];\n this.handleSelected(this.selected);\n }\n }\n\n if (changedProperties.has('items')) {\n //\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n public handleSelected(selected: any) {\n const evt = new Event('change', { bubbles: true });\n this.dispatchEvent(evt);\n }\n\n private getValue(obj: any): any {\n if (!obj) {\n return null;\n }\n\n const path = this.valueKey.split('.');\n let current = obj;\n while (path.length > 0) {\n const key = path.shift();\n current = current[key];\n }\n return current;\n }\n\n public setSelection(value: string) {\n const index = this.items.findIndex(item => {\n return this.getValue(item) === value;\n });\n this.cursorIndex = index;\n this.selected = this.items[index];\n const evt = new Event('change', { bubbles: true });\n this.dispatchEvent(evt);\n }\n\n public getItemIndex(value: string) {\n return this.items.findIndex(option => this.getValue(option) === value);\n }\n\n public removeItem(value: string) {\n const index = this.getItemIndex(value);\n this.items.splice(index, 1);\n this.items = [...this.items];\n\n // if we were at the end, move us down\n this.cursorIndex = Math.max(\n 0,\n Math.min(this.items.length - 1, this.cursorIndex - 1)\n );\n\n // request a change even if it is the same, the item is different\n this.requestUpdate('cursorIndex');\n this.requestUpdate('items');\n }\n\n public getSelection(): any {\n return this.selected;\n }\n\n public refresh(): void {\n this.refreshKey = 'requested_' + new Date().getTime();\n }\n\n public setEndpoint(endpoint: string, nextSelection: any = null) {\n this.endpoint = endpoint;\n this.nextSelection = nextSelection;\n }\n\n public getRefreshEndpoint() {\n return this.endpoint;\n }\n\n /**\n * Refreshes the first page, updating any found items in our list\n */\n private async refreshTop(): Promise {\n const refreshEndpoint = this.getRefreshEndpoint();\n if (!refreshEndpoint) {\n return;\n }\n\n // cancel any outstanding requests\n while (this.pending.length > 0) {\n const pending = this.pending.pop();\n pending.abort();\n }\n\n const controller = new AbortController();\n this.pending.push(controller);\n\n const prevItem = this.items[this.cursorIndex];\n\n try {\n const page = await fetchResultsPage(\n this.getRefreshEndpoint(),\n controller\n );\n\n const items = [...this.items];\n // remove any dupes already in our list\n if (page.results) {\n page.results.forEach((newOption: any) => {\n if (this.sanitizeOption) {\n this.sanitizeOption(newOption);\n }\n const newValue = this.getValue(newOption);\n const removeIndex = items.findIndex(\n option => this.getValue(option) === newValue\n );\n\n if (removeIndex > -1) {\n items.splice(removeIndex, 1);\n }\n });\n\n // insert our new items at the front\n let results = page.results;\n if (this.reverseRefresh) {\n results = page.results.reverse();\n }\n const newItems = [...results, ...items];\n\n const topItem = newItems[0];\n if (\n !this.mostRecentItem ||\n JSON.stringify(this.mostRecentItem) !== JSON.stringify(topItem)\n ) {\n this.mostRecentItem = topItem;\n }\n\n if (prevItem) {\n const newItem = newItems[this.cursorIndex];\n const prevValue = this.getValue(prevItem);\n if (prevValue !== this.getValue(newItem)) {\n const newIndex = newItems.findIndex(\n option => this.getValue(option) === prevValue\n );\n this.cursorIndex = newIndex;\n\n // make sure our focused item is visible\n window.setTimeout(() => {\n const options = this.shadowRoot.querySelector('temba-options');\n if (options) {\n const option =\n options.shadowRoot.querySelector('.option.focused');\n option.scrollIntoView({ block: 'end', inline: 'nearest' });\n }\n }, 0);\n }\n }\n\n this.items = newItems;\n }\n } catch (error) {\n console.error(error);\n }\n }\n\n private async fetchItems(): Promise {\n // cancel any outstanding requests\n while (this.pending.length > 0) {\n const pending = this.pending.pop();\n pending.abort();\n }\n\n let endpoint = this.endpoint;\n let pagesToFetch = this.pages || 1;\n let pages = 0;\n let nextPage = null;\n\n let fetchedItems: any[] = [];\n\n while (pagesToFetch > 0 && endpoint) {\n const controller = new AbortController();\n this.pending.push(controller);\n\n try {\n const page = await fetchResultsPage(endpoint, controller);\n\n // sanitize our options if necessary\n if (this.sanitizeOption) {\n page.results.forEach(this.sanitizeOption);\n }\n\n if (page.results) {\n fetchedItems = fetchedItems.concat(page.results);\n }\n\n // save our next pages\n nextPage = page.next;\n endpoint = nextPage;\n pagesToFetch--;\n pages++;\n } catch (error) {\n // aborted\n this.reset();\n console.log(error);\n return;\n }\n\n this.nextPage = nextPage;\n }\n this.pages = pages;\n\n const topItem = fetchedItems[0];\n if (\n !this.mostRecentItem ||\n JSON.stringify(this.mostRecentItem) !== JSON.stringify(topItem)\n ) {\n this.mostRecentItem = topItem;\n }\n\n // see if our cursor needs to move to stay on the same item\n const newItem = fetchedItems[this.cursorIndex];\n\n if (\n !this.nextSelection &&\n this.selected &&\n newItem &&\n this.getValue(newItem) !== this.getValue(this.selected)\n ) {\n const index = fetchedItems.findIndex(item => {\n return this.getValue(item) === this.getValue(this.selected);\n });\n\n // old selection is in the new fetch\n if (index > -1) {\n this.cursorIndex = index;\n }\n // old selection is missing from the new fetch\n else {\n // if our index didn't change, our item still did, fire change\n if (this.cursorIndex === 0) {\n this.requestUpdate('cursorIndex');\n }\n // otherwise select the first item\n else {\n this.cursorIndex = 0;\n }\n }\n }\n\n // save our results\n this.items = fetchedItems;\n this.loading = false;\n this.pending = [];\n\n if (this.nextSelection) {\n this.setSelection(this.nextSelection);\n this.nextSelection = false;\n } else {\n if (this.cursorIndex === -1 && !this.isMobile()) {\n this.cursorIndex = 0;\n }\n }\n\n // TODO: Not sure why this is needed\n // this.requestUpdate('cursorIndex');\n\n if (this.value) {\n this.setSelection(this.value);\n this.value = null;\n } else if (this.isMobile() && !this.selected) {\n this.cursorIndex = -1;\n this.value = null;\n this.selected = null;\n const evt = new Event('change', { bubbles: true });\n this.dispatchEvent(evt);\n }\n\n return Promise.resolve();\n }\n\n private handleScrollThreshold() {\n if (this.nextPage && !this.loading) {\n this.loading = true;\n fetchResultsPage(this.nextPage).then((page: ResultsPage) => {\n if (this.sanitizeOption) {\n page.results.forEach(this.sanitizeOption);\n }\n\n this.items = [...this.items, ...page.results];\n this.nextPage = page.next;\n this.pages++;\n this.loading = false;\n });\n }\n }\n\n public renderHeader(): TemplateResult {\n return null;\n }\n\n public renderFooter(): TemplateResult {\n return null;\n }\n\n public getListStyle() {\n return '';\n }\n\n protected handleSelection(event: CustomEvent) {\n const { selected, index } = event.detail;\n\n this.selected = selected;\n this.cursorIndex = index;\n\n event.stopPropagation();\n event.preventDefault();\n }\n\n public render(): TemplateResult {\n return html`\n ${this.renderHeader()}\n \n \n \n ${this.renderFooter()}\n `;\n }\n}\n","import { html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { TembaList } from './TembaList';\nimport { Contact } from '../interfaces';\nimport { Icon } from '../vectoricon';\n\nexport class TicketList extends TembaList {\n @property({ type: String })\n agent = '';\n\n public getRefreshEndpoint() {\n if (this.items.length > 0) {\n const lastActivity = this.items[0].ticket.last_activity_on;\n return (\n this.endpoint + '?after=' + new Date(lastActivity).getTime() * 1000\n );\n }\n return this.endpoint;\n }\n\n constructor() {\n super();\n\n this.valueKey = 'ticket.uuid';\n this.renderOption = (contact: Contact): TemplateResult => {\n return html`\n \n \n
    \n \n ${contact.name}\n
    \n ${contact.ticket.closed_on\n ? null\n : contact.last_msg\n ? html`\n \n ${\n contact.last_msg.direction === 'I'\n ? html``\n : null\n }\n ${\n contact.last_msg.text\n ? contact.last_msg.text\n : contact.last_msg.attachments\n ? html`
    \n
    \n \n
    \n Attachment\n
    \n
    \n
    `\n : 'Unsupported Message'\n }\n \n `\n : null}\n \n \n
    \n ${!contact.ticket.closed_on && contact.ticket.assignee\n ? html``\n : null}\n
    \n \n \n\n
    \n \n
    \n \n `;\n };\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { ContactStoreElement } from './ContactStoreElement';\nimport { Icon } from '../vectoricon';\nimport { capitalize } from '../utils';\n\nconst STATUS = {\n active: 'Active',\n blocked: 'Blocked',\n stopped: 'Stopped',\n archived: 'Archived',\n};\n\nconst SCHEMES = {\n tel: 'Phone',\n whatsapp: 'WhatsApp',\n fcm: 'Firebase Cloud Messaging',\n twitter: 'Twitter',\n};\n\nexport class ContactDetails extends ContactStoreElement {\n static get styles() {\n return css`\n .urn {\n display: flex;\n padding: 0.4em 1em 0.8em 1em;\n border-bottom: 1px solid #e6e6e6;\n margin-bottom: 0.5em;\n }\n\n .urn .path {\n margin-left: 0.2em;\n }\n\n .wrapper {\n padding-top: 0em;\n }\n\n .groups {\n padding: 0.4em 0.5em 0.6em 0.5em;\n border-bottom: 1px solid #e6e6e6;\n margin-bottom: 0.4em;\n }\n .group {\n margin-right: 0.7em;\n margin-bottom: 0.7em;\n }\n\n .label {\n font-size: 0.8em;\n color: rgb(136, 136, 136);\n margin-left: 0.5em;\n margin-bottom: 0.4em;\n }\n `;\n }\n\n // Not sure if we want to include name here or not, so hold onto this for the moment\n // ${this.data.name ? html``:null}\n\n public render(): TemplateResult {\n if (!this.data) {\n return;\n }\n\n const lang = this.store.getLanguageName(this.data.language);\n\n return html`\n
    \n ${this.data.groups.length > 0\n ? html`
    \n
    Groups
    \n ${this.data.groups.map(group => {\n return html`\n ${group.name}\n `;\n })}\n
    `\n : null}\n ${this.data.urns.map(urn => {\n const parts = urn.split(':');\n let scheme = SCHEMES[parts[0]];\n if (!scheme) {\n scheme = capitalize(parts[0] as any);\n }\n return html``;\n })}\n\n \n ${lang\n ? html``\n : null}\n\n \n \n
    \n `;\n }\n}\n","import { css, html, LitElement, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\n\nexport class Alert extends LitElement {\n static get styles() {\n return css`\n :host {\n display: block;\n }\n\n .temba-alert {\n color: rgba(0, 0, 0, 0.8);\n padding: 0.65rem 1rem;\n border: 1px solid rgba(0, 0, 0, 0.35);\n border-left: 10px solid rgba(0, 0, 0, 0.35);\n border-radius: var(--curvature-widget);\n box-shadow: var(--shadow);\n }\n\n .temba-info {\n background: var(--color-info);\n border-color: var(--color-info-border);\n }\n\n .temba-warning {\n background: var(--color-warning);\n border-color: var(--color-warning-border);\n }\n\n .temba-error {\n border-color: var(--color-error);\n background: #fff;\n border: 1px solid var(--color-error);\n border-left: 10px solid var(--color-error);\n }\n `;\n }\n\n @property({ type: String })\n level = 'info';\n\n public render(): TemplateResult {\n return html`\n
    \n `;\n }\n}\n","import { TemplateResult, html, css, PropertyValueMap } from 'lit';\nimport { unsafeHTML } from 'lit-html/directives/unsafe-html.js';\nimport { property } from 'lit/decorators.js';\nimport { getClasses, postJSON, stopEvent, WebResponse } from '../utils';\nimport { TextInput } from '../textinput/TextInput';\nimport '../alert/Alert';\nimport { Contact, CustomEventType } from '../interfaces';\nimport { FormElement } from '../FormElement';\nimport { Checkbox } from '../checkbox/Checkbox';\nimport { msg } from '@lit/localize';\nimport { OmniOption, Omnibox } from '../omnibox/Omnibox';\n\nconst QUEIT_MILLIS = 2000;\n\ninterface SummaryResponse {\n total: number;\n sample: Contact[];\n query: string;\n fields: { [uuid: string]: { label: string; type: string } };\n error?: string;\n warnings: string[];\n blockers: string[];\n}\n\nexport class ContactSearch extends FormElement {\n static get styles() {\n return css`\n :host {\n color: var(--color-text);\n }\n\n .urn {\n width: 120px;\n }\n\n .name {\n width: 160px;\n }\n\n .date {\n text-align: right;\n }\n\n .field-header {\n font-size: 80%;\n color: var(--color-text-dark);\n }\n\n .field-header.date {\n text-align: right;\n }\n\n .more {\n font-size: 90%;\n padding-top: 5px;\n padding-right: 3px;\n text-align: right;\n width: 100px;\n vertical-align: top;\n }\n\n table {\n width: 100%;\n }\n\n .contact td {\n border-bottom: 1px solid var(--color-borders);\n padding: 5px 3px;\n }\n\n .table-footer td {\n padding: 10px 3px;\n }\n\n .query-replaced,\n .count-replaced {\n display: inline-block;\n background: var(--color-primary-light);\n color: var(--color-text-dark);\n padding: 3px 6px;\n border-radius: var(--curvature);\n font-size: 85%;\n margin: 0px 3px;\n }\n\n temba-loading {\n transform: scale(0);\n max-width: 0;\n opacity: 0;\n transition: transform 200ms ease-in-out;\n }\n\n .fetching temba-loading {\n transform: scale(1);\n max-width: 500px;\n opacity: 1;\n display: block;\n }\n\n .error {\n margin-top: 10px;\n }\n\n .match-count {\n padding: 4px;\n margin-top: 6px;\n }\n\n .linked {\n color: var(--color-link-primary);\n text-decoration: none;\n cursor: pointer;\n }\n\n .header td {\n border-bottom: 0px solid var(--color-borders);\n padding: 5px 3px;\n }\n\n .expanded .header td {\n border-bottom: 2px solid var(--color-borders);\n }\n\n td.field-header,\n tr.table-footer,\n tr.contact {\n display: none;\n }\n\n .expanded td.field-header {\n display: table-cell;\n }\n\n .expanded tr.contact,\n .expanded tr.table-footer {\n display: table-row;\n }\n\n .query {\n display: var(--contact-search-query-display);\n margin-bottom: 10px;\n }\n\n .results {\n display: none;\n }\n\n .summary {\n min-height: 2.2em;\n display: flex;\n flex-grow: 1;\n align-items: center;\n }\n\n .summary .result-count {\n flex-grow: 1;\n }\n\n .results.empty {\n display: none !important;\n }\n\n .results.initialized {\n display: flex;\n align-items: center;\n margin-top: 0.5em;\n margin-left: 0.6em;\n }\n\n .advanced-icon {\n cursor: pointer;\n margin-right: 0.5em;\n }\n\n .query .advanced-icon {\n margin-top: 1em;\n margin-right: 1em;\n }\n\n .advanced-icon:hover {\n --icon-color: var(--color-link-primary-hover) !important;\n }\n\n .query {\n --textarea-height: 5em;\n }\n\n #recipients {\n margin-bottom: 1em;\n display: block;\n }\n\n temba-alert {\n margin: 1em 0;\n }\n `;\n }\n\n @property({ type: Boolean })\n in_a_flow: boolean;\n\n @property({ type: Boolean })\n started_previously: boolean;\n\n @property({ type: Boolean })\n not_seen_since_days: boolean;\n\n @property({ type: Boolean })\n fetching: boolean;\n\n @property({ type: Boolean })\n expanded: boolean;\n\n @property({ type: String })\n endpoint: string;\n\n @property({ type: String })\n placeholder = '';\n\n @property({ type: String })\n name = '';\n\n @property({ type: String })\n query = '';\n\n @property({ type: Number })\n inactiveThreshold = 1000;\n\n @property({ type: Number })\n inactiveDays = 90;\n\n @property({ type: Object, attribute: false })\n summary: SummaryResponse;\n\n @property({ type: Object, attribute: false })\n flow: any;\n\n @property({ type: Array })\n recipients: OmniOption[] = [];\n\n @property({ type: Boolean })\n advanced = false;\n\n @property({ type: String })\n refreshKey = '0';\n\n public refresh(): void {\n this.refreshKey = 'requested_' + new Date().getTime();\n }\n\n @property({ type: Object })\n private exclusions = {};\n\n private lastQuery: number;\n private initialized = false;\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n\n if (changedProperties.has('advanced') && this.advanced) {\n return;\n }\n\n // if we remove the in_a_flow option, make sure it's not part of our exclusions\n if (changedProperties.has('in_a_flow') && !this.in_a_flow) {\n delete this.exclusions['in_a_flow'];\n this.requestUpdate('exclusions');\n }\n\n if (\n (changedProperties.has('query') && this.advanced) ||\n (changedProperties.has('refreshKey') && this.refreshKey !== '0')\n ) {\n this.summary = null;\n // this.errors = [];\n this.fireCustomEvent(CustomEventType.ContentChanged, { reset: true });\n if (this.lastQuery) {\n window.clearTimeout(this.lastQuery);\n this.fetching = false;\n }\n\n if (this.query.trim().length > 0 || this.recipients.length > 0) {\n this.fetching = true;\n this.lastQuery = window.setTimeout(() => {\n this.fetchSummary();\n }, QUEIT_MILLIS);\n }\n }\n }\n\n public fetchSummary(): any {\n if (this.endpoint) {\n const group_uuids = this.recipients\n .filter((value: OmniOption) => value.type === 'group')\n .map((value: OmniOption) => value.id);\n\n const contact_uuids = this.recipients\n .filter((value: OmniOption) => value.type === 'contact')\n .map((value: OmniOption) => value.id);\n\n postJSON(this.endpoint, {\n include: this.advanced\n ? { query: this.query }\n : { contact_uuids, group_uuids },\n\n exclude: this.exclusions,\n }).then((response: WebResponse) => {\n this.fetching = false;\n if (response.status === 200) {\n this.summary = response.json as SummaryResponse;\n if (!this.advanced) {\n this.query = this.summary.query;\n }\n this.setValue({\n advanced: this.advanced,\n query: this.query,\n exclusions: this.exclusions,\n recipients: this.recipients,\n });\n\n if (this.summary.error) {\n this.errors = [this.summary.error];\n } else {\n this.errors = [];\n }\n this.requestUpdate('errors');\n this.fireCustomEvent(CustomEventType.ContentChanged, this.summary);\n } else {\n this.summary = response.json as SummaryResponse;\n if (this.summary.error) {\n this.errors = [this.summary.error];\n }\n this.requestUpdate('errors');\n this.fireCustomEvent(CustomEventType.ContentChanged, this.summary);\n }\n });\n }\n }\n\n private handleAdvancedToggle(evt: MouseEvent) {\n stopEvent(evt);\n this.recipients = [];\n this.exclusions = {};\n if (this.advanced) {\n this.query = '';\n this.value = null;\n }\n this.advanced = !this.advanced;\n\n this.setValue({\n advanced: this.advanced,\n query: this.query,\n exclusions: this.exclusions,\n recipients: this.recipients,\n });\n }\n\n private handleQueryChange(evt: KeyboardEvent) {\n const input = evt.target as TextInput;\n this.query = input.inputElement.value;\n }\n\n private handleRecipientsChanged(evt: any) {\n if (this.refreshKey !== '0' || this.initialized) {\n this.refresh();\n } else {\n this.initialized = true;\n }\n }\n\n private handleExclusionChanged(evt: any) {\n if (evt.target.tagName === 'TEMBA-CHECKBOX') {\n const ex = JSON.stringify(this.exclusions);\n const checkbox = evt.target as Checkbox;\n let value = checkbox.checked as any;\n\n if (!value) {\n delete this.exclusions[checkbox.name];\n } else {\n if (checkbox.name === 'not_seen_since_days') {\n value = 90;\n }\n\n this.exclusions[checkbox.name] = value;\n }\n\n if (ex !== JSON.stringify(this.exclusions)) {\n this.refresh();\n }\n }\n }\n\n public render(): TemplateResult {\n let summary: TemplateResult;\n if (this.summary) {\n if (!this.summary.error) {\n const count = this.summary.total || 0;\n\n summary = html`\n
    \n Found\n \n ${count.toLocaleString()}\n \n contact${count !== 1 ? 's' : ''}\n
    \n \n
    \n
    \n ${this.advanced\n ? html` \n Start Over`\n : html` \n Edit Query`}\n
    \n
    \n \n `;\n }\n }\n\n if (\n this.summary &&\n this.summary.blockers &&\n this.summary.blockers.length > 0\n ) {\n return html`${this.summary.blockers.map(\n error =>\n html`${unsafeHTML(error)}`\n )}`;\n }\n\n return html`\n ${this.advanced\n ? html`
    \n \n \n
    `\n : html`\n \n\n ${this.not_seen_since_days\n ? html``\n : null}\n ${this.in_a_flow\n ? html``\n : null}\n ${this.started_previously\n ? html``\n : null}`}\n\n \n \n
    ${summary}
    \n \n\n ${this.summary && this.summary.warnings\n ? this.summary.warnings.map(\n warning =>\n html`${unsafeHTML(warning)}`\n )\n : ``}\n `;\n }\n}\n","import { LitElement, TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { Icon, SVG_FINGERPRINT } from '.';\nimport { getClasses } from '../utils';\n\nexport class VectorIcon extends LitElement {\n @property({ type: String })\n name: string;\n\n @property({ type: String })\n prefix: string;\n\n // same as name but without implicit coloring\n @property({ type: String })\n id: string;\n\n @property({ type: Number })\n size = 1;\n\n @property({ type: Boolean })\n spin: boolean;\n\n @property({ type: Boolean })\n clickable: boolean;\n\n @property({ type: Boolean })\n circled: boolean;\n\n @property({ type: String })\n animateChange: string;\n\n @property({ type: String })\n animateClick: string;\n\n @property({ type: Number })\n animationDuration = 200;\n\n @property({ type: String })\n src = '';\n\n @property({ type: Number, attribute: false })\n steps = 2;\n\n @property({ type: Number, attribute: false })\n animationStep: number;\n\n @property({ type: String })\n easing = 'cubic-bezier(0.68, -0.55, 0.265, 1.55)';\n\n static get styles() {\n return css`\n :host {\n display: flex-inline;\n align-items: center;\n align-self: center;\n }\n\n .sheet {\n color: var(--icon-color);\n transform: scale(1);\n transition: fill 100ms ease-in-out,\n background 200ms cubic-bezier(0.68, -0.55, 0.265, 1.55),\n padding 200ms cubic-bezier(0.68, -0.55, 0.265, 1.55),\n margin 200ms cubic-bezier(0.68, -0.55, 0.265, 1.55);\n }\n\n .sheet.spin {\n transform: rotate(0deg);\n }\n\n .sheet.spin-1 {\n transform: rotate(180deg);\n }\n\n .sheet.spin-2 {\n transform: rotate(360deg);\n }\n\n .sheet.spin-3 {\n transform: rotate(0deg);\n transition-duration: 0ms !important;\n }\n\n .sheet.pulse {\n transform: scale(1);\n }\n\n .sheet.pulse-1 {\n transform: scale(1.2);\n }\n\n .clickable:hover {\n cursor: pointer;\n fill: var(--color-link-primary) !important;\n background: rgb(255, 255, 255);\n }\n\n .circled {\n background: var(--icon-color-circle);\n padding: 0.15em;\n margin: -0.15em;\n box-shadow: var(--shadow);\n }\n\n .wrapper {\n display: flex;\n flex-direction: column;\n border-radius: 999px;\n transition: background 200ms linear,\n transform 300ms cubic-bezier(0.68, -0.55, 0.265, 1.55),\n padding 150ms linear, margin 150ms linear;\n }\n\n .wrapper.clickable {\n transform: scale(1);\n }\n\n .wrapper.clickable:hover {\n --icon-circle-size: 0.35em;\n --icon-background: var(--icon-color-circle-hover);\n }\n\n .wrapper.clickable {\n padding: var(--icon-circle-size);\n margin: calc(-1 * var(--icon-circle-size));\n background: var(--icon-background);\n }\n\n .spin-forever {\n animation-name: spin;\n animation-duration: 2000ms;\n animation-iteration-count: infinite;\n animation-timing-function: linear;\n }\n\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n `;\n }\n\n constructor() {\n super();\n }\n\n private lastName: string;\n\n public firstUpdated(changes: Map) {\n super.firstUpdated(changes);\n if (changes.has('animateChange')) {\n // set our default duration if we need one\n if (!changes.has('animationDuration')) {\n this.animationDuration = this.steps * this.animationDuration;\n }\n\n if (this.animateChange === 'spin') {\n this.steps = 3;\n this.animationDuration = 400;\n this.easing = 'linear';\n }\n }\n }\n\n public handleClicked() {\n if (this.animateClick) {\n this.animationStep = 1;\n }\n }\n\n public updated(changes: Map) {\n super.updated(changes);\n\n if (changes.has('animationStep')) {\n // if we are halfway through, change the icon\n if (this.lastName && this.animationStep >= this.steps / 2) {\n this.lastName = null;\n this.requestUpdate();\n }\n\n setTimeout(() => {\n if (this.animationStep > 0 && this.animationStep < this.steps) {\n this.animationStep++;\n } else {\n this.animationStep = 0;\n }\n }, this.animationDuration / this.steps);\n }\n\n if (changes.has('name') && this.animateChange) {\n this.lastName = changes.get('name');\n\n // our name changed, lets animate it\n if (this.lastName && this.animateChange) {\n this.animationStep = 1;\n }\n }\n }\n\n public render(): TemplateResult {\n if (!this.name) {\n return null;\n }\n\n // let icon name mappings take precedence\n let name = this.lastName || this.name;\n\n // special case our channel icon fallback\n if (name.startsWith('channel_') && !Icon[name]) {\n name = Icon.channel_ex;\n } else {\n name = Icon[name.replace('icon.', '')] || name;\n }\n\n // referencing icons by id is explicit\n if (!name) {\n name = this.id;\n }\n\n return html`\n \n 0,\n [this.animateClick]: !!this.animateClick,\n [this.animateClick + '-' + this.animationStep]:\n this.animationStep > 0,\n })}\"\n >\n \n \n \n `;\n }\n}\n","import { TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { RapidElement } from '../RapidElement';\nimport { Select } from '../select/Select';\nimport { Icon } from '../vectoricon';\n\nenum OmniType {\n Group = 'group',\n Contact = 'contact',\n}\n\nexport interface OmniOption {\n id: string;\n name: string;\n type: OmniType;\n urn?: string;\n count?: number;\n contact?: string;\n scheme?: string;\n}\n\nconst postNameStyle = {\n color: 'var(--color-text-dark)',\n padding: '0px 6px',\n fontSize: '12px',\n};\n\nexport class Omnibox extends RapidElement {\n static get styles() {\n return css`\n temba-select:focus {\n outline: none;\n box-shadow: none;\n }\n\n :host {\n }\n `;\n }\n\n @property()\n endpoint: string;\n\n @property()\n name: string;\n\n @property({ type: Boolean })\n groups = false;\n\n @property({ type: Boolean })\n contacts = false;\n\n @property({ type: Array })\n value: OmniOption[] = [];\n\n @property({ type: Array })\n errors: string[];\n\n @property()\n placeholder = 'Select recipients';\n\n @property({ type: Boolean })\n disabled = false;\n\n @property({ type: String, attribute: 'help_text' })\n helpText: string;\n\n @property({ type: Boolean, attribute: 'help_always' })\n helpAlways: boolean;\n\n @property({ type: Boolean, attribute: 'widget_only' })\n widgetOnly: boolean;\n\n @property({ type: Boolean, attribute: 'hide_label' })\n hideLabel: boolean;\n\n @property({ type: String })\n label: string;\n\n @property({ type: String, attribute: 'info_text' })\n infoText = '';\n\n /** An option in the drop down */\n private renderOption(option: OmniOption): TemplateResult {\n return html`\n
    \n
    ${this.getIcon(option)}
    \n
    ${option.name}
    \n \n ${this.getPostName(option)}\n
    \n \n `;\n }\n\n private getPostName(option: OmniOption): TemplateResult {\n const style = { ...postNameStyle };\n\n if (option.urn && option.type === OmniType.Contact) {\n if (option.urn !== option.name) {\n return html`
    ${option.urn}
    `;\n }\n }\n\n if (option.type === OmniType.Group) {\n return html`\n
    ${option.count.toLocaleString()}
    \n `;\n }\n\n return null;\n }\n\n /** Selection in the multi-select select box */\n private renderSelection(option: OmniOption): TemplateResult {\n return html`\n \n
    \n ${this.getIcon(option)}\n
    \n \n ${option.name}\n \n \n ${this.getPostName(option)}\n \n \n `;\n }\n\n private getIcon(option: OmniOption): TemplateResult {\n if (option.type === OmniType.Group) {\n return html``;\n }\n\n if (option.type === OmniType.Contact) {\n return html``;\n }\n }\n\n private getEndpoint() {\n const endpoint = this.endpoint;\n let types = '&types=';\n if (this.groups) {\n types += 'g';\n }\n\n if (this.contacts) {\n types += 'c';\n }\n\n return endpoint + types;\n }\n\n public getValues(): any[] {\n const select = this.shadowRoot.querySelector('temba-select') as Select;\n return select.values;\n }\n\n public isMatch() {\n return true;\n }\n\n public render(): TemplateResult {\n return html`\n
    \n \n `;\n }\n}\n","export const getMiddle = (a: DOMRect, b: DOMRect) => {\n return a.top + a.height / 2 - b.height / 2;\n};\n\nexport const getCenter = (a: DOMRect, b: DOMRect) => {\n return a.left + a.width / 2 - b.width / 2;\n};\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { RapidElement } from '../RapidElement';\nimport { getClasses } from '../utils';\nimport { getCenter, getMiddle } from './helpers';\n\nexport class Tip extends RapidElement {\n static get styles() {\n return css`\n .tip {\n transition: opacity 200ms ease-in-out;\n margin: 0px;\n position: fixed;\n opacity: 0;\n background: #fff;\n padding: 4px 8px;\n pointer-events: none;\n border-radius: var(--curvature-widget);\n box-shadow: 0 1px 10px 10px rgba(0, 0, 0, 0.035),\n 0 1px 3px 0px rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);\n font-size: 14px;\n z-index: 10000;\n color: #333;\n }\n\n .tip.hide-on-change {\n transition: none;\n }\n\n .show {\n opacity: 1;\n }\n\n .slot {\n display: flex;\n flex-direction: column;\n }\n\n .arrow {\n position: absolute;\n color: #fff;\n font-size: 10px;\n line-height: 0px;\n }\n\n .◀ {\n text-shadow: -1px 2px 2px rgba(0, 0, 0, 0.1);\n }\n\n .▶ {\n text-shadow: 1px 2px 2px rgba(0, 0, 0, 0.1);\n }\n\n .▼ {\n text-shadow: 0px 3px 3px rgba(0, 0, 0, 0.1);\n }\n\n .▲ {\n text-shadow: 0px -1px 1px rgba(0, 0, 0, 0.1);\n }\n `;\n }\n\n @property({ type: String })\n text: string;\n\n @property({ type: Boolean })\n visible = false;\n\n @property({ type: String })\n position = 'auto';\n\n @property({ type: Boolean })\n hideOnChange: boolean;\n\n @property({ type: Number, attribute: false })\n top: number;\n\n @property({ type: Number, attribute: false })\n left: number;\n\n @property({ type: Number, attribute: false })\n width: number;\n\n @property({ type: Boolean, attribute: false })\n poppedTop: boolean;\n\n arrow: string;\n arrowTop: number;\n arrowLeft: number;\n arrowDirection: string;\n\n lastEnter = 0;\n failSafe = 0;\n\n public updated(changed: Map) {\n if ((changed.has('visible') || changed.has('text')) && this.visible) {\n this.calculatePosition();\n }\n\n if (changed.has('text') && this.hideOnChange) {\n this.visible = false;\n }\n }\n\n private calculatePosition() {\n if (this.visible) {\n const tipBounds = this.getDiv('.tip').getBoundingClientRect();\n const anchorBounds = this.getDiv('.slot').getBoundingClientRect();\n\n // TODO: pick a direction automatically\n let tipSide = this.position;\n if (tipSide === 'auto') {\n tipSide = 'left';\n }\n\n this.arrowLeft = 0;\n this.arrowTop = 0;\n\n if (tipSide === 'left') {\n this.left = anchorBounds.left - tipBounds.width - 16;\n this.top = getMiddle(anchorBounds, tipBounds);\n\n // position our arrow\n this.arrowTop = tipBounds.height / 2;\n this.arrowLeft = tipBounds.width - 1;\n this.arrow = '▶';\n } else if (tipSide === 'right') {\n this.left = anchorBounds.right + 12;\n this.top = getMiddle(anchorBounds, tipBounds);\n\n this.arrowTop = tipBounds.height / 2;\n this.arrowLeft = -8;\n this.arrow = '◀';\n } else if (tipSide === 'top') {\n this.top = anchorBounds.top - tipBounds.height - 12;\n this.left = getCenter(anchorBounds, tipBounds);\n\n this.arrowTop = tipBounds.height + 2;\n this.arrowLeft = tipBounds.width / 2 - 4;\n this.arrow = '▼';\n } else if (tipSide === 'bottom') {\n this.top = anchorBounds.bottom + 10;\n this.left = getCenter(anchorBounds, tipBounds);\n\n this.arrowTop = -2;\n this.arrowLeft = tipBounds.width / 2 - 3;\n this.arrow = '▲';\n }\n }\n }\n\n private handleMouseEnter() {\n this.lastEnter = window.setTimeout(() => {\n this.visible = true;\n this.failSafe = window.setTimeout(() => {\n this.visible = false;\n }, 2000);\n }, 600);\n }\n\n private handleMouseLeave() {\n window.clearTimeout(this.lastEnter);\n window.clearTimeout(this.failSafe);\n this.visible = false;\n }\n\n public render(): TemplateResult {\n const tipStyle: any = {\n top: this.top ? `${this.top}px` : '0px',\n left: this.left ? `${this.left}px` : '0px',\n };\n\n const arrowStyle: any = {\n top: this.arrowTop ? `${this.arrowTop}px` : '0px',\n left: this.arrowLeft ? `${this.arrowLeft}px` : '0px',\n };\n\n if (this.width) {\n tipStyle.width = `${this.width}px`;\n }\n\n const classes = getClasses({\n tip: true,\n show: this.visible,\n top: this.poppedTop,\n 'hide-on-change': this.hideOnChange,\n });\n\n return html`\n \n \n
    \n
    \n ${this.text}\n
    \n ${this.arrow}\n
    \n
    \n `;\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { debounce, fetchResults, getClasses, renderAvatar } from '../utils';\nimport { Icon } from '../vectoricon';\nimport { Dropdown } from '../dropdown/Dropdown';\nimport { NotificationList } from './NotificationList';\nimport { ResizeElement } from '../ResizeElement';\nexport interface MenuItem {\n id?: string;\n vanity_id?: string;\n name?: string;\n verbose_name?: string;\n count?: number;\n icon?: string;\n collapsed_icon?: string;\n endpoint?: string;\n loading?: boolean;\n bottom?: boolean;\n level?: number;\n href?: string;\n show_header?: boolean;\n items?: MenuItem[];\n inline?: boolean;\n type?: string;\n on_submit?: string;\n bubble?: string;\n popup?: boolean;\n avatar?: string;\n trigger?: boolean;\n event?: string;\n mobile?: boolean;\n}\n\ninterface MenuItemState {\n collapsed?: string;\n}\n\nconst findItem = (\n items: MenuItem[],\n id: string\n): { item: MenuItem; index: number } => {\n const search = items || [];\n\n const index = search.findIndex((item: MenuItem) => {\n return item.id == id || item.vanity_id == id;\n });\n\n if (index > -1) {\n const item = search[index];\n return { item, index };\n }\n\n return { item: null, index: -1 };\n};\n\nexport class TembaMenu extends ResizeElement {\n static get styles() {\n return css`\n :host {\n width: 100%;\n display: block;\n --color-widget-bg-focused: transparent;\n --options-block-shadow: none;\n }\n\n .bubble {\n width: 0.6em;\n height: 0.6em;\n right: 0em;\n bottom: 0em;\n border-radius: 99em;\n border: 0.12em solid rgba(0, 0, 0, 0.1);\n position: absolute;\n }\n\n .bubble.count {\n position: relative;\n width: inherit;\n height: inherit;\n right: inherit;\n bottom: inherit;\n color: #fff;\n line-height: 1em;\n padding: 0.12em;\n min-width: 1em;\n text-align: center;\n }\n\n .section {\n font-size: 1.5em;\n margin-bottom: 0.2em;\n color: var(--color-text-dark);\n }\n\n .collapse-toggle {\n width: 0.5em;\n cursor: pointer;\n display: block;\n margin-right: 5px;\n margin-top: 3px;\n margin-bottom: 3px;\n }\n\n .collapse-toggle:hover {\n background: rgb(100, 100, 100, 0.05);\n }\n\n .item {\n cursor: pointer;\n user-select: none;\n -webkit-user-select: none;\n display: flex;\n --icon-color: var(--color-text-dark);\n }\n\n .item.selected,\n .item.pressed {\n background: var(--color-selection);\n color: var(--color-primary-dark);\n --icon-color: var(--color-primary-dark);\n }\n\n .root {\n display: flex;\n flex-direction: row;\n height: 100%;\n }\n\n .level {\n display: flex;\n flex-direction: column;\n }\n\n .level.hidden {\n display: none;\n }\n\n .popup {\n --icon-color: rgba(255, 255, 255, 0.7);\n }\n\n .level-0 > .item,\n .level-0 > temba-dropdown > div[slot='toggle'] > .avatar {\n padding: 0px;\n --icon-color: rgba(255, 255, 255, 0.7);\n flex-direction: column;\n border: 0px solid green;\n width: 100%;\n display: flex;\n align-items: center;\n }\n\n .level-0 > temba-dropdown .icon-wrapper {\n padding: 0.2em 0.4em 0.2em 0.4em;\n }\n\n .level-0 > .item.selected::before,\n .level-0 > .item.selected::after {\n content: ' ';\n height: var(--curvature);\n background: var(--color-primary-dark);\n display: block;\n width: 100%;\n }\n\n .level-0 > .item.selected::before {\n border-bottom-right-radius: var(--curvature);\n }\n\n .level-0 .item > temba-tip {\n padding: 0.5em 0em;\n }\n\n .level-0 > .item.selected::after {\n border-top-right-radius: var(--curvature);\n }\n\n .level-0 {\n padding-top: var(--menu-padding) !important;\n }\n\n .level-0 > .empty {\n background: var(--color-primary-dark);\n align-self: stretch;\n flex-grow: 1;\n }\n\n .level-0 > .bottom {\n height: 1em;\n background: var(--color-primary-dark);\n }\n\n .level-0 > temba-dropdown.open > div[slot='toggle'] > .avatar {\n background: transparent !important;\n }\n\n .level-0 {\n background: var(--color-primary-dark);\n }\n\n temba-dropdown {\n }\n\n temba-dropdown > div[slot='dropdown'] .avatar > .details {\n margin-left: 0.75em;\n }\n\n temba-dropdown > div[slot='dropdown'] .bubble.count {\n margin-right: 0.75em;\n }\n\n .level-0 > .item > .details,\n .level-0 > temba-dropdown > div[slot='toggle'] .details {\n display: none !important;\n }\n\n .avatar {\n align-items: center;\n }\n\n temba-dropdown > div[slot='dropdown'] {\n }\n\n temba-dropdown > div[slot='dropdown'] .avatar .avatar-circle,\n temba-dropdown > div[slot='dropdown'] .avatar .bubble {\n font-size: 0.7em;\n }\n\n .level-0.expanded {\n background: inherit;\n }\n\n .level-0 > .item.selected {\n background: white;\n --icon-color: var(--color-primary-dark);\n }\n\n .level {\n padding: var(--menu-padding);\n }\n\n .level-0 {\n padding: 0px;\n }\n\n .top {\n display: flex;\n align-items: center;\n flex-direction: column;\n }\n\n .item {\n padding: 0.2em 0.75em;\n margin-top: 0.1em;\n border-radius: var(--curvature);\n display: flex;\n min-width: 12em;\n position: relative;\n }\n\n .item > temba-icon {\n margin-right: 0.5em;\n }\n\n .item > .details > .name {\n flex-grow: 1;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n width: 0;\n }\n\n .level-0 .item {\n margin-top: 0em;\n border-radius: 0px;\n min-width: inherit;\n max-width: inherit;\n }\n\n .popup:hover {\n --icon-color: #fff;\n }\n\n .level-0 > .item > temba-icon {\n margin-right: 0px;\n }\n\n .level-0 > .item > .name {\n min-width: 0px;\n }\n\n .count {\n align-self: center;\n margin-left: 1em;\n font-size: 0.8em;\n font-weight: 400;\n }\n\n .level-0 > .item-top {\n background: var(--color-primary-dark);\n min-height: var(--curvature);\n }\n\n .level-0 > .item-bottom {\n background: var(--color-primary-dark);\n min-height: var(--curvature);\n }\n\n .level-0 > .item-bottom.selected {\n border-top-right-radius: var(--curvature);\n }\n\n .level-0 > .item-top.selected {\n border-bottom-right-radius: var(--curvature);\n }\n\n .level-0 > .item:hover {\n background: rgba(255, 255, 255, 0.15);\n --icon-color: #fff;\n }\n\n .level-0 > .item.selected:hover {\n background: white;\n --icon-color: var(--color-primary-dark);\n cursor: default;\n }\n\n .item.inline {\n border: 0px solid transparent;\n }\n\n .level-1,\n .level-2 {\n border-right: 1px solid rgba(0 0 0 / 8%);\n box-shadow: rgb(0 0 0 / 6%) 4px 0px 6px 1px;\n }\n\n .level-1 {\n transition: opacity 100ms linear, margin 200ms linear;\n overflow-y: scroll;\n }\n\n .mobile.root {\n height: 100svh;\n }\n\n .mobile.root.fully-collapsed {\n height: initial;\n }\n\n .root.fully-collapsed.mobile .level.level-0 {\n padding-right: 0.5em;\n }\n\n .root.fully-collapsed.mobile .level.level-0 {\n flex-direction: row;\n }\n\n .root.fully-collapsed.mobile .level.level-0 > .item {\n display: none;\n }\n\n .root.fully-collapsed.mobile .level.level-0 > .empty {\n display: block;\n width: 100%;\n min-width: inherit;\n max-width: inherit;\n }\n\n .root .level.level-0 > .show-mobile {\n display: none;\n }\n\n .root.mobile .level.level-0 > .show-mobile {\n display: flex;\n }\n\n .root.fully-collapsed.mobile .level.level-0 > .show-mobile {\n display: contents !important;\n }\n\n .root.fully-collapsed.mobile .level.level-0 .expand-icon {\n max-height: 100%;\n padding: 1em;\n }\n\n .mobile.fully-collapsed.root {\n flex-direction: column;\n }\n\n .mobile.fully-collapsed.root .level-0 {\n padding-top: 0px !important;\n }\n\n .mobile.fully-collapsed .level-1 {\n display: none;\n }\n\n .mobile .level-1 {\n flex-grow: 1;\n }\n\n .mobile .level-1 .item {\n max-width: inherit;\n min-width: inherit;\n }\n\n .mobile .level-1 .section {\n max-width: inherit;\n min-width: inherit;\n }\n\n .mobile.fully-collapsed .item {\n }\n\n .mobile .expand-icon {\n transition: none;\n transform: rotate(-90deg);\n align-self: center;\n }\n\n .mobile.fully-collapsed .level-0 .empty {\n flex-grow: 1;\n }\n\n .mobile.fully-collapsed .top-spacer {\n flex-grow: 0;\n }\n\n .mobile.fully-collapsed #dd-workspace {\n display: none;\n }\n\n .mobile.fully-collapsed .expand-icon {\n transform: none;\n }\n\n .level-2 {\n background: #fbfbfb;\n overflow-y: auto;\n }\n\n .level-2 .item .details {\n overflow: hidden;\n }\n\n .level-2 .item {\n min-width: 12em;\n max-width: 12em;\n }\n\n .level-1 .item {\n overflow: hidden;\n max-width: 12em;\n min-width: 12em;\n min-height: 1.5em;\n max-height: 1.5em;\n transition: min-width var(--transition-speed) !important;\n }\n\n .collapsed .item {\n overflow: hidden;\n min-width: 0;\n margin: 0;\n }\n\n .item .details {\n opacity: 1;\n min-height: 1.5em;\n max-height: 1.5em;\n align-items: center;\n }\n\n .collapsed .item {\n margin-bottom: 0.5em;\n }\n\n .collapsed .item .details {\n overflow: hidden;\n max-height: 0em;\n max-width: 0em;\n }\n\n .collapsed .item .details {\n max-height: 0em;\n }\n\n .collapsed .item temba-icon {\n margin-right: 0;\n }\n\n .section {\n max-width: 12em;\n }\n\n .collapsed .section {\n opacity: 0;\n max-width: 0em;\n max-height: 0.6em;\n }\n\n .collapsed.level-1 {\n overflow: hidden;\n padding: 0.5em;\n --icon-color: #999;\n }\n\n .collapsed .item .right {\n flex-grow: 1;\n }\n\n .collapse-icon {\n display: none;\n }\n\n .collapsed .collapse-icon {\n --icon-color: #ccc;\n display: block;\n }\n\n .collapsed .item.iconless {\n max-height: 0em;\n padding: 0em;\n min-height: 0em;\n margin-bottom: 0em;\n }\n\n .divider {\n height: 1px;\n background: #f3f3f3;\n margin: 0.5em 0.75em;\n min-height: 1px;\n }\n\n .space {\n margin: 0.5em;\n }\n\n .collapsed .divider {\n height: 0;\n margin: 0;\n padding: 0;\n min-height: 0px;\n }\n\n .sub-section {\n font-size: 0.9rem;\n color: #888;\n margin-top: 1rem;\n margin-left: 0.3rem;\n }\n\n .fully-collapsed .level-1 {\n margin-left: -208px;\n pointer-events: none;\n border: none;\n overflow: hidden;\n }\n\n .fully-collapsed .level-1 > * {\n opacity: 0;\n }\n\n .fully-collapsed .level-1 .item,\n .fully-collapsed .level-1 .divider {\n opacity: 0;\n }\n\n .fully-collapsed .level-2,\n .fully-collapsed .level-3 {\n display: none;\n }\n\n temba-button {\n margin-top: 0.2em;\n margin-bottom: 0.2em;\n margin-left: 0.75em;\n margin-right: 0.75em;\n }\n\n .expand-icon {\n transform: rotate(180deg);\n --icon-color: rgba(255, 255, 255, 0.5);\n cursor: pointer;\n max-height: 0px;\n overflow: hidden;\n opacity: 0;\n transition: all 400ms ease-in-out 400ms;\n }\n\n .expand-icon:hover {\n --icon-color: #fff;\n }\n\n .fully-collapsed .expand-icon {\n padding-top: 0.5em;\n max-height: 2em;\n opacity: 1;\n }\n\n .section-header {\n display: flex;\n align-items: center;\n }\n\n .section-header .section {\n flex-grow: 1;\n }\n\n .section-header temba-icon {\n --icon-color: #ddd;\n cursor: pointer;\n padding-bottom: 0.5em;\n padding-right: 0.5em;\n }\n\n .section-header temba-icon:hover {\n --icon-color: var(--color-link-primary);\n }\n\n a {\n text-decoration: none;\n color: var(--color-text-dark);\n }\n\n slot[name='header'] {\n display: none;\n }\n\n slot[name='header'].show-header {\n display: block;\n }\n\n .icon-wrapper {\n position: relative;\n padding: 0.2em 0.4em 0.2em 0em;\n }\n\n .level-0 .icon-wrapper {\n padding: 0.4em 0.9em;\n }\n `;\n }\n\n @property({ type: Boolean })\n wraps = false;\n\n @property({ type: Boolean })\n wait: boolean;\n\n @property({ type: String })\n endpoint: string;\n\n @property({ type: String })\n expanding: string;\n\n @property({ type: String })\n value: string;\n\n // submenu to constrain to\n @property({ type: String })\n submenu: string;\n\n @property({ type: Boolean })\n collapsed: boolean;\n\n @property({ type: Object })\n pressedItem: MenuItem;\n\n // http promise to monitor for completeness\n public httpComplete: Promise;\n\n root: MenuItem;\n selection: string[] = [];\n state: { [id: string]: MenuItemState } = {};\n\n constructor() {\n super();\n this.doRefresh = this.doRefresh.bind(this);\n\n // scroll any lists to the top\n this.addEventListener('blur', () => {\n this.shadowRoot\n .querySelectorAll('temba-list, temba-notification-list')\n .forEach((ele: NotificationList) => {\n ele.scrollToTop();\n });\n });\n }\n\n public setBubble(id: string, color: string) {\n const found = findItem(this.root.items, id);\n if (found && found.item) {\n found.item.bubble = color;\n this.requestUpdate('root');\n return true;\n }\n return false;\n }\n\n private getMenuItemState(id: string): MenuItemState {\n let itemState = {};\n if (id) {\n itemState = this.state[id];\n if (!itemState) {\n itemState = {};\n this.state[id] = itemState;\n }\n }\n return itemState;\n }\n\n public updated(changes: Map) {\n if (changes.has('endpoint')) {\n this.root = {\n level: -1,\n endpoint: this.endpoint,\n };\n\n if (!this.wait) {\n this.loadItems(this.root);\n } else {\n this.fireCustomEvent(CustomEventType.Ready);\n }\n }\n\n if (changes.has('root')) {\n if (this.value) {\n this.setFocusedItem(this.value);\n this.value = null;\n }\n }\n }\n\n public reset() {\n this.loadItems(this.root);\n }\n\n public async doRefresh() {\n const path = [...this.selection];\n let item = this.root;\n\n while (path.length > 0) {\n this.loadItems(item);\n // we need to wait until the load is complete before doing the replace\n await this.httpComplete;\n const id = path.shift();\n item = (item.items || []).find(_item => _item.id == id);\n }\n\n this.loadItems(item);\n\n // refresh any embedded lists\n this.shadowRoot\n .querySelectorAll('temba-notification-list')\n .forEach((ele: NotificationList) => {\n ele.refresh();\n });\n }\n\n public refresh = debounce(this.doRefresh, 200);\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n private loadItems(item: MenuItem, event: MouseEvent = null) {\n if (item && item.endpoint) {\n item.loading = true;\n this.httpComplete = fetchResults(item.endpoint).then(\n (items: MenuItem[]) => {\n items.forEach(newItem => {\n if (!newItem.items) {\n const prevItem = (item.items || []).find(\n prev => prev.id == newItem.id\n );\n if (prevItem && prevItem.items) {\n newItem.items = prevItem.items;\n }\n }\n });\n\n // update our item level\n items.forEach(subItem => {\n subItem.level = item.level + 1;\n // if we came with preset items, set the level for them accordingly\n if (subItem.items) {\n subItem.items.forEach(inlineItem => {\n inlineItem.level = item.level + 2;\n });\n }\n });\n\n item.items = items;\n item.loading = false;\n\n if (this.submenu && this.selection.length == 0) {\n const sub = this.getMenuItemForSelection([this.submenu]);\n this.handleItemClicked(event, sub);\n }\n\n if (!this.wait) {\n this.fireCustomEvent(CustomEventType.Ready);\n this.wait = true;\n }\n\n this.requestUpdate('root');\n this.scrollSelectedIntoView();\n }\n );\n }\n }\n\n private handleItemClicked(\n event: MouseEvent,\n menuItem: MenuItem,\n parent: MenuItem = null\n ) {\n if (parent && parent.popup) {\n const dropdown = this.shadowRoot.querySelector(\n 'temba-dropdown'\n ) as Dropdown;\n if (dropdown) {\n dropdown.blur();\n }\n\n if (event) {\n this.fireCustomEvent(CustomEventType.ButtonClicked, {\n item: menuItem,\n selection: this.getSelection(),\n parent,\n });\n }\n\n return;\n }\n\n if (menuItem.popup) {\n if (event) {\n this.fireCustomEvent(CustomEventType.ButtonClicked, {\n item: menuItem,\n selection: this.getSelection(),\n parent,\n });\n }\n return;\n }\n\n if (event) {\n event.preventDefault();\n event.stopPropagation();\n if (event.metaKey && menuItem.href) {\n window.open(menuItem.href, '_blank');\n return;\n }\n }\n\n if (parent && parent.inline) {\n this.handleItemClicked(null, parent);\n }\n\n if (this.collapsed && !this.isMobile()) {\n this.collapsed = false;\n }\n\n if (this.isMobile()) {\n this.collapsed = true;\n }\n\n if (menuItem.trigger || menuItem.event) {\n this.fireCustomEvent(CustomEventType.ButtonClicked, {\n item: menuItem,\n selection: this.getSelection(),\n parent,\n });\n return;\n }\n\n // update our selection\n if (menuItem.level >= this.selection.length) {\n this.selection.push(menuItem.vanity_id || menuItem.id);\n } else {\n this.selection.splice(\n menuItem.level,\n this.selection.length - menuItem.level,\n menuItem.vanity_id || menuItem.id\n );\n }\n\n if (menuItem.endpoint) {\n this.loadItems(menuItem, event);\n\n // make sure change events fire for events with hrefs\n if (!menuItem.href) {\n return;\n }\n } else {\n this.requestUpdate();\n }\n\n if (menuItem.href) {\n this.dispatchEvent(new Event('change'));\n }\n\n this.fireCustomEvent(CustomEventType.ButtonClicked, {\n item: menuItem,\n selection: this.getSelection(),\n parent,\n });\n }\n\n public scrollSelectedIntoView() {\n // makes sure we are scrolled into view\n window.setTimeout(() => {\n const eles = this.shadowRoot.querySelectorAll('.selected');\n eles.forEach(ele => {\n ele.scrollIntoView({ block: 'end', behavior: 'smooth' });\n });\n }, 0);\n }\n\n public clickItem(id: string): boolean {\n const path = [...this.selection];\n path.splice(path.length - 1, 1, id);\n const item = this.getMenuItemForSelection(path);\n\n if (item) {\n this.handleItemClicked(null, item);\n this.scrollSelectedIntoView();\n return true;\n }\n return false;\n }\n\n public getMenuItem(): MenuItem {\n return this.getMenuItemForSelection([...this.selection]);\n }\n\n public getMenuItemForSelection(selection: string[]) {\n const path = [...selection];\n let items = this.root.items;\n let item = null;\n while (path.length > 0) {\n const step = path.splice(0, 1)[0];\n if (items) {\n item = findItem(items, step).item;\n if (item) {\n items = item.items;\n } else {\n break;\n }\n } else {\n break;\n }\n }\n\n return item;\n }\n\n public getSelection() {\n return this.selection;\n }\n\n public handleExpand() {\n this.collapsed = false;\n }\n\n public handleCollapse() {\n this.collapsed = true;\n }\n\n public async setFocusedItem(path: string) {\n const focusedPath = path.split('/').filter(step => !!step);\n if (!this.root) {\n return;\n }\n\n // if we don't match at the first level, we are a noop\n if (focusedPath.length > 0) {\n const rootItem = findItem(this.root.items, focusedPath[0]).item;\n if (!rootItem) {\n return;\n }\n }\n\n const newPath = [];\n let level = this.root;\n while (focusedPath.length > 0) {\n const nextId = focusedPath.shift();\n if (nextId) {\n if (!level.items) {\n this.loadItems(level);\n await this.httpComplete;\n }\n\n level = findItem(level.items, nextId).item;\n if (!level) {\n focusedPath.splice(0, focusedPath.length);\n } else {\n newPath.push(nextId);\n }\n }\n }\n\n this.selection = newPath;\n this.refresh();\n this.requestUpdate('root');\n }\n\n private isSelected(menuItem: MenuItem) {\n if (menuItem.level < this.selection.length) {\n const selected =\n this.selection[menuItem.level] == (menuItem.vanity_id || menuItem.id);\n return selected;\n }\n return false;\n }\n\n private isExpanded(menuItem: MenuItem) {\n const expanded = !!this.selection.find(\n id => id === menuItem.vanity_id || menuItem.id\n );\n return expanded;\n }\n\n private renderMenuItem = (\n menuItem: MenuItem,\n parent: MenuItem = null\n ): TemplateResult => {\n if (menuItem.type === 'divider') {\n return html`
    `;\n }\n\n if (menuItem.type === 'temba-notification-list') {\n return html``;\n }\n\n if (menuItem.type === 'space') {\n return html`
    `;\n }\n\n if (menuItem.type === 'section' || menuItem.inline) {\n return html`
    ${menuItem.name}
    `;\n }\n\n if (menuItem.type === 'modax-button') {\n return html` {\n this.handleItemClicked(event, menuItem);\n }}\n />`;\n }\n\n const isSelected = this.isSelected(menuItem);\n const isChildSelected =\n isSelected && this.selection.length > menuItem.level + 1;\n\n let icon = menuItem.icon\n ? html`
    \n ${menuItem.bubble && !menuItem.count\n ? html`
    `\n : null}\n `\n : null;\n\n const collapsedIcon = menuItem.collapsed_icon\n ? html``\n : null;\n\n const itemClasses = getClasses({\n ['menu-' + menuItem.id]: true,\n 'child-selected': isChildSelected,\n selected: isSelected,\n item: !(menuItem.avatar && menuItem.level === 0),\n avatar: !!menuItem.avatar,\n popup: menuItem.popup,\n inline: menuItem.inline,\n expanding: this.expanding && this.expanding === menuItem.id,\n expanded: this.isExpanded(menuItem),\n iconless: !icon && !collapsedIcon && !menuItem.avatar,\n pressed: this.pressedItem && this.pressedItem.id == menuItem.id,\n 'show-mobile': menuItem.mobile,\n });\n\n if (menuItem.avatar) {\n icon = renderAvatar({\n name: menuItem.avatar,\n tip: false,\n scale: parent ? 0.9 : 1.2,\n });\n if (menuItem.bubble) {\n icon = html`${icon}${menuItem.bubble\n ? html``\n : null}`;\n }\n icon = html`
    ${icon}
    `;\n }\n\n const item = html`\n {\n event.preventDefault();\n this.pressedItem = null;\n this.handleItemClicked(event, menuItem, parent);\n }}\n @mousedown=${() => {\n if (menuItem.level > 0) {\n this.pressedItem = menuItem;\n }\n }}\n @mouseleave=${() => {\n this.pressedItem = null;\n }}\n >\n ${menuItem.level === 0\n ? menuItem.avatar\n ? icon\n : html`${icon}`\n : html`${icon}${collapsedIcon}`}\n\n
    \n \n ${menuItem.name}\n
    \n ${menuItem.level > 0\n ? menuItem.inline\n ? html``\n : html`${menuItem.count || menuItem.count == 0\n ? html`\n \n ${menuItem.count.toLocaleString()}\n \n `\n : html`
    `}`\n : null}\n \n
    \n \n `;\n\n if (menuItem.popup) {\n return html`\n \n
    ${item}
    \n
    \n
    \n ${(menuItem.items || []).map((child: MenuItem) => {\n child.level = menuItem.level + 1;\n return html`${this.renderMenuItem(child, menuItem)}`;\n })}\n
    \n
    \n \n `;\n }\n return item;\n };\n\n public render(): TemplateResult {\n if (!this.root || !this.root.items) {\n return null;\n }\n\n let items = this.root.items || [];\n const levels = [];\n\n const expandIcon = this.isMobile() ? Icon.menu : Icon.menu_collapse;\n\n levels.push(\n html`
    \n
    \n
    \n \n
    \n
    \n
    \n\n ${items\n .filter(item => !item.bottom)\n .map((item: MenuItem) => {\n return this.renderMenuItem(item);\n })}\n\n
    \n ${items\n .filter(item => !!item.bottom)\n .map((item: MenuItem) => {\n return this.renderMenuItem(item);\n })}\n
    \n
    `\n );\n\n this.selection.forEach((id, index) => {\n const selected = findItem(items, id).item;\n\n let collapsed = false;\n if (selected) {\n items = selected.items;\n const itemState = this.getMenuItemState(selected.id);\n // users set an explicit collapse state\n if (itemState.collapsed) {\n collapsed = itemState.collapsed === 'collapsed';\n }\n // otherwise pick a default collapse state\n else {\n if (this.selection.length > selected.level + 2) {\n collapsed = false;\n }\n }\n } else {\n items = null;\n }\n\n const collapseIcon = this.isMobile() ? Icon.close : Icon.menu_collapse;\n\n if (items && items.length > 0 && !selected.inline) {\n levels.push(\n html`\n ${!this.submenu\n ? html`\n \n
    \n
    ${selected.name}
    \n\n ${index == 0 && !this.collapsed\n ? html``\n : null}\n
    \n `\n : null}\n ${items.map((item: MenuItem) => {\n if (item.inline && item.items) {\n return html`${this.renderMenuItem(item)}\n
    \n ${(item.items || []).map((child: MenuItem) => {\n return this.renderMenuItem(child, item);\n })}\n
    `;\n }\n return this.renderMenuItem(item);\n })}\n `\n );\n }\n });\n\n const menu = html`\n ${levels}\n `;\n return html`${menu}`;\n }\n}\n","import { LitElement, TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\n\nexport class Anchor extends LitElement {\n static get styles() {\n return css`\n :host {\n color: var(--color-link-primary);\n display: inline-block;\n }\n\n slot:hover {\n cursor: pointer;\n text-decoration: underline;\n }\n `;\n }\n\n @property({ type: String })\n href: string;\n\n private handleClick(evt: MouseEvent) {\n // TODO: fire event instead to be handled upstream\n (window as any).goto(evt);\n }\n\n public render(): TemplateResult {\n return html``;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\nimport { getClasses } from '../utils';\nimport { ContactStoreElement } from '../contacts/ContactStoreElement';\n\nexport class Dropdown extends RapidElement {\n static get styles() {\n return css`\n .wrapper {\n position: relative;\n }\n\n .toggle {\n cursor: pointer;\n }\n\n .dropdown-wrapper {\n position: relative;\n overflow: auto;\n }\n\n .dropdown {\n position: absolute;\n opacity: 0;\n z-index: 2;\n pointer-events: none;\n padding: 0;\n border-radius: var(--curvature);\n background: #fff;\n transform: translateY(1em) scale(0.9);\n transition: all calc(0.8 * var(--transition-speed)) var(--bounce);\n user-select: none;\n margin-top: 0px;\n margin-left: 0px;\n box-shadow: var(--dropdown-shadow);\n }\n\n .dropdown:focus {\n outline: none;\n }\n\n .arrow {\n content: '';\n width: 0px;\n height: 0;\n top: -6px;\n z-index: 10;\n position: absolute;\n border-left: 6px solid transparent;\n border-right: 6px solid transparent;\n border-bottom: 6px solid white;\n }\n\n .open .dropdown {\n opacity: 1;\n pointer-events: auto;\n transform: translateY(0.5em) scale(1);\n }\n\n .mask {\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n opacity: 0;\n transition: opacity var(--transition-speed) ease-in-out;\n pointer-events: none;\n z-index: 1;\n }\n\n .mask.open {\n opacity: 1;\n pointer-events: auto;\n }\n\n .right {\n right: 0;\n }\n `;\n }\n\n @property({ type: Boolean })\n open = false;\n\n @property({ type: Boolean })\n top = false;\n\n @property({ type: Boolean })\n bottom = false;\n\n @property({ type: Boolean })\n left = false;\n\n @property({ type: Boolean })\n right = false;\n\n @property({ type: Number })\n arrowSize = 6;\n\n @property({ type: Number })\n arrowOffset = this.arrowSize * 2;\n\n @property({ type: Number })\n offsetX = 0;\n\n @property({ type: Number })\n offsetY = 0;\n\n @property({ type: Boolean })\n mask = false;\n\n constructor() {\n super();\n this.ensureOnScreen = this.ensureOnScreen.bind(this);\n }\n\n public firstUpdated(props: any) {\n super.firstUpdated(props);\n\n const arrow = this.shadowRoot.querySelector('.arrow') as HTMLDivElement;\n arrow.style.borderWidth = this.arrowSize + 'px';\n arrow.style.top = '-' + this.arrowSize + 'px';\n\n if (this.arrowOffset < 0) {\n arrow.style.right = Math.abs(this.arrowOffset) + 'px';\n } else {\n arrow.style.left = this.arrowOffset + 'px';\n }\n\n const dropdown = this.shadowRoot.querySelector(\n '.dropdown'\n ) as HTMLDivElement;\n\n dropdown.addEventListener('blur', () => {\n // we nest this to deal with clicking the toggle to close\n // as we don't want it to toggle an immediate open, probably\n // a better way to deal with this\n window.setTimeout(() => {\n this.open = false;\n // blur our host element too\n (this.shadowRoot.host as HTMLDivElement).blur();\n }, 200);\n });\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n const dropdown = this.shadowRoot.querySelector(\n '.dropdown'\n ) as HTMLDivElement;\n\n if (changedProperties.has('offsetY') || changedProperties.has('offsetX')) {\n dropdown.style.marginTop = this.offsetY + 'px';\n if (dropdown.offsetLeft + dropdown.clientWidth > window.outerWidth) {\n dropdown.style.marginLeft =\n '-' + (dropdown.clientWidth - this.clientWidth - this.offsetX) + 'px';\n } else {\n if (this.right) {\n dropdown.style.marginRight = this.offsetX + 'px';\n } else {\n dropdown.style.marginLeft = this.offsetX + 'px';\n }\n }\n }\n\n if (changedProperties.has('open')) {\n // check right away if we are on the screen, and then again moments after render\n window.setTimeout(this.ensureOnScreen, 0);\n window.setTimeout(this.ensureOnScreen, 100);\n }\n }\n\n public ensureOnScreen() {\n const dropdown = this.shadowRoot.querySelector(\n '.dropdown'\n ) as HTMLDivElement;\n\n if (dropdown) {\n // dropdown will go off the screen, let's push it up\n const toggle = this.querySelector('div[slot=\"toggle\"]');\n\n if (!toggle) {\n return;\n }\n\n if (dropdown.getBoundingClientRect().bottom > window.innerHeight - 100) {\n if (this.bottom) {\n dropdown.style.top = toggle.clientHeight + 'px';\n } else {\n dropdown.style.top = '';\n dropdown.style.bottom = toggle.clientHeight + 'px';\n }\n } else if (dropdown.getBoundingClientRect().top < 0) {\n if (this.bottom) {\n dropdown.style.top = toggle.clientHeight + 'px';\n } else {\n dropdown.style.top = toggle.clientHeight + 'px';\n dropdown.style.bottom = '';\n }\n }\n\n if (dropdown.getBoundingClientRect().right > window.innerWidth) {\n dropdown.style.left = '';\n dropdown.style.right = '0px';\n } else if (dropdown.getBoundingClientRect().left < 0) {\n dropdown.style.left = 0 + 'px';\n dropdown.style.right = '';\n }\n }\n }\n\n public handleToggleClicked(event: MouseEvent): void {\n event.preventDefault();\n event.stopPropagation();\n if (!this.open) {\n this.open = true;\n\n const dropdown = this.shadowRoot.querySelector(\n '.dropdown'\n ) as HTMLDivElement;\n dropdown.focus();\n }\n }\n\n private handleDropdownMouseDown(event: MouseEvent): void {\n // block mouse down when clicking inside dropdown so we don't lose focus yet\n event.preventDefault();\n event.stopPropagation();\n }\n\n public render(): TemplateResult {\n return html`\n ${this.mask\n ? html`
    `\n : null}\n\n
    \n \n \n
    \n
    \n \n
    \n
    \n
    \n `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { RapidElement } from '../RapidElement';\nimport { getClasses } from '../utils';\nimport { Tab } from './Tab';\n\nexport class TabPane extends RapidElement {\n static get styles() {\n return css`\n :host {\n display: flex;\n flex-direction: column;\n min-height: 0;\n flex-grow: 1;\n }\n\n .tabs {\n display: flex;\n align-items: stretch;\n }\n\n .tab {\n user-select: none;\n padding: 0.5em 0.7em;\n margin: 0em 0em;\n cursor: pointer;\n display: flex;\n font-size: 1.01em;\n align-items: center;\n border-radius: var(--curvature);\n border-bottom-right-radius: 0px;\n border-bottom-left-radius: 0px;\n border: 0px solid rgba(0, 0, 0, 0.45);\n color: var(--color-text-dark);\n --icon-color: var(--color-text-dark);\n white-space: nowrap;\n transition: all 100ms linear;\n }\n\n .focusedname .tab .name {\n transition: all 0s linear !important;\n }\n\n .focusedname .tab.selected .name {\n transition: all 200ms linear !important;\n }\n\n .tab.hidden {\n display: none;\n }\n\n .tab temba-icon {\n }\n\n .tab .name {\n margin-left: 0.4em;\n max-width: 80px;\n overflow: hidden;\n transition: max-width 500ms ease-in-out, margin 500ms ease-in-out;\n white-space: nowrap;\n text-overflow: ellipsis;\n }\n\n .tab .badge {\n margin-left: 0.4em;\n }\n\n @media (max-width: 900px) {\n .collapses .tab .name {\n max-width: 0px;\n margin: 0;\n }\n }\n\n @media (max-width: 600px) {\n .collapses .tab .badge {\n display: none;\n }\n }\n\n .focusedname .tab.selected {\n transform: none;\n }\n\n .focusedname .tab .name {\n max-width: 0px;\n margin: 0;\n transition: max-width 200ms linear, margin 200ms linear;\n }\n\n .focusedname .tab.selected .name {\n margin-left: 0.4em;\n max-width: 200px;\n }\n\n .tab {\n transform: scale(0.9) translate(0em, -0.05em);\n --icon-color: #aaa;\n color: #aaa;\n }\n\n .tab.selected {\n }\n\n .tab.selected,\n .tab.selected:hover {\n cursor: default;\n box-shadow: 0px -3px 3px 1px rgba(0, 0, 0, 0.02);\n background: var(--focused-tab-color, #fff);\n transform: scale(1) translateY(0em);\n --icon-color: #666;\n color: #666;\n }\n\n .bottom .tab.selected {\n }\n\n .tab:hover {\n --icon-color: #666;\n color: #666;\n background: rgba(0, 0, 0, 0.02);\n }\n\n .pane {\n display: flex;\n flex-direction: column;\n flex-grow: 1;\n background: var(--focused-tab-color, #fff);\n border-radius: var(--curvature);\n box-shadow: var(\n --tabs-shadow,\n rgba(0, 0, 0, 0.1) 0px 1px 3px 0px,\n rgba(0, 0, 0, 0.03) 0px 1px 2px 0px\n );\n min-height: 0;\n }\n\n .pane.first {\n border-top-left-radius: 0px;\n overflow: hidden;\n }\n\n .badge {\n }\n\n .count {\n border-radius: 99px;\n background: rgba(0, 0, 0, 0.05);\n color: rgba(0, 0, 0, 0.5);\n font-size: 0.6em;\n font-weight: 400;\n padding: 0.1em 0.4em;\n min-width: 1em;\n text-align: center;\n }\n\n .notify .count {\n background: var(--color-alert);\n color: #fff;\n }\n\n .bottom.tabs .tab {\n border-radius: 0em;\n }\n\n .bottom.pane {\n border-radius: 0em;\n }\n\n .bottom.pane.first {\n border-bottom-left-radius: 0px;\n }\n\n .bottom .tab.first {\n border-bottom-left-radius: var(--curvature);\n }\n\n .embedded.pane {\n box-shadow: none;\n margin: 0;\n }\n\n .embedded.tabs {\n margin: 0;\n }\n\n .embedded .tab {\n }\n\n .embedded.tabs .tab.selected {\n box-shadow: none !important;\n }\n\n .embedded.pane {\n // padding: 0.3em;\n }\n\n .check {\n margin-left: 0.4em;\n }\n `;\n }\n\n @property({ type: Boolean })\n embedded = false;\n\n @property({ type: Boolean })\n collapses = false;\n\n // are the tabs on the bottom of the pane?\n @property({ type: Boolean })\n bottom = false;\n\n // Only shows the name if the tab is focused\n @property({ type: Boolean })\n focusedName = false;\n\n @property({ type: Number })\n index = -1;\n\n @property({ type: String })\n refresh = '';\n\n private handleTabClick(event: MouseEvent): void {\n this.index = parseInt(\n (event.currentTarget as HTMLDivElement).dataset.index\n );\n event.preventDefault();\n event.stopPropagation();\n this.requestUpdate('index');\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n if (changedProperties.has('index')) {\n const tabs = this.getTabs();\n if (tabs.length > this.index) {\n for (let i = 0; i < tabs.length; i++) {\n const tab = tabs[i];\n tab.selected = i == this.index;\n if (tab.selected) {\n tab.style.display = 'flex';\n } else {\n tab.style.display = 'none';\n }\n }\n }\n this.fireEvent(CustomEventType.ContextChanged);\n }\n\n // if our current tab is hidden, select the first visible one\n if (this.index > -1) {\n const tabs = this.getTabs();\n if (this.getTab(this.index).hidden) {\n for (let i = 0; i < tabs.length; i++) {\n const tab = this.getTab(i);\n if (!tab.hidden) {\n this.index = i;\n return;\n }\n }\n }\n }\n }\n\n public getCurrentTab(): Tab {\n return this.getTabs()[this.index];\n }\n\n public getTab(index: number): Tab {\n return this.getTabs()[index];\n }\n\n public handleTabContentChanged() {\n this.requestUpdate();\n }\n\n public getTabs(): Tab[] {\n const tabs: Tab[] = [];\n for (const t of this.children) {\n if (t.tagName === 'TEMBA-TAB') {\n const tab = t as Tab;\n tabs.push(tab);\n }\n }\n return tabs;\n }\n\n public render(): TemplateResult {\n const tabs = this.getTabs();\n\n return html`\n ${this.bottom\n ? html`\n \n `\n : null}\n\n \n ${tabs.map(\n (tab, index) => html`\n \n ${tab.icon ? html`` : null}\n
    ${tab.name}
    \n ${tab.hasBadge()\n ? html`\n
    \n ${tab.count > 0\n ? html`
    \n ${tab.count.toLocaleString()}\n
    `\n : null}\n
    \n `\n : null}\n ${tab.checked\n ? html``\n : null}\n \n `\n )}\n\n
    \n
    \n \n
    \n \n ${!this.bottom\n ? html`\n \n `\n : null}\n `;\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\nimport { getClasses } from '../utils';\n\nexport class Tab extends RapidElement {\n static get styles() {\n return css`\n :host {\n display: flex;\n flex-direction: column;\n flex-grow: 1; \n min-height: 0;\n } \n \n slot {\n // display: none;\n \n\n slot.selected {\n // display: flex;\n // flex-direction: column;\n // flex-grow: 1;\n }\n `;\n }\n\n @property({ type: String })\n name: string;\n\n @property({ type: String })\n icon: string;\n\n @property({ type: String })\n selectionColor: string;\n\n @property({ type: String })\n selectionBackground: string;\n\n @property({ type: Boolean })\n selected = false;\n\n @property({ type: Boolean })\n notify = false;\n\n @property({ type: Boolean })\n hidden = false;\n\n @property({ type: Number })\n count = 0;\n\n @property({ type: Boolean })\n checked = false;\n\n public hasBadge() {\n return this.count > 0;\n }\n\n public render(): TemplateResult {\n return html` `;\n }\n}\n","import { LitElement, TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { getClasses } from '../utils';\nimport { styleMap } from 'lit-html/directives/style-map.js';\n\nexport default class Label extends LitElement {\n static get styles() {\n return css`\n :host {\n display: inline-block;\n }\n\n slot {\n white-space: nowrap;\n overflow-x: hidden;\n text-overflow: ellipsis;\n display: block;\n }\n\n .mask {\n padding: 3px 8px;\n border-radius: 12px;\n display: flex;\n }\n\n temba-icon {\n margin-right: 0.3em;\n padding-bottom: 0.1em;\n }\n\n .label.clickable .mask:hover {\n background: var(--color-background-hover, rgb(0, 0, 0, 0.05));\n }\n\n .label {\n font-size: 0.8em;\n font-weight: 400;\n border-radius: 12px;\n box-shadow: var(--widget-shadow, 0 0.04em 0.08em rgba(0, 0, 0, 0.15));\n background: var(--color-overlay-light);\n color: var(--color-overlay-light-text);\n --icon-color: var(--color-overlay-light-text);\n text-shadow: none;\n }\n\n .danger {\n background: tomato;\n color: #fff;\n --icon-color: #fff;\n }\n\n .primary {\n background: var(--color-primary-dark);\n color: var(--color-text-light);\n --icon-color: var(--color-text-light);\n }\n\n .secondary {\n background: var(--color-secondary-dark);\n color: var(--color-text-light);\n --icon-color: var(--color-text-light);\n }\n\n .tertiary {\n background: var(--color-tertiary);\n color: var(--color-text-light);\n --icon-color: var(--color-text-light);\n }\n\n .dark {\n background: var(--color-overlay-dark);\n text-shadow: none;\n }\n\n .clickable {\n cursor: pointer;\n }\n\n .shadow {\n box-shadow: 1px 1px 2px 1px rgba(0, 0, 0, 0.1);\n }\n `;\n }\n\n @property({ type: Boolean })\n clickable: boolean;\n\n @property({ type: Boolean })\n primary: boolean;\n\n @property({ type: Boolean })\n secondary: boolean;\n\n @property({ type: Boolean })\n tertiary: boolean;\n\n @property({ type: Boolean })\n danger: boolean;\n\n @property({ type: Boolean })\n dark: boolean;\n\n @property({ type: Boolean })\n shadow: boolean;\n\n @property({ type: String })\n icon: string;\n\n @property()\n backgroundColor: string;\n\n @property()\n textColor: string;\n\n public render(): TemplateResult {\n const labelStyle = {};\n\n if (this.backgroundColor) {\n labelStyle['background'] = this.backgroundColor;\n }\n\n if (this.textColor) {\n labelStyle['color'] = this.textColor;\n labelStyle['--icon-color'] = this.textColor;\n }\n\n return html`\n \n
    \n ${this.icon ? html`` : null}\n \n
    \n \n `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\n\nexport class ContactName extends RapidElement {\n @property({ type: String })\n name: string;\n\n @property({ type: String })\n urn: string;\n\n @property({ type: Number, attribute: 'icon-size' })\n size = 20;\n\n static get styles() {\n return css`\n :host {\n display: flex;\n align-items: center;\n }\n\n temba-urn {\n margin-right: 0.2em;\n }\n\n .name {\n font-size: var(--contact-name-font-size, 1.5rem);\n overflow: hidden;\n max-height: 2rem;\n line-height: 2rem;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: 1;\n text-overflow: ellipsis;\n }\n `;\n }\n public render(): TemplateResult {\n const urn = this.urn\n ? html``\n : null;\n return html`\n ${urn}\n
    \n ${this.name ? this.name : this.urn ? this.urn.split(':')[1] : ''}\n
    \n \n `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\n\nexport class ContactUrn extends RapidElement {\n @property({ type: String })\n urn: string;\n\n @property({ type: String })\n scheme: string;\n\n @property({ type: Number })\n size = 20;\n\n static get styles() {\n return css`\n :host {\n display: flex;\n align-items: center;\n }\n .urn {\n box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.04) inset;\n padding: 3px;\n border: 1px solid #ddd;\n border-radius: 18rem;\n background: #eee;\n margin-right: 0.2em;\n }\n\n .small {\n padding: 0px;\n border: 0px;\n box-shadow: none;\n margin-right: 0.5em;\n }\n `;\n }\n\n public render(): TemplateResult {\n const scheme = this.scheme || this.urn.split(':')[0];\n return html`\n \n `;\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { getClasses, postJSON } from '../utils';\nimport { ContactFieldEditor } from './ContactFieldEditor';\nimport { ContactStoreElement } from './ContactStoreElement';\nimport { Checkbox } from '../checkbox/Checkbox';\n\nconst MIN_FOR_FILTER = 10;\n\nexport class ContactFields extends ContactStoreElement {\n static get styles() {\n return css`\n .field {\n display: flex;\n margin: 0.3em 0.3em;\n box-shadow: 0 0 0.2em rgba(0, 0, 0, 0.15);\n border-radius: 0px;\n align-items: center;\n overflow: hidden;\n }\n\n .show-all .unset,\n .featured {\n display: block !important;\n }\n\n .unset {\n display: none;\n }\n\n .field:hover {\n box-shadow: 1px 1px 6px 2px rgba(0, 0, 0, 0.05),\n 0px 0px 0px 2px var(--color-link-primary);\n cursor: pointer;\n }\n\n .label {\n padding: 0.25em 1em;\n border-top-left-radius: 0px;\n border-bottom-left-radius: 0px;\n color: #777;\n font-size: 0.9em;\n font-weight: 400;\n box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.1) inset;\n }\n\n .value {\n --icon-color: #ddd;\n max-width: 150px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n padding: 0.25em 1em;\n border-top-right-radius: 0px;\n border-bottom-right-radius: 0px;\n font-size: 0.9em;\n }\n\n .toggle {\n display: flex;\n background: #fff;\n align-items: center;\n margin-bottom: 0.5em;\n }\n\n .disabled .toggle {\n display: none;\n }\n `;\n }\n\n @property({ type: Boolean })\n system: boolean;\n\n @property({ type: Boolean })\n dirty: boolean;\n\n @property({ type: Boolean })\n showAll: boolean;\n\n @property({ type: String })\n timezone: string;\n\n @property({ type: String })\n role: string;\n\n @property({ type: Boolean })\n disabled = false;\n\n connectedCallback(): void {\n super.connectedCallback();\n this.handleFieldChanged = this.handleFieldChanged.bind(this);\n }\n\n private isAgent(): boolean {\n return this.role === 'T';\n }\n\n protected updated(\n changes: PropertyValueMap | Map\n ): void {\n super.updated(changes);\n if (changes.has('data')) {\n if (Object.keys(this.data.fields).length <= MIN_FOR_FILTER) {\n this.showAll = true;\n }\n }\n }\n\n public handleFieldChanged(evt: InputEvent) {\n const field = evt.currentTarget as ContactFieldEditor;\n const value = field.value;\n postJSON('/api/v2/contacts.json?uuid=' + this.data.uuid, {\n fields: { [field.key]: value },\n })\n .then((response: any) => {\n field.handleResponse(response);\n\n // returns a single contact with latest updates\n this.setContact(response.json);\n })\n .catch(error => {\n field.handleResponse(error);\n });\n }\n\n public handleToggle(evt: Event) {\n const checkbox = evt.currentTarget as Checkbox;\n this.showAll = checkbox.checked;\n }\n\n public render(): TemplateResult {\n if (this.data) {\n const fieldsToShow = Object.entries(this.data.fields).sort(\n (a: [string, string], b: [string, string]) => {\n const [ak] = a;\n const [bk] = b;\n const fieldA = this.store.getContactField(ak);\n const fieldB = this.store.getContactField(bk);\n\n if (fieldA.type === 'ward') {\n return 1;\n }\n\n if (fieldB.type === 'ward') {\n return -1;\n }\n\n if (\n fieldA.type === 'district' &&\n fieldB.type !== 'ward' &&\n fieldB.type !== 'district'\n ) {\n return 1;\n }\n\n if (\n fieldB.type === 'district' &&\n fieldA.type !== 'ward' &&\n fieldA.type !== 'district'\n ) {\n return -1;\n }\n\n if (\n fieldA.type === 'state' &&\n fieldB.type !== 'ward' &&\n fieldB.type !== 'district' &&\n fieldB.type !== 'state'\n ) {\n return 1;\n }\n\n if (\n fieldB.type === 'state' &&\n fieldA.type !== 'ward' &&\n fieldA.type !== 'district' &&\n fieldA.type !== 'state'\n ) {\n return -1;\n }\n\n if (fieldA.featured && !fieldB.featured) {\n return -1;\n }\n\n if (fieldB.featured && !fieldA.featured) {\n return 1;\n }\n\n const priority = fieldB.priority - fieldA.priority;\n if (priority !== 0) {\n return priority;\n }\n\n return ak.localeCompare(bk);\n }\n );\n\n if (fieldsToShow.length == 0) {\n return html``;\n }\n\n const fields = fieldsToShow.map((entry: [string, string]) => {\n const [k, v] = entry;\n const field = this.store.getContactField(k);\n return html``;\n });\n\n return html`\n
    \n
    ${fields}
    \n ${Object.keys(this.data.fields).length >= MIN_FOR_FILTER\n ? html`
    \n
    \n
    \n \n
    \n
    `\n : null}\n
    \n `;\n }\n\n return super.render();\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { FormElement } from '../FormElement';\nimport { CustomEventType } from '../interfaces';\nimport { RapidElement } from '../RapidElement';\nimport { InputType, TextInput } from '../textinput/TextInput';\nimport { Icon } from '../vectoricon';\nimport { getClasses, WebResponse } from '../utils';\n\nenum Status {\n Success = 'success',\n Failure = 'failure',\n Saving = 'saving',\n Ready = 'ready',\n}\n\nexport class ContactFieldEditor extends RapidElement {\n @property({ type: String })\n key: string;\n\n @property({ type: String })\n value: string;\n\n @property({ type: String })\n name: string;\n\n @property({ type: String })\n type: string;\n\n @property({ type: String })\n timezone: string;\n\n @property({ type: String })\n icon = navigator.clipboard ? Icon.copy : '';\n\n @property({ type: String })\n iconClass = '';\n\n @property({ type: String })\n status: Status = Status.Ready;\n\n @property({ type: Boolean })\n disabled = false;\n\n @property({ type: Boolean })\n dirty = false;\n\n static get styles() {\n return css`\n :host {\n --transition-speed: 0ms;\n }\n\n .wrapper {\n --temba-textinput-padding: 1.4em 0.8em 0.4em 0.8em;\n --disabled-opacity: 1;\n position: relative;\n --color-widget-bg: transparent;\n --color-widget-bg-focused: #fff;\n --widget-box-shadow: none;\n padding-bottom: 0.6em;\n border-bottom: 1px solid #ececec;\n }\n\n .wrapper.disabled {\n --color-widget-border: transparent;\n }\n\n .wrapper.mutable:hover {\n }\n\n .wrapper.mutable {\n --color-widget-border: rgb(235, 235, 235);\n --color-widget-bg: transparent;\n --input-cursor: pointer;\n\n border-bottom: none;\n margin-bottom: 0.5em;\n padding-bottom: 0em;\n }\n\n .mutable.success {\n --color-widget-border: rgba(var(--success-rgb), 0.6);\n }\n\n .mutable.failure {\n --color-widget-border: rgba(var(--error-rgb), 0.3) !important;\n }\n\n .mutable .dirty {\n --color-widget-border: rgb(235, 235, 235);\n }\n\n .prefix {\n border-top-left-radius: var(--curvature-widget);\n border-bottom-left-radius: var(--curvature-widget);\n cursor: pointer !important;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n display: flex;\n padding: 0em 0.5em;\n position: absolute;\n margin-top: 0.2em;\n pointer-events: none;\n }\n\n .wrapper {\n margin-bottom: 0.5em;\n }\n\n .prefix .name {\n padding: 0em 0.4em;\n color: rgba(100, 100, 100, 0.7);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n font-size: 0.8em;\n }\n\n .postfix {\n display: flex;\n align-items: stretch;\n margin-left: 1em;\n }\n\n .popper {\n background: rgba(0, 0, 0, 0.03);\n border-top-right-radius: var(--curvature-widget);\n border-bottom-right-radius: var(--curvature-widget);\n --icon-color: #888;\n display: flex;\n cursor: default;\n transition: all var(--transition-speed) ease-in-out;\n align-items: stretch;\n margin: -1px;\n }\n\n temba-icon[name='calendar'] {\n --icon-color: rgba(0, 0, 0, 0.2);\n }\n\n temba-icon:hover {\n --icon-color: rgba(0, 0, 0, 0.5);\n }\n\n temba-icon {\n cursor: pointer;\n --icon-color: rgba(0, 0, 0, 0.3);\n }\n\n temba-textinput:focus .popper,\n temba-textinput:hover .popper {\n display: flex;\n }\n\n .disabled temba-textinput .postfix {\n display: none;\n padding: none;\n }\n\n .unset temba-textinput .popper .copy,\n .unset temba-textinput .popper .search {\n display: none;\n }\n\n .unset temba-textinput:focus .popper .copy,\n .unset temba-textinput:hover .popper .copy,\n .unset temba-textinput:focus .popper .save,\n .unset temba-textinput:hover .popper .save {\n display: none;\n }\n\n .popper temba-icon {\n padding: 0.5em 0em;\n padding-right: 1em;\n }\n\n .popper:first-child {\n padding: 0.5em 0em;\n padding-right: 0.5em;\n padding-left: 1em;\n }\n\n .popper:last-child {\n padding-right: 0em;\n }\n\n .copy.clicked temba-icon {\n transform: scale(1.2);\n }\n\n temba-icon {\n transition: all 200ms ease-in-out;\n }\n\n temba-datepicker {\n position: relative;\n }\n\n .save-state {\n display: flex;\n align-items: center;\n }\n\n .save-button {\n padding-right: 1em;\n }\n\n .dirty .copy,\n .dirty .search {\n display: none;\n }\n\n .saving .copy,\n .saving .search {\n display: none;\n }\n\n .success .copy,\n .success .search {\n display: none;\n }\n\n .failure .copy,\n .failure .search {\n display: none;\n }\n\n .popper.success {\n background: rgb(var(--success-rgb));\n }\n\n .popper.failure {\n background: rgb(var(--error-rgb));\n }\n\n .popper.success temba-icon,\n .popper.failure temba-icon {\n --icon-color: #fff !important;\n }\n\n .popper.dirty {\n background: rgba(0, 0, 0, 0.03);\n }\n\n temba-datepicker .popper {\n border-radius: 0px;\n }\n\n temba-datepicker .popper:first-child {\n padding: 0;\n }\n\n .dirty temba-datepicker .popper:first-child {\n padding-left: 1em;\n }\n\n .success temba-datepicker .popper:first-child {\n padding-left: 1em;\n }\n\n .failure temba-datepicker .popper:first-child {\n padding-left: 1em;\n }\n\n .saving temba-datepicker .popper:first-child {\n padding-left: 1em;\n }\n\n temba-datepicker .postfix {\n margin-left: 0;\n }\n\n .saving temba-datepicker,\n .saving temba-textinput {\n pointer-events: none !important;\n cursor: default !important;\n opacity: 0.7;\n }\n `;\n }\n\n connectedCallback(): void {\n super.connectedCallback();\n this.handleInput = this.handleInput.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n }\n\n public handleIconClick(evt: MouseEvent) {\n const ele = evt.target as HTMLDivElement;\n const icon = ele.getAttribute('icon-action');\n const input = this.shadowRoot.querySelector('temba-textinput') as TextInput;\n\n if (icon === 'copy') {\n if (navigator.clipboard) {\n this.iconClass = 'clicked';\n navigator.clipboard.writeText(input.getDisplayValue()).then(() => {\n window.setTimeout(() => {\n this.iconClass = '';\n }, 300);\n });\n }\n }\n\n if (icon === 'search') {\n this.fireCustomEvent(CustomEventType.ButtonClicked, {\n key: this.key,\n value: this.value,\n });\n }\n\n evt.preventDefault();\n evt.stopPropagation();\n }\n\n public handleResponse(response: WebResponse) {\n if (response.status === 200) {\n this.value = response.json.fields[this.key];\n // this.status = Status.Success;\n // on success lets go back to ready state for now\n this.status = Status.Ready;\n this.dirty = false;\n } else {\n this.status = Status.Failure;\n this.dirty = false;\n }\n }\n\n public handleSubmit() {\n const input = this.shadowRoot.querySelector(\n 'temba-textinput, temba-datepicker'\n ) as FormElement;\n\n if (input.value !== this.value) {\n this.dirty = true;\n this.status = Status.Saving;\n this.value = input.value;\n this.fireEvent('change');\n }\n }\n\n public handleChange(evt: Event) {\n evt.preventDefault();\n evt.stopPropagation();\n }\n\n public handleDateChange(evt: Event) {\n evt.preventDefault();\n evt.stopPropagation();\n this.dirty = true;\n }\n\n public handleInput(evt: KeyboardEvent) {\n const input = evt.currentTarget as TextInput;\n if (evt.key === 'Enter') {\n input.blur();\n this.handleSubmit();\n } else {\n if (input.value !== this.value) {\n this.dirty = true;\n }\n }\n }\n\n private getInputType(type: string): string {\n if (type === 'numeric') {\n return InputType.Number;\n }\n return InputType.Text;\n }\n\n public render(): TemplateResult {\n const state = html`
    \n ${this.dirty\n ? html``\n : html` ${this.status === Status.Saving\n ? html``\n : null}\n ${this.status === Status.Success && !this.dirty\n ? html``\n : null}\n ${this.status === Status.Failure\n ? html``\n : null}`}\n
    `;\n\n return html`\n \n ${this.type === 'datetime'\n ? html`\n \n
    \n
    ${this.name}
    \n
    \n
    \n \n ${state}\n
    \n \n \n `\n : html`\n \n
    \n
    ${this.name}
    \n
    \n\n
    \n \n ${state}\n\n \n \n
    \n \n \n `}\n \n `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { Group } from '../interfaces';\nimport { debounce, getClasses } from '../utils';\nimport { Icon } from '../vectoricon';\nimport { ContactStoreElement } from './ContactStoreElement';\n\nconst STATUS = {\n stopped: { name: 'Stopped' },\n blocked: { name: 'Blocked' },\n archived: { name: 'Archived' },\n};\n\nexport class ContactBadges extends ContactStoreElement {\n static get styles() {\n return css`\n .wrapper {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n temba-label {\n margin: 0.3em;\n }\n\n .expanded .badges {\n max-height: inherit;\n }\n\n .expanded .show-button {\n opacity: 1;\n margin-bottom: 0em;\n margin-top: -0.5em;\n }\n\n .expanded .show-line {\n width: 98%;\n opacity: 1;\n }\n\n .badges {\n display: flex;\n overflow: hidden;\n flex-wrap: wrap;\n max-height: 2.2em;\n align-self: flex-start;\n }\n\n .show-button {\n transition: all var(--transition-speed) ease-in-out\n var(--transition-speed);\n opacity: 0;\n display: flex;\n padding: 0em 1em;\n margin-top: -0.8em;\n cursor: pointer;\n --icon-color-circle: #fff;\n margin-bottom: -1.5em;\n }\n\n .show-line {\n height: 1px;\n width: 100%;\n background: rgba(0, 0, 0, 0.05);\n margin-top: 1em;\n width: 0px;\n transition: width calc(var(--transition-speed) * 2) linear\n var(--transition-speed);\n }\n\n .has-more .show-line {\n width: 98%;\n }\n\n .has-more .show-button {\n opacity: 1;\n margin-bottom: 0em;\n margin-top: -0.5em;\n }\n\n .show-button temba-icon {\n border-radius: 9999px;\n }\n `;\n }\n\n @property({ type: Boolean })\n hasMore = false;\n\n @property({ type: Boolean })\n expanded = false;\n\n private handleResized() {\n if (this.shadowRoot) {\n const badges = this.shadowRoot.querySelector('.badges');\n if (badges) {\n this.hasMore = badges.scrollHeight > badges.clientHeight;\n }\n }\n }\n\n public updated(changedProperties: Map) {\n super.updated(changedProperties);\n if (changedProperties.has('data')) {\n if (!changedProperties.get('data')) {\n const badges = this.shadowRoot.querySelector('.badges');\n new ResizeObserver(\n debounce(this.handleResized.bind(this), 200)\n ).observe(badges);\n }\n }\n }\n\n public render(): TemplateResult {\n if (this.data) {\n const status = STATUS[this.data.status];\n return html`\n \n
    \n ${status && this.data.status !== 'active'\n ? html`\n \n ${status.name}\n \n `\n : null}\n ${this.data.flow\n ? html`\n \n ${this.data.flow.name}\n \n `\n : null}\n ${this.data.language\n ? html`\n \n ${this.store.getLanguageName(this.data.language)}\n \n `\n : null}\n ${this.data.groups.map((group: Group) => {\n return html`\n \n ${group.name}\n \n `;\n })}\n
    \n
    \n\n
    \n {\n this.expanded = !this.expanded;\n }}\n circled\n name=${!this.expanded ? Icon.down : Icon.up}\n animateChange=\"spin\"\n >\n
    \n \n `;\n } else {\n return null;\n }\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport {\n CustomEventType,\n ScheduledEvent,\n ScheduledEventType,\n} from '../interfaces';\nimport { StoreElement } from '../store/StoreElement';\nimport { Icon } from '../vectoricon';\n\nconst ICONS = {\n [ScheduledEventType.CampaignEvent]: Icon.campaign,\n [ScheduledEventType.ScheduledBroadcast]: Icon.message,\n [ScheduledEventType.ScheduledTrigger]: Icon.trigger,\n};\n\nexport class ContactPending extends StoreElement {\n @property({ type: String })\n contact: string;\n\n @property({ type: Object, attribute: false })\n data: ScheduledEvent[];\n\n @property({ type: String })\n lang_weekly = 'Weekly';\n\n @property({ type: String })\n lang_daily = 'Daily';\n\n @property({ type: String })\n lang_once = 'Once';\n\n REPEAT_PERIOD = {\n O: this.lang_once,\n D: this.lang_daily,\n W: this.lang_weekly,\n };\n\n static get styles() {\n return css`\n :host {\n }\n\n a,\n .linked {\n color: var(--color-link-primary);\n cursor: pointer;\n }\n\n a:hover,\n .linked:hover {\n text-decoration: underline;\n color: var(--color-link-primary-hover);\n }\n\n .type {\n background: rgba(0, 0, 0, 0.02);\n padding: 1em;\n display: flex;\n align-self: stretch;\n --icon-color: rgba(50, 50, 50, 0.25);\n border-top-left-radius: var(--curvature);\n border-bottom-left-radius: var(--curvature);\n }\n\n .details {\n display: flex;\n flex-direction: column;\n padding: 0.5em 1em;\n flex-grow: 1;\n }\n\n .campaign {\n display: flex;\n color: var(--text-color);\n --icon-color: var(--text-color);\n align-self: center;\n white-space: nowrap;\n }\n\n .message {\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n padding: 0.1em;\n }\n\n .event {\n margin-bottom: 0.5em;\n border-radius: var(--curvature);\n display: flex;\n flex-direction: row;\n align-items: center;\n box-shadow: 0 0 8px 1px rgba(0, 0, 0, 0.055),\n 0 0 0px 1px rgba(0, 0, 0, 0.02);\n }\n\n .event:hover {\n cursor: pointer;\n box-shadow: 0 0 8px 1px rgba(0, 0, 0, 0.055),\n 0 0 0px 2px var(--color-link-primary);\n }\n\n .time {\n white-space: nowrap;\n background: rgba(0, 0, 0, 0.02);\n border-top-right-radius: var(--curvature);\n border-bottom-right-radius: var(--curvature);\n display: flex;\n align-self: stretch;\n padding: 0 1em;\n min-width: 5em;\n }\n\n .duration {\n align-self: center;\n flex-grow: 1;\n text-align: center;\n }\n\n .flow {\n display: inline-block;\n }\n\n temba-tip {\n cursor: default;\n }\n\n .scheduled-by {\n font-size: 0.85em;\n display: flex;\n color: var(--text-color);\n --icon-color: var(--text-color);\n }\n\n .scheduled-by temba-icon {\n margin-right: 0.25em;\n }\n\n .scheduled-by .name {\n flex-grow: 1;\n }\n `;\n }\n\n constructor() {\n super();\n this.handleEventClicked = this.handleEventClicked.bind(this);\n }\n\n protected updated(\n changes: PropertyValueMap | Map\n ): void {\n super.updated(changes);\n if (changes.has('contact')) {\n if (this.contact) {\n this.url = `/contact/scheduled/${this.contact}/`;\n } else {\n this.url = null;\n }\n }\n }\n\n public handleEventClicked(event: ScheduledEvent) {\n this.fireCustomEvent(CustomEventType.Selection, event);\n }\n\n public renderEvent(scheduledEvent: ScheduledEvent) {\n return html`\n this.handleEventClicked(scheduledEvent)}\"\n >\n
    \n \n
    \n\n
    \n
    \n ${scheduledEvent.flow\n ? html` Start ${scheduledEvent.flow.name}`\n : null}\n ${scheduledEvent.message\n ? html`
    ${scheduledEvent.message}
    `\n : null}\n
    \n\n
    \n ${scheduledEvent.campaign\n ? html`
    \n \n
    ${scheduledEvent.campaign.name}
    \n
    `\n : html`\n ${scheduledEvent.type === ScheduledEventType.ScheduledTrigger\n ? html``\n : null}\n
    \n ${this.REPEAT_PERIOD[scheduledEvent.repeat_period]}\n
    \n `}\n
    \n
    \n\n
    \n
    \n \n ${this.store.getShortDurationFromIso(scheduledEvent.scheduled)}\n \n
    \n
    \n \n `;\n }\n\n public render(): TemplateResult {\n if (this.data) {\n if (this.data.length > 0) {\n return html`\n ${this.data.map(event => {\n return this.renderEvent(event);\n })}\n `;\n } else {\n return html``;\n }\n }\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType, Ticket, TicketStatus, User } from '../interfaces';\nimport { StoreElement } from '../store/StoreElement';\nimport { getClasses, postJSON, stopEvent } from '../utils';\nimport { Icon } from '../vectoricon';\n\nconst dropdownUserScale = 0.7;\nconst inlineUserScale = 0.8;\n\nexport class ContactTickets extends StoreElement {\n @property({ type: String })\n agent: string;\n\n @property({ type: String })\n contact: string;\n\n @property({ type: String })\n ticket: string;\n\n @property({ type: Boolean })\n clickable = false;\n\n @property({ type: Boolean })\n expandable = false;\n\n @property({ type: Boolean })\n expanded = false;\n\n @property({ type: Object, attribute: false })\n data: Ticket[];\n\n static get styles() {\n return css`\n :host {\n }\n\n :hover {\n }\n\n .ticket.expandable:hover,\n .ticket.clickable:hover {\n cursor: pointer;\n box-shadow: 0 0 8px 1px rgba(0, 0, 0, 0.055),\n 0 0 0px 2px var(--color-link-primary);\n }\n\n .header {\n display: flex;\n flex-direction: row;\n flex-grow: 1;\n }\n\n .tickets {\n display: flex;\n flex-direction: column;\n padding: 0.3em 0.8em;\n }\n\n .count {\n margin-left: 0.5em;\n }\n\n .ticket {\n background: #fff;\n display: flex;\n flex-direction: column;\n margin-bottom: 0.5em;\n border-radius: var(--curvature);\n display: flex;\n flex-direction: column;\n align-items: stretch;\n box-shadow: 0 0 8px 1px rgba(0, 0, 0, 0.055),\n 0 0 0px 1px rgba(0, 0, 0, 0.02);\n transition: all 200ms ease-in-out;\n }\n\n .ticket .topic {\n overflow: hidden;\n text-overflow: ellipsis;\n margin: 0.5em 0.75em 0.5em 0.75em;\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: 1;\n flex-grow: 2;\n }\n\n .ticket .body {\n max-height: 0px;\n overflow-y: auto;\n -webkit-line-clamp: none;\n white-space: normal;\n width: initial;\n padding: 0.5em 0.75em 0em 0.75em;\n max-height: 40vh;\n display: none;\n margin-bottom: 0.5em;\n border-top: 1px solid #e6e6e6;\n }\n\n .ticket.expanded .body {\n display: block;\n }\n\n .status {\n --icon-color: #999;\n }\n\n .ticket.closed {\n background: #f9f9f9;\n color: #888;\n }\n\n .resolve {\n color: var(--color-primary-dark);\n }\n\n .dropdown {\n color: rgb(45, 45, 45);\n z-index: 50;\n width: 18em;\n }\n\n .option-group {\n padding: 0.4em;\n border-bottom: 1px solid #f3f3f3;\n }\n\n .option-group temba-user {\n flex-grow: 1;\n }\n\n .assigned .user {\n flex-grow: 1;\n }\n\n .assigned {\n display: flex;\n align-items: center;\n }\n\n .assigned temba-button {\n margin-right: 0.75em;\n }\n\n .assigned .user:hover {\n cursor: default;\n background: none;\n }\n\n .options {\n max-height: 40vh;\n overflow-y: auto;\n border-bottom: none;\n }\n\n .user {\n display: flex;\n align-items: center;\n border-radius: var(--curvature);\n cursor: pointer;\n }\n\n .user:hover {\n background: var(--color-selection);\n }\n\n .user .name {\n display: -webkit-box;\n -webkit-line-clamp: 1;\n -webkit-box-orient: vertical;\n overflow: hidden;\n flex-grow: 1;\n }\n\n .user temba-button {\n margin-left: 0.5em;\n }\n\n .current-user {\n font-weight: 400;\n }\n\n .details {\n display: flex;\n align-items: center;\n flex-shrink: 1;\n margin-right: 0.5em;\n }\n\n .details .date {\n padding: 0em 0.5em;\n }\n\n .details .toggle {\n padding-right: 0.5em;\n }\n `;\n }\n\n prepareData(data: any): any {\n if (data && data.length) {\n data.sort((a: Ticket, b: Ticket) => {\n if (a.status == TicketStatus.Open && b.status == TicketStatus.Closed) {\n return -1;\n }\n\n if (b.status == TicketStatus.Open && a.status == TicketStatus.Closed) {\n return 1;\n }\n\n if (\n a.status == TicketStatus.Closed &&\n b.status == TicketStatus.Closed\n ) {\n return (\n new Date(b.closed_on).getTime() - new Date(a.closed_on).getTime()\n );\n }\n\n return (\n new Date(b.opened_on).getTime() - new Date(a.opened_on).getTime()\n );\n });\n }\n return data;\n }\n\n protected updated(\n changes: PropertyValueMap | Map\n ): void {\n super.updated(changes);\n if (changes.has('contact') || changes.has('ticket')) {\n if (this.contact) {\n this.url = `/api/v2/tickets.json?contact=${this.contact}${\n this.ticket ? '&ticket=' + this.ticket : ''\n }`;\n } else {\n this.url = null;\n }\n }\n }\n\n private handleClose(uuid: string) {\n postJSON(`/api/v2/ticket_actions.json`, {\n tickets: [uuid],\n action: 'close',\n })\n .then(() => {\n this.refresh();\n })\n .catch((response: any) => {\n console.error(response);\n });\n }\n\n private handleReopen(uuid: string) {\n postJSON(`/api/v2/ticket_actions.json`, {\n tickets: [uuid],\n action: 'reopen',\n })\n .then(() => {\n this.refresh();\n })\n .catch((response: any) => {\n console.error(response);\n });\n }\n\n public handleTicketAssignment(uuid: string, email: string) {\n // if its already assigned to use, it's a noop\n const ticket = this.data.find(ticket => ticket.uuid === uuid);\n if (ticket.assignee && ticket.assignee.email === email) {\n return;\n }\n this.blur();\n\n postJSON(`/api/v2/ticket_actions.json`, {\n tickets: [uuid],\n action: 'assign',\n assignee: email,\n })\n .then(() => {\n this.refresh();\n })\n .catch((response: any) => {\n console.error(response);\n });\n return true;\n }\n\n public renderTicket(ticket: Ticket) {\n const date = ticket.opened_on;\n const users = this.store.getAssignableUsers();\n const agent = users.find(user => user.email === this.agent);\n return html`\n {\n if (this.clickable) {\n this.fireCustomEvent(CustomEventType.ButtonClicked, { ticket });\n } else if (this.expandable) {\n this.expanded = !this.expanded;\n }\n }}\n class=\"ticket ${ticket.status} ${getClasses({\n clickable: this.clickable,\n expandable: this.expandable,\n expanded: this.expanded,\n })}\"\n >\n
    \n
    ${ticket.topic.name}
    \n\n
    \n
    \n \n
    \n\n ${ticket.status === TicketStatus.Closed\n ? html`
    \n {\n event.preventDefault();\n event.stopPropagation();\n this.handleReopen(ticket.uuid);\n }}\n >\n
    `\n : html`\n
    \n \n
    \n ${ticket.assignee\n ? html`\n \n `\n : html`\n \n `}\n
    \n\n {\n stopEvent(event);\n }}\n >\n ${ticket.assignee\n ? html`\n \n \n {\n stopEvent(event);\n this.handleTicketAssignment(\n ticket.uuid,\n null\n );\n }}\n >\n
    \n `\n : null}\n ${agent &&\n (!ticket.assignee ||\n agent.email !== ticket.assignee.email)\n ? html`\n {\n stopEvent(event);\n this.handleTicketAssignment(\n ticket.uuid,\n agent.email\n );\n }}\n >\n \n
    \n `\n : null}\n\n
    \n ${this.store.getAssignableUsers().map(user => {\n if (\n ticket.assignee &&\n user.email === ticket.assignee.email\n ) {\n return null;\n }\n\n if (user.email === this.agent) {\n return null;\n }\n return html` {\n stopEvent(event);\n this.handleTicketAssignment(\n ticket.uuid,\n user.email\n );\n }}\n >\n \n
    `;\n })}\n
    \n \n \n \n \n {\n event.preventDefault();\n event.stopPropagation();\n this.handleClose(ticket.uuid);\n }}\n ?clickable=${open}\n />\n
    \n `}\n \n \n
    ${ticket.body}
    \n \n `;\n }\n\n public render(): TemplateResult {\n if (this.data && this.data.length > 0) {\n const tickets = this.data.map(ticket => {\n return this.renderTicket(ticket);\n });\n return html`${tickets}`;\n }\n\n return html``;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { property } from 'lit/decorators.js';\nimport { FormElement } from '../FormElement';\nimport { getClasses } from '../utils';\n\nexport class TembaSlider extends FormElement {\n static get styles() {\n return css`\n :host {\n display: block;\n }\n\n .track {\n height: 2px;\n border-top: 0.5em solid #fff;\n border-bottom: 0.5em solid #fff;\n background: #ddd;\n flex-grow: 1;\n }\n\n .circle {\n margin-bottom: -1.05em;\n margin-left: -0.5em;\n width: 0.75em;\n height: 0.75em;\n border: 2px solid #999;\n border-radius: 999px;\n position: relative;\n background: #fff;\n box-shadow: 0 0 0 4px rgb(255, 255, 255);\n transition: transform 200ms ease-in-out;\n }\n\n .grabbed .track {\n cursor: pointer;\n }\n\n :hover .circle {\n border-color: #777;\n cursor: pointer;\n }\n\n .grabbed .circle {\n border-color: var(--color-primary-dark);\n background: #fff;\n }\n\n .grabbed .circle {\n transform: scale(1.2);\n }\n\n .wrapper {\n display: flex;\n align-items: center;\n }\n\n .pre,\n .post {\n font-size: 0.9em;\n color: #999;\n padding: 0em 1em;\n }\n `;\n }\n\n @property({ type: Boolean })\n range = false;\n\n @property({ type: Number })\n min = 0;\n\n @property({ type: Number })\n max = 100;\n\n circleX = 0;\n grabbed = false;\n\n public firstUpdated(changes: Map) {\n super.firstUpdated(changes);\n this.handleMouseMove = this.handleMouseMove.bind(this);\n this.handleMouseUp = this.handleMouseUp.bind(this);\n }\n\n public updated(changedProperties: Map): void {\n if (changedProperties.has('value')) {\n this.updateCircle();\n }\n }\n\n public updateValue(evt: MouseEvent) {\n const track = this.shadowRoot.querySelector('.track') as HTMLDivElement;\n const left = evt.pageX - track.offsetLeft;\n const pct = left / track.offsetWidth;\n\n const range = this.max - this.min;\n const pctAsValue = range * pct + this.min;\n this.value =\n '' + Math.max(this.min, Math.min(Math.round(pctAsValue), this.max));\n }\n\n public handleMouseMove(evt: MouseEvent) {\n if (this.grabbed) {\n this.updateValue(evt);\n }\n }\n\n public handleTrackDown(evt: MouseEvent) {\n this.grabbed = true;\n document.addEventListener('mousemove', this.handleMouseMove);\n document.addEventListener('mouseup', this.handleMouseUp);\n document.querySelector('html').classList.add('dragging');\n this.updateValue(evt);\n this.requestUpdate();\n }\n\n public handleMouseUp(evt: MouseEvent) {\n this.grabbed = false;\n this.updateValue(evt);\n this.requestUpdate();\n\n document.removeEventListener('mousemove', this.handleMouseMove);\n document.removeEventListener('mouseup', this.handleMouseUp);\n document.querySelector('html').classList.remove('dragging');\n }\n\n public updateCircle() {\n const track = this.shadowRoot.querySelector('.track') as HTMLDivElement;\n const pre = this.shadowRoot.querySelector('.pre') as HTMLDivElement;\n const range = this.max - this.min;\n let cValue = parseInt(this.value);\n if (!cValue || cValue < this.min) {\n cValue = this.min;\n } else if (cValue > this.max) {\n cValue = this.max;\n }\n this.value = '' + cValue;\n const pct = (cValue - this.min) / range;\n const pctAsPixels = track.offsetWidth * pct;\n\n this.circleX = pctAsPixels + (pre ? pre.offsetWidth : 0);\n this.requestUpdate();\n }\n\n public render(): TemplateResult {\n return html`
    \n
    \n
    \n ${this.range ? html`
    ${this.min}
    ` : null}\n
    \n ${this.range ? html`
    ${this.max}
    ` : null}\n
    \n `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { Checkbox } from '../checkbox/Checkbox';\nimport { Select } from '../select/Select';\nimport { capitalize } from '../utils';\nimport { Icon } from '../vectoricon';\nimport { TembaList } from './TembaList';\n\nconst FLOW_COLOR = 'rgb(223, 65, 159)';\n\nexport class RunList extends TembaList {\n @property({ type: String })\n flow: string;\n\n @property({ type: Object, attribute: false })\n results: any[];\n\n @property({ type: Boolean })\n responses = true;\n\n @property({ type: Object })\n resultPreview: any;\n\n @property({ type: Object })\n selectedRun: any;\n\n private resultKeys = {};\n\n static get styles() {\n return css`\n :host {\n overflow-y: auto !important;\n --contact-name-font-size: 1em;\n }\n\n @media only screen and (max-height: 768px) {\n temba-options {\n max-height: 20vh;\n }\n }\n\n temba-options {\n display: block;\n width: 100%;\n flex-grow: 1;\n }\n `;\n }\n\n public firstUpdated(changedProperties: Map) {\n super.firstUpdated(changedProperties);\n }\n\n public updated(changedProperties: Map): void {\n super.updated(changedProperties);\n if (changedProperties.has('responses') || changedProperties.has('flow')) {\n if (this.flow) {\n this.endpoint = `/api/v2/runs.json?flow=${this.flow}${\n this.responses ? '&responded=1' : ''\n }`;\n }\n }\n\n if (changedProperties.has('resultPreview')) {\n this.createRenderOption();\n }\n\n if (changedProperties.has('results')) {\n if (this.results) {\n const select = this.shadowRoot.querySelector('temba-select') as Select;\n select.setOptions(this.results);\n this.resultKeys = this.results.reduce(\n (current, result) => ({ ...current, [result.key]: result }),\n {}\n );\n }\n }\n }\n\n public renderResultPreview(run: any) {\n if (this.resultPreview) {\n const runResult = run.values[this.resultPreview.key];\n if (runResult) {\n if (this.resultPreview.categories.length > 1) {\n if (runResult.category) {\n return runResult.category;\n }\n } else {\n return runResult.value;\n }\n }\n }\n return null;\n }\n\n public removeRun(id: number) {\n this.items = this.items.filter(run => run.id !== id);\n this.cursorIndex = Math.min(this.cursorIndex, this.items.length);\n this.requestUpdate('cursorIndex');\n }\n\n public getIcon(run: any): TemplateResult {\n let icon = null;\n if (run.exit_type == 'completed') {\n icon = html``;\n } else if (run.exit_type == 'interrupted') {\n icon = html``;\n } else if (run.exit_type == 'expired') {\n icon = html``;\n } else if (!run.exit_type) {\n if (run.responded) {\n icon = html``;\n } else {\n icon = html``;\n }\n }\n return icon;\n }\n\n public createRenderOption() {\n this.renderOption = (run: any): TemplateResult => {\n let statusStyle = '';\n\n if (!run.exited_on) {\n statusStyle = 'font-weight:400;';\n }\n\n if (!run.responded) {\n statusStyle += '';\n }\n\n return html`\n
    \n \n \n
    \n\n \n ${this.renderResultPreview(run)}\n \n\n
    \n \n
    \n ${this.getIcon(run)}\n \n `;\n };\n }\n\n public getRefreshEndpoint() {\n if (this.items.length > 0) {\n const modifiedOn = this.items[0].modified_on;\n return this.endpoint + '&after=' + modifiedOn;\n }\n return this.endpoint;\n }\n\n public toggleResponded() {\n this.responses = (\n this.shadowRoot.querySelector('#responded') as Checkbox\n ).checked;\n }\n\n public handleColumnChanged(event: any) {\n if (event.target.values.length > 0) {\n this.resultPreview = event.target.values[0];\n } else {\n this.resultPreview = null;\n }\n }\n\n public handleSelected(selected: any) {\n this.selectedRun = selected;\n }\n\n public getListStyle(): string {\n return '';\n }\n\n public renderHeader(): TemplateResult {\n return html`\n
    \n
    \n ${this.results\n ? html`\n \n `\n : null}\n
    \n
    \n \n
    \n
    \n \n Last Updated\n \n `;\n }\n\n public renderFooter(): TemplateResult {\n if (!this.selectedRun || !this.resultKeys) {\n return null;\n }\n\n const resultKeys = Object.keys(this.selectedRun.values);\n\n return html` \n
    \n \n
    \n \n \n ${this.selectedRun.exit_type\n ? html`\n
    \n ${this.getIcon(this.selectedRun)}\n
    \n ${capitalize(this.selectedRun.exit_type)} \n
    \n \n
    \n `\n : html`${this.getIcon(this.selectedRun)}\n
    \n
    Started 
    \n \n
    `}\n
    \n
    \n
    \n
    \n
    \n ${new Date(this.selectedRun.created_on).toLocaleString()}\n
    \n \n Started\n
    \n \n \n \n\n ${resultKeys.length > 0\n ? html`\n
    \n \n
    \n
    \n\n \n \n \n \n \n \n\n ${Object.keys(this.selectedRun.values).map((key: string) => {\n const result = this.selectedRun.values[key];\n const meta = this.resultKeys[key];\n\n // if our result is no longer represented in the flow, skip it\n if (meta) {\n return html`\n \n \n \n `;\n }\n return null;\n })}\n
    ResultCategoryValue
    ${result.name}\n ${meta.categories.length > 1 ? result.category : '--'}\n ${result.value}
    \n \n `\n : null}\n \n `;\n }\n\n constructor() {\n super();\n this.reverseRefresh = false;\n this.valueKey = 'uuid';\n this.hideShadow = true;\n this.createRenderOption();\n }\n}\n","import { html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { FlowDetails } from '../interfaces';\nimport { StoreElement } from '../store/StoreElement';\n\nexport class FlowStoreElement extends StoreElement {\n @property({ type: String })\n flow: string;\n\n @property({ type: Object, attribute: false })\n data: FlowDetails;\n\n @property({ type: String })\n endpoint = '/api/v2/flows.json?uuid=';\n\n prepareData(data: any) {\n if (data && data.length > 0) {\n data = data[0];\n }\n return data;\n }\n\n protected updated(\n changes: PropertyValueMap | Map\n ): void {\n super.updated(changes);\n if (changes.has('flow')) {\n if (this.flow) {\n this.url = `${this.endpoint}${this.flow}`;\n } else {\n this.url = null;\n }\n }\n }\n\n public render(): TemplateResult {\n if (!this.data) {\n return;\n }\n return html`
    `;\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { ContactStoreElement } from './ContactStoreElement';\n\nexport class ContactNameFetch extends ContactStoreElement {\n @property({ type: Number, attribute: 'icon-size' })\n size = 20;\n\n static get styles() {\n return css`\n :host {\n display: flex;\n }\n\n temba-urn {\n margin-right: 0.2em;\n margin-top: 2px;\n }\n `;\n }\n\n public render(): TemplateResult {\n if (this.data) {\n return html` 0 ? this.data.urns[0] : null}\n >\n `;\n }\n return super.render();\n }\n}\n","import { TemplateResult, html, css, PropertyValueMap } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { FormElement } from '../FormElement';\nimport { getClasses } from '../utils';\nimport { DateTime } from 'luxon';\n\nexport default class DatePicker extends FormElement {\n static get styles() {\n return css`\n :host {\n display: block;\n }\n\n input {\n width: inherit;\n }\n\n .container {\n border-radius: var(--curvature);\n border: 1px solid var(--color-widget-border);\n display: flex;\n cursor: pointer;\n box-shadow: var(--widget-box-shadow);\n flex-wrap: wrap;\n overflow: hidden;\n }\n\n .input-wrapper {\n padding: var(--temba-textinput-padding);\n flex-grow: 1;\n }\n\n .tz {\n margin-left: 0.5em;\n font-size: 0.8em;\n flex-direction: column;\n align-self: stretch;\n color: #888;\n display: flex;\n align-items: flex-start;\n flex-direction: column;\n padding: 0em 1em;\n font-weight: 400;\n cursor: pointer;\n margin: auto 0;\n }\n\n .tz .label {\n font-size: 0.8em;\n color: #aaa;\n white-space: nowrap;\n text-overflow: ellipsis;\n }\n\n .tz .zone {\n white-space: nowrap;\n text-overflow: ellipsis;\n }\n\n .tz-wrapper {\n background: #efefef;\n display: flex;\n flex-direction: row;\n align-items: center;\n padding: 0.4em 0em;\n }\n\n .container:focus-within {\n border-color: var(--color-focus);\n background: var(--color-widget-bg-focused);\n box-shadow: var(--widget-box-shadow-focused);\n }\n\n input {\n color: var(--color-widget-text);\n border: 0px;\n font-family: var(--font-family);\n outline: none;\n width: 100%;\n font-size: 13px;\n padding: 0px;\n margin: 0px;\n line-height: 1em;\n }\n\n input.unset {\n color: #ddd;\n }\n\n input.unset:focus {\n color: var(--color-widget-text);\n }\n\n input:focus {\n outline: none;\n }\n\n .disabled ::-webkit-calendar-picker-indicator {\n display: none;\n }\n\n .disabled .tz-wrapper {\n border-radius: var(--curvature);\n }\n\n ::-webkit-calendar-picker-indicator {\n background-image: url('data:image/svg+xml;utf8,');\n cursor: pointer;\n margin: 0;\n padding: 0;\n }\n\n ::-webkit-calendar-picker-indicator:hover {\n background-image: url('data:image/svg+xml;utf8,');\n cursor: pointer;\n margin: 0;\n padding: 0;\n }\n `;\n }\n\n @property({ type: String })\n timezone = '';\n\n @property({ type: String })\n timezoneFriendly = '';\n\n @property({ type: Object })\n datetime = null;\n\n @property({ type: Boolean })\n time = false;\n\n /** we just return the value since it should be a string */\n public serializeValue(value: any): string {\n return value;\n }\n\n public constructor() {\n super();\n }\n\n protected firstUpdated(\n changed: PropertyValueMap | Map\n ): void {\n if (changed.has('value')) {\n // default to the local browser zone\n if (this.time) {\n this.timezone =\n this.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;\n this.timezoneFriendly = this.timezone\n .replace('_', ' ')\n .replace('/', ', ');\n\n if (this.value) {\n // we fire a change event on blur\n let datetime = DateTime.fromSQL(this.value).setZone(this.timezone);\n // if we can't read it as a sql stamp, try iso\n if (datetime.invalid) {\n datetime = DateTime.fromISO(this.value).setZone(this.timezone);\n }\n this.datetime = datetime;\n this.value = this.datetime.toUTC().toISO();\n }\n } else {\n this.datetime = DateTime.fromSQL(this.value);\n this.value = this.datetime.toISODate();\n }\n }\n }\n\n public updated(changed: Map): void {\n super.updated(changed);\n if (changed.has('timezone') && this.time) {\n this.timezone =\n this.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;\n this.timezoneFriendly = this.timezone\n .replace('_', ' ')\n .replace('/', ', ');\n this.requestUpdate('value');\n }\n }\n\n public handleChange(event) {\n event.preventDefault();\n event.stopPropagation();\n if (this.time) {\n this.datetime = DateTime.fromISO(event.target.value, {\n zone: this.timezone,\n });\n this.value = this.datetime.toUTC().toISO();\n } else {\n this.value = event.target.value;\n }\n this.fireEvent('change');\n }\n\n public handleClicked() {\n this.shadowRoot.querySelector('input').focus();\n }\n\n public render(): TemplateResult {\n const classes = getClasses({ unset: !this.value });\n\n let dateWidgetValue = null;\n if (this.time && this.datetime && !this.datetime.invalid) {\n dateWidgetValue = this.datetime.toFormat(\"yyyy-LL-dd'T'HH:mm\");\n } else if (!this.time) {\n dateWidgetValue = this.value;\n }\n\n return html`\n \n
    \n \n
    \n \n
    \n ${this.time\n ? html`\n
    \n
    \n
    Time Zone
    \n
    ${this.timezoneFriendly}
    \n
    \n
    \n `\n : null}\n \n
    \n \n `;\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { ContactField, CustomEventType } from '../interfaces';\n\nimport { SortableList } from '../list/SortableList';\nimport { StoreElement } from '../store/StoreElement';\nimport { TextInput } from '../textinput/TextInput';\nimport { postJSON } from '../utils';\n\nconst TYPE_NAMES = {\n text: 'Text',\n numeric: 'Number',\n number: 'Number',\n datetime: 'Date & Time',\n state: 'State',\n ward: 'Ward',\n district: 'District',\n};\n\nconst matches = (field: ContactField, query: string): boolean => {\n if (!query) {\n return true;\n }\n const search = (\n field.label +\n field.key +\n TYPE_NAMES[field.value_type]\n ).toLowerCase();\n if (search.toLowerCase().indexOf(query) > -1) {\n return true;\n }\n return false;\n};\n\nexport class FieldManager extends StoreElement {\n static get styles() {\n return css`\n :host {\n display: flex;\n flex-grow: 1;\n flex-direction: column;\n min-height: 0px;\n }\n\n .featured,\n .other-fields {\n background: #fff;\n border-radius: var(--curvature);\n box-shadow: var(--shadow);\n margin-bottom: 1em;\n display: flex;\n flex-direction: column;\n }\n\n .featured {\n max-height: 40%;\n }\n\n .other-fields {\n flex-grow: 2;\n min-height: 0px;\n margin-bottom: 0px;\n }\n\n temba-textinput {\n margin-bottom: 1em;\n }\n\n .scroll-box {\n overflow-y: auto;\n flex-grow: 1;\n flex-direction: column;\n display: flex;\n }\n\n .header temba-icon {\n margin-right: 0.5em;\n }\n\n .label {\n flex-grow: 1;\n }\n\n .header {\n padding: 0.5em 1em;\n display: flex;\n align-items: flex-start;\n border-bottom: 1px solid var(--color-widget-border);\n }\n\n .featured-field {\n user-select: none;\n }\n\n temba-sortable-list {\n padding: 0.5em 0em;\n width: 100%;\n overflow-y: auto;\n }\n\n .scroll-box {\n padding: 0.5em 0em;\n }\n\n temba-icon[name='usages']:hover {\n --icon-color: var(--color-link-primary);\n }\n\n .field:hover temba-icon[name='delete_small'] {\n opacity: 1 !important;\n cursor: pointer !important;\n pointer-events: all !important;\n }\n\n temba-icon[name='delete_small']:hover {\n --icon-color: var(--color-link-primary);\n }\n\n .field {\n border: 1px solid transparent;\n margin: 0 0.5em;\n border-radius: var(--curvature);\n }\n\n .featured temba-sortable-list .field:hover {\n cursor: move;\n border-color: #e6e6e6;\n background: #fcfcfc;\n }\n `;\n }\n\n @property({ type: String, attribute: 'priority-endpoint' })\n priorityEndpoint: string;\n\n @property({ type: Object, attribute: false })\n featuredFields: ContactField[];\n\n @property({ type: Object, attribute: false })\n otherFieldKeys: string[] = [];\n\n @property({ type: String })\n draggingId: string;\n\n @property({ type: String })\n query = '';\n\n protected firstUpdated(\n _changedProperties: PropertyValueMap | Map\n ): void {\n super.firstUpdated(_changedProperties);\n this.url = this.store.fieldsEndpoint;\n }\n\n private filterFields() {\n const filteredKeys = this.store.getFieldKeys().filter(key => {\n const field = this.store.getContactField(key);\n if (field.featured) {\n return false;\n }\n return matches(field, this.query);\n });\n\n // sort by the label instead of the key\n filteredKeys.sort((a, b) => {\n return this.store\n .getContactField(a)\n .label.localeCompare(this.store.getContactField(b).label);\n });\n\n const featured: ContactField[] = [];\n this.store.getFeaturedFields().forEach(field => {\n if (matches(field, this.query)) {\n featured.push(field);\n }\n });\n\n this.otherFieldKeys = filteredKeys;\n this.featuredFields = featured;\n }\n\n protected updated(\n properties: PropertyValueMap | Map\n ): void {\n super.update(properties);\n if (properties.has('data')) {\n this.filterFields();\n } else if (properties.has('query')) {\n this.filterFields();\n }\n }\n\n private handleSaveOrder(event) {\n const list = event.currentTarget as SortableList;\n postJSON(\n this.priorityEndpoint,\n list\n .getIds()\n .reverse()\n .reduce((map, key, idx) => {\n map[key] = idx;\n return map;\n }, {})\n ).then(() => {\n this.store.refreshFields();\n });\n }\n\n private handleOrderChanged(event) {\n const swapsies = event.detail;\n const temp = this.featuredFields[swapsies.fromIdx];\n this.featuredFields[swapsies.fromIdx] = this.featuredFields[swapsies.toIdx];\n this.featuredFields[swapsies.toIdx] = temp;\n this.requestUpdate('featuredFields');\n }\n\n private handleDragStart(event) {\n this.draggingId = event.detail.id;\n }\n\n private handleDragStop() {\n this.draggingId = null;\n }\n\n private handleFieldAction(event: MouseEvent) {\n const ele = event.target as HTMLDivElement;\n const key = ele.dataset.key;\n const action = ele.dataset.action;\n this.fireCustomEvent(CustomEventType.Selection, { key, action });\n }\n\n private handleSearch(event) {\n this.query = (event.target.value || '').trim();\n }\n\n private hasUsages(field: ContactField): boolean {\n return (\n field.usages.campaign_events + field.usages.flows + field.usages.groups >\n 0\n );\n }\n\n private renderField(field: ContactField) {\n return html`\n \n \n \n ${field.label}\n \n ${this.hasUsages(field)\n ? html`\n \n `\n : null}\n
    \n \n \n @fields.${field.key}\n \n
    ${TYPE_NAMES[field.value_type]}
    \n \n \n `;\n }\n\n public render(): TemplateResult {\n if (!this.featuredFields) {\n return null;\n }\n\n return html`\n \n\n ${this.featuredFields.length > 0\n ? html`\n
    \n
    \n \n
    Featured
    \n
    \n ${this.query\n ? html`\n
    \n ${this.featuredFields.map(field =>\n this.renderField(field)\n )}\n
    \n `\n : html`\n \n ${this.featuredFields.map(field =>\n this.renderField(field)\n )}\n \n `}\n
    \n `\n : null}\n\n
    \n
    \n \n
    Everything Else
    \n
    \n
    \n ${this.otherFieldKeys.map(field =>\n this.renderField(this.store.getContactField(field))\n )}\n
    \n
    \n `;\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { RapidElement } from '../RapidElement';\n\n/**\n * A simple list that can be sorted by dragging\n */\n\n// how far we have to drag before it starts\nconst DRAG_THRESHOLD = 5;\nexport class SortableList extends RapidElement {\n static get styles() {\n return css`\n :host {\n margin: auto;\n }\n\n .container {\n user-select: none;\n }\n\n .dragging {\n background: var(--color-selection);\n }\n\n .sortable {\n transition: all 300ms ease-in-out;\n display: flex;\n padding: 0.4em 0;\n }\n\n .sortable:hover temba-icon {\n opacity: 1;\n cursor: move;\n }\n\n .ghost {\n position: absolute;\n opacity: 0.5;\n transition: none;\n }\n\n .slot {\n flex-grow: 1;\n }\n\n slot > * {\n user-select: none;\n }\n\n temba-icon {\n opacity: 0.1;\n padding: 0.2em 0.5em;\n transition: all 300ms ease-in-out;\n }\n `;\n }\n\n @property({ type: String })\n draggingId: string;\n\n ghostElement: HTMLDivElement = null;\n downEle: HTMLDivElement = null;\n xOffset = 0;\n yOffset = 0;\n yDown = 0;\n\n draggingIdx = -1;\n draggingEle = null;\n\n public constructor() {\n super();\n this.handleMouseMove = this.handleMouseMove.bind(this);\n this.handleMouseUp = this.handleMouseUp.bind(this);\n this.handleMouseDown = this.handleMouseDown.bind(this);\n }\n\n protected firstUpdated(\n _changedProperties: PropertyValueMap | Map\n ): void {\n super.firstUpdated(_changedProperties);\n }\n\n public getIds() {\n return this.shadowRoot\n .querySelector('slot')\n .assignedElements()\n .map(ele => ele.id);\n }\n\n private getRowIndex(id: string): number {\n return this.shadowRoot\n .querySelector('slot')\n .assignedElements()\n .findIndex(ele => ele.id === id);\n }\n\n private getOverlappingElement(mouseY: number): HTMLDivElement {\n const ghostRect = this.ghostElement.getBoundingClientRect();\n\n const ele = this.shadowRoot\n .querySelector('slot')\n .assignedElements()\n .find(otherEle => {\n const rect = otherEle.getBoundingClientRect();\n\n // don't return ourselves\n if (otherEle.id === this.ghostElement.id) {\n return false;\n }\n\n if (mouseY > this.yDown) {\n // moving down\n return ghostRect.top < rect.bottom && ghostRect.bottom > rect.bottom;\n } else {\n // moving up\n return rect.top < ghostRect.bottom && rect.bottom > ghostRect.bottom;\n }\n });\n return ele as HTMLDivElement;\n }\n\n private handleMouseDown(event: MouseEvent) {\n let ele = event.target as HTMLDivElement;\n ele = ele.closest('.sortable');\n if (ele) {\n this.downEle = ele;\n this.draggingId = ele.id;\n this.draggingIdx = this.getRowIndex(ele.id);\n this.draggingEle = ele;\n\n this.xOffset = event.clientX - ele.offsetLeft;\n this.yOffset = event.clientY - ele.offsetTop;\n this.yDown = event.clientY;\n\n document.addEventListener('mousemove', this.handleMouseMove);\n document.addEventListener('mouseup', this.handleMouseUp);\n }\n }\n\n private handleMouseMove(event: MouseEvent) {\n const scrollTop = this.shadowRoot\n .querySelector('slot')\n .assignedElements()[0].parentElement.scrollTop;\n\n if (\n !this.ghostElement &&\n this.downEle &&\n Math.abs(event.clientY - this.yDown) > DRAG_THRESHOLD\n ) {\n this.fireCustomEvent(CustomEventType.DragStart, {\n id: this.downEle.id,\n });\n\n this.ghostElement = this.downEle.cloneNode(true) as HTMLDivElement;\n this.ghostElement.classList.add('ghost');\n\n const computedStyle = getComputedStyle(this.downEle);\n\n this.ghostElement.style.width =\n this.downEle.clientWidth -\n parseFloat(computedStyle.paddingLeft) -\n parseFloat(computedStyle.paddingRight) +\n 'px';\n const container = this.shadowRoot.querySelector('.container');\n\n container.appendChild(this.ghostElement);\n\n this.downEle = null;\n }\n\n if (this.ghostElement) {\n this.ghostElement.style.left = event.clientX - this.xOffset + 'px';\n this.ghostElement.style.top =\n event.clientY - this.yOffset - scrollTop + 'px';\n\n const other = this.getOverlappingElement(event.clientY);\n if (other) {\n const otherIdx = this.getRowIndex(other.id);\n const dragId = this.ghostElement.id;\n const otherId = other.id;\n\n this.fireCustomEvent(CustomEventType.OrderChanged, {\n from: dragId,\n to: otherId,\n fromIdx: this.draggingIdx,\n toIdx: otherIdx,\n });\n\n // TODO: Dont do swapping, just send the full order?\n this.draggingIdx = otherIdx;\n this.draggingId = otherId;\n }\n }\n }\n\n private handleMouseUp() {\n if (this.draggingId) {\n this.fireCustomEvent(CustomEventType.DragStop, {\n id: this.draggingId,\n });\n\n this.draggingId = null;\n this.downEle = null;\n\n if (this.ghostElement) {\n this.ghostElement.remove();\n this.ghostElement = null;\n }\n }\n document.removeEventListener('mousemove', this.handleMouseMove);\n document.removeEventListener('mouseup', this.handleMouseUp);\n this.dispatchEvent(new Event('change'));\n }\n\n public render(): TemplateResult {\n return html`\n
    \n \n
    \n `;\n }\n}\n","import { TemplateResult, html, css } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\n\nimport { RapidElement } from '../RapidElement';\nimport { getUrl, WebResponse } from '../utils';\n\nconst HEADERS = {\n 'Temba-Content-Menu': '1',\n 'Temba-Spa': '1',\n};\nexport interface ContentMenuItem {\n type: string;\n as_button: boolean;\n label: string;\n url: string;\n disabled: boolean;\n modal_id: string;\n on_submit: string;\n primary: boolean;\n title: string;\n on_click: null;\n link_class: string;\n}\n\nexport enum ContentMenuItemType {\n LINK = 'link',\n JS = 'js',\n URL_POST = 'url_post',\n MODAX = 'modax',\n DIVIDER = 'divider',\n}\n\nexport class ContentMenu extends RapidElement {\n static get styles() {\n return css`\n .container {\n --button-y: 0.4em;\n --button-x: 1em;\n display: flex;\n }\n\n .button_item,\n .primary_button_item {\n margin-left: 1rem;\n }\n\n .toggle {\n --icon-color: rgb(102, 102, 102);\n padding: 0.5rem;\n margin-left: 0.5rem;\n }\n\n .toggle:hover {\n background: rgba(0, 0, 0, 0.05);\n border-radius: var(--curvature);\n --icon-color: rgb(136, 136, 136);\n }\n\n .dropdown {\n padding: 1rem 1.5rem;\n color: rgb(45, 45, 45);\n z-index: 50;\n min-width: 200px;\n }\n\n .divider {\n border-bottom: 1px solid rgb(237, 237, 237);\n margin: 1rem -1.5em;\n }\n\n .item {\n white-space: nowrap;\n margin: 0.2em 0em;\n font-size: 1.1rem;\n cursor: pointer;\n font-weight: 400;\n }\n\n .item:hover {\n color: var(--color-link-primary);\n }\n `;\n }\n\n @property({ type: String })\n endpoint: string;\n\n @property({ type: Number })\n legacy: number;\n\n @property({ type: Array, attribute: false })\n buttons: ContentMenuItem[] = [];\n\n @property({ type: Array, attribute: false })\n items: ContentMenuItem[] = [];\n\n private fetchContentMenu() {\n const url = this.endpoint;\n if (url) {\n const legacy = this.legacy;\n const headers = HEADERS;\n if (legacy) {\n delete headers['Temba-Spa'];\n }\n\n //ok, fetch the content menu\n getUrl(url, null, headers)\n .then((response: WebResponse) => {\n const json = response.json;\n const contentMenu = json.items as ContentMenuItem[];\n\n //populate (or initialize) the buttons and items\n if (contentMenu) {\n this.buttons = contentMenu.filter(item => item.as_button);\n this.items = contentMenu.filter(item => !item.as_button);\n } else {\n this.buttons = [];\n this.items = [];\n }\n\n //fire custom loaded event type when we're finished\n this.fireCustomEvent(CustomEventType.Loaded, {\n buttons: this.buttons,\n items: this.items,\n });\n })\n .catch((error: any) => {\n console.error(error);\n });\n }\n }\n\n public refresh() {\n this.fetchContentMenu();\n }\n\n protected updated(changes: Map) {\n super.updated(changes);\n\n if (changes.has('endpoint') || changes.has('legacy')) {\n this.fetchContentMenu();\n }\n }\n\n private handleItemClicked(item: ContentMenuItem, event: MouseEvent) {\n this.fireCustomEvent(CustomEventType.Selection, { item, event });\n }\n\n public render(): TemplateResult {\n return html`\n
    \n ${this.buttons.map(button => {\n return html` this.handleItemClicked(button, event)}\n >\n ${button.label}\n `;\n })}\n ${this.items && this.items.length > 0\n ? html`\n
    \n \n
    \n
    \n ${this.items.map(item => {\n if (item.type === ContentMenuItemType.DIVIDER) {\n return html`
    `;\n } else {\n return html` this.handleItemClicked(item, event)}\n >\n ${item.label}\n
    `;\n }\n })}\n
    \n `\n : null}\n \n `;\n }\n}\n","import { css, html, PropertyValueMap, TemplateResult } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\nimport { Store } from '../store/Store';\nimport { DateTime } from 'luxon';\n\nexport const Display = {\n date: DateTime.DATE_SHORT,\n datetime: DateTime.DATETIME_SHORT,\n time: DateTime.TIME_SIMPLE,\n timedate: 'timedate',\n duration: 'duration',\n relative: 'relative',\n day: 'LLL d',\n};\n\nexport class TembaDate extends RapidElement {\n static get styles() {\n return css`\n .date {\n display: inline;\n }\n `;\n }\n\n @property({ type: String })\n value: string;\n\n @property({ type: String })\n display = 'date';\n\n @property({ type: Object, attribute: false })\n datetime: DateTime;\n\n store: Store;\n\n protected firstUpdated(\n changedProperties: PropertyValueMap | Map\n ): void {\n super.firstUpdated(changedProperties);\n this.store = document.querySelector('temba-store');\n }\n\n protected updated(\n changedProperties: PropertyValueMap | Map\n ): void {\n super.updated(changedProperties);\n if (changedProperties.has('value')) {\n this.datetime = DateTime.fromISO(this.value);\n }\n }\n\n public connectedCallback(): void {\n super.connectedCallback();\n }\n\n public render(): TemplateResult {\n if (this.datetime && this.store) {\n this.datetime.setLocale(this.store.getLocale());\n\n let formatted = '';\n if (this.display === Display.timedate) {\n const hours = Math.abs(\n this.datetime.diffNow().milliseconds / 1000 / 60 / 60\n );\n if (hours < 24) {\n formatted = this.datetime.toLocaleString(Display.time);\n } else if (hours < 24 * 365) {\n formatted = this.datetime.toFormat(Display.day);\n } else {\n formatted = this.datetime.toLocaleString(Display.date);\n }\n } else if (this.display === Display.relative) {\n const minutes = Math.abs(\n this.datetime.diffNow().milliseconds / 1000 / 60\n );\n if (minutes < 1) {\n return html`just now`;\n }\n\n formatted = this.store.getShortDuration(this.datetime);\n } else if (this.display === Display.duration) {\n const minutes = Math.abs(\n this.datetime.diffNow().milliseconds / 1000 / 60\n );\n if (minutes < 1) {\n return html`just now`;\n }\n formatted = this.store.getShortDuration(this.datetime);\n } else if (this.display === Display.day) {\n formatted = this.datetime.toLocaleString(Display.day);\n } else {\n formatted = this.datetime.toLocaleString(Display[this.display]);\n }\n\n return html`${formatted}`;\n }\n }\n}\n","import { css, html, TemplateResult } from 'lit';\nimport { property, customElement } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\nimport { getUrl } from '../utils';\nimport { unsafeHTML } from 'lit-html/directives/unsafe-html.js';\n\n@customElement('temba-remote')\nexport default class Remote extends RapidElement {\n @property({ type: String })\n endpoint: string;\n\n @property({ attribute: false })\n body: any = html``;\n\n static get styles() {\n return css``;\n }\n\n public updated(changes: Map) {\n super.updated(changes);\n\n if (changes.has('endpoint')) {\n getUrl(this.endpoint).then(response => {\n this.body = unsafeHTML(response.body);\n });\n }\n }\n\n public render(): TemplateResult {\n return html`${this.body}`;\n }\n}\n","/* eslint-disable @typescript-eslint/no-this-alias */\nimport { LitElement, TemplateResult, html, css, PropertyValueMap } from 'lit';\nimport { property } from 'lit/decorators.js';\n\ninterface Message {\n text: string;\n type: string;\n chat_id?: string;\n origin?: string;\n timestamp: number;\n}\n\nenum ChatStatus {\n DISCONNECTED = 'disconnected',\n CONNECTING = 'connecting',\n CONNECTED = 'connected',\n}\n\n// how long of a window to show time between batches\nconst BATCH_TIME_WINDOW = 30 * 60 * 1000;\n\nconst TIME_FORMAT = { hour: 'numeric', minute: '2-digit' } as any;\nconst DAY_FORMAT = {\n weekday: undefined,\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n} as any;\nconst VERBOSE_FORMAT = {\n weekday: undefined,\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n hour: 'numeric',\n minute: '2-digit',\n} as any;\n\nexport class WebChat extends LitElement {\n static get styles() {\n return css`\n :host {\n display: flex-inline;\n align-items: center;\n align-self: center;\n --curvature: 0.6em;\n --color-primary: hsla(208, 70%, 55%, 1);\n font-family: 'Roboto', 'Helvetica Neue', sans-serif;\n font-weight: 400;\n font-size: 1.1em;\n --toggle-speed: 80ms;\n }\n\n .header {\n background: var(--color-primary);\n height: 3em;\n display: flex;\n align-items: center;\n width: 100%;\n }\n\n .header slot {\n flex-grow: 1;\n padding: 1em;\n color: rgba(255, 255, 255, 0.9);\n font-size: 1.2em;\n display: block;\n }\n\n .header .close-button {\n margin: 0.5em;\n color: rgba(255, 255, 255, 0.5);\n cursor: pointer;\n }\n\n .header .close-button:hover {\n cursor: pointer;\n color: rgba(255, 255, 255, 1);\n }\n\n .block {\n margin-bottom: 1em;\n }\n\n .time {\n text-align: center;\n font-size: 0.8em;\n color: #999;\n margin-top: 2em;\n border-top: 1px solid #f8f8f8;\n padding: 1em;\n margin-left: 4em;\n margin-right: 4em;\n }\n\n .first .time {\n margin-top: 0;\n border-top: none;\n padding-top: 0;\n }\n\n .row {\n display: flex;\n flex-direction: row;\n align-items: flex-start;\n }\n\n .input-panel {\n padding: 1em;\n background: #fff;\n }\n\n .avatar {\n margin-top: 0.6em;\n margin-right: 0.6em;\n flex-shrink: 0;\n width: 2em;\n height: 2em;\n overflow: hidden;\n border-radius: 100%;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 3px 7px 0px,\n rgba(0, 0, 0, 0.2) 0px 1px 2px 0px,\n inset 0 0 0 0.15em rgba(0, 0, 0, 0.1);\n }\n\n .toggle {\n flex-shrink: 0;\n width: 4em;\n height: 4em;\n overflow: hidden;\n border-radius: 100%;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 1em 0.7em,\n rgba(0, 0, 0, 0.2) 0px 1px 2px 0px,\n inset 0 0 0 0.25em rgba(0, 0, 0, 0.1);\n cursor: pointer;\n transition: box-shadow var(--toggle-speed) ease-out;\n position: absolute;\n bottom: 0.5em;\n right: 1em;\n }\n\n .toggle:hover {\n box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 1em 0.7em,\n rgba(0, 0, 0, 0.4) 0px 1px 2px 0px,\n inset 0 0 0 0.25em rgba(0, 0, 0, 0.2);\n }\n\n .incoming .row {\n flex-direction: row-reverse;\n margin-left: 1em;\n }\n\n .bubble {\n padding: 1em;\n padding-bottom: 0.5em;\n background: #fafafa;\n border-radius: var(--curvature);\n max-width: 70%;\n }\n\n .bubble .name {\n font-size: 0.95em;\n font-weight: 400;\n color: #888;\n margin-bottom: 0.25em;\n }\n\n .outgoing .bubble {\n border-top-left-radius: 0;\n }\n\n .incoming .bubble {\n background: var(--color-primary);\n color: white;\n border-top-right-radius: 0;\n text-align: right;\n }\n\n .message {\n margin-bottom: 0.5em;\n line-height: 1.2em;\n }\n\n .chat {\n max-width: 50vw;\n width: 28rem;\n border-radius: var(--curvature);\n overflow: hidden;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 3px 7px 0px,\n rgba(0, 0, 0, 0.2) 0px 1px 2px 0px, rgba(0, 0, 0, 0.1) 5em 5em 5em 5em;\n position: absolute;\n bottom: 3em;\n right: 1em;\n transition: all var(--toggle-speed) ease-out;\n transform: scale(0.9);\n pointer-events: none;\n opacity: 0;\n }\n\n .chat.open {\n bottom: 5em;\n opacity: 1;\n transform: scale(1);\n pointer-events: initial;\n }\n\n .messages {\n background: #fff;\n }\n\n .scroll {\n height: 40rem;\n max-height: 60vh;\n overflow: auto;\n -webkit-overflow-scrolling: touch;\n overflow-scrolling: touch;\n padding: 1em 1em 0 1em;\n }\n\n .messages:before {\n content: '';\n background: /* Shadow TOP */ radial-gradient(\n farthest-side at 50% 0,\n rgba(0, 0, 0, 0.2),\n rgba(0, 0, 0, 0)\n )\n center top;\n height: 10px;\n display: block;\n position: absolute;\n max-width: 50vw;\n width: 28rem;\n transition: opacity var(--toggle-speed) ease-out;\n }\n\n .messages:after {\n content: '';\n background: /* Shadow BOTTOM */ radial-gradient(\n farthest-side at 50% 100%,\n rgba(0, 0, 0, 0.2),\n rgba(0, 0, 0, 0)\n )\n center bottom;\n height: 10px;\n display: block;\n position: absolute;\n margin-top: -10px;\n max-width: 50vw;\n width: 28rem;\n margin-right: 5em;\n transition: opacity var(--toggle-speed) ease-out;\n }\n\n .scroll-at-top .messages:before {\n opacity: 0;\n }\n\n .scroll-at-bottom .messages:after {\n opacity: 0;\n }\n\n .input {\n border: none;\n flex-grow: 1;\n color: #333;\n font-size: 1em;\n }\n\n .input:focus {\n outline: none;\n }\n\n input::placeholder {\n opacity: 0.3;\n }\n\n .input.inactive {\n // pointer-events: none;\n // opacity: 0.3;\n }\n\n .active {\n }\n\n .send-icon {\n color: #eee;\n pointer-events: none;\n transform: rotate(-45deg);\n transition: transform 0.2s ease-out;\n }\n\n .pending .send-icon {\n color: var(--color-primary);\n pointer-events: initial;\n transform: rotate(0deg);\n }\n\n .notice {\n padding: 1em;\n background: #f8f8f8;\n color: #666;\n text-align: center;\n cursor: pointer;\n }\n\n .connecting .notice {\n display: flex;\n justify-content: center;\n }\n\n .connecting .notice temba-icon {\n margin-left: 0.5em;\n }\n\n .reconnect {\n color: var(--color-primary);\n text-decoration: underline;\n font-size: 0.9em;\n }\n\n .input:disabled {\n background: transparent !important;\n }\n `;\n }\n\n @property({ type: String })\n channel: string;\n\n @property({ type: String })\n urn: string;\n\n @property({ type: Array })\n messages: Message[][] = [];\n\n // is our socket connection established\n @property({ type: String })\n status: ChatStatus = ChatStatus.DISCONNECTED;\n\n // is the chat widget open\n @property({ type: Boolean })\n open = false;\n\n @property({ type: Boolean })\n hasPendingText = false;\n\n @property({ type: Boolean, attribute: false })\n hideTopScroll = true;\n\n @property({ type: Boolean, attribute: false })\n hideBottomScroll = true;\n\n @property({ type: String })\n host: string;\n\n private sock: WebSocket;\n\n public constructor() {\n super();\n }\n\n private handleReconnect() {\n this.openSocket();\n }\n\n private openSocket(): void {\n if (this.status !== ChatStatus.DISCONNECTED) {\n return;\n }\n\n this.status = ChatStatus.CONNECTING;\n const webChat = this;\n let url = `ws://localhost:8070/start/${this.channel}/`;\n if (this.urn) {\n url = `${url}?chat_id=${this.urn}`;\n }\n this.sock = new WebSocket(url);\n this.sock.onclose = function (event: CloseEvent) {\n console.log('Socket closed', event);\n webChat.status = ChatStatus.DISCONNECTED;\n };\n this.sock.onmessage = function (event: MessageEvent) {\n console.log(event);\n webChat.status = ChatStatus.CONNECTED;\n const msg = JSON.parse(event.data) as Message;\n if (msg.type === 'chat_started') {\n if (webChat.urn !== msg.chat_id) {\n webChat.messages = [];\n }\n webChat.urn = msg.chat_id;\n webChat.requestUpdate('messages');\n } else if (msg.type === 'chat_resumed') {\n webChat.urn = msg.chat_id;\n } else if (msg.type === 'msg_out') {\n msg['timestamp'] = new Date().getTime();\n webChat.addMessage(msg);\n webChat.requestUpdate('messages');\n }\n };\n }\n\n private restoreFromLocal(): void {\n const data = JSON.parse(localStorage.getItem('temba-chat') || '{}');\n const urn = 'urn' in data ? data['urn'] : null;\n if (urn && !this.urn) {\n this.urn = urn;\n const messages = 'messages' in data ? data['messages'] : [];\n this.messages.push(...messages);\n }\n }\n\n private writeToLocal(): void {\n // console.log('Writing to localStorage..');\n if (this.urn) {\n const data = { urn: this.urn, messages: this.messages, version: 1 };\n localStorage.setItem('temba-chat', JSON.stringify(data));\n }\n }\n\n public firstUpdated(\n changed: PropertyValueMap | Map\n ): void {\n super.firstUpdated(changed);\n }\n\n private focusInput() {\n const input = this.shadowRoot.querySelector('.input') as any;\n if (input) {\n input.focus();\n }\n }\n\n public updated(\n changed: PropertyValueMap | Map\n ): void {\n super.updated(changed);\n\n if (this.open && changed.has('open') && changed.get('open') !== undefined) {\n const scroll = this.shadowRoot.querySelector('.scroll');\n const hasScroll = scroll.scrollHeight > scroll.clientHeight;\n this.hideBottomScroll = true;\n this.hideTopScroll = !hasScroll;\n this.scrollToBottom();\n\n if (this.status === ChatStatus.DISCONNECTED) {\n this.openSocket();\n }\n }\n\n if (changed.has('status')) {\n if (this.status === ChatStatus.CONNECTED) {\n this.focusInput();\n }\n }\n\n if (changed.has('channel')) {\n this.restoreFromLocal();\n }\n\n if (changed.has('messages')) {\n // console.log('messages changed', this.messages);\n this.writeToLocal();\n // console.log(this.messages);\n this.scrollToBottom();\n }\n }\n\n private addMessage(msg: Message) {\n let lastGroup =\n this.messages.length > 0 ? this.messages[this.messages.length - 1] : [];\n const isSame = lastGroup.length === 0 || lastGroup[0].origin === msg.origin;\n if (!isSame) {\n lastGroup = [];\n }\n if (lastGroup.length === 0) {\n this.messages.push(lastGroup);\n }\n lastGroup.push(msg);\n }\n\n public openChat(): void {\n this.open = true;\n }\n\n public handleKeyUp(event: any) {\n if (this.hasPendingText && event.key === 'Enter') {\n this.sendPendingMessage();\n }\n\n this.hasPendingText = event.target.value.length > 0;\n }\n\n private sendPendingMessage() {\n if (this.status === ChatStatus.CONNECTED) {\n const input = this.shadowRoot.querySelector('.input') as any;\n const text = input.value;\n input.value = '';\n\n const msg = {\n type: 'msg_in',\n text: text,\n timestamp: new Date().getTime(),\n };\n\n this.addMessage(msg);\n this.sock.send(JSON.stringify(msg));\n this.requestUpdate('messages');\n this.hasPendingText = input.value.length > 0;\n }\n }\n\n private scrollToBottom() {\n const scroll = this.shadowRoot.querySelector('.scroll');\n if (scroll) {\n scroll.scrollTop = scroll.scrollHeight;\n this.hideBottomScroll = true;\n }\n }\n\n private renderMessageGroup(\n messages: Message[],\n idx: number,\n groups: Message[][]\n ): TemplateResult {\n let lastBatchTime = null;\n if (idx > 0) {\n const lastGroup = groups[idx - 1];\n if (lastGroup && lastGroup.length > 0) {\n lastBatchTime = lastGroup[lastGroup.length - 1].timestamp;\n }\n }\n\n const newBatchTime = messages[0].timestamp;\n const showTime = newBatchTime - lastBatchTime > BATCH_TIME_WINDOW;\n\n let timeDisplay = null;\n if (showTime) {\n let lastTime = null;\n const newTime = new Date(newBatchTime);\n if (lastBatchTime) {\n lastTime = new Date(lastBatchTime);\n }\n const showDay = !lastTime || newTime.getDate() !== lastTime.getDate();\n if (showDay) {\n timeDisplay = html`
    \n ${newTime.toLocaleDateString(undefined, DAY_FORMAT)}\n
    `;\n } else {\n timeDisplay = html`
    \n ${newTime.toLocaleTimeString(undefined, TIME_FORMAT)}\n
    `;\n }\n }\n\n const blockTime = new Date(messages[messages.length - 1].timestamp);\n const incoming = !messages[0].origin;\n\n return html` \n ${timeDisplay}\n
    \n ${!incoming\n ? html`\n
    \n `\n : null}\n\n
    \n ${!incoming ? html`
    Henry McHelper
    ` : null}\n ${messages.map(msg => html`
    ${msg.text}
    `)}\n
    \n \n `;\n }\n\n private handleScroll(event: any) {\n this.hideBottomScroll =\n Math.round(event.target.scrollTop + event.target.clientHeight) >=\n event.target.scrollHeight;\n this.hideTopScroll = event.target.scrollTop === 0;\n }\n\n private handleClickInputPanel(event: MouseEvent) {\n event.preventDefault();\n event.stopPropagation();\n const input = this.shadowRoot.querySelector('.input') as any;\n input.focus();\n }\n\n private toggleChat() {\n this.open = !this.open;\n }\n\n public render(): TemplateResult {\n return html`\n \n
    \n \n \n
    \n
    \n
    \n ${this.messages\n ? this.messages.map(\n (msgGroup, idx, groups) =>\n html`${this.renderMessageGroup(msgGroup, idx, groups)}`\n )\n : null}\n
    \n
    \n\n ${this.status === ChatStatus.DISCONNECTED\n ? html`
    \n
    This chat is not currently connected.
    \n
    \n Click here to reconnect\n
    \n
    \n
    `\n : null}\n ${this.status === ChatStatus.CONNECTING\n ? html`
    \n
    Connecting
    \n \n
    `\n : null}\n ${this.status === ChatStatus.CONNECTED\n ? html` \n \n \n `\n : null}\n \n\n
    \n
    \n \n `;\n }\n}\n","import { TemplateResult, html, css } from 'lit';\nimport { FormElement } from '../FormElement';\nimport { property } from 'lit/decorators.js';\nimport { Icon } from '../vectoricon';\nimport { Attachment, CustomEventType, Language } from '../interfaces';\nimport {\n formatFileSize,\n getClasses,\n postFormData,\n truncate,\n DEFAULT_MEDIA_ENDPOINT,\n WebResponse,\n isImageAttachment,\n} from '../utils';\nimport { Completion } from '../completion/Completion';\nimport { Select } from '../select/Select';\nimport { TabPane } from '../tabpane/TabPane';\nimport { EventHandler } from '../RapidElement';\n\nexport class Compose extends FormElement {\n static get styles() {\n return css`\n .container {\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n position: relative;\n\n border-radius: var(--curvature-widget);\n background: var(--color-widget-bg);\n border: var(--compose-border, 1px solid var(--color-widget-border));\n transition: all ease-in-out var(--transition-speed);\n box-shadow: var(--compose-shadow, var(--widget-box-shadow));\n caret-color: var(--input-caret);\n }\n\n .drop-mask {\n opacity: 0;\n pointer-events: none;\n position: absolute;\n height: 100%;\n width: 100%;\n bottom: 0;\n right: 0;\n background: rgba(210, 243, 184, 0.8);\n border-radius: var(--curvature-widget);\n transition: opacity ease-in-out var(--transition-speed);\n display: flex;\n align-items: center;\n text-align: center;\n }\n\n .highlight .drop-mask {\n opacity: 1;\n }\n\n .drop-mask > div {\n margin: auto;\n border-radius: var(--curvature-widget);\n font-weight: 400;\n color: rgba(0, 0, 0, 0.5);\n }\n\n .items {\n }\n\n .chatbox {\n --color-widget-border: none;\n --curvature-widget: var(\n --compose-curvature,\n var(--curvature) var(--curvature) 0px 0px\n );\n --textarea-min-height: var(--textarea-min-height, 4em);\n --widget-box-shadow: none;\n padding: var(--compose-padding, 0px);\n }\n\n .attachments {\n }\n .attachments-list {\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n padding: 0.2em;\n }\n .attachment-item {\n padding: 0.4em;\n }\n .attachment-item.error {\n background: #fff;\n color: rgba(250, 0, 0, 0.75);\n padding: 0.2em;\n margin: 0.3em 0.5em;\n border-radius: var(--curvature);\n display: block;\n }\n\n .remove-item {\n position: absolute;\n --icon-color: #ccc;\n background: #fff;\n border-radius: 99%;\n transform: scale(0);\n transition: transform 200ms linear;\n }\n\n .attachment-item:hover .remove-item {\n transform: scale(1);\n }\n\n .remove-item:hover {\n --icon-color: #333;\n cursor: pointer;\n }\n\n .remove-item.error:hover {\n background: rgba(250, 0, 0, 0.1);\n }\n\n .remove-item.error {\n background: rgba(250, 0, 0, 0.05);\n color: rgba(250, 0, 0, 0.75);\n }\n .attachment-name {\n align-self: center;\n font-size: 12px;\n padding: 2px 8px;\n }\n\n .actions {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 0em;\n background: #f9f9f9;\n border-bottom-left-radius: var(--curvature);\n border-bottom-right-radius: var(--curvature);\n border-top: solid 1px var(--color-widget-border);\n }\n\n #upload-input {\n display: none;\n }\n .upload-label {\n display: flex;\n align-items: center;\n }\n .upload-icon {\n color: rgb(102, 102, 102);\n }\n .actions-right {\n display: flex;\n align-items: center;\n }\n temba-charcount {\n margin-right: 5px;\n overflow: hidden;\n --temba-charcount-counts-margin-top: 0px;\n --temba-charcount-summary-margin-top: 0px;\n --temba-charcount-summary-position: fixed;\n --temba-charcount-summary-right: 105px;\n --temba-charcount-summary-bottom: 105px;\n }\n temba-button {\n --button-y: 1px;\n --button-x: 12px;\n }\n .send-error {\n color: rgba(250, 0, 0, 0.75);\n font-size: var(--help-text-size);\n }\n\n .language {\n margin-bottom: 0.6em;\n display: block;\n }\n\n .top-right {\n align-items: center;\n display: flex;\n }\n\n #send-button {\n margin: 0.3em;\n }\n\n temba-tabs {\n --focused-tab-color: #f4f4f4;\n }\n\n .quick-replies {\n margin: 0.8em;\n }\n\n .add-attachment {\n padding: 1em;\n background: #eee;\n border-radius: var(--curvature);\n color: #aaa;\n margin: 0.5em;\n }\n\n .add-attachment:hover {\n background: #e9e9e9;\n cursor: pointer;\n }\n\n temba-loading {\n margin: auto 1em;\n }\n\n .optins {\n padding: 1em;\n }\n `;\n }\n\n @property({ type: Number })\n index = 1;\n\n @property({ type: Number })\n maxAttachments = 3;\n\n @property({ type: Number })\n maxLength = 640;\n\n @property({ type: Boolean })\n completion: boolean;\n\n @property({ type: Boolean })\n chatbox: boolean;\n\n @property({ type: Boolean })\n attachments: boolean;\n\n @property({ type: Boolean })\n quickReplies: boolean;\n\n @property({ type: Boolean })\n optIns: boolean;\n\n @property({ type: Boolean })\n counter: boolean;\n\n @property({ type: Boolean })\n pendingDrop: boolean;\n\n @property({ type: Boolean })\n button: boolean;\n\n @property({ type: String })\n currentText = '';\n\n @property({ type: String })\n initialText = '';\n\n @property({ type: String })\n accept = ''; //e.g. \".xls,.xlsx\"\n\n @property({ type: String, attribute: false })\n endpoint = DEFAULT_MEDIA_ENDPOINT;\n\n @property({ type: Boolean, attribute: false })\n uploading: boolean;\n\n @property({ type: Array })\n languages: Language[] = [];\n\n @property({ type: Array })\n currentAttachments: Attachment[] = [];\n\n @property({ type: Array })\n currentQuickReplies: { name: string; value: string }[] = [];\n\n @property({ type: Array })\n currentOptin: { name: string; uuid: string }[] = [];\n\n @property({ type: String })\n optinEndpoint = '/api/v2/optins.json';\n\n @property({ type: Array, attribute: false })\n failedAttachments: Attachment[] = [];\n\n @property({ type: String })\n buttonName = 'Send';\n\n @property({ type: Boolean, attribute: false })\n buttonDisabled = true;\n\n @property({ type: String, attribute: false })\n buttonError = '';\n\n @property({ type: Boolean, attribute: 'widget_only' })\n widgetOnly: boolean;\n\n @property({ type: Array })\n errors: string[];\n\n @property({ type: Object })\n langValues: {\n [lang: string]: {\n text: string;\n attachments: Attachment[];\n quick_replies: string[];\n optin?: { name: string; uuid: string };\n };\n } = {};\n\n @property({ type: String })\n currentLanguage = 'und';\n\n public constructor() {\n super();\n }\n\n private isBaseLanguage(): boolean {\n return (\n this.currentLanguage == 'und' ||\n this.currentLanguage == this.languages[0].iso\n );\n }\n\n private handleTabChanged() {\n const tabs = this.shadowRoot.querySelector('temba-tabs') as TabPane;\n const tab = tabs.getCurrentTab();\n if (tab) {\n // check we are going for the first attachment\n if (tab.icon == 'attachment') {\n if (this.currentAttachments.length == 0) {\n this.handleUploadFileIconClicked();\n }\n }\n }\n }\n\n public getEventHandlers(): EventHandler[] {\n return [\n { event: CustomEventType.ContextChanged, method: this.handleTabChanged },\n ];\n }\n\n public firstUpdated(changes: Map): void {\n super.firstUpdated(changes);\n\n if (changes.has('languages') && this.languages.length > 0) {\n this.currentLanguage = this.languages[0].iso;\n }\n\n if (changes.has('value')) {\n this.langValues = this.getDeserializedValue() || {};\n }\n this.setFocusOnChatbox();\n }\n\n public updated(changes: Map): void {\n super.updated(changes);\n\n if (changes.has('currentLanguage') && this.langValues) {\n let langValue = {\n text: '',\n attachments: [],\n quick_replies: [],\n };\n\n if (this.currentLanguage in this.langValues) {\n langValue = this.langValues[this.currentLanguage];\n }\n\n this.currentText = langValue.text;\n this.initialText = langValue.text;\n this.currentAttachments = langValue.attachments;\n this.currentQuickReplies = (langValue.quick_replies || []).map(value => {\n return { name: value, value };\n });\n this.currentOptin = langValue['optin'] ? [langValue['optin']] : [];\n this.setFocusOnChatbox();\n\n // TODO: this feels like it shouldn't be needed\n const chatbox = this.shadowRoot.querySelector('.chatbox') as any;\n if (chatbox) {\n chatbox.value = this.initialText;\n }\n this.resetTabs();\n this.requestUpdate('currentAttachments');\n }\n\n if (\n (this.langValues &&\n (changes.has('currentText') ||\n changes.has('currentAttachments') ||\n changes.has('currentQuickReplies'))) ||\n changes.has('currentOptin')\n ) {\n this.toggleButton();\n\n const trimmed = this.currentText ? this.currentText.trim() : '';\n if (\n trimmed ||\n this.currentAttachments.length > 0 ||\n this.currentQuickReplies.length > 0\n ) {\n this.langValues[this.currentLanguage] = {\n text: trimmed,\n attachments: this.currentAttachments,\n quick_replies: this.currentQuickReplies.map(option => option.value),\n optin: this.currentOptin.length > 0 ? this.currentOptin[0] : null,\n };\n } else {\n delete this.langValues[this.currentLanguage];\n }\n this.fireCustomEvent(CustomEventType.ContentChanged, this.langValues);\n this.requestUpdate('langValues');\n this.setValue(this.langValues);\n }\n }\n\n private setFocusOnChatbox(): void {\n if (this.chatbox) {\n const completion = this.shadowRoot.querySelector(\n '.chatbox'\n ) as Completion;\n if (completion) {\n window.setTimeout(() => {\n completion.focus();\n // this.resetTabs();\n }, 0);\n }\n }\n }\n\n public reset(): void {\n (this.shadowRoot.querySelector('.chatbox') as HTMLInputElement).value = '';\n this.initialText = '';\n this.currentText = '';\n this.currentQuickReplies = [];\n this.currentAttachments = [];\n this.failedAttachments = [];\n this.buttonError = '';\n }\n\n private handleQuickReplyChange(event: InputEvent) {\n this.requestUpdate('currentQuickReplies');\n }\n\n private handleOptInChange(event: InputEvent) {\n this.currentOptin = (event.target as any).values;\n this.requestUpdate('optIn');\n }\n\n private handleChatboxChange(evt: Event) {\n const chatbox = evt.target as HTMLInputElement;\n this.currentText = chatbox.value;\n }\n\n private handleDragEnter(evt: DragEvent): void {\n this.highlight(evt);\n }\n\n private handleDragOver(evt: DragEvent): void {\n this.highlight(evt);\n }\n\n private handleDragLeave(evt: DragEvent): void {\n this.unhighlight(evt);\n }\n\n private handleDrop(evt: DragEvent): void {\n if (this.canAcceptAttachments()) {\n this.unhighlight(evt);\n const dt = evt.dataTransfer;\n if (dt) {\n const files = dt.files;\n this.uploadFiles(files);\n }\n }\n }\n\n private preventDefaults(evt: Event): void {\n evt.preventDefault();\n evt.stopPropagation();\n }\n\n private highlight(evt: DragEvent): void {\n if (this.canAcceptAttachments()) {\n this.pendingDrop = true;\n this.preventDefaults(evt);\n }\n }\n\n private unhighlight(evt: DragEvent): void {\n if (this.canAcceptAttachments()) {\n this.pendingDrop = false;\n this.preventDefaults(evt);\n }\n }\n\n private handleUploadFileIconClicked(): void {\n this.dispatchEvent(new Event('change'));\n }\n\n private handleUploadFileInputChanged(evt: Event): void {\n const target = evt.target as HTMLInputElement;\n const files = target.files;\n this.uploadFiles(files);\n }\n\n public canAcceptAttachments() {\n return (\n this.attachments && this.currentAttachments.length < this.maxAttachments\n );\n }\n\n public uploadFiles(files: FileList): void {\n let filesToUpload = [];\n if (this.currentAttachments && this.currentAttachments.length > 0) {\n //remove duplicate files that have already been uploaded\n filesToUpload = [...files].filter(file => {\n const index = this.currentAttachments.findIndex(\n value => value.filename === file.name && value.size === file.size\n );\n if (index === -1) {\n return file;\n }\n });\n } else {\n filesToUpload = [...files];\n }\n filesToUpload.map(fileToUpload => {\n this.uploadFile(fileToUpload);\n });\n }\n\n private uploadFile(file: File): void {\n this.uploading = true;\n\n const url = this.endpoint;\n const payload = new FormData();\n payload.append('file', file);\n postFormData(url, payload)\n .then((response: WebResponse) => {\n if (this.currentAttachments.length >= this.maxAttachments) {\n this.addFailedAttachment(file, 'Too many attachments');\n } else {\n const attachment = response.json as Attachment;\n if (attachment) {\n this.addCurrentAttachment(attachment);\n }\n }\n })\n .catch((error: WebResponse) => {\n let uploadError = '';\n if (error.status === 400) {\n uploadError = error.json.file[0];\n } else {\n uploadError = 'Server failure';\n }\n console.error(uploadError);\n this.addFailedAttachment(file, uploadError);\n })\n .finally(() => {\n this.uploading = false;\n });\n }\n\n private addCurrentAttachment(attachmentToAdd: any) {\n this.currentAttachments.push(attachmentToAdd);\n this.requestUpdate('currentAttachments');\n }\n private removeCurrentAttachment(attachmentToRemove: any) {\n this.currentAttachments = this.currentAttachments.filter(\n currentAttachment => currentAttachment !== attachmentToRemove\n );\n this.requestUpdate('currentAttachments');\n }\n\n private addFailedAttachment(file: File, error: string) {\n const failedAttachment = {\n uuid: Math.random().toString(36).slice(2, 6),\n content_type: file.type,\n filename: file.name,\n url: file.name,\n size: file.size,\n error: error,\n } as Attachment;\n this.failedAttachments.push(failedAttachment);\n this.requestUpdate('failedAttachments');\n }\n private removeFailedAttachment(attachmentToRemove: any) {\n this.failedAttachments = this.failedAttachments.filter(\n (failedAttachment: any) => failedAttachment !== attachmentToRemove\n );\n this.requestUpdate('failedAttachments');\n }\n\n private handleRemoveFileClicked(evt: Event): void {\n const target = evt.target as HTMLDivElement;\n\n const currentAttachmentToRemove = this.currentAttachments.find(\n ({ uuid }) => uuid === target.id\n );\n if (currentAttachmentToRemove) {\n this.removeCurrentAttachment(currentAttachmentToRemove);\n }\n\n const failedAttachmentToRemove = this.failedAttachments.find(\n ({ uuid }) => uuid === target.id\n );\n if (failedAttachmentToRemove) {\n this.removeFailedAttachment(failedAttachmentToRemove);\n }\n }\n\n public toggleButton() {\n if (this.button) {\n this.buttonError = '';\n const chatboxEmpty = this.currentText.trim().length === 0;\n const attachmentsEmpty = this.currentAttachments.length === 0;\n if (this.chatbox && this.attachments) {\n this.buttonDisabled = chatboxEmpty && attachmentsEmpty;\n } else if (this.chatbox) {\n this.buttonDisabled = chatboxEmpty;\n } else if (this.attachments) {\n this.buttonDisabled = attachmentsEmpty;\n } else {\n this.buttonDisabled = true;\n }\n }\n }\n\n private handleSendClick(evt: Event) {\n evt.stopPropagation();\n this.handleSend();\n }\n\n private handleSendEnter(evt: KeyboardEvent) {\n if (this.button) {\n if (evt.key === 'Enter' && !evt.shiftKey) {\n if (this.completion) {\n const chat = evt.target as Completion;\n if (!chat.hasVisibleOptions()) {\n this.handleSend();\n this.preventDefaults(evt);\n }\n } else {\n this.handleSend();\n this.preventDefaults(evt);\n }\n }\n }\n }\n\n private handleSend() {\n if (!this.buttonDisabled) {\n this.buttonDisabled = true;\n const name = this.buttonName;\n this.fireCustomEvent(CustomEventType.ButtonClicked, { name });\n }\n }\n\n private handleLanguageChange(evt: Event) {\n const select = evt.target as Select;\n this.currentLanguage = select.values[0].iso;\n }\n\n public resetTabs() {\n (this.shadowRoot.querySelector('temba-tabs') as TabPane).index = -1;\n }\n\n public render(): TemplateResult {\n return html`\n \n ${this.languages.length > 1\n ? html`\n `\n : null}\n\n \n
    Upload Attachment
    \n\n ${this.chatbox ? html`${this.getChatbox()}` : null}\n\n
    ${this.getActions()}
    \n \n \n `;\n }\n\n private getChatbox(): TemplateResult {\n if (this.completion) {\n return html`\n `;\n } else {\n return html`\n `;\n }\n }\n\n private getAttachments(): TemplateResult {\n return html`\n ${this.attachments\n ? html`
    \n ${this.currentAttachments.map(validAttachment => {\n return html`
    \n \n ${isImageAttachment(validAttachment)\n ? html``\n : html``}\n
    `;\n })}\n ${this.getUploader()}\n
    \n ${this.failedAttachments.map(invalidAttachment => {\n return html`
    \n \n \n
    \n
    \n ${truncate(invalidAttachment.filename, 25)}\n (${formatFileSize(0, 0)}) - Attachment failed\n
    \n `;\n })}`\n : null}\n `;\n }\n\n private getActions(): TemplateResult {\n const showOptins = this.optIns && this.isBaseLanguage();\n return html`\n \n ${this.attachments\n ? html`\n
    ${this.getAttachments()}
    \n `\n : null}\n ${this.quickReplies\n ? html`\n \n `\n : null}\n 0}\n >\n \n \n\n
    \n ${this.buttonError\n ? html`
    ${this.buttonError}
    `\n : null}\n ${this.counter ? this.getCounter() : null}\n ${this.button ? this.getButton() : null}\n
    \n \n `;\n }\n\n private getUploader(): TemplateResult {\n if (this.uploading) {\n return html``;\n } else {\n return this.currentAttachments.length < this.maxAttachments\n ? html`\n \n \n \n \n `\n : null;\n }\n }\n\n private getCounter(): TemplateResult {\n return html``;\n }\n\n private getButton(): TemplateResult {\n return html` `;\n }\n}\n","import { css, html, PropertyValueMap } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { RapidElement } from '../RapidElement';\nimport { getClasses } from '../utils';\nimport { styleMap } from 'lit-html/directives/style-map.js';\n\n/**\n * This component relies on a bit of sleight of hand magic\n * to achieve it's effect. As such, it requires the use of\n * computed animation times and window.setTimeout().\n */\nexport class Lightbox extends RapidElement {\n static get styles() {\n return css`\n :host {\n position: absolute;\n }\n\n .mask {\n display: flex;\n opacity: 0;\n background: rgba(0, 0, 0, 0.5);\n position: absolute;\n height: 100svh;\n width: 100svw;\n pointer-events: none;\n }\n\n .zoom .mask {\n opacity: 1;\n pointer-events: auto;\n }\n\n .matte {\n position: absolute;\n transform: translate(400, 400) scale(3, 3);\n border-radius: 2%;\n overflow: hidden;\n box-shadow: 0 0 12px 3px rgba(0, 0, 0, 0.15);\n }\n `;\n }\n\n @property({ type: Number })\n animationTime = 300;\n\n @property({ type: Boolean })\n show = false;\n\n @property({ type: Boolean })\n zoom = false;\n\n @property({ type: Number })\n zoomPct = 0.9;\n\n private ele: HTMLElement;\n private left: number;\n private top: number;\n private height: number;\n private width: number;\n private scale = 1;\n private xTrans = '0px';\n private yTrans = '0px';\n\n protected updated(\n changed: PropertyValueMap | Map\n ): void {\n if (changed.has('show') && this.show) {\n window.setTimeout(() => {\n this.zoom = true;\n }, 0);\n }\n\n if (changed.has('zoom') && !this.zoom && this.show) {\n window.setTimeout(() => {\n this.show = false;\n }, this.animationTime);\n }\n }\n\n public showElement(ele: HTMLElement) {\n // size our matte according to the ele's boundaries\n const bounds = ele.getBoundingClientRect();\n this.ele = ele.cloneNode() as HTMLElement;\n this.left = bounds.left;\n this.top = bounds.top;\n this.width = bounds.width;\n this.height = bounds.height;\n\n this.xTrans = '0px';\n this.yTrans = '0px';\n this.scale = 1;\n\n let desiredWidth = this.width;\n let desiredHeight = this.height;\n let desiredScale = this.scale;\n\n const maxHeight = window.innerHeight * this.zoomPct;\n const maxWidth = window.innerWidth * this.zoomPct;\n\n // if the width fits, constrain by height\n if (this.width * (maxHeight / this.height) < maxWidth) {\n desiredHeight = window.innerHeight * this.zoomPct;\n desiredScale = desiredHeight / this.height;\n desiredWidth = this.width * desiredScale;\n } else {\n desiredWidth = window.innerWidth * this.zoomPct;\n desiredScale = desiredWidth / this.width;\n desiredHeight = this.height * desiredScale;\n }\n\n const xGrowth = (desiredWidth - this.width) / 2;\n const xDest = (window.innerWidth - desiredWidth) / 2;\n this.xTrans = xDest - this.left + xGrowth + 'px';\n\n const yGrowth = (desiredHeight - this.height) / 2;\n const yDest = (window.innerHeight - desiredHeight) / 2;\n this.yTrans = yDest - this.top + yGrowth + 'px';\n\n this.scale = desiredScale;\n this.show = true;\n }\n\n public handleClick() {\n this.zoom = false;\n }\n\n public render() {\n const styles = {\n transition: `transform ${this.animationTime}ms ease, box-shadow ${this.animationTime}ms ease`,\n };\n\n if (this.show) {\n styles['left'] = this.left + 'px';\n styles['top'] = this.top + 'px';\n styles['width'] = this.width + 'px';\n styles['height'] = this.height + 'px';\n }\n\n if (this.zoom) {\n styles[\n 'transform'\n ] = `translate(${this.xTrans}, ${this.yTrans}) scale(${this.scale}, ${this.scale})`;\n }\n\n return html`\n \n \n
    \n ${this.show ? this.ele : null}\n
    \n \n `;\n }\n}\n","import { html, css, PropertyValueMap } from 'lit';\nimport { FormElement } from '../FormElement';\nimport { property } from 'lit/decorators.js';\nimport { getClasses, hslToHex } from '../utils';\nimport { TextInput } from '../textinput/TextInput';\n\nexport class ColorPicker extends FormElement {\n @property({ type: Boolean })\n expanded = false;\n\n @property({ type: String })\n previewColor = '#ffffff';\n\n @property({ type: String })\n labelColor = '#ffffffee';\n\n @property({ type: Boolean })\n selecting = false;\n\n @property({ type: Number }) hue: number;\n @property({ type: Number }) saturation = 100;\n @property({ type: Number }) lightness = 50;\n @property({ type: String }) hex = '';\n\n static get styles() {\n return css`\n :host {\n color: var(--color-text);\n display: inline-block;\n --curvature: 0.55em;\n width: 100%;\n\n --temba-textinput-padding: 0.4em;\n }\n\n temba-textinput {\n margin-left: 0.3em;\n width: 5em;\n }\n\n temba-field {\n display: block;\n width: 100%;\n }\n\n .wrapper {\n border: 1px solid var(--color-widget-border);\n padding: calc(var(--curvature) / 2);\n border-radius: calc(var(--curvature) * 1.5);\n transition: all calc(var(--transition-speed) * 2) var(--bounce);\n\n display: flex;\n flex-grow: 0;\n }\n\n .picker-wrapper {\n display: flex;\n flex-direction: row;\n align-items: stretch;\n transition: all calc(var(--transition-speed) * 2) var(--bounce);\n flex-grow: 0;\n }\n\n .preview {\n width: initial;\n border-radius: var(--curvature);\n padding: 0.2em 0.5em;\n font-weight: 400;\n border: 2px solid rgba(0, 0, 0, 0.1);\n white-space: nowrap;\n cursor: pointer;\n transition: transform calc(var(--transition-speed) * 0.5) var(--bounce);\n }\n\n .preview.selecting {\n transform: scale(1.05);\n }\n\n .wrapper.expanded {\n flex-grow: 1 !important;\n }\n\n .wrapper.expanded .picker-wrapper {\n flex-grow: 1 !important;\n }\n\n .wrapper.expanded .preview {\n pointer-events: none;\n }\n\n .wrapper.expanded .color-picker {\n margin-left: calc(var(--curvature) / 2);\n }\n\n .wrapper.expanded temba-textinput {\n display: block;\n }\n\n .color-picker {\n border-radius: var(--curvature);\n cursor: pointer;\n transition: all calc(var(--transition-speed) * 2) var(--bounce);\n flex-grow: 1;\n position: relative;\n width: 100%;\n height: 100%;\n background-image: linear-gradient(\n to bottom,\n rgba(0, 0, 0, 0) 60%,\n rgba(0, 0, 0, 0.5) 90%,\n rgba(0, 0, 0, 1)\n ),\n linear-gradient(\n to top,\n rgba(255, 255, 255, 0) 60%,\n rgba(255, 255, 255, 0.8) 90%,\n rgba(255, 255, 255, 1)\n ),\n linear-gradient(\n to right,\n hsla(0, 100%, 50%, 1),\n hsla(60, 100%, 50%, 1),\n hsla(120, 100%, 50%, 1),\n hsla(180, 100%, 50%, 1),\n hsla(240, 100%, 50%, 1),\n hsla(300, 100%, 50%, 1),\n hsla(360, 100%, 50%, 1)\n );\n mix-blend-mode: multiply;\n }\n\n .color-picker:focus {\n outline: none;\n }\n `;\n }\n\n protected firstUpdated(\n _changedProperties: PropertyValueMap | Map\n ): void {\n super.firstUpdated(_changedProperties);\n }\n\n public updated(changed: Map): void {\n super.updated(changed);\n\n if (changed.has('value')) {\n this.previewColor = this.value || '#9c9c9c';\n this.hex = this.value;\n }\n\n if (changed.has('selecting')) {\n if (this.selecting) {\n window.setTimeout(() => {\n this.selecting = false;\n }, 100);\n }\n }\n\n if (changed.has('previewLabel') && this.hue) {\n this.hex = hslToHex(this.hue, this.saturation, this.lightness);\n }\n }\n\n private handleBlur(event: FocusEvent) {\n if (this.expanded) {\n this.expanded = false;\n }\n }\n\n private handleMouseOut(event: MouseEvent) {\n this.previewColor = this.value;\n this.hex = this.value;\n }\n\n private handleMouseMove(event: MouseEvent) {\n if (this.expanded) {\n const rect = (event.target as HTMLElement).getBoundingClientRect();\n const x = event.clientX - rect.left;\n const y = event.clientY - rect.top;\n this.hue = (x / rect.width) * 360;\n this.lightness = 100 - (y / rect.height) * 100;\n this.previewColor = `hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, 1)`;\n this.hex = hslToHex(this.hue, this.saturation, this.lightness);\n }\n }\n\n private handlePreviewClick(event: MouseEvent) {\n this.expanded = !this.expanded;\n this.selecting = true;\n (this.shadowRoot.querySelector('.color-picker') as HTMLDivElement).focus();\n }\n\n private handleColorClick(event: MouseEvent) {\n if (this.expanded) {\n const rect = (event.target as HTMLElement).getBoundingClientRect();\n const x = event.clientX - rect.left;\n const y = event.clientY - rect.top;\n this.hue = (x / rect.width) * 360;\n this.lightness = 100 - (y / rect.height) * 100;\n this.previewColor = `hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, 1)`;\n this.value = this.hex;\n this.selecting = true;\n this.expanded = false;\n }\n\n if (!this.expanded) {\n //\n }\n }\n\n private handleHexInput(event: InputEvent) {\n const hex = (event.target as TextInput).value;\n if (hex.startsWith('#')) {\n this.previewColor = hex;\n this.value = hex;\n }\n }\n\n public serializeValue(value: any): string {\n return value;\n }\n\n public render() {\n return html`\n \n
    \n
    \n
    \n \n ${this.label}\n
    \n
    \n
    \n \n \n \n \n `;\n }\n}\n","import { PropertyValueMap, css, html } from 'lit';\nimport { getClasses } from '../utils';\nimport { property } from 'lit/decorators.js';\nimport { CustomEventType } from '../interfaces';\nimport { ResizeElement } from '../ResizeElement';\n\nexport class Resizer extends ResizeElement {\n static styles = css`\n :host {\n display: block;\n position: relative;\n width: var(--box-width, 200px);\n --resizer-handle-size: 15px;\n }\n\n .resizer {\n position: absolute;\n right: calc(var(--resizer-handle-size) * -1);\n height: 100%;\n cursor: col-resize;\n padding: 0 calc(var(--resizer-handle-size) / 2);\n z-index: 1;\n }\n\n .resizer-handle {\n position: relative;\n width: 4px;\n background: rgba(0, 0, 0, 0);\n height: 100%;\n }\n\n .resizer:hover .resizer-handle {\n background: rgba(0, 0, 0, 0.05);\n width: 3px;\n margin-right: -1px;\n }\n\n .resizing .resizer-handle {\n background: rgba(0, 0, 0, 0.1) !important;\n width: 3px;\n margin-right: -1px;\n }\n\n slot {\n margin-right: var(--resizer-handle-size);\n background: red;\n }\n `;\n\n initialX: number;\n boxWidth: number;\n\n @property({ type: Number })\n minWidth = 200;\n\n @property({ type: Number })\n maxWidth = 2000;\n\n @property({ type: Boolean })\n resizing = false;\n\n @property({ type: Number })\n currentWidth: number;\n\n constructor() {\n super();\n this.startResize = this.startResize.bind(this);\n this.resize = this.resize.bind(this);\n this.stopResize = this.stopResize.bind(this);\n }\n\n protected updated(\n _changedProperties: PropertyValueMap | Map\n ): void {\n super.updated(_changedProperties);\n if (_changedProperties.has('currentWidth')) {\n this.style.setProperty('--box-width', `${this.currentWidth}px`);\n }\n }\n\n public setWidth(width: number) {\n const newWidth = Math.min(Math.max(width, this.minWidth), this.maxWidth);\n this.currentWidth = newWidth;\n }\n\n startResize(e: MouseEvent) {\n this.initialX = e.x;\n this.boxWidth = this.offsetWidth;\n document.body.style.userSelect = 'none';\n this.resizing = true;\n window.addEventListener('mousemove', this.resize);\n window.addEventListener('mouseup', this.stopResize);\n this.requestUpdate();\n }\n\n resize(event: MouseEvent) {\n const dx = event.x - this.initialX;\n this.setWidth(this.boxWidth + dx);\n }\n\n stopResize() {\n document.body.style.userSelect = 'initial';\n window.removeEventListener('mousemove', this.resize);\n window.removeEventListener('mouseup', this.stopResize);\n this.requestUpdate();\n this.resizing = false;\n\n this.fireCustomEvent(CustomEventType.Resized, { width: this.currentWidth });\n }\n\n render() {\n return html`\n \n
    \n \n \n `;\n }\n}\n","import { css, html } from 'lit';\nimport { RapidElement } from '../RapidElement';\nimport { property } from 'lit/decorators.js';\nimport { getClasses } from '../utils';\nimport { Lightbox } from '../lightbox/Lightbox';\nimport { styleMap } from 'lit-html/directives/style-map.js';\n\nexport class Thumbnail extends RapidElement {\n static get styles() {\n return css`\n :host {\n display: inline-block;\n }\n\n .zooming.wrapper {\n padding: 0 !important;\n border-radius: 0;\n }\n\n .zooming .thumb {\n border-radius: 0;\n }\n\n .wrapper {\n padding: var(--thumb-padding, 0.4em);\n background: #fff;\n border-radius: var(--curvature);\n box-shadow: var(--widget-box-shadow);\n }\n\n .thumb {\n }\n `;\n }\n\n @property({ type: String })\n url: string;\n\n @property({ type: String })\n label: string;\n\n @property({ type: Boolean })\n zoom = true;\n\n @property({ type: Boolean })\n zooming = false;\n\n public handleClick(evt: MouseEvent) {\n window.setTimeout(() => {\n const lightbox = document.querySelector('temba-lightbox') as Lightbox;\n lightbox.showElement(this);\n }, 0);\n }\n\n public render() {\n if (this.zooming) {\n return html`\n \n \n ${this.label}\n \n \n `;\n } else {\n return html`\n
    \n\n
    \n ${this.label}\n
    \n
    \n `;\n }\n }\n}\n","import { css } from 'lit';\n\nexport const CroppieCSS = css`\n .croppie-container {\n width: 100%;\n height: 100%;\n }\n\n .croppie-container .cr-image {\n z-index: -1;\n position: absolute;\n top: 0;\n left: 0;\n transform-origin: 0 0;\n max-height: none;\n max-width: none;\n }\n\n .croppie-container .cr-boundary {\n position: relative;\n overflow: hidden;\n margin: 0 auto;\n z-index: 1;\n width: 100%;\n height: 100%;\n }\n\n .croppie-container .cr-viewport,\n .croppie-container .cr-resizer {\n position: absolute;\n border: 2px solid #fff;\n margin: auto;\n top: 0;\n bottom: 0;\n right: 0;\n left: 0;\n box-shadow: 0 0 2000px 2000px rgba(0, 0, 0, 0.5);\n z-index: 0;\n }\n\n .croppie-container .cr-resizer {\n z-index: 2;\n box-shadow: none;\n pointer-events: none;\n }\n\n .croppie-container .cr-resizer-vertical,\n .croppie-container .cr-resizer-horisontal {\n position: absolute;\n pointer-events: all;\n }\n\n .croppie-container .cr-resizer-vertical::after,\n .croppie-container .cr-resizer-horisontal::after {\n display: block;\n position: absolute;\n box-sizing: border-box;\n border: 1px solid black;\n background: #fff;\n width: 10px;\n height: 10px;\n content: '';\n }\n\n .croppie-container .cr-resizer-vertical {\n bottom: -5px;\n cursor: row-resize;\n width: 100%;\n height: 10px;\n }\n\n .croppie-container .cr-resizer-vertical::after {\n left: 50%;\n margin-left: -5px;\n }\n\n .croppie-container .cr-resizer-horisontal {\n right: -5px;\n cursor: col-resize;\n width: 10px;\n height: 100%;\n }\n\n .croppie-container .cr-resizer-horisontal::after {\n top: 50%;\n margin-top: -5px;\n }\n\n .croppie-container .cr-original-image {\n display: none;\n }\n\n .croppie-container .cr-vp-circle {\n border-radius: 50%;\n }\n\n .croppie-container .cr-overlay {\n z-index: 1;\n position: absolute;\n cursor: move;\n touch-action: none;\n }\n\n .croppie-container .cr-slider-wrap {\n width: 75%;\n margin: 15px auto;\n text-align: center;\n }\n\n .croppie-result {\n position: relative;\n overflow: hidden;\n }\n\n .croppie-result img {\n position: absolute;\n }\n\n .croppie-container .cr-image,\n .croppie-container .cr-overlay,\n .croppie-container .cr-viewport {\n -webkit-transform: translateZ(0);\n -moz-transform: translateZ(0);\n -ms-transform: translateZ(0);\n transform: translateZ(0);\n }\n\n /*************************************/\n /***** STYLING RANGE INPUT ***********/\n /*************************************/\n /*http://brennaobrien.com/blog/2014/05/style-input-type-range-in-every-browser.html */\n /*************************************/\n\n .cr-slider {\n -webkit-appearance: none;\n /*removes default webkit styles*/\n /*border: 1px solid white; */ /*fix for FF unable to apply focus style bug */\n width: 300px;\n /*required for proper track sizing in FF*/\n max-width: 100%;\n padding-top: 8px;\n padding-bottom: 8px;\n background-color: transparent;\n }\n\n .cr-slider::-webkit-slider-runnable-track {\n width: 100%;\n height: 3px;\n background: rgba(0, 0, 0, 0.5);\n border: 0;\n border-radius: 3px;\n }\n\n .cr-slider::-webkit-slider-thumb {\n -webkit-appearance: none;\n border: none;\n height: 16px;\n width: 16px;\n border-radius: 50%;\n background: #ddd;\n margin-top: -6px;\n }\n\n .cr-slider:focus {\n outline: none;\n }\n /*\n.cr-slider:focus::-webkit-slider-runnable-track {\nbackground: #ccc;\n}\n*/\n\n .cr-slider::-moz-range-track {\n width: 100%;\n height: 3px;\n background: rgba(0, 0, 0, 0.5);\n border: 0;\n border-radius: 3px;\n }\n\n .cr-slider::-moz-range-thumb {\n border: none;\n height: 16px;\n width: 16px;\n border-radius: 50%;\n background: #ddd;\n margin-top: -6px;\n }\n\n /*hide the outline behind the border*/\n .cr-slider:-moz-focusring {\n outline: 1px solid white;\n outline-offset: -1px;\n }\n\n .cr-slider::-ms-track {\n width: 100%;\n height: 5px;\n background: transparent;\n /*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */\n border-color: transparent; /*leave room for the larger thumb to overflow with a transparent border */\n border-width: 6px 0;\n color: transparent; /*remove default tick marks*/\n }\n .cr-slider::-ms-fill-lower {\n background: rgba(0, 0, 0, 0.5);\n border-radius: 10px;\n }\n .cr-slider::-ms-fill-upper {\n background: rgba(0, 0, 0, 0.5);\n border-radius: 10px;\n }\n .cr-slider::-ms-thumb {\n border: none;\n height: 16px;\n width: 16px;\n border-radius: 50%;\n background: #ddd;\n margin-top: 1px;\n }\n .cr-slider:focus::-ms-fill-lower {\n background: rgba(0, 0, 0, 0.5);\n }\n .cr-slider:focus::-ms-fill-upper {\n background: rgba(0, 0, 0, 0.5);\n }\n /*******************************************/\n\n /***********************************/\n /* Rotation Tools */\n /***********************************/\n .cr-rotate-controls {\n position: absolute;\n bottom: 5px;\n left: 5px;\n z-index: 1;\n }\n .cr-rotate-controls button {\n border: 0;\n background: none;\n }\n .cr-rotate-controls i:before {\n display: inline-block;\n font-style: normal;\n font-weight: 900;\n font-size: 22px;\n }\n .cr-rotate-l i:before {\n content: '↺';\n }\n .cr-rotate-r i:before {\n content: '↻';\n }\n`;\n","/* eslint-disable @typescript-eslint/no-this-alias */\nimport { html, css, PropertyValueMap } from 'lit';\nimport { CroppieCSS } from './CroppieCSS';\nimport { property } from 'lit/decorators.js';\nimport { Icon } from '../vectoricon';\nimport { FormElement } from '../FormElement';\n\nexport class ImagePicker extends FormElement {\n static styles = css`\n ${CroppieCSS}\n\n .croppie {\n max-width: 400px;\n border: 0px solid #ccc;\n border-radius: 0.5em;\n overflow: hidden;\n background: #fff;\n margin-top: -20%;\n box-shadow: 0 0 15px 5px rgba(0, 0, 0, 0.1);\n }\n\n .croppie .controls {\n display: flex;\n align-items: center;\n flex-direction: row;\n justify-content: center;\n position: absolute;\n z-index: 1;\n width: 400px;\n margin-top: -42px;\n }\n\n .toggle {\n height: 110px;\n width: 110px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .circle .toggle {\n border-radius: 50%;\n }\n\n .toggle.set {\n box-shadow: rgba(0, 0, 0, 0.1) 0px 3px 7px 0px,\n rgba(0, 0, 0, 0.2) 0px 1px 2px 0px, inset 0 0 0 5px rgba(0, 0, 0, 0.1);\n }\n\n .toggle.set:hover {\n box-shadow: rgba(0, 0, 0, 0.1) 0px 3px 7px 0px,\n rgba(0, 0, 0, 0.2) 0px 1px 2px 0px, inset 0 0 0 5px rgba(0, 0, 0, 0.2);\n }\n\n .toggle temba-icon {\n color: rgba(0, 0, 0, 0.2);\n padding: 5px;\n }\n\n toggle:hover temba-icon {\n color: rgba(0, 0, 0, 0.8);\n }\n\n .toggle.set temba-icon {\n border-radius: 50%;\n margin-right: -90%;\n margin-bottom: -50%;\n background: rgba(240, 240, 240, 1);\n box-shadow: rgba(0, 0, 0, 0.2) 0px 1px 2px 0px;\n }\n\n .toggle.set:hover temba-icon {\n background: #fff;\n color: var(--color-primary-dark);\n }\n\n .circle .toggle.set temba-icon {\n margin-right: -70%;\n margin-bottom: -70%;\n }\n\n .hidden {\n display: none;\n }\n\n .controls temba-icon {\n margin: 0em 0.75em;\n background: rgba(255, 255, 255, 0.8);\n border-radius: 50%;\n padding: 6px;\n transition: all 0.1s ease-in-out;\n }\n\n .controls {\n pointer-events: none;\n display: flex;\n }\n\n .controls temba-icon {\n pointer-events: all;\n }\n\n .controls temba-icon.close {\n color: rgba(0, 0, 0, 0.2);\n background: rgba(255, 255, 255, 0.2);\n }\n\n .controls temba-icon.submit {\n color: rgba(0, 0, 0, 0.2);\n box-shadow: inset 0 0 0 2px rgba(0, 0, 0, 0.1);\n }\n\n .controls temba-icon:hover {\n color: white;\n cursor: pointer;\n background: var(--color-primary-dark);\n }\n `;\n\n @property({ type: String })\n tempImage: string;\n\n @property({ type: String })\n url: string;\n\n @property({ type: String })\n shape = 'square';\n\n @property({ type: Boolean, attribute: false })\n showCroppie = false;\n\n uploadReader = new FileReader();\n croppie: any;\n\n protected firstUpdated(\n changed: PropertyValueMap | Map\n ): void {\n super.firstUpdated(changed);\n const picker = this;\n\n this.uploadReader.onload = function () {\n picker.launchCroppie(picker.uploadReader.result as any);\n };\n }\n\n public updated(changed: Map): void {\n super.updated(changed);\n if (changed.has('url')) {\n this.setAttribute('url', this.url);\n }\n }\n\n private closeCroppie() {\n this.showCroppie = false;\n const wrapper = this.shadowRoot.querySelector('.croppie .embed');\n if (wrapper.firstChild) {\n wrapper.removeChild(wrapper.firstChild);\n }\n }\n\n private launchCroppie(url: string) {\n const wrapper = this.shadowRoot.querySelector('.croppie .embed');\n if (wrapper.firstChild) {\n wrapper.removeChild(wrapper.firstChild);\n }\n this.showCroppie = true;\n const ele = document.createElement('div');\n wrapper.appendChild(ele);\n\n const Croppie = (window as any).Croppie;\n this.croppie = new Croppie(ele, {\n enableExif: true,\n viewport: {\n width: 300,\n height: 300,\n type: this.shape,\n },\n boundary: {\n width: 400,\n height: 400,\n },\n });\n\n this.croppie.bind({ url });\n }\n\n private saveResult() {\n const picker = this;\n this.croppie\n .result({\n type: 'blob',\n size: 'viewport',\n format: 'webp',\n quality: 1,\n circle: false,\n })\n .then(function (resp: any) {\n const blob = resp;\n picker.url = URL.createObjectURL(blob);\n\n // const blob = dataURItoBlob(resp);\n const fd = new FormData();\n fd.append(picker.name, blob, 'filename.webp');\n\n picker.value = fd;\n picker.closeCroppie();\n });\n }\n\n private handleToggleClicked() {\n const fileInput = this.shadowRoot.querySelector('#file');\n (fileInput as any).click();\n }\n\n private handleFileChanged(e: Event) {\n const input = e.target as any;\n if (input.files.length > 0) {\n this.uploadReader.readAsDataURL(input.files[0]);\n }\n input.value = '';\n }\n\n protected render() {\n return html`\n
    \n \n \n
    \n \n
    \n \n \n
    \n
    \n
    \n \n
    \n \n
    \n \n \n
    \n `;\n }\n}\n","import { LitElement, css, html } from 'lit';\nimport { property } from 'lit/decorators.js';\n\nexport class Mask extends LitElement {\n static styles = css`\n .mask {\n position: fixed;\n top: 0;\n left: 0;\n z-index: 100;\n width: 100vw;\n height: 100vh;\n background: rgba(0, 0, 0, 0.6);\n display: none;\n align-items: center;\n justify-content: center;\n }\n\n .show {\n display: flex;\n }\n `;\n\n @property({ type: Boolean })\n show = false;\n\n render() {\n return html`
    \n \n
    `;\n }\n}\n","import { PropertyValueMap, TemplateResult, css, html } from 'lit';\nimport { property } from 'lit/decorators.js';\nimport { User } from '../interfaces';\nimport { StoreMonitorElement } from '../store/StoreMonitorElement';\nimport { colorHash, extractInitials } from '../utils';\n\nexport class TembaUser extends StoreMonitorElement {\n public static styles = css`\n :host {\n display: flex;\n }\n\n .wrapper {\n display: flex;\n flex-direction: row;\n align-items: center;\n flex-grow: 1;\n }\n\n .name {\n flex-grow: 1;\n display: -webkit-box;\n -webkit-line-clamp: 1;\n -webkit-box-orient: vertical;\n overflow: hidden;\n }\n `;\n\n @property({ type: String })\n email: string;\n\n @property({ type: Number })\n scale: number;\n\n @property({ type: Boolean })\n name: string;\n\n @property({ type: Object, attribute: false })\n user: User;\n\n @property({ type: String, attribute: false })\n background: string;\n\n @property({ type: String, attribute: false })\n initials: string;\n\n @property({ type: String, attribute: false })\n fullName: string;\n\n public updated(\n changed: PropertyValueMap | Map\n ): void {\n super.updated(changed);\n if (changed.has('email')) {\n this.user = this.store.getUser(this.email);\n if (this.user) {\n this.fullName = [this.user.first_name, this.user.last_name].join(' ');\n if (this.user.avatar) {\n this.background = `url('${this.user.avatar}') center / contain no-repeat`;\n this.initials = '';\n } else {\n this.background = colorHash.hex(this.fullName);\n this.initials = extractInitials(this.fullName);\n }\n }\n }\n }\n\n public render(): TemplateResult {\n if (!this.user) {\n return null;\n }\n\n return html`
    \n \n ${this.initials\n ? html` \n
    ${this.initials}
    \n
    `\n : null}\n
    \n ${this.name\n ? html`\n ${this.fullName}\n `\n : null}\n `;\n }\n}\n","import { property } from 'lit/decorators.js';\nimport { FormElement } from '../FormElement';\nimport { TemplateResult, html, css, PropertyValueMap } from 'lit';\nimport { CustomEventType } from '../interfaces';\n\ninterface Component {\n name: string;\n type: string;\n content: string;\n params: { type: string }[];\n}\n\ninterface Translation {\n locale: string;\n status: string;\n channel: { uuid: string; name: string };\n components: Component[];\n}\n\ninterface Template {\n created_on: string;\n modified_on: string;\n name: string;\n translations: Translation[];\n uuid: string;\n}\n\nexport class TemplateEditor extends FormElement {\n static get styles() {\n return css`\n .component {\n background: #fff;\n border: 1px solid var(--color-widget-border);\n border-radius: var(--curvature);\n padding: 1em;\n margin-top: 1em;\n }\n .picker {\n margin-bottom: 0.5em;\n display: block;\n }\n .param {\n display: flex;\n margin-bottom: 0.5em;\n align-items: center;\n }\n label {\n margin-right: 0.5em;\n }\n\n .content span {\n margin-right: 0.25em;\n }\n\n .error-message {\n padding-left: 0.5em;\n }\n\n .variable {\n display: inline-block;\n margin: 0.25em 0em;\n margin-right: 0.25em;\n }\n\n .button-wrapper {\n margin-top: 1em;\n background: #f9f9f9;\n border-radius: var(--curvature);\n padding: 0.5em;\n display: flex;\n flex-direction: column;\n }\n\n .button-header {\n font-weight: normal;\n margin-left: 0.25em;\n margin-bottom: -0.5em;\n font-size: 0.9em;\n color: #777;\n }\n\n .buttons {\n display: flex;\n align-items: center;\n flex-wrap: wrap;\n }\n\n .button {\n background: #fff;\n padding: 0.3em 1em;\n border: 1px solid #e6e6e6;\n border-radius: var(--curvature);\n min-height: 23px;\n display: flex;\n flex-direction: row;\n align-items: center;\n margin-right: 0.5em;\n margin-top: 0.5em;\n align-items: center;\n }\n\n .button .display {\n margin-right: 0.5em;\n background: #f9f9f9;\n padding: 0.25em 1em;\n border-radius: var(--curvature);\n }\n\n temba-textinput,\n temba-completion {\n --temba-textinput-padding: 5px 5px;\n --temba-textinput-font-size: 0.9em;\n line-height: initial;\n }\n\n .template {\n background: #fff;\n border-radius: var(--curvature);\n border: 1px solid var(--color-widget-border);\n padding: 1em;\n line-height: 2.2em;\n }\n `;\n }\n\n @property({ type: String })\n url: string;\n\n // initial template uuid\n @property({ type: String })\n template: string;\n\n @property({ type: Object })\n selectedTemplate: Template;\n\n @property({ type: String })\n lang = 'eng-US';\n\n // component key to array of strings for variables\n @property({ type: Object })\n params: { [key: string]: string[] };\n\n @property({ type: Object, attribute: false })\n translation: Translation;\n\n @property({ type: Boolean })\n translating: boolean;\n\n public firstUpdated(\n changes: PropertyValueMap | Map\n ): void {\n super.firstUpdated(changes);\n }\n\n public updated(changedProperties: Map): void {\n super.updated(changedProperties);\n }\n\n private handleTemplateChanged(event: CustomEvent) {\n this.selectedTemplate = (event.target as any).values[0] as Template;\n const [lang, loc] = this.lang.split('-');\n\n const newParams = {};\n if (this.selectedTemplate) {\n this.selectedTemplate.translations.forEach(translation => {\n if (\n translation.locale === this.lang ||\n (!loc && translation.locale.split('-')[0] === lang)\n ) {\n this.translation = translation;\n for (const comp of translation.components) {\n const compParams = comp.params || [];\n if (compParams.length > 0) {\n // create an array for the length of params\n newParams[comp.name] = new Array(compParams.length).fill('');\n }\n }\n\n // if we are looking at the same template copy our params on top\n if (this.template === this.selectedTemplate.uuid) {\n for (const key of Object.keys(this.params || {})) {\n if (newParams[key]) {\n for (let i = 0; i < this.params[key].length; i++) {\n newParams[key][i] = this.params[key][i];\n }\n }\n }\n }\n }\n });\n } else {\n this.translation = null;\n }\n\n this.params = newParams;\n this.fireCustomEvent(CustomEventType.ContextChanged, {\n template: this.selectedTemplate,\n translation: this.translation,\n params: this.params,\n });\n }\n\n private handleVariableChanged(event: CustomEvent) {\n const target = event.target as HTMLInputElement;\n const index = parseInt(target.getAttribute('index'));\n this.params[target.name][index - 1] = target.value;\n this.fireCustomEvent(CustomEventType.ContentChanged, {\n template: this.selectedTemplate,\n translation: this.translation,\n params: this.params,\n });\n }\n\n private renderVariables(component: Component) {\n const parts = component.content.split(/{{(\\d+)}}/g);\n if (parts.length > 0) {\n const variables = parts.map((part, index) => {\n const paramIndex = Math.round(index / 2);\n if (index % 2 === 0) {\n return html`${part}`;\n }\n return html``;\n });\n return html`
    ${variables}
    `;\n }\n }\n\n public renderComponents(components: Component[]): TemplateResult {\n const nonButtons = components\n .filter(comp => !comp.type.startsWith('button/'))\n .map(\n component =>\n html`
    \n ${this.renderVariables(component)}\n
    `\n );\n const buttonComponents = components.filter(comp =>\n comp.type.startsWith('button/')\n );\n const buttons =\n buttonComponents.length > 0 ? this.renderButtons(buttonComponents) : null;\n return html`
    ${nonButtons}
    \n
    \n ${buttons}\n
    \n
    `;\n }\n\n public renderButtons(components): TemplateResult {\n const buttons = components.map(component => {\n if (component.display) {\n return html`\n
    \n
    ${component.display}
    \n ${this.renderVariables(component)}\n
    \n `;\n } else {\n return html`\n
    ${this.renderVariables(component)}
    \n `;\n }\n });\n return html`
    \n
    Template Buttons
    \n
    ${buttons}
    \n
    `;\n }\n\n public render(): TemplateResult {\n let content = null;\n if (this.translation) {\n content = this.renderComponents(this.translation.components);\n } else {\n content = html`
    \n No approved translation was found for current language.\n
    `;\n }\n\n return html`\n
    \n template.status !== 'approved'}\n placeholder=\"Select a template\"\n @temba-content-changed=${this.swallowEvent}\n @change=${this.handleTemplateChanged}\n >\n \n\n ${this.template ? html`
    ${content}
    ` : null}\n
    \n `;\n }\n}\n","import { Checkbox } from './src/checkbox/Checkbox';\nimport { TextInput } from './src/textinput/TextInput';\nimport { Store } from './src/store/Store';\nimport { Select } from './src/select/Select';\nimport { Completion } from './src/completion/Completion';\nimport { Modax } from './src/dialog/Modax';\nimport { Dialog } from './src/dialog/Dialog';\nimport { Button } from './src/button/Button';\nimport { FormField } from './src/formfield/FormField';\nimport { Loading } from './src/loading/Loading';\nimport { CharCount } from './src/charcount/CharCount';\nimport { Options } from './src/options/Options';\nimport { ContactChat } from './src/contacts/ContactChat';\nimport { ContactHistory } from './src/contacts/ContactHistory';\nimport { TicketList } from './src/list/TicketList';\nimport { ContactDetails } from './src/contacts/ContactDetails';\nimport { TembaList } from './src/list/TembaList';\nimport { ContactSearch } from './src/contactsearch/ContactSearch';\nimport { VectorIcon } from './src/vectoricon/VectorIcon';\nimport { Alert } from './src/alert/Alert';\nimport { Omnibox } from './src/omnibox/Omnibox';\nimport { Tip } from './src/tip/Tip';\nimport { TembaMenu } from './src/list/TembaMenu';\nimport { Anchor } from './src/anchor/Anchor';\nimport { Dropdown } from './src/dropdown/Dropdown';\nimport { TabPane } from './src/tabpane/TabPane';\nimport { Tab } from './src/tabpane/Tab';\nimport Label from './src/label/Label';\nimport { ContactName } from './src/contacts/ContactName';\nimport { ContactUrn } from './src/contacts/ContactUrn';\nimport { ContactFields } from './src/contacts/ContactFields';\nimport { ContactFieldEditor } from './src/contacts/ContactFieldEditor';\n\nimport { ContactBadges } from './src/contacts/ContactBadges';\nimport { ContactPending } from './src/contacts/ContactPending';\nimport { ContactTickets } from './src/contacts/ContactTickets';\nimport { TembaSlider } from './src/slider/TembaSlider';\nimport { RunList } from './src/list/RunList';\nimport { FlowStoreElement } from './src/flow/FlowStoreElement';\nimport { ContactNameFetch } from './src/contacts/ContactNameFetch';\nimport DatePicker from './src/datepicker/DatePicker';\nimport { FieldManager } from './src/fields/FieldManager';\nimport { SortableList } from './src/list/SortableList';\nimport { ContentMenu } from './src/list/ContentMenu';\nimport { TembaDate } from './src/date/TembaDate';\nimport Remote from './src/remote/Remote';\nimport { Compose } from './src/compose/Compose';\nimport { Lightbox } from './src/lightbox/Lightbox';\nimport { ColorPicker } from './src/colorpicker/ColorPicker';\nimport { Resizer } from './src/resizer/Resizer';\nimport { Thumbnail } from './src/thumbnail/Thumbnail';\nimport { NotificationList } from './src/list/NotificationList';\nimport { WebChat } from './src/webchat/WebChat';\nimport { ImagePicker } from './src/imagepicker/ImagePicker';\nimport { Mask } from './src/mask/Mask';\nimport { TembaUser } from './src/user/TembaUser';\nimport { TemplateEditor } from './src/templates/TemplateEditor';\n\nexport function addCustomElement(name: string, comp: any) {\n if (!window.customElements.get(name)) {\n window.customElements.define(name, comp);\n }\n}\n\naddCustomElement('temba-anchor', Anchor);\naddCustomElement('temba-alert', Alert);\naddCustomElement('temba-store', Store);\naddCustomElement('temba-textinput', TextInput);\naddCustomElement('temba-datepicker', DatePicker);\naddCustomElement('temba-date', TembaDate);\naddCustomElement('temba-completion', Completion);\naddCustomElement('temba-checkbox', Checkbox);\naddCustomElement('temba-select', Select);\naddCustomElement('temba-options', Options);\naddCustomElement('temba-loading', Loading);\naddCustomElement('temba-lightbox', Lightbox);\naddCustomElement('temba-button', Button);\naddCustomElement('temba-omnibox', Omnibox);\naddCustomElement('temba-tip', Tip);\naddCustomElement('temba-contact-name', ContactName);\naddCustomElement('temba-contact-name-fetch', ContactNameFetch);\naddCustomElement('temba-contact-field', ContactFieldEditor);\naddCustomElement('temba-contact-fields', ContactFields);\naddCustomElement('temba-field-manager', FieldManager);\naddCustomElement('temba-urn', ContactUrn);\naddCustomElement('temba-content-menu', ContentMenu);\n\naddCustomElement('temba-field', FormField);\naddCustomElement('temba-dialog', Dialog);\naddCustomElement('temba-modax', Modax);\naddCustomElement('temba-charcount', CharCount);\naddCustomElement('temba-contact-history', ContactHistory);\naddCustomElement('temba-contact-chat', ContactChat);\naddCustomElement('temba-contact-details', ContactDetails);\naddCustomElement('temba-ticket-list', TicketList);\naddCustomElement('temba-notification-list', NotificationList);\naddCustomElement('temba-list', TembaList);\naddCustomElement('temba-sortable-list', SortableList);\naddCustomElement('temba-run-list', RunList);\naddCustomElement('temba-flow-details', FlowStoreElement);\naddCustomElement('temba-label', Label);\naddCustomElement('temba-menu', TembaMenu);\naddCustomElement('temba-remote', Remote);\naddCustomElement('temba-contact-search', ContactSearch);\naddCustomElement('temba-icon', VectorIcon);\naddCustomElement('temba-dropdown', Dropdown);\naddCustomElement('temba-tabs', TabPane);\naddCustomElement('temba-tab', Tab);\naddCustomElement('temba-contact-badges', ContactBadges);\naddCustomElement('temba-contact-pending', ContactPending);\naddCustomElement('temba-contact-tickets', ContactTickets);\naddCustomElement('temba-slider', TembaSlider);\naddCustomElement('temba-content-menu', ContentMenu);\naddCustomElement('temba-compose', Compose);\naddCustomElement('temba-color-picker', ColorPicker);\naddCustomElement('temba-resizer', Resizer);\naddCustomElement('temba-thumbnail', Thumbnail);\naddCustomElement('temba-webchat', WebChat);\naddCustomElement('temba-image-picker', ImagePicker);\naddCustomElement('temba-mask', Mask);\naddCustomElement('temba-user', TembaUser);\naddCustomElement('temba-template-editor', TemplateEditor);\n","import { css, html, TemplateResult } from 'lit';\nimport { TembaList } from './TembaList';\nimport { Options } from '../options/Options';\nimport { Icon } from '../vectoricon';\n\ninterface Notification {\n created_on: string;\n type: string;\n target_url: string;\n is_seen: boolean;\n export?: {\n type: string;\n };\n import?: {\n type: string;\n num_records: number;\n };\n incident?: {\n type: string;\n started_on: string;\n ended_on?: string;\n };\n}\n\nexport class NotificationList extends TembaList {\n reverseRefresh = false;\n internalFocusDisabled = true;\n static get styles() {\n return css`\n :host {\n --option-hover-bg: #f9f9f9;\n }\n\n .header {\n padding: 0.25em 1em;\n background: #f9f9f9;\n border-top-left-radius: var(--curvature);\n border-top-right-radius: var(--curvature);\n display: flex;\n color: #999;\n border-bottom: 1px solid #f3f3f3;\n }\n\n .header temba-icon {\n margin-right: 0.35em;\n }\n\n .footer {\n background: #f9f9f9;\n }\n\n .title {\n font-weight: normal;\n }\n `;\n }\n\n constructor() {\n super();\n this.valueKey = 'target_url';\n this.renderOption = (notification: Notification): TemplateResult => {\n let icon = null;\n let body = null;\n const color = '#333';\n\n if (notification.type === 'incident:started') {\n if (notification.incident.type === 'org:flagged') {\n icon = Icon.incidents;\n body =\n 'Your workspace was flagged, please contact support for assistance.';\n } else if (notification.incident.type === 'org:suspended') {\n icon = Icon.incidents;\n body =\n 'Your workspace was suspended, please contact support for assistance.';\n } else if (notification.incident.type === 'channel:disconnected') {\n icon = Icon.channel;\n body = 'Your android channel is not connected';\n } else if (notification.incident.type === 'channel:templates_failed') {\n icon = Icon.channel;\n body = 'Your WhatsApp channel templates failed syncing';\n } else if (notification.incident.type === 'webhooks:unhealthy') {\n icon = Icon.webhook;\n body = 'Your webhook calls are not working properly.';\n }\n } else if (notification.type === 'import:finished') {\n if (notification.import.type === 'contact') {\n icon = Icon.contact_import;\n body = `Imported ${notification.import.num_records.toLocaleString()} contacts`;\n }\n } else if (notification.type === 'export:finished') {\n if (notification.export.type === 'contact') {\n icon = Icon.contact_export;\n body = 'Exported contacts';\n } else if (notification.export.type === 'message') {\n icon = Icon.message_export;\n body = 'Exported messages';\n } else if (notification.export.type === 'results') {\n icon = Icon.results_export;\n body = 'Exported flow results';\n } else if (notification.export.type === 'ticket') {\n icon = Icon.tickets_export;\n body = 'Exported tickets';\n }\n } else if (notification.type === 'tickets:activity') {\n icon = Icon.tickets;\n body = 'New ticket activity';\n } else if (notification.type === 'tickets:opened') {\n icon = Icon.tickets;\n body = 'New unassigned ticket';\n }\n return html`\n ${icon\n ? html`
    \n \n
    `\n : null}\n
    \n
    ${body}
    \n \n
    \n `;\n };\n }\n\n public renderHeader(): TemplateResult {\n return html`
    \n \n
    Notifications
    \n
    `;\n }\n\n protected handleSelection(event: CustomEvent) {\n super.handleSelected(event);\n }\n\n public scrollToTop(): void {\n // scroll back to the top\n window.setTimeout(() => {\n const options = this.shadowRoot.querySelector('temba-options') as Options;\n options.scrollToTop();\n }, 1000);\n }\n}\n","import { css, html, LitElement, TemplateResult } from 'lit';\nimport { FeatureProperties } from '../interfaces';\nimport { getUrl, postJSON, WebResponse } from '../utils';\nimport { TextInput } from '../textinput/TextInput';\nimport { styleMap } from 'lit-html/directives/style-map.js';\nimport { FormElement } from '../FormElement';\nimport { Icon } from '../vectoricon';\n\nimport { property } from 'lit/decorators.js';\nimport { Select } from '../select/Select';\n\nexport class AliasEditor extends LitElement {\n static get styles() {\n return css`\n :host {\n line-height: normal;\n }\n\n temba-textinput {\n height: 150px;\n }\n\n #left-column {\n display: inline-block;\n margin-left: 10px;\n width: 300px;\n z-index: 100;\n }\n\n .search {\n margin-bottom: 10px;\n }\n\n .feature {\n padding: 4px 14px;\n font-size: 16px;\n }\n\n .level-0 {\n margin-left: 0px;\n }\n\n .level-1 {\n margin-left: 5px;\n font-size: 95%;\n }\n\n .level-2 {\n margin-left: 10px;\n font-size: 90%;\n }\n\n .level-3 {\n margin-left: 15px;\n font-size: 85%;\n }\n\n .feature-name {\n display: inline-block;\n }\n\n .clickable {\n text-decoration: none;\n cursor: pointer;\n color: var(--color-link-primary);\n }\n\n .clickable.secondary {\n color: var(--color-link-secondary);\n }\n\n .clickable:hover {\n text-decoration: underline;\n color: var(--color-link-primary-hover);\n }\n\n .feature:hover .showonhover {\n visibility: visible;\n }\n\n .showonhover {\n visibility: hidden;\n }\n\n .aliases {\n color: #bbb;\n font-size: 80%;\n display: inline;\n margin-left: 5px;\n }\n\n temba-label {\n margin-right: 3px;\n margin-bottom: 3px;\n vertical-align: top;\n }\n\n .selected {\n display: flex;\n flex-direction: column;\n padding: 15px;\n padding-bottom: 40px;\n }\n\n .selected .name {\n font-size: 18px;\n padding: 5px;\n }\n\n .selected .help {\n padding: 5px 2px;\n font-size: 11px;\n color: var(--color-secondary-light);\n }\n\n #right-column {\n vertical-align: top;\n margin-left: 20px;\n display: inline-block;\n }\n\n leaflet-map {\n height: 600px;\n width: 800px;\n border: 0px solid #999;\n border-radius: var(--curvature);\n }\n\n .edit {\n display: inline-block;\n margin-right: 0px;\n }\n `;\n }\n\n @property({ type: Array, attribute: false })\n path: FeatureProperties[] = [];\n\n @property()\n endpoint: string;\n\n @property()\n osmId: string;\n\n @property({ type: Object })\n hovered: FeatureProperties;\n\n @property({ type: Object })\n editFeature: FeatureProperties;\n\n @property({ type: String, attribute: false })\n editFeatureAliases: string;\n\n public constructor() {\n super();\n }\n\n public updated(changedProperties: Map) {\n if (changedProperties.has('osmId')) {\n // going up the tree doesn't require a fetch\n const newPath = [];\n for (const feature of this.path) {\n newPath.push(feature);\n if (feature.osm_id === this.osmId) {\n this.path = [...newPath];\n this.hideAliasDialog();\n return;\n }\n }\n\n this.fetchFeature();\n }\n }\n\n private fetchFeature() {\n getUrl(this.getEndpoint() + 'boundaries/' + this.osmId + '/').then(\n (response: WebResponse) => {\n this.path = response.json as FeatureProperties[];\n this.hideAliasDialog();\n }\n );\n }\n\n private handleMapClicked(feature: FeatureProperties): void {\n this.hovered = null;\n if (!feature || feature.osm_id !== this.osmId) {\n this.osmId = feature.osm_id;\n }\n }\n\n private handlePlaceClicked(feature: FeatureProperties) {\n this.osmId = feature.osm_id;\n }\n\n private handleSearchSelection(evt: CustomEvent) {\n const selection = evt.detail.selected as FeatureProperties;\n this.showAliasDialog(selection);\n const select = this.shadowRoot.querySelector('temba-select') as Select;\n select.clear();\n }\n\n private isMatch(option: any, query: string) {\n return `${option.name} ${option.aliases}`.toLowerCase().indexOf(query) > -1;\n }\n\n private renderFeature(\n feature: FeatureProperties,\n remainingPath: FeatureProperties[]\n ): TemplateResult {\n const selectedFeature = this.path[this.path.length - 1];\n const clickable =\n (feature.has_children || feature.level === 0) &&\n feature !== selectedFeature;\n const renderedFeature = html`\n
    \n {\n if (feature.level > 0) {\n this.hovered = feature;\n }\n }}\n @mouseout=${() => {\n this.hovered = null;\n }}\n class=\"level-${feature.level}\"\n >\n {\n if (clickable) {\n this.handlePlaceClicked(feature);\n }\n }}\n >\n ${feature.name}\n
    \n\n
    \n ${feature.aliases.split('\\n').map((alias: string) =>\n alias.trim().length > 0\n ? html`\n {\n this.showAliasDialog(feature);\n }}\n light\n clickable\n >${alias}\n `\n : null\n )}\n ${feature.level > 0\n ? html`\n {\n this.showAliasDialog(feature);\n evt.preventDefault();\n evt.stopPropagation();\n }}\n >\n \n
    \n `\n : ''}\n \n \n \n `;\n\n const renderedChildren = (feature.children || []).map(\n (child: FeatureProperties) => {\n if (\n remainingPath.length > 0 &&\n remainingPath[0].osm_id === child.osm_id\n ) {\n return this.renderFeature(remainingPath[0], remainingPath.slice(1));\n }\n\n if (\n remainingPath.length === 0 ||\n remainingPath[0].children.length === 0\n ) {\n return this.renderFeature(child, remainingPath);\n }\n\n return null;\n }\n );\n\n return html` ${renderedFeature} ${renderedChildren} `;\n }\n\n public showAliasDialog(feature: FeatureProperties) {\n this.editFeatureAliases = feature.aliases;\n this.editFeature = feature;\n const aliasDialog = this.shadowRoot.getElementById('alias-dialog');\n if (aliasDialog) {\n aliasDialog.setAttribute('open', '');\n }\n }\n\n public hideAliasDialog() {\n const aliasDialog = this.shadowRoot.getElementById('alias-dialog');\n this.editFeature = null;\n this.editFeatureAliases = null;\n if (aliasDialog) {\n aliasDialog.removeAttribute('open');\n }\n\n this.requestUpdate();\n }\n\n private getEndpoint(): string {\n return this.endpoint + (!this.endpoint.endsWith('/') ? '/' : '');\n }\n\n private handleDialogClick(evt: CustomEvent) {\n const button = evt.detail.button;\n if (button.name === 'Save') {\n const textarea = this.shadowRoot.getElementById(\n this.editFeature.osm_id\n ) as TextInput;\n const aliases = textarea.inputElement.value;\n const payload = { osm_id: this.editFeature.osm_id, aliases };\n postJSON(\n this.getEndpoint() + 'boundaries/' + this.editFeature.osm_id + '/',\n payload\n ).then(() => {\n this.fetchFeature();\n });\n }\n\n if (button.name === 'Cancel') {\n this.hideAliasDialog();\n }\n }\n\n private getOptions(response: WebResponse) {\n return response.json.filter((option: any) => option.level > 0);\n }\n\n private getOptionsComplete(newestOptions: FeatureProperties[]) {\n return newestOptions.length === 0;\n }\n\n private renderOptionDetail(option: FeatureProperties): TemplateResult {\n const labelStyles = {\n marginTop: '3px',\n marginRight: '3px',\n };\n\n const aliasList = option.aliases.split('\\n');\n const aliases = aliasList.map((alias: string) =>\n alias.trim().length > 0\n ? html`\n ${alias}\n `\n : null\n );\n return html`\n
    ${option.path.replace(/>/gi, '‣')}
    \n
    ${aliases}
    \n `;\n }\n\n public render(): TemplateResult {\n if (this.path.length === 0) {\n return html``;\n }\n\n // if we are a leaf, have our map show the level above\n const selectedFeature = this.path[this.path.length - 1];\n const mapFeature =\n selectedFeature.children.length === 0\n ? this.path[this.path.length - 2]\n : selectedFeature;\n\n const editFeatureId = this.editFeature ? this.editFeature.osm_id : null;\n const editFeatureName = this.editFeature ? this.editFeature.name : null;\n\n return html`\n
    \n
    \n \n
    \n
    \n ${this.renderFeature(this.path[0], this.path.slice(1))}\n
    \n
    \n\n
    \n \n \n
    \n\n \n
    \n \n
    \n \n `;\n }\n}\n","/* @preserve\n * Leaflet 1.5.1+build.2e3e0ff, a JS library for interactive maps. http://leafletjs.com\n * (c) 2010-2018 Vladimir Agafonkin, (c) 2010-2011 CloudMade\n */\n\n(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n\ttypeof define === 'function' && define.amd ? define(['exports'], factory) :\n\t(factory((global.L = {})));\n}(this, (function (exports) { 'use strict';\n\nvar version = \"1.5.1+build.2e3e0ffb\";\n\n/*\r\n * @namespace Util\r\n *\r\n * Various utility functions, used by Leaflet internally.\r\n */\r\n\r\nvar freeze = Object.freeze;\r\nObject.freeze = function (obj) { return obj; };\r\n\r\n// @function extend(dest: Object, src?: Object): Object\r\n// Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.\r\nfunction extend(dest) {\r\n\tvar i, j, len, src;\r\n\r\n\tfor (j = 1, len = arguments.length; j < len; j++) {\r\n\t\tsrc = arguments[j];\r\n\t\tfor (i in src) {\r\n\t\t\tdest[i] = src[i];\r\n\t\t}\r\n\t}\r\n\treturn dest;\r\n}\r\n\r\n// @function create(proto: Object, properties?: Object): Object\r\n// Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)\r\nvar create = Object.create || (function () {\r\n\tfunction F() {}\r\n\treturn function (proto) {\r\n\t\tF.prototype = proto;\r\n\t\treturn new F();\r\n\t};\r\n})();\r\n\r\n// @function bind(fn: Function, …): Function\r\n// Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).\r\n// Has a `L.bind()` shortcut.\r\nfunction bind(fn, obj) {\r\n\tvar slice = Array.prototype.slice;\r\n\r\n\tif (fn.bind) {\r\n\t\treturn fn.bind.apply(fn, slice.call(arguments, 1));\r\n\t}\r\n\r\n\tvar args = slice.call(arguments, 2);\r\n\r\n\treturn function () {\r\n\t\treturn fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);\r\n\t};\r\n}\r\n\r\n// @property lastId: Number\r\n// Last unique ID used by [`stamp()`](#util-stamp)\r\nvar lastId = 0;\r\n\r\n// @function stamp(obj: Object): Number\r\n// Returns the unique ID of an object, assigning it one if it doesn't have it.\r\nfunction stamp(obj) {\r\n\t/*eslint-disable */\r\n\tobj._leaflet_id = obj._leaflet_id || ++lastId;\r\n\treturn obj._leaflet_id;\r\n\t/* eslint-enable */\r\n}\r\n\r\n// @function throttle(fn: Function, time: Number, context: Object): Function\r\n// Returns a function which executes function `fn` with the given scope `context`\r\n// (so that the `this` keyword refers to `context` inside `fn`'s code). The function\r\n// `fn` will be called no more than one time per given amount of `time`. The arguments\r\n// received by the bound function will be any arguments passed when binding the\r\n// function, followed by any arguments passed when invoking the bound function.\r\n// Has an `L.throttle` shortcut.\r\nfunction throttle(fn, time, context) {\r\n\tvar lock, args, wrapperFn, later;\r\n\r\n\tlater = function () {\r\n\t\t// reset lock and call if queued\r\n\t\tlock = false;\r\n\t\tif (args) {\r\n\t\t\twrapperFn.apply(context, args);\r\n\t\t\targs = false;\r\n\t\t}\r\n\t};\r\n\r\n\twrapperFn = function () {\r\n\t\tif (lock) {\r\n\t\t\t// called too soon, queue to call later\r\n\t\t\targs = arguments;\r\n\r\n\t\t} else {\r\n\t\t\t// call and lock until later\r\n\t\t\tfn.apply(context, arguments);\r\n\t\t\tsetTimeout(later, time);\r\n\t\t\tlock = true;\r\n\t\t}\r\n\t};\r\n\r\n\treturn wrapperFn;\r\n}\r\n\r\n// @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number\r\n// Returns the number `num` modulo `range` in such a way so it lies within\r\n// `range[0]` and `range[1]`. The returned value will be always smaller than\r\n// `range[1]` unless `includeMax` is set to `true`.\r\nfunction wrapNum(x, range, includeMax) {\r\n\tvar max = range[1],\r\n\t min = range[0],\r\n\t d = max - min;\r\n\treturn x === max && includeMax ? x : ((x - min) % d + d) % d + min;\r\n}\r\n\r\n// @function falseFn(): Function\r\n// Returns a function which always returns `false`.\r\nfunction falseFn() { return false; }\r\n\r\n// @function formatNum(num: Number, digits?: Number): Number\r\n// Returns the number `num` rounded to `digits` decimals, or to 6 decimals by default.\r\nfunction formatNum(num, digits) {\r\n\tdigits = (digits === undefined ? 6 : digits);\r\n\treturn +(Math.round(num + ('e+' + digits)) + ('e-' + digits));\r\n}\r\n\r\n// @function trim(str: String): String\r\n// Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)\r\nfunction trim(str) {\r\n\treturn str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '');\r\n}\r\n\r\n// @function splitWords(str: String): String[]\r\n// Trims and splits the string on whitespace and returns the array of parts.\r\nfunction splitWords(str) {\r\n\treturn trim(str).split(/\\s+/);\r\n}\r\n\r\n// @function setOptions(obj: Object, options: Object): Object\r\n// Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.\r\nfunction setOptions(obj, options) {\r\n\tif (!obj.hasOwnProperty('options')) {\r\n\t\tobj.options = obj.options ? create(obj.options) : {};\r\n\t}\r\n\tfor (var i in options) {\r\n\t\tobj.options[i] = options[i];\r\n\t}\r\n\treturn obj.options;\r\n}\r\n\r\n// @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String\r\n// Converts an object into a parameter URL string, e.g. `{a: \"foo\", b: \"bar\"}`\r\n// translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will\r\n// be appended at the end. If `uppercase` is `true`, the parameter names will\r\n// be uppercased (e.g. `'?A=foo&B=bar'`)\r\nfunction getParamString(obj, existingUrl, uppercase) {\r\n\tvar params = [];\r\n\tfor (var i in obj) {\r\n\t\tparams.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));\r\n\t}\r\n\treturn ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');\r\n}\r\n\r\nvar templateRe = /\\{ *([\\w_-]+) *\\}/g;\r\n\r\n// @function template(str: String, data: Object): String\r\n// Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`\r\n// and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string\r\n// `('Hello foo, bar')`. You can also specify functions instead of strings for\r\n// data values — they will be evaluated passing `data` as an argument.\r\nfunction template(str, data) {\r\n\treturn str.replace(templateRe, function (str, key) {\r\n\t\tvar value = data[key];\r\n\r\n\t\tif (value === undefined) {\r\n\t\t\tthrow new Error('No value provided for variable ' + str);\r\n\r\n\t\t} else if (typeof value === 'function') {\r\n\t\t\tvalue = value(data);\r\n\t\t}\r\n\t\treturn value;\r\n\t});\r\n}\r\n\r\n// @function isArray(obj): Boolean\r\n// Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)\r\nvar isArray = Array.isArray || function (obj) {\r\n\treturn (Object.prototype.toString.call(obj) === '[object Array]');\r\n};\r\n\r\n// @function indexOf(array: Array, el: Object): Number\r\n// Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)\r\nfunction indexOf(array, el) {\r\n\tfor (var i = 0; i < array.length; i++) {\r\n\t\tif (array[i] === el) { return i; }\r\n\t}\r\n\treturn -1;\r\n}\r\n\r\n// @property emptyImageUrl: String\r\n// Data URI string containing a base64-encoded empty GIF image.\r\n// Used as a hack to free memory from unused images on WebKit-powered\r\n// mobile devices (by setting image `src` to this string).\r\nvar emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';\r\n\r\n// inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/\r\n\r\nfunction getPrefixed(name) {\r\n\treturn window['webkit' + name] || window['moz' + name] || window['ms' + name];\r\n}\r\n\r\nvar lastTime = 0;\r\n\r\n// fallback for IE 7-8\r\nfunction timeoutDefer(fn) {\r\n\tvar time = +new Date(),\r\n\t timeToCall = Math.max(0, 16 - (time - lastTime));\r\n\r\n\tlastTime = time + timeToCall;\r\n\treturn window.setTimeout(fn, timeToCall);\r\n}\r\n\r\nvar requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;\r\nvar cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||\r\n\t\tgetPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };\r\n\r\n// @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number\r\n// Schedules `fn` to be executed when the browser repaints. `fn` is bound to\r\n// `context` if given. When `immediate` is set, `fn` is called immediately if\r\n// the browser doesn't have native support for\r\n// [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),\r\n// otherwise it's delayed. Returns a request ID that can be used to cancel the request.\r\nfunction requestAnimFrame(fn, context, immediate) {\r\n\tif (immediate && requestFn === timeoutDefer) {\r\n\t\tfn.call(context);\r\n\t} else {\r\n\t\treturn requestFn.call(window, bind(fn, context));\r\n\t}\r\n}\r\n\r\n// @function cancelAnimFrame(id: Number): undefined\r\n// Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).\r\nfunction cancelAnimFrame(id) {\r\n\tif (id) {\r\n\t\tcancelFn.call(window, id);\r\n\t}\r\n}\r\n\n\nvar Util = (Object.freeze || Object)({\n\tfreeze: freeze,\n\textend: extend,\n\tcreate: create,\n\tbind: bind,\n\tlastId: lastId,\n\tstamp: stamp,\n\tthrottle: throttle,\n\twrapNum: wrapNum,\n\tfalseFn: falseFn,\n\tformatNum: formatNum,\n\ttrim: trim,\n\tsplitWords: splitWords,\n\tsetOptions: setOptions,\n\tgetParamString: getParamString,\n\ttemplate: template,\n\tisArray: isArray,\n\tindexOf: indexOf,\n\temptyImageUrl: emptyImageUrl,\n\trequestFn: requestFn,\n\tcancelFn: cancelFn,\n\trequestAnimFrame: requestAnimFrame,\n\tcancelAnimFrame: cancelAnimFrame\n});\n\n// @class Class\r\n// @aka L.Class\r\n\r\n// @section\r\n// @uninheritable\r\n\r\n// Thanks to John Resig and Dean Edwards for inspiration!\r\n\r\nfunction Class() {}\r\n\r\nClass.extend = function (props) {\r\n\r\n\t// @function extend(props: Object): Function\r\n\t// [Extends the current class](#class-inheritance) given the properties to be included.\r\n\t// Returns a Javascript function that is a class constructor (to be called with `new`).\r\n\tvar NewClass = function () {\r\n\r\n\t\t// call the constructor\r\n\t\tif (this.initialize) {\r\n\t\t\tthis.initialize.apply(this, arguments);\r\n\t\t}\r\n\r\n\t\t// call all constructor hooks\r\n\t\tthis.callInitHooks();\r\n\t};\r\n\r\n\tvar parentProto = NewClass.__super__ = this.prototype;\r\n\r\n\tvar proto = create(parentProto);\r\n\tproto.constructor = NewClass;\r\n\r\n\tNewClass.prototype = proto;\r\n\r\n\t// inherit parent's statics\r\n\tfor (var i in this) {\r\n\t\tif (this.hasOwnProperty(i) && i !== 'prototype' && i !== '__super__') {\r\n\t\t\tNewClass[i] = this[i];\r\n\t\t}\r\n\t}\r\n\r\n\t// mix static properties into the class\r\n\tif (props.statics) {\r\n\t\textend(NewClass, props.statics);\r\n\t\tdelete props.statics;\r\n\t}\r\n\r\n\t// mix includes into the prototype\r\n\tif (props.includes) {\r\n\t\tcheckDeprecatedMixinEvents(props.includes);\r\n\t\textend.apply(null, [proto].concat(props.includes));\r\n\t\tdelete props.includes;\r\n\t}\r\n\r\n\t// merge options\r\n\tif (proto.options) {\r\n\t\tprops.options = extend(create(proto.options), props.options);\r\n\t}\r\n\r\n\t// mix given properties into the prototype\r\n\textend(proto, props);\r\n\r\n\tproto._initHooks = [];\r\n\r\n\t// add method for calling all hooks\r\n\tproto.callInitHooks = function () {\r\n\r\n\t\tif (this._initHooksCalled) { return; }\r\n\r\n\t\tif (parentProto.callInitHooks) {\r\n\t\t\tparentProto.callInitHooks.call(this);\r\n\t\t}\r\n\r\n\t\tthis._initHooksCalled = true;\r\n\r\n\t\tfor (var i = 0, len = proto._initHooks.length; i < len; i++) {\r\n\t\t\tproto._initHooks[i].call(this);\r\n\t\t}\r\n\t};\r\n\r\n\treturn NewClass;\r\n};\r\n\r\n\r\n// @function include(properties: Object): this\r\n// [Includes a mixin](#class-includes) into the current class.\r\nClass.include = function (props) {\r\n\textend(this.prototype, props);\r\n\treturn this;\r\n};\r\n\r\n// @function mergeOptions(options: Object): this\r\n// [Merges `options`](#class-options) into the defaults of the class.\r\nClass.mergeOptions = function (options) {\r\n\textend(this.prototype.options, options);\r\n\treturn this;\r\n};\r\n\r\n// @function addInitHook(fn: Function): this\r\n// Adds a [constructor hook](#class-constructor-hooks) to the class.\r\nClass.addInitHook = function (fn) { // (Function) || (String, args...)\r\n\tvar args = Array.prototype.slice.call(arguments, 1);\r\n\r\n\tvar init = typeof fn === 'function' ? fn : function () {\r\n\t\tthis[fn].apply(this, args);\r\n\t};\r\n\r\n\tthis.prototype._initHooks = this.prototype._initHooks || [];\r\n\tthis.prototype._initHooks.push(init);\r\n\treturn this;\r\n};\r\n\r\nfunction checkDeprecatedMixinEvents(includes) {\r\n\tif (typeof L === 'undefined' || !L || !L.Mixin) { return; }\r\n\r\n\tincludes = isArray(includes) ? includes : [includes];\r\n\r\n\tfor (var i = 0; i < includes.length; i++) {\r\n\t\tif (includes[i] === L.Mixin.Events) {\r\n\t\t\tconsole.warn('Deprecated include of L.Mixin.Events: ' +\r\n\t\t\t\t'this property will be removed in future releases, ' +\r\n\t\t\t\t'please inherit from L.Evented instead.', new Error().stack);\r\n\t\t}\r\n\t}\r\n}\n\n/*\r\n * @class Evented\r\n * @aka L.Evented\r\n * @inherits Class\r\n *\r\n * A set of methods shared between event-powered classes (like `Map` and `Marker`). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire `'click'` event).\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * map.on('click', function(e) {\r\n * \talert(e.latlng);\r\n * } );\r\n * ```\r\n *\r\n * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:\r\n *\r\n * ```js\r\n * function onClick(e) { ... }\r\n *\r\n * map.on('click', onClick);\r\n * map.off('click', onClick);\r\n * ```\r\n */\r\n\r\nvar Events = {\r\n\t/* @method on(type: String, fn: Function, context?: Object): this\r\n\t * Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`).\r\n\t *\r\n\t * @alternative\r\n\t * @method on(eventMap: Object): this\r\n\t * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`\r\n\t */\r\n\ton: function (types, fn, context) {\r\n\r\n\t\t// types can be a map of types/handlers\r\n\t\tif (typeof types === 'object') {\r\n\t\t\tfor (var type in types) {\r\n\t\t\t\t// we don't process space-separated events here for performance;\r\n\t\t\t\t// it's a hot path since Layer uses the on(obj) syntax\r\n\t\t\t\tthis._on(type, types[type], fn);\r\n\t\t\t}\r\n\r\n\t\t} else {\r\n\t\t\t// types can be a string of space-separated words\r\n\t\t\ttypes = splitWords(types);\r\n\r\n\t\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\t\tthis._on(types[i], fn, context);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t/* @method off(type: String, fn?: Function, context?: Object): this\r\n\t * Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener.\r\n\t *\r\n\t * @alternative\r\n\t * @method off(eventMap: Object): this\r\n\t * Removes a set of type/listener pairs.\r\n\t *\r\n\t * @alternative\r\n\t * @method off: this\r\n\t * Removes all listeners to all events on the object. This includes implicitly attached events.\r\n\t */\r\n\toff: function (types, fn, context) {\r\n\r\n\t\tif (!types) {\r\n\t\t\t// clear all listeners if called without arguments\r\n\t\t\tdelete this._events;\r\n\r\n\t\t} else if (typeof types === 'object') {\r\n\t\t\tfor (var type in types) {\r\n\t\t\t\tthis._off(type, types[type], fn);\r\n\t\t\t}\r\n\r\n\t\t} else {\r\n\t\t\ttypes = splitWords(types);\r\n\r\n\t\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\t\tthis._off(types[i], fn, context);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// attach listener (without syntactic sugar now)\r\n\t_on: function (type, fn, context) {\r\n\t\tthis._events = this._events || {};\r\n\r\n\t\t/* get/init listeners for type */\r\n\t\tvar typeListeners = this._events[type];\r\n\t\tif (!typeListeners) {\r\n\t\t\ttypeListeners = [];\r\n\t\t\tthis._events[type] = typeListeners;\r\n\t\t}\r\n\r\n\t\tif (context === this) {\r\n\t\t\t// Less memory footprint.\r\n\t\t\tcontext = undefined;\r\n\t\t}\r\n\t\tvar newListener = {fn: fn, ctx: context},\r\n\t\t listeners = typeListeners;\r\n\r\n\t\t// check if fn already there\r\n\t\tfor (var i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\tif (listeners[i].fn === fn && listeners[i].ctx === context) {\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tlisteners.push(newListener);\r\n\t},\r\n\r\n\t_off: function (type, fn, context) {\r\n\t\tvar listeners,\r\n\t\t i,\r\n\t\t len;\r\n\r\n\t\tif (!this._events) { return; }\r\n\r\n\t\tlisteners = this._events[type];\r\n\r\n\t\tif (!listeners) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (!fn) {\r\n\t\t\t// Set all removed listeners to noop so they are not called if remove happens in fire\r\n\t\t\tfor (i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\t\tlisteners[i].fn = falseFn;\r\n\t\t\t}\r\n\t\t\t// clear all listeners for a type if function isn't specified\r\n\t\t\tdelete this._events[type];\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (context === this) {\r\n\t\t\tcontext = undefined;\r\n\t\t}\r\n\r\n\t\tif (listeners) {\r\n\r\n\t\t\t// find fn and remove it\r\n\t\t\tfor (i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\t\tvar l = listeners[i];\r\n\t\t\t\tif (l.ctx !== context) { continue; }\r\n\t\t\t\tif (l.fn === fn) {\r\n\r\n\t\t\t\t\t// set the removed listener to noop so that's not called if remove happens in fire\r\n\t\t\t\t\tl.fn = falseFn;\r\n\r\n\t\t\t\t\tif (this._firingCount) {\r\n\t\t\t\t\t\t/* copy array in case events are being fired */\r\n\t\t\t\t\t\tthis._events[type] = listeners = listeners.slice();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tlisteners.splice(i, 1);\r\n\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t// @method fire(type: String, data?: Object, propagate?: Boolean): this\r\n\t// Fires an event of the specified type. You can optionally provide an data\r\n\t// object — the first argument of the listener function will contain its\r\n\t// properties. The event can optionally be propagated to event parents.\r\n\tfire: function (type, data, propagate) {\r\n\t\tif (!this.listens(type, propagate)) { return this; }\r\n\r\n\t\tvar event = extend({}, data, {\r\n\t\t\ttype: type,\r\n\t\t\ttarget: this,\r\n\t\t\tsourceTarget: data && data.sourceTarget || this\r\n\t\t});\r\n\r\n\t\tif (this._events) {\r\n\t\t\tvar listeners = this._events[type];\r\n\r\n\t\t\tif (listeners) {\r\n\t\t\t\tthis._firingCount = (this._firingCount + 1) || 1;\r\n\t\t\t\tfor (var i = 0, len = listeners.length; i < len; i++) {\r\n\t\t\t\t\tvar l = listeners[i];\r\n\t\t\t\t\tl.fn.call(l.ctx || this, event);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tthis._firingCount--;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (propagate) {\r\n\t\t\t// propagate the event to parents (set with addEventParent)\r\n\t\t\tthis._propagateEvent(event);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method listens(type: String): Boolean\r\n\t// Returns `true` if a particular event type has any listeners attached to it.\r\n\tlistens: function (type, propagate) {\r\n\t\tvar listeners = this._events && this._events[type];\r\n\t\tif (listeners && listeners.length) { return true; }\r\n\r\n\t\tif (propagate) {\r\n\t\t\t// also check parents for listeners if event propagates\r\n\t\t\tfor (var id in this._eventParents) {\r\n\t\t\t\tif (this._eventParents[id].listens(type, propagate)) { return true; }\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t},\r\n\r\n\t// @method once(…): this\r\n\t// Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.\r\n\tonce: function (types, fn, context) {\r\n\r\n\t\tif (typeof types === 'object') {\r\n\t\t\tfor (var type in types) {\r\n\t\t\t\tthis.once(type, types[type], fn);\r\n\t\t\t}\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tvar handler = bind(function () {\r\n\t\t\tthis\r\n\t\t\t .off(types, fn, context)\r\n\t\t\t .off(types, handler, context);\r\n\t\t}, this);\r\n\r\n\t\t// add a listener that's executed once and removed after that\r\n\t\treturn this\r\n\t\t .on(types, fn, context)\r\n\t\t .on(types, handler, context);\r\n\t},\r\n\r\n\t// @method addEventParent(obj: Evented): this\r\n\t// Adds an event parent - an `Evented` that will receive propagated events\r\n\taddEventParent: function (obj) {\r\n\t\tthis._eventParents = this._eventParents || {};\r\n\t\tthis._eventParents[stamp(obj)] = obj;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeEventParent(obj: Evented): this\r\n\t// Removes an event parent, so it will stop receiving propagated events\r\n\tremoveEventParent: function (obj) {\r\n\t\tif (this._eventParents) {\r\n\t\t\tdelete this._eventParents[stamp(obj)];\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_propagateEvent: function (e) {\r\n\t\tfor (var id in this._eventParents) {\r\n\t\t\tthis._eventParents[id].fire(e.type, extend({\r\n\t\t\t\tlayer: e.target,\r\n\t\t\t\tpropagatedFrom: e.target\r\n\t\t\t}, e), true);\r\n\t\t}\r\n\t}\r\n};\r\n\r\n// aliases; we should ditch those eventually\r\n\r\n// @method addEventListener(…): this\r\n// Alias to [`on(…)`](#evented-on)\r\nEvents.addEventListener = Events.on;\r\n\r\n// @method removeEventListener(…): this\r\n// Alias to [`off(…)`](#evented-off)\r\n\r\n// @method clearAllEventListeners(…): this\r\n// Alias to [`off()`](#evented-off)\r\nEvents.removeEventListener = Events.clearAllEventListeners = Events.off;\r\n\r\n// @method addOneTimeEventListener(…): this\r\n// Alias to [`once(…)`](#evented-once)\r\nEvents.addOneTimeEventListener = Events.once;\r\n\r\n// @method fireEvent(…): this\r\n// Alias to [`fire(…)`](#evented-fire)\r\nEvents.fireEvent = Events.fire;\r\n\r\n// @method hasEventListeners(…): Boolean\r\n// Alias to [`listens(…)`](#evented-listens)\r\nEvents.hasEventListeners = Events.listens;\r\n\r\nvar Evented = Class.extend(Events);\n\n/*\r\n * @class Point\r\n * @aka L.Point\r\n *\r\n * Represents a point with `x` and `y` coordinates in pixels.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var point = L.point(200, 300);\r\n * ```\r\n *\r\n * All Leaflet methods and options that accept `Point` objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent:\r\n *\r\n * ```js\r\n * map.panBy([200, 300]);\r\n * map.panBy(L.point(200, 300));\r\n * ```\r\n *\r\n * Note that `Point` does not inherit from Leafet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nfunction Point(x, y, round) {\r\n\t// @property x: Number; The `x` coordinate of the point\r\n\tthis.x = (round ? Math.round(x) : x);\r\n\t// @property y: Number; The `y` coordinate of the point\r\n\tthis.y = (round ? Math.round(y) : y);\r\n}\r\n\r\nvar trunc = Math.trunc || function (v) {\r\n\treturn v > 0 ? Math.floor(v) : Math.ceil(v);\r\n};\r\n\r\nPoint.prototype = {\r\n\r\n\t// @method clone(): Point\r\n\t// Returns a copy of the current point.\r\n\tclone: function () {\r\n\t\treturn new Point(this.x, this.y);\r\n\t},\r\n\r\n\t// @method add(otherPoint: Point): Point\r\n\t// Returns the result of addition of the current and the given points.\r\n\tadd: function (point) {\r\n\t\t// non-destructive, returns a new point\r\n\t\treturn this.clone()._add(toPoint(point));\r\n\t},\r\n\r\n\t_add: function (point) {\r\n\t\t// destructive, used directly for performance in situations where it's safe to modify existing point\r\n\t\tthis.x += point.x;\r\n\t\tthis.y += point.y;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method subtract(otherPoint: Point): Point\r\n\t// Returns the result of subtraction of the given point from the current.\r\n\tsubtract: function (point) {\r\n\t\treturn this.clone()._subtract(toPoint(point));\r\n\t},\r\n\r\n\t_subtract: function (point) {\r\n\t\tthis.x -= point.x;\r\n\t\tthis.y -= point.y;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method divideBy(num: Number): Point\r\n\t// Returns the result of division of the current point by the given number.\r\n\tdivideBy: function (num) {\r\n\t\treturn this.clone()._divideBy(num);\r\n\t},\r\n\r\n\t_divideBy: function (num) {\r\n\t\tthis.x /= num;\r\n\t\tthis.y /= num;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method multiplyBy(num: Number): Point\r\n\t// Returns the result of multiplication of the current point by the given number.\r\n\tmultiplyBy: function (num) {\r\n\t\treturn this.clone()._multiplyBy(num);\r\n\t},\r\n\r\n\t_multiplyBy: function (num) {\r\n\t\tthis.x *= num;\r\n\t\tthis.y *= num;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method scaleBy(scale: Point): Point\r\n\t// Multiply each coordinate of the current point by each coordinate of\r\n\t// `scale`. In linear algebra terms, multiply the point by the\r\n\t// [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)\r\n\t// defined by `scale`.\r\n\tscaleBy: function (point) {\r\n\t\treturn new Point(this.x * point.x, this.y * point.y);\r\n\t},\r\n\r\n\t// @method unscaleBy(scale: Point): Point\r\n\t// Inverse of `scaleBy`. Divide each coordinate of the current point by\r\n\t// each coordinate of `scale`.\r\n\tunscaleBy: function (point) {\r\n\t\treturn new Point(this.x / point.x, this.y / point.y);\r\n\t},\r\n\r\n\t// @method round(): Point\r\n\t// Returns a copy of the current point with rounded coordinates.\r\n\tround: function () {\r\n\t\treturn this.clone()._round();\r\n\t},\r\n\r\n\t_round: function () {\r\n\t\tthis.x = Math.round(this.x);\r\n\t\tthis.y = Math.round(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method floor(): Point\r\n\t// Returns a copy of the current point with floored coordinates (rounded down).\r\n\tfloor: function () {\r\n\t\treturn this.clone()._floor();\r\n\t},\r\n\r\n\t_floor: function () {\r\n\t\tthis.x = Math.floor(this.x);\r\n\t\tthis.y = Math.floor(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method ceil(): Point\r\n\t// Returns a copy of the current point with ceiled coordinates (rounded up).\r\n\tceil: function () {\r\n\t\treturn this.clone()._ceil();\r\n\t},\r\n\r\n\t_ceil: function () {\r\n\t\tthis.x = Math.ceil(this.x);\r\n\t\tthis.y = Math.ceil(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method trunc(): Point\r\n\t// Returns a copy of the current point with truncated coordinates (rounded towards zero).\r\n\ttrunc: function () {\r\n\t\treturn this.clone()._trunc();\r\n\t},\r\n\r\n\t_trunc: function () {\r\n\t\tthis.x = trunc(this.x);\r\n\t\tthis.y = trunc(this.y);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method distanceTo(otherPoint: Point): Number\r\n\t// Returns the cartesian distance between the current and the given points.\r\n\tdistanceTo: function (point) {\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\tvar x = point.x - this.x,\r\n\t\t y = point.y - this.y;\r\n\r\n\t\treturn Math.sqrt(x * x + y * y);\r\n\t},\r\n\r\n\t// @method equals(otherPoint: Point): Boolean\r\n\t// Returns `true` if the given point has the same coordinates.\r\n\tequals: function (point) {\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\treturn point.x === this.x &&\r\n\t\t point.y === this.y;\r\n\t},\r\n\r\n\t// @method contains(otherPoint: Point): Boolean\r\n\t// Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).\r\n\tcontains: function (point) {\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\treturn Math.abs(point.x) <= Math.abs(this.x) &&\r\n\t\t Math.abs(point.y) <= Math.abs(this.y);\r\n\t},\r\n\r\n\t// @method toString(): String\r\n\t// Returns a string representation of the point for debugging purposes.\r\n\ttoString: function () {\r\n\t\treturn 'Point(' +\r\n\t\t formatNum(this.x) + ', ' +\r\n\t\t formatNum(this.y) + ')';\r\n\t}\r\n};\r\n\r\n// @factory L.point(x: Number, y: Number, round?: Boolean)\r\n// Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.\r\n\r\n// @alternative\r\n// @factory L.point(coords: Number[])\r\n// Expects an array of the form `[x, y]` instead.\r\n\r\n// @alternative\r\n// @factory L.point(coords: Object)\r\n// Expects a plain object of the form `{x: Number, y: Number}` instead.\r\nfunction toPoint(x, y, round) {\r\n\tif (x instanceof Point) {\r\n\t\treturn x;\r\n\t}\r\n\tif (isArray(x)) {\r\n\t\treturn new Point(x[0], x[1]);\r\n\t}\r\n\tif (x === undefined || x === null) {\r\n\t\treturn x;\r\n\t}\r\n\tif (typeof x === 'object' && 'x' in x && 'y' in x) {\r\n\t\treturn new Point(x.x, x.y);\r\n\t}\r\n\treturn new Point(x, y, round);\r\n}\n\n/*\r\n * @class Bounds\r\n * @aka L.Bounds\r\n *\r\n * Represents a rectangular area in pixel coordinates.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var p1 = L.point(10, 10),\r\n * p2 = L.point(40, 60),\r\n * bounds = L.bounds(p1, p2);\r\n * ```\r\n *\r\n * All Leaflet methods that accept `Bounds` objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:\r\n *\r\n * ```js\r\n * otherBounds.intersects([[10, 10], [40, 60]]);\r\n * ```\r\n *\r\n * Note that `Bounds` does not inherit from Leafet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nfunction Bounds(a, b) {\r\n\tif (!a) { return; }\r\n\r\n\tvar points = b ? [a, b] : a;\r\n\r\n\tfor (var i = 0, len = points.length; i < len; i++) {\r\n\t\tthis.extend(points[i]);\r\n\t}\r\n}\r\n\r\nBounds.prototype = {\r\n\t// @method extend(point: Point): this\r\n\t// Extends the bounds to contain the given point.\r\n\textend: function (point) { // (Point)\r\n\t\tpoint = toPoint(point);\r\n\r\n\t\t// @property min: Point\r\n\t\t// The top left corner of the rectangle.\r\n\t\t// @property max: Point\r\n\t\t// The bottom right corner of the rectangle.\r\n\t\tif (!this.min && !this.max) {\r\n\t\t\tthis.min = point.clone();\r\n\t\t\tthis.max = point.clone();\r\n\t\t} else {\r\n\t\t\tthis.min.x = Math.min(point.x, this.min.x);\r\n\t\t\tthis.max.x = Math.max(point.x, this.max.x);\r\n\t\t\tthis.min.y = Math.min(point.y, this.min.y);\r\n\t\t\tthis.max.y = Math.max(point.y, this.max.y);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getCenter(round?: Boolean): Point\r\n\t// Returns the center point of the bounds.\r\n\tgetCenter: function (round) {\r\n\t\treturn new Point(\r\n\t\t (this.min.x + this.max.x) / 2,\r\n\t\t (this.min.y + this.max.y) / 2, round);\r\n\t},\r\n\r\n\t// @method getBottomLeft(): Point\r\n\t// Returns the bottom-left point of the bounds.\r\n\tgetBottomLeft: function () {\r\n\t\treturn new Point(this.min.x, this.max.y);\r\n\t},\r\n\r\n\t// @method getTopRight(): Point\r\n\t// Returns the top-right point of the bounds.\r\n\tgetTopRight: function () { // -> Point\r\n\t\treturn new Point(this.max.x, this.min.y);\r\n\t},\r\n\r\n\t// @method getTopLeft(): Point\r\n\t// Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).\r\n\tgetTopLeft: function () {\r\n\t\treturn this.min; // left, top\r\n\t},\r\n\r\n\t// @method getBottomRight(): Point\r\n\t// Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).\r\n\tgetBottomRight: function () {\r\n\t\treturn this.max; // right, bottom\r\n\t},\r\n\r\n\t// @method getSize(): Point\r\n\t// Returns the size of the given bounds\r\n\tgetSize: function () {\r\n\t\treturn this.max.subtract(this.min);\r\n\t},\r\n\r\n\t// @method contains(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle contains the given one.\r\n\t// @alternative\r\n\t// @method contains(point: Point): Boolean\r\n\t// Returns `true` if the rectangle contains the given point.\r\n\tcontains: function (obj) {\r\n\t\tvar min, max;\r\n\r\n\t\tif (typeof obj[0] === 'number' || obj instanceof Point) {\r\n\t\t\tobj = toPoint(obj);\r\n\t\t} else {\r\n\t\t\tobj = toBounds(obj);\r\n\t\t}\r\n\r\n\t\tif (obj instanceof Bounds) {\r\n\t\t\tmin = obj.min;\r\n\t\t\tmax = obj.max;\r\n\t\t} else {\r\n\t\t\tmin = max = obj;\r\n\t\t}\r\n\r\n\t\treturn (min.x >= this.min.x) &&\r\n\t\t (max.x <= this.max.x) &&\r\n\t\t (min.y >= this.min.y) &&\r\n\t\t (max.y <= this.max.y);\r\n\t},\r\n\r\n\t// @method intersects(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle intersects the given bounds. Two bounds\r\n\t// intersect if they have at least one point in common.\r\n\tintersects: function (bounds) { // (Bounds) -> Boolean\r\n\t\tbounds = toBounds(bounds);\r\n\r\n\t\tvar min = this.min,\r\n\t\t max = this.max,\r\n\t\t min2 = bounds.min,\r\n\t\t max2 = bounds.max,\r\n\t\t xIntersects = (max2.x >= min.x) && (min2.x <= max.x),\r\n\t\t yIntersects = (max2.y >= min.y) && (min2.y <= max.y);\r\n\r\n\t\treturn xIntersects && yIntersects;\r\n\t},\r\n\r\n\t// @method overlaps(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle overlaps the given bounds. Two bounds\r\n\t// overlap if their intersection is an area.\r\n\toverlaps: function (bounds) { // (Bounds) -> Boolean\r\n\t\tbounds = toBounds(bounds);\r\n\r\n\t\tvar min = this.min,\r\n\t\t max = this.max,\r\n\t\t min2 = bounds.min,\r\n\t\t max2 = bounds.max,\r\n\t\t xOverlaps = (max2.x > min.x) && (min2.x < max.x),\r\n\t\t yOverlaps = (max2.y > min.y) && (min2.y < max.y);\r\n\r\n\t\treturn xOverlaps && yOverlaps;\r\n\t},\r\n\r\n\tisValid: function () {\r\n\t\treturn !!(this.min && this.max);\r\n\t}\r\n};\r\n\r\n\r\n// @factory L.bounds(corner1: Point, corner2: Point)\r\n// Creates a Bounds object from two corners coordinate pairs.\r\n// @alternative\r\n// @factory L.bounds(points: Point[])\r\n// Creates a Bounds object from the given array of points.\r\nfunction toBounds(a, b) {\r\n\tif (!a || a instanceof Bounds) {\r\n\t\treturn a;\r\n\t}\r\n\treturn new Bounds(a, b);\r\n}\n\n/*\r\n * @class LatLngBounds\r\n * @aka L.LatLngBounds\r\n *\r\n * Represents a rectangular geographical area on a map.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var corner1 = L.latLng(40.712, -74.227),\r\n * corner2 = L.latLng(40.774, -74.125),\r\n * bounds = L.latLngBounds(corner1, corner2);\r\n * ```\r\n *\r\n * All Leaflet methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:\r\n *\r\n * ```js\r\n * map.fitBounds([\r\n * \t[40.712, -74.227],\r\n * \t[40.774, -74.125]\r\n * ]);\r\n * ```\r\n *\r\n * Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners _outside_ the [-180, 180] degrees longitude range.\r\n *\r\n * Note that `LatLngBounds` does not inherit from Leafet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nfunction LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])\r\n\tif (!corner1) { return; }\r\n\r\n\tvar latlngs = corner2 ? [corner1, corner2] : corner1;\r\n\r\n\tfor (var i = 0, len = latlngs.length; i < len; i++) {\r\n\t\tthis.extend(latlngs[i]);\r\n\t}\r\n}\r\n\r\nLatLngBounds.prototype = {\r\n\r\n\t// @method extend(latlng: LatLng): this\r\n\t// Extend the bounds to contain the given point\r\n\r\n\t// @alternative\r\n\t// @method extend(otherBounds: LatLngBounds): this\r\n\t// Extend the bounds to contain the given bounds\r\n\textend: function (obj) {\r\n\t\tvar sw = this._southWest,\r\n\t\t ne = this._northEast,\r\n\t\t sw2, ne2;\r\n\r\n\t\tif (obj instanceof LatLng) {\r\n\t\t\tsw2 = obj;\r\n\t\t\tne2 = obj;\r\n\r\n\t\t} else if (obj instanceof LatLngBounds) {\r\n\t\t\tsw2 = obj._southWest;\r\n\t\t\tne2 = obj._northEast;\r\n\r\n\t\t\tif (!sw2 || !ne2) { return this; }\r\n\r\n\t\t} else {\r\n\t\t\treturn obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;\r\n\t\t}\r\n\r\n\t\tif (!sw && !ne) {\r\n\t\t\tthis._southWest = new LatLng(sw2.lat, sw2.lng);\r\n\t\t\tthis._northEast = new LatLng(ne2.lat, ne2.lng);\r\n\t\t} else {\r\n\t\t\tsw.lat = Math.min(sw2.lat, sw.lat);\r\n\t\t\tsw.lng = Math.min(sw2.lng, sw.lng);\r\n\t\t\tne.lat = Math.max(ne2.lat, ne.lat);\r\n\t\t\tne.lng = Math.max(ne2.lng, ne.lng);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method pad(bufferRatio: Number): LatLngBounds\r\n\t// Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.\r\n\t// For example, a ratio of 0.5 extends the bounds by 50% in each direction.\r\n\t// Negative values will retract the bounds.\r\n\tpad: function (bufferRatio) {\r\n\t\tvar sw = this._southWest,\r\n\t\t ne = this._northEast,\r\n\t\t heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,\r\n\t\t widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;\r\n\r\n\t\treturn new LatLngBounds(\r\n\t\t new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),\r\n\t\t new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));\r\n\t},\r\n\r\n\t// @method getCenter(): LatLng\r\n\t// Returns the center point of the bounds.\r\n\tgetCenter: function () {\r\n\t\treturn new LatLng(\r\n\t\t (this._southWest.lat + this._northEast.lat) / 2,\r\n\t\t (this._southWest.lng + this._northEast.lng) / 2);\r\n\t},\r\n\r\n\t// @method getSouthWest(): LatLng\r\n\t// Returns the south-west point of the bounds.\r\n\tgetSouthWest: function () {\r\n\t\treturn this._southWest;\r\n\t},\r\n\r\n\t// @method getNorthEast(): LatLng\r\n\t// Returns the north-east point of the bounds.\r\n\tgetNorthEast: function () {\r\n\t\treturn this._northEast;\r\n\t},\r\n\r\n\t// @method getNorthWest(): LatLng\r\n\t// Returns the north-west point of the bounds.\r\n\tgetNorthWest: function () {\r\n\t\treturn new LatLng(this.getNorth(), this.getWest());\r\n\t},\r\n\r\n\t// @method getSouthEast(): LatLng\r\n\t// Returns the south-east point of the bounds.\r\n\tgetSouthEast: function () {\r\n\t\treturn new LatLng(this.getSouth(), this.getEast());\r\n\t},\r\n\r\n\t// @method getWest(): Number\r\n\t// Returns the west longitude of the bounds\r\n\tgetWest: function () {\r\n\t\treturn this._southWest.lng;\r\n\t},\r\n\r\n\t// @method getSouth(): Number\r\n\t// Returns the south latitude of the bounds\r\n\tgetSouth: function () {\r\n\t\treturn this._southWest.lat;\r\n\t},\r\n\r\n\t// @method getEast(): Number\r\n\t// Returns the east longitude of the bounds\r\n\tgetEast: function () {\r\n\t\treturn this._northEast.lng;\r\n\t},\r\n\r\n\t// @method getNorth(): Number\r\n\t// Returns the north latitude of the bounds\r\n\tgetNorth: function () {\r\n\t\treturn this._northEast.lat;\r\n\t},\r\n\r\n\t// @method contains(otherBounds: LatLngBounds): Boolean\r\n\t// Returns `true` if the rectangle contains the given one.\r\n\r\n\t// @alternative\r\n\t// @method contains (latlng: LatLng): Boolean\r\n\t// Returns `true` if the rectangle contains the given point.\r\n\tcontains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean\r\n\t\tif (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {\r\n\t\t\tobj = toLatLng(obj);\r\n\t\t} else {\r\n\t\t\tobj = toLatLngBounds(obj);\r\n\t\t}\r\n\r\n\t\tvar sw = this._southWest,\r\n\t\t ne = this._northEast,\r\n\t\t sw2, ne2;\r\n\r\n\t\tif (obj instanceof LatLngBounds) {\r\n\t\t\tsw2 = obj.getSouthWest();\r\n\t\t\tne2 = obj.getNorthEast();\r\n\t\t} else {\r\n\t\t\tsw2 = ne2 = obj;\r\n\t\t}\r\n\r\n\t\treturn (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&\r\n\t\t (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);\r\n\t},\r\n\r\n\t// @method intersects(otherBounds: LatLngBounds): Boolean\r\n\t// Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.\r\n\tintersects: function (bounds) {\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tvar sw = this._southWest,\r\n\t\t ne = this._northEast,\r\n\t\t sw2 = bounds.getSouthWest(),\r\n\t\t ne2 = bounds.getNorthEast(),\r\n\r\n\t\t latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),\r\n\t\t lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);\r\n\r\n\t\treturn latIntersects && lngIntersects;\r\n\t},\r\n\r\n\t// @method overlaps(otherBounds: Bounds): Boolean\r\n\t// Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.\r\n\toverlaps: function (bounds) {\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tvar sw = this._southWest,\r\n\t\t ne = this._northEast,\r\n\t\t sw2 = bounds.getSouthWest(),\r\n\t\t ne2 = bounds.getNorthEast(),\r\n\r\n\t\t latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),\r\n\t\t lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);\r\n\r\n\t\treturn latOverlaps && lngOverlaps;\r\n\t},\r\n\r\n\t// @method toBBoxString(): String\r\n\t// Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data.\r\n\ttoBBoxString: function () {\r\n\t\treturn [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');\r\n\t},\r\n\r\n\t// @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean\r\n\t// Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number.\r\n\tequals: function (bounds, maxMargin) {\r\n\t\tif (!bounds) { return false; }\r\n\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\treturn this._southWest.equals(bounds.getSouthWest(), maxMargin) &&\r\n\t\t this._northEast.equals(bounds.getNorthEast(), maxMargin);\r\n\t},\r\n\r\n\t// @method isValid(): Boolean\r\n\t// Returns `true` if the bounds are properly initialized.\r\n\tisValid: function () {\r\n\t\treturn !!(this._southWest && this._northEast);\r\n\t}\r\n};\r\n\r\n// TODO International date line?\r\n\r\n// @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)\r\n// Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.\r\n\r\n// @alternative\r\n// @factory L.latLngBounds(latlngs: LatLng[])\r\n// Creates a `LatLngBounds` object defined by the geographical points it contains. Very useful for zooming the map to fit a particular set of locations with [`fitBounds`](#map-fitbounds).\r\nfunction toLatLngBounds(a, b) {\r\n\tif (a instanceof LatLngBounds) {\r\n\t\treturn a;\r\n\t}\r\n\treturn new LatLngBounds(a, b);\r\n}\n\n/* @class LatLng\r\n * @aka L.LatLng\r\n *\r\n * Represents a geographical point with a certain latitude and longitude.\r\n *\r\n * @example\r\n *\r\n * ```\r\n * var latlng = L.latLng(50.5, 30.5);\r\n * ```\r\n *\r\n * All Leaflet methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent:\r\n *\r\n * ```\r\n * map.panTo([50, 30]);\r\n * map.panTo({lon: 30, lat: 50});\r\n * map.panTo({lat: 50, lng: 30});\r\n * map.panTo(L.latLng(50, 30));\r\n * ```\r\n *\r\n * Note that `LatLng` does not inherit from Leaflet's `Class` object,\r\n * which means new classes can't inherit from it, and new methods\r\n * can't be added to it with the `include` function.\r\n */\r\n\r\nfunction LatLng(lat, lng, alt) {\r\n\tif (isNaN(lat) || isNaN(lng)) {\r\n\t\tthrow new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');\r\n\t}\r\n\r\n\t// @property lat: Number\r\n\t// Latitude in degrees\r\n\tthis.lat = +lat;\r\n\r\n\t// @property lng: Number\r\n\t// Longitude in degrees\r\n\tthis.lng = +lng;\r\n\r\n\t// @property alt: Number\r\n\t// Altitude in meters (optional)\r\n\tif (alt !== undefined) {\r\n\t\tthis.alt = +alt;\r\n\t}\r\n}\r\n\r\nLatLng.prototype = {\r\n\t// @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean\r\n\t// Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number.\r\n\tequals: function (obj, maxMargin) {\r\n\t\tif (!obj) { return false; }\r\n\r\n\t\tobj = toLatLng(obj);\r\n\r\n\t\tvar margin = Math.max(\r\n\t\t Math.abs(this.lat - obj.lat),\r\n\t\t Math.abs(this.lng - obj.lng));\r\n\r\n\t\treturn margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);\r\n\t},\r\n\r\n\t// @method toString(): String\r\n\t// Returns a string representation of the point (for debugging purposes).\r\n\ttoString: function (precision) {\r\n\t\treturn 'LatLng(' +\r\n\t\t formatNum(this.lat, precision) + ', ' +\r\n\t\t formatNum(this.lng, precision) + ')';\r\n\t},\r\n\r\n\t// @method distanceTo(otherLatLng: LatLng): Number\r\n\t// Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines).\r\n\tdistanceTo: function (other) {\r\n\t\treturn Earth.distance(this, toLatLng(other));\r\n\t},\r\n\r\n\t// @method wrap(): LatLng\r\n\t// Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.\r\n\twrap: function () {\r\n\t\treturn Earth.wrapLatLng(this);\r\n\t},\r\n\r\n\t// @method toBounds(sizeInMeters: Number): LatLngBounds\r\n\t// Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.\r\n\ttoBounds: function (sizeInMeters) {\r\n\t\tvar latAccuracy = 180 * sizeInMeters / 40075017,\r\n\t\t lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);\r\n\r\n\t\treturn toLatLngBounds(\r\n\t\t [this.lat - latAccuracy, this.lng - lngAccuracy],\r\n\t\t [this.lat + latAccuracy, this.lng + lngAccuracy]);\r\n\t},\r\n\r\n\tclone: function () {\r\n\t\treturn new LatLng(this.lat, this.lng, this.alt);\r\n\t}\r\n};\r\n\r\n\r\n\r\n// @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng\r\n// Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).\r\n\r\n// @alternative\r\n// @factory L.latLng(coords: Array): LatLng\r\n// Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.\r\n\r\n// @alternative\r\n// @factory L.latLng(coords: Object): LatLng\r\n// Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.\r\n\r\nfunction toLatLng(a, b, c) {\r\n\tif (a instanceof LatLng) {\r\n\t\treturn a;\r\n\t}\r\n\tif (isArray(a) && typeof a[0] !== 'object') {\r\n\t\tif (a.length === 3) {\r\n\t\t\treturn new LatLng(a[0], a[1], a[2]);\r\n\t\t}\r\n\t\tif (a.length === 2) {\r\n\t\t\treturn new LatLng(a[0], a[1]);\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\tif (a === undefined || a === null) {\r\n\t\treturn a;\r\n\t}\r\n\tif (typeof a === 'object' && 'lat' in a) {\r\n\t\treturn new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);\r\n\t}\r\n\tif (b === undefined) {\r\n\t\treturn null;\r\n\t}\r\n\treturn new LatLng(a, b, c);\r\n}\n\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.Base\r\n * Object that defines coordinate reference systems for projecting\r\n * geographical points into pixel (screen) coordinates and back (and to\r\n * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See\r\n * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).\r\n *\r\n * Leaflet defines the most usual CRSs by default. If you want to use a\r\n * CRS not defined by default, take a look at the\r\n * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.\r\n *\r\n * Note that the CRS instances do not inherit from Leafet's `Class` object,\r\n * and can't be instantiated. Also, new classes can't inherit from them,\r\n * and methods can't be added to them with the `include` function.\r\n */\r\n\r\nvar CRS = {\r\n\t// @method latLngToPoint(latlng: LatLng, zoom: Number): Point\r\n\t// Projects geographical coordinates into pixel coordinates for a given zoom.\r\n\tlatLngToPoint: function (latlng, zoom) {\r\n\t\tvar projectedPoint = this.projection.project(latlng),\r\n\t\t scale = this.scale(zoom);\r\n\r\n\t\treturn this.transformation._transform(projectedPoint, scale);\r\n\t},\r\n\r\n\t// @method pointToLatLng(point: Point, zoom: Number): LatLng\r\n\t// The inverse of `latLngToPoint`. Projects pixel coordinates on a given\r\n\t// zoom into geographical coordinates.\r\n\tpointToLatLng: function (point, zoom) {\r\n\t\tvar scale = this.scale(zoom),\r\n\t\t untransformedPoint = this.transformation.untransform(point, scale);\r\n\r\n\t\treturn this.projection.unproject(untransformedPoint);\r\n\t},\r\n\r\n\t// @method project(latlng: LatLng): Point\r\n\t// Projects geographical coordinates into coordinates in units accepted for\r\n\t// this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).\r\n\tproject: function (latlng) {\r\n\t\treturn this.projection.project(latlng);\r\n\t},\r\n\r\n\t// @method unproject(point: Point): LatLng\r\n\t// Given a projected coordinate returns the corresponding LatLng.\r\n\t// The inverse of `project`.\r\n\tunproject: function (point) {\r\n\t\treturn this.projection.unproject(point);\r\n\t},\r\n\r\n\t// @method scale(zoom: Number): Number\r\n\t// Returns the scale used when transforming projected coordinates into\r\n\t// pixel coordinates for a particular zoom. For example, it returns\r\n\t// `256 * 2^zoom` for Mercator-based CRS.\r\n\tscale: function (zoom) {\r\n\t\treturn 256 * Math.pow(2, zoom);\r\n\t},\r\n\r\n\t// @method zoom(scale: Number): Number\r\n\t// Inverse of `scale()`, returns the zoom level corresponding to a scale\r\n\t// factor of `scale`.\r\n\tzoom: function (scale) {\r\n\t\treturn Math.log(scale / 256) / Math.LN2;\r\n\t},\r\n\r\n\t// @method getProjectedBounds(zoom: Number): Bounds\r\n\t// Returns the projection's bounds scaled and transformed for the provided `zoom`.\r\n\tgetProjectedBounds: function (zoom) {\r\n\t\tif (this.infinite) { return null; }\r\n\r\n\t\tvar b = this.projection.bounds,\r\n\t\t s = this.scale(zoom),\r\n\t\t min = this.transformation.transform(b.min, s),\r\n\t\t max = this.transformation.transform(b.max, s);\r\n\r\n\t\treturn new Bounds(min, max);\r\n\t},\r\n\r\n\t// @method distance(latlng1: LatLng, latlng2: LatLng): Number\r\n\t// Returns the distance between two geographical coordinates.\r\n\r\n\t// @property code: String\r\n\t// Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)\r\n\t//\r\n\t// @property wrapLng: Number[]\r\n\t// An array of two numbers defining whether the longitude (horizontal) coordinate\r\n\t// axis wraps around a given range and how. Defaults to `[-180, 180]` in most\r\n\t// geographical CRSs. If `undefined`, the longitude axis does not wrap around.\r\n\t//\r\n\t// @property wrapLat: Number[]\r\n\t// Like `wrapLng`, but for the latitude (vertical) axis.\r\n\r\n\t// wrapLng: [min, max],\r\n\t// wrapLat: [min, max],\r\n\r\n\t// @property infinite: Boolean\r\n\t// If true, the coordinate space will be unbounded (infinite in both axes)\r\n\tinfinite: false,\r\n\r\n\t// @method wrapLatLng(latlng: LatLng): LatLng\r\n\t// Returns a `LatLng` where lat and lng has been wrapped according to the\r\n\t// CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.\r\n\twrapLatLng: function (latlng) {\r\n\t\tvar lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,\r\n\t\t lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,\r\n\t\t alt = latlng.alt;\r\n\r\n\t\treturn new LatLng(lat, lng, alt);\r\n\t},\r\n\r\n\t// @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds\r\n\t// Returns a `LatLngBounds` with the same size as the given one, ensuring\r\n\t// that its center is within the CRS's bounds.\r\n\t// Only accepts actual `L.LatLngBounds` instances, not arrays.\r\n\twrapLatLngBounds: function (bounds) {\r\n\t\tvar center = bounds.getCenter(),\r\n\t\t newCenter = this.wrapLatLng(center),\r\n\t\t latShift = center.lat - newCenter.lat,\r\n\t\t lngShift = center.lng - newCenter.lng;\r\n\r\n\t\tif (latShift === 0 && lngShift === 0) {\r\n\t\t\treturn bounds;\r\n\t\t}\r\n\r\n\t\tvar sw = bounds.getSouthWest(),\r\n\t\t ne = bounds.getNorthEast(),\r\n\t\t newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),\r\n\t\t newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);\r\n\r\n\t\treturn new LatLngBounds(newSw, newNe);\r\n\t}\r\n};\n\n/*\n * @namespace CRS\n * @crs L.CRS.Earth\n *\n * Serves as the base for CRS that are global such that they cover the earth.\n * Can only be used as the base for other CRS and cannot be used directly,\n * since it does not have a `code`, `projection` or `transformation`. `distance()` returns\n * meters.\n */\n\nvar Earth = extend({}, CRS, {\n\twrapLng: [-180, 180],\n\n\t// Mean Earth Radius, as recommended for use by\n\t// the International Union of Geodesy and Geophysics,\n\t// see http://rosettacode.org/wiki/Haversine_formula\n\tR: 6371000,\n\n\t// distance between two geographical points using spherical law of cosines approximation\n\tdistance: function (latlng1, latlng2) {\n\t\tvar rad = Math.PI / 180,\n\t\t lat1 = latlng1.lat * rad,\n\t\t lat2 = latlng2.lat * rad,\n\t\t sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),\n\t\t sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),\n\t\t a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,\n\t\t c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\t\treturn this.R * c;\n\t}\n});\n\n/*\r\n * @namespace Projection\r\n * @projection L.Projection.SphericalMercator\r\n *\r\n * Spherical Mercator projection — the most common projection for online maps,\r\n * used by almost all free and commercial tile providers. Assumes that Earth is\r\n * a sphere. Used by the `EPSG:3857` CRS.\r\n */\r\n\r\nvar earthRadius = 6378137;\r\n\r\nvar SphericalMercator = {\r\n\r\n\tR: earthRadius,\r\n\tMAX_LATITUDE: 85.0511287798,\r\n\r\n\tproject: function (latlng) {\r\n\t\tvar d = Math.PI / 180,\r\n\t\t max = this.MAX_LATITUDE,\r\n\t\t lat = Math.max(Math.min(max, latlng.lat), -max),\r\n\t\t sin = Math.sin(lat * d);\r\n\r\n\t\treturn new Point(\r\n\t\t\tthis.R * latlng.lng * d,\r\n\t\t\tthis.R * Math.log((1 + sin) / (1 - sin)) / 2);\r\n\t},\r\n\r\n\tunproject: function (point) {\r\n\t\tvar d = 180 / Math.PI;\r\n\r\n\t\treturn new LatLng(\r\n\t\t\t(2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,\r\n\t\t\tpoint.x * d / this.R);\r\n\t},\r\n\r\n\tbounds: (function () {\r\n\t\tvar d = earthRadius * Math.PI;\r\n\t\treturn new Bounds([-d, -d], [d, d]);\r\n\t})()\r\n};\n\n/*\r\n * @class Transformation\r\n * @aka L.Transformation\r\n *\r\n * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`\r\n * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing\r\n * the reverse. Used by Leaflet in its projections code.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var transformation = L.transformation(2, 5, -1, 10),\r\n * \tp = L.point(1, 2),\r\n * \tp2 = transformation.transform(p), // L.point(7, 8)\r\n * \tp3 = transformation.untransform(p2); // L.point(1, 2)\r\n * ```\r\n */\r\n\r\n\r\n// factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)\r\n// Creates a `Transformation` object with the given coefficients.\r\nfunction Transformation(a, b, c, d) {\r\n\tif (isArray(a)) {\r\n\t\t// use array properties\r\n\t\tthis._a = a[0];\r\n\t\tthis._b = a[1];\r\n\t\tthis._c = a[2];\r\n\t\tthis._d = a[3];\r\n\t\treturn;\r\n\t}\r\n\tthis._a = a;\r\n\tthis._b = b;\r\n\tthis._c = c;\r\n\tthis._d = d;\r\n}\r\n\r\nTransformation.prototype = {\r\n\t// @method transform(point: Point, scale?: Number): Point\r\n\t// Returns a transformed point, optionally multiplied by the given scale.\r\n\t// Only accepts actual `L.Point` instances, not arrays.\r\n\ttransform: function (point, scale) { // (Point, Number) -> Point\r\n\t\treturn this._transform(point.clone(), scale);\r\n\t},\r\n\r\n\t// destructive transform (faster)\r\n\t_transform: function (point, scale) {\r\n\t\tscale = scale || 1;\r\n\t\tpoint.x = scale * (this._a * point.x + this._b);\r\n\t\tpoint.y = scale * (this._c * point.y + this._d);\r\n\t\treturn point;\r\n\t},\r\n\r\n\t// @method untransform(point: Point, scale?: Number): Point\r\n\t// Returns the reverse transformation of the given point, optionally divided\r\n\t// by the given scale. Only accepts actual `L.Point` instances, not arrays.\r\n\tuntransform: function (point, scale) {\r\n\t\tscale = scale || 1;\r\n\t\treturn new Point(\r\n\t\t (point.x / scale - this._b) / this._a,\r\n\t\t (point.y / scale - this._d) / this._c);\r\n\t}\r\n};\r\n\r\n// factory L.transformation(a: Number, b: Number, c: Number, d: Number)\r\n\r\n// @factory L.transformation(a: Number, b: Number, c: Number, d: Number)\r\n// Instantiates a Transformation object with the given coefficients.\r\n\r\n// @alternative\r\n// @factory L.transformation(coefficients: Array): Transformation\r\n// Expects an coefficients array of the form\r\n// `[a: Number, b: Number, c: Number, d: Number]`.\r\n\r\nfunction toTransformation(a, b, c, d) {\r\n\treturn new Transformation(a, b, c, d);\r\n}\n\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.EPSG3857\r\n *\r\n * The most common CRS for online maps, used by almost all free and commercial\r\n * tile providers. Uses Spherical Mercator projection. Set in by default in\r\n * Map's `crs` option.\r\n */\r\n\r\nvar EPSG3857 = extend({}, Earth, {\r\n\tcode: 'EPSG:3857',\r\n\tprojection: SphericalMercator,\r\n\r\n\ttransformation: (function () {\r\n\t\tvar scale = 0.5 / (Math.PI * SphericalMercator.R);\r\n\t\treturn toTransformation(scale, 0.5, -scale, 0.5);\r\n\t}())\r\n});\r\n\r\nvar EPSG900913 = extend({}, EPSG3857, {\r\n\tcode: 'EPSG:900913'\r\n});\n\n// @namespace SVG; @section\n// There are several static functions which can be called without instantiating L.SVG:\n\n// @function create(name: String): SVGElement\n// Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),\n// corresponding to the class name passed. For example, using 'line' will return\n// an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).\nfunction svgCreate(name) {\n\treturn document.createElementNS('http://www.w3.org/2000/svg', name);\n}\n\n// @function pointsToPath(rings: Point[], closed: Boolean): String\n// Generates a SVG path string for multiple rings, with each ring turning\n// into \"M..L..L..\" instructions\nfunction pointsToPath(rings, closed) {\n\tvar str = '',\n\ti, j, len, len2, points, p;\n\n\tfor (i = 0, len = rings.length; i < len; i++) {\n\t\tpoints = rings[i];\n\n\t\tfor (j = 0, len2 = points.length; j < len2; j++) {\n\t\t\tp = points[j];\n\t\t\tstr += (j ? 'L' : 'M') + p.x + ' ' + p.y;\n\t\t}\n\n\t\t// closes the ring for polygons; \"x\" is VML syntax\n\t\tstr += closed ? (svg ? 'z' : 'x') : '';\n\t}\n\n\t// SVG complains about empty path strings\n\treturn str || 'M0 0';\n}\n\n/*\r\n * @namespace Browser\r\n * @aka L.Browser\r\n *\r\n * A namespace with static properties for browser/feature detection used by Leaflet internally.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * if (L.Browser.ielt9) {\r\n * alert('Upgrade your browser, dude!');\r\n * }\r\n * ```\r\n */\r\n\r\nvar style$1 = document.documentElement.style;\r\n\r\n// @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).\r\nvar ie = 'ActiveXObject' in window;\r\n\r\n// @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.\r\nvar ielt9 = ie && !document.addEventListener;\r\n\r\n// @property edge: Boolean; `true` for the Edge web browser.\r\nvar edge = 'msLaunchUri' in navigator && !('documentMode' in document);\r\n\r\n// @property webkit: Boolean;\r\n// `true` for webkit-based browsers like Chrome and Safari (including mobile versions).\r\nvar webkit = userAgentContains('webkit');\r\n\r\n// @property android: Boolean\r\n// `true` for any browser running on an Android platform.\r\nvar android = userAgentContains('android');\r\n\r\n// @property android23: Boolean; `true` for browsers running on Android 2 or Android 3.\r\nvar android23 = userAgentContains('android 2') || userAgentContains('android 3');\r\n\r\n/* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */\r\nvar webkitVer = parseInt(/WebKit\\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit\r\n// @property androidStock: Boolean; `true` for the Android stock browser (i.e. not Chrome)\r\nvar androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);\r\n\r\n// @property opera: Boolean; `true` for the Opera browser\r\nvar opera = !!window.opera;\r\n\r\n// @property chrome: Boolean; `true` for the Chrome browser.\r\nvar chrome = userAgentContains('chrome');\r\n\r\n// @property gecko: Boolean; `true` for gecko-based browsers like Firefox.\r\nvar gecko = userAgentContains('gecko') && !webkit && !opera && !ie;\r\n\r\n// @property safari: Boolean; `true` for the Safari browser.\r\nvar safari = !chrome && userAgentContains('safari');\r\n\r\nvar phantom = userAgentContains('phantom');\r\n\r\n// @property opera12: Boolean\r\n// `true` for the Opera browser supporting CSS transforms (version 12 or later).\r\nvar opera12 = 'OTransition' in style$1;\r\n\r\n// @property win: Boolean; `true` when the browser is running in a Windows platform\r\nvar win = navigator.platform.indexOf('Win') === 0;\r\n\r\n// @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.\r\nvar ie3d = ie && ('transition' in style$1);\r\n\r\n// @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.\r\nvar webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;\r\n\r\n// @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.\r\nvar gecko3d = 'MozPerspective' in style$1;\r\n\r\n// @property any3d: Boolean\r\n// `true` for all browsers supporting CSS transforms.\r\nvar any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;\r\n\r\n// @property mobile: Boolean; `true` for all browsers running in a mobile device.\r\nvar mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');\r\n\r\n// @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.\r\nvar mobileWebkit = mobile && webkit;\r\n\r\n// @property mobileWebkit3d: Boolean\r\n// `true` for all webkit-based browsers in a mobile device supporting CSS transforms.\r\nvar mobileWebkit3d = mobile && webkit3d;\r\n\r\n// @property msPointer: Boolean\r\n// `true` for browsers implementing the Microsoft touch events model (notably IE10).\r\nvar msPointer = !window.PointerEvent && window.MSPointerEvent;\r\n\r\n// @property pointer: Boolean\r\n// `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).\r\nvar pointer = !!(window.PointerEvent || msPointer);\r\n\r\n// @property touch: Boolean\r\n// `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).\r\n// This does not necessarily mean that the browser is running in a computer with\r\n// a touchscreen, it only means that the browser is capable of understanding\r\n// touch events.\r\nvar touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||\r\n\t\t(window.DocumentTouch && document instanceof window.DocumentTouch));\r\n\r\n// @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.\r\nvar mobileOpera = mobile && opera;\r\n\r\n// @property mobileGecko: Boolean\r\n// `true` for gecko-based browsers running in a mobile device.\r\nvar mobileGecko = mobile && gecko;\r\n\r\n// @property retina: Boolean\r\n// `true` for browsers on a high-resolution \"retina\" screen or on any screen when browser's display zoom is more than 100%.\r\nvar retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;\r\n\r\n\r\n// @property canvas: Boolean\r\n// `true` when the browser supports [``](https://developer.mozilla.org/docs/Web/API/Canvas_API).\r\nvar canvas = (function () {\r\n\treturn !!document.createElement('canvas').getContext;\r\n}());\r\n\r\n// @property svg: Boolean\r\n// `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).\r\nvar svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);\r\n\r\n// @property vml: Boolean\r\n// `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).\r\nvar vml = !svg && (function () {\r\n\ttry {\r\n\t\tvar div = document.createElement('div');\r\n\t\tdiv.innerHTML = '';\r\n\r\n\t\tvar shape = div.firstChild;\r\n\t\tshape.style.behavior = 'url(#default#VML)';\r\n\r\n\t\treturn shape && (typeof shape.adj === 'object');\r\n\r\n\t} catch (e) {\r\n\t\treturn false;\r\n\t}\r\n}());\r\n\r\n\r\nfunction userAgentContains(str) {\r\n\treturn navigator.userAgent.toLowerCase().indexOf(str) >= 0;\r\n}\r\n\n\nvar Browser = (Object.freeze || Object)({\n\tie: ie,\n\tielt9: ielt9,\n\tedge: edge,\n\twebkit: webkit,\n\tandroid: android,\n\tandroid23: android23,\n\tandroidStock: androidStock,\n\topera: opera,\n\tchrome: chrome,\n\tgecko: gecko,\n\tsafari: safari,\n\tphantom: phantom,\n\topera12: opera12,\n\twin: win,\n\tie3d: ie3d,\n\twebkit3d: webkit3d,\n\tgecko3d: gecko3d,\n\tany3d: any3d,\n\tmobile: mobile,\n\tmobileWebkit: mobileWebkit,\n\tmobileWebkit3d: mobileWebkit3d,\n\tmsPointer: msPointer,\n\tpointer: pointer,\n\ttouch: touch,\n\tmobileOpera: mobileOpera,\n\tmobileGecko: mobileGecko,\n\tretina: retina,\n\tcanvas: canvas,\n\tsvg: svg,\n\tvml: vml\n});\n\n/*\n * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.\n */\n\n\nvar POINTER_DOWN = msPointer ? 'MSPointerDown' : 'pointerdown';\nvar POINTER_MOVE = msPointer ? 'MSPointerMove' : 'pointermove';\nvar POINTER_UP = msPointer ? 'MSPointerUp' : 'pointerup';\nvar POINTER_CANCEL = msPointer ? 'MSPointerCancel' : 'pointercancel';\nvar TAG_WHITE_LIST = ['INPUT', 'SELECT', 'OPTION'];\n\nvar _pointers = {};\nvar _pointerDocListener = false;\n\n// DomEvent.DoubleTap needs to know about this\nvar _pointersCount = 0;\n\n// Provides a touch events wrapper for (ms)pointer events.\n// ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890\n\nfunction addPointerListener(obj, type, handler, id) {\n\tif (type === 'touchstart') {\n\t\t_addPointerStart(obj, handler, id);\n\n\t} else if (type === 'touchmove') {\n\t\t_addPointerMove(obj, handler, id);\n\n\t} else if (type === 'touchend') {\n\t\t_addPointerEnd(obj, handler, id);\n\t}\n\n\treturn this;\n}\n\nfunction removePointerListener(obj, type, id) {\n\tvar handler = obj['_leaflet_' + type + id];\n\n\tif (type === 'touchstart') {\n\t\tobj.removeEventListener(POINTER_DOWN, handler, false);\n\n\t} else if (type === 'touchmove') {\n\t\tobj.removeEventListener(POINTER_MOVE, handler, false);\n\n\t} else if (type === 'touchend') {\n\t\tobj.removeEventListener(POINTER_UP, handler, false);\n\t\tobj.removeEventListener(POINTER_CANCEL, handler, false);\n\t}\n\n\treturn this;\n}\n\nfunction _addPointerStart(obj, handler, id) {\n\tvar onDown = bind(function (e) {\n\t\tif (e.pointerType !== 'mouse' && e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {\n\t\t\t// In IE11, some touch events needs to fire for form controls, or\n\t\t\t// the controls will stop working. We keep a whitelist of tag names that\n\t\t\t// need these events. For other target tags, we prevent default on the event.\n\t\t\tif (TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {\n\t\t\t\tpreventDefault(e);\n\t\t\t} else {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t_handlePointer(e, handler);\n\t});\n\n\tobj['_leaflet_touchstart' + id] = onDown;\n\tobj.addEventListener(POINTER_DOWN, onDown, false);\n\n\t// need to keep track of what pointers and how many are active to provide e.touches emulation\n\tif (!_pointerDocListener) {\n\t\t// we listen documentElement as any drags that end by moving the touch off the screen get fired there\n\t\tdocument.documentElement.addEventListener(POINTER_DOWN, _globalPointerDown, true);\n\t\tdocument.documentElement.addEventListener(POINTER_MOVE, _globalPointerMove, true);\n\t\tdocument.documentElement.addEventListener(POINTER_UP, _globalPointerUp, true);\n\t\tdocument.documentElement.addEventListener(POINTER_CANCEL, _globalPointerUp, true);\n\n\t\t_pointerDocListener = true;\n\t}\n}\n\nfunction _globalPointerDown(e) {\n\t_pointers[e.pointerId] = e;\n\t_pointersCount++;\n}\n\nfunction _globalPointerMove(e) {\n\tif (_pointers[e.pointerId]) {\n\t\t_pointers[e.pointerId] = e;\n\t}\n}\n\nfunction _globalPointerUp(e) {\n\tdelete _pointers[e.pointerId];\n\t_pointersCount--;\n}\n\nfunction _handlePointer(e, handler) {\n\te.touches = [];\n\tfor (var i in _pointers) {\n\t\te.touches.push(_pointers[i]);\n\t}\n\te.changedTouches = [e];\n\n\thandler(e);\n}\n\nfunction _addPointerMove(obj, handler, id) {\n\tvar onMove = function (e) {\n\t\t// don't fire touch moves when mouse isn't down\n\t\tif ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }\n\n\t\t_handlePointer(e, handler);\n\t};\n\n\tobj['_leaflet_touchmove' + id] = onMove;\n\tobj.addEventListener(POINTER_MOVE, onMove, false);\n}\n\nfunction _addPointerEnd(obj, handler, id) {\n\tvar onUp = function (e) {\n\t\t_handlePointer(e, handler);\n\t};\n\n\tobj['_leaflet_touchend' + id] = onUp;\n\tobj.addEventListener(POINTER_UP, onUp, false);\n\tobj.addEventListener(POINTER_CANCEL, onUp, false);\n}\n\n/*\r\n * Extends the event handling code with double tap support for mobile browsers.\r\n */\r\n\r\nvar _touchstart = msPointer ? 'MSPointerDown' : pointer ? 'pointerdown' : 'touchstart';\r\nvar _touchend = msPointer ? 'MSPointerUp' : pointer ? 'pointerup' : 'touchend';\r\nvar _pre = '_leaflet_';\r\n\r\n// inspired by Zepto touch code by Thomas Fuchs\r\nfunction addDoubleTapListener(obj, handler, id) {\r\n\tvar last, touch$$1,\r\n\t doubleTap = false,\r\n\t delay = 250;\r\n\r\n\tfunction onTouchStart(e) {\r\n\t\tvar count;\r\n\r\n\t\tif (pointer) {\r\n\t\t\tif ((!edge) || e.pointerType === 'mouse') { return; }\r\n\t\t\tcount = _pointersCount;\r\n\t\t} else {\r\n\t\t\tcount = e.touches.length;\r\n\t\t}\r\n\r\n\t\tif (count > 1) { return; }\r\n\r\n\t\tvar now = Date.now(),\r\n\t\t delta = now - (last || now);\r\n\r\n\t\ttouch$$1 = e.touches ? e.touches[0] : e;\r\n\t\tdoubleTap = (delta > 0 && delta <= delay);\r\n\t\tlast = now;\r\n\t}\r\n\r\n\tfunction onTouchEnd(e) {\r\n\t\tif (doubleTap && !touch$$1.cancelBubble) {\r\n\t\t\tif (pointer) {\r\n\t\t\t\tif ((!edge) || e.pointerType === 'mouse') { return; }\r\n\t\t\t\t// work around .type being readonly with MSPointer* events\r\n\t\t\t\tvar newTouch = {},\r\n\t\t\t\t prop, i;\r\n\r\n\t\t\t\tfor (i in touch$$1) {\r\n\t\t\t\t\tprop = touch$$1[i];\r\n\t\t\t\t\tnewTouch[i] = prop && prop.bind ? prop.bind(touch$$1) : prop;\r\n\t\t\t\t}\r\n\t\t\t\ttouch$$1 = newTouch;\r\n\t\t\t}\r\n\t\t\ttouch$$1.type = 'dblclick';\r\n\t\t\ttouch$$1.button = 0;\r\n\t\t\thandler(touch$$1);\r\n\t\t\tlast = null;\r\n\t\t}\r\n\t}\r\n\r\n\tobj[_pre + _touchstart + id] = onTouchStart;\r\n\tobj[_pre + _touchend + id] = onTouchEnd;\r\n\tobj[_pre + 'dblclick' + id] = handler;\r\n\r\n\tobj.addEventListener(_touchstart, onTouchStart, false);\r\n\tobj.addEventListener(_touchend, onTouchEnd, false);\r\n\r\n\t// On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),\r\n\t// the browser doesn't fire touchend/pointerup events but does fire\r\n\t// native dblclicks. See #4127.\r\n\t// Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.\r\n\tobj.addEventListener('dblclick', handler, false);\r\n\r\n\treturn this;\r\n}\r\n\r\nfunction removeDoubleTapListener(obj, id) {\r\n\tvar touchstart = obj[_pre + _touchstart + id],\r\n\t touchend = obj[_pre + _touchend + id],\r\n\t dblclick = obj[_pre + 'dblclick' + id];\r\n\r\n\tobj.removeEventListener(_touchstart, touchstart, false);\r\n\tobj.removeEventListener(_touchend, touchend, false);\r\n\tif (!edge) {\r\n\t\tobj.removeEventListener('dblclick', dblclick, false);\r\n\t}\r\n\r\n\treturn this;\r\n}\n\n/*\r\n * @namespace DomUtil\r\n *\r\n * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)\r\n * tree, used by Leaflet internally.\r\n *\r\n * Most functions expecting or returning a `HTMLElement` also work for\r\n * SVG elements. The only difference is that classes refer to CSS classes\r\n * in HTML and SVG classes in SVG.\r\n */\r\n\r\n\r\n// @property TRANSFORM: String\r\n// Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).\r\nvar TRANSFORM = testProp(\r\n\t['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);\r\n\r\n// webkitTransition comes first because some browser versions that drop vendor prefix don't do\r\n// the same for the transitionend event, in particular the Android 4.1 stock browser\r\n\r\n// @property TRANSITION: String\r\n// Vendor-prefixed transition style name.\r\nvar TRANSITION = testProp(\r\n\t['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);\r\n\r\n// @property TRANSITION_END: String\r\n// Vendor-prefixed transitionend event name.\r\nvar TRANSITION_END =\r\n\tTRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';\r\n\r\n\r\n// @function get(id: String|HTMLElement): HTMLElement\r\n// Returns an element given its DOM id, or returns the element itself\r\n// if it was passed directly.\r\nfunction get(id) {\r\n\treturn typeof id === 'string' ? document.getElementById(id) : id;\r\n}\r\n\r\n// @function getStyle(el: HTMLElement, styleAttrib: String): String\r\n// Returns the value for a certain style attribute on an element,\r\n// including computed values or values set through CSS.\r\nfunction getStyle(el, style) {\r\n\tvar value = el.style[style] || (el.currentStyle && el.currentStyle[style]);\r\n\r\n\tif ((!value || value === 'auto') && document.defaultView) {\r\n\t\tvar css = document.defaultView.getComputedStyle(el, null);\r\n\t\tvalue = css ? css[style] : null;\r\n\t}\r\n\treturn value === 'auto' ? null : value;\r\n}\r\n\r\n// @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement\r\n// Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.\r\nfunction create$1(tagName, className, container) {\r\n\tvar el = document.createElement(tagName);\r\n\tel.className = className || '';\r\n\r\n\tif (container) {\r\n\t\tcontainer.appendChild(el);\r\n\t}\r\n\treturn el;\r\n}\r\n\r\n// @function remove(el: HTMLElement)\r\n// Removes `el` from its parent element\r\nfunction remove(el) {\r\n\tvar parent = el.parentNode;\r\n\tif (parent) {\r\n\t\tparent.removeChild(el);\r\n\t}\r\n}\r\n\r\n// @function empty(el: HTMLElement)\r\n// Removes all of `el`'s children elements from `el`\r\nfunction empty(el) {\r\n\twhile (el.firstChild) {\r\n\t\tel.removeChild(el.firstChild);\r\n\t}\r\n}\r\n\r\n// @function toFront(el: HTMLElement)\r\n// Makes `el` the last child of its parent, so it renders in front of the other children.\r\nfunction toFront(el) {\r\n\tvar parent = el.parentNode;\r\n\tif (parent && parent.lastChild !== el) {\r\n\t\tparent.appendChild(el);\r\n\t}\r\n}\r\n\r\n// @function toBack(el: HTMLElement)\r\n// Makes `el` the first child of its parent, so it renders behind the other children.\r\nfunction toBack(el) {\r\n\tvar parent = el.parentNode;\r\n\tif (parent && parent.firstChild !== el) {\r\n\t\tparent.insertBefore(el, parent.firstChild);\r\n\t}\r\n}\r\n\r\n// @function hasClass(el: HTMLElement, name: String): Boolean\r\n// Returns `true` if the element's class attribute contains `name`.\r\nfunction hasClass(el, name) {\r\n\tif (el.classList !== undefined) {\r\n\t\treturn el.classList.contains(name);\r\n\t}\r\n\tvar className = getClass(el);\r\n\treturn className.length > 0 && new RegExp('(^|\\\\s)' + name + '(\\\\s|$)').test(className);\r\n}\r\n\r\n// @function addClass(el: HTMLElement, name: String)\r\n// Adds `name` to the element's class attribute.\r\nfunction addClass(el, name) {\r\n\tif (el.classList !== undefined) {\r\n\t\tvar classes = splitWords(name);\r\n\t\tfor (var i = 0, len = classes.length; i < len; i++) {\r\n\t\t\tel.classList.add(classes[i]);\r\n\t\t}\r\n\t} else if (!hasClass(el, name)) {\r\n\t\tvar className = getClass(el);\r\n\t\tsetClass(el, (className ? className + ' ' : '') + name);\r\n\t}\r\n}\r\n\r\n// @function removeClass(el: HTMLElement, name: String)\r\n// Removes `name` from the element's class attribute.\r\nfunction removeClass(el, name) {\r\n\tif (el.classList !== undefined) {\r\n\t\tel.classList.remove(name);\r\n\t} else {\r\n\t\tsetClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));\r\n\t}\r\n}\r\n\r\n// @function setClass(el: HTMLElement, name: String)\r\n// Sets the element's class.\r\nfunction setClass(el, name) {\r\n\tif (el.className.baseVal === undefined) {\r\n\t\tel.className = name;\r\n\t} else {\r\n\t\t// in case of SVG element\r\n\t\tel.className.baseVal = name;\r\n\t}\r\n}\r\n\r\n// @function getClass(el: HTMLElement): String\r\n// Returns the element's class.\r\nfunction getClass(el) {\r\n\t// Check if the element is an SVGElementInstance and use the correspondingElement instead\r\n\t// (Required for linked SVG elements in IE11.)\r\n\tif (el.correspondingElement) {\r\n\t\tel = el.correspondingElement;\r\n\t}\r\n\treturn el.className.baseVal === undefined ? el.className : el.className.baseVal;\r\n}\r\n\r\n// @function setOpacity(el: HTMLElement, opacity: Number)\r\n// Set the opacity of an element (including old IE support).\r\n// `opacity` must be a number from `0` to `1`.\r\nfunction setOpacity(el, value) {\r\n\tif ('opacity' in el.style) {\r\n\t\tel.style.opacity = value;\r\n\t} else if ('filter' in el.style) {\r\n\t\t_setOpacityIE(el, value);\r\n\t}\r\n}\r\n\r\nfunction _setOpacityIE(el, value) {\r\n\tvar filter = false,\r\n\t filterName = 'DXImageTransform.Microsoft.Alpha';\r\n\r\n\t// filters collection throws an error if we try to retrieve a filter that doesn't exist\r\n\ttry {\r\n\t\tfilter = el.filters.item(filterName);\r\n\t} catch (e) {\r\n\t\t// don't set opacity to 1 if we haven't already set an opacity,\r\n\t\t// it isn't needed and breaks transparent pngs.\r\n\t\tif (value === 1) { return; }\r\n\t}\r\n\r\n\tvalue = Math.round(value * 100);\r\n\r\n\tif (filter) {\r\n\t\tfilter.Enabled = (value !== 100);\r\n\t\tfilter.Opacity = value;\r\n\t} else {\r\n\t\tel.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';\r\n\t}\r\n}\r\n\r\n// @function testProp(props: String[]): String|false\r\n// Goes through the array of style names and returns the first name\r\n// that is a valid style name for an element. If no such name is found,\r\n// it returns false. Useful for vendor-prefixed styles like `transform`.\r\nfunction testProp(props) {\r\n\tvar style = document.documentElement.style;\r\n\r\n\tfor (var i = 0; i < props.length; i++) {\r\n\t\tif (props[i] in style) {\r\n\t\t\treturn props[i];\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n// @function setTransform(el: HTMLElement, offset: Point, scale?: Number)\r\n// Resets the 3D CSS transform of `el` so it is translated by `offset` pixels\r\n// and optionally scaled by `scale`. Does not have an effect if the\r\n// browser doesn't support 3D CSS transforms.\r\nfunction setTransform(el, offset, scale) {\r\n\tvar pos = offset || new Point(0, 0);\r\n\r\n\tel.style[TRANSFORM] =\r\n\t\t(ie3d ?\r\n\t\t\t'translate(' + pos.x + 'px,' + pos.y + 'px)' :\r\n\t\t\t'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +\r\n\t\t(scale ? ' scale(' + scale + ')' : '');\r\n}\r\n\r\n// @function setPosition(el: HTMLElement, position: Point)\r\n// Sets the position of `el` to coordinates specified by `position`,\r\n// using CSS translate or top/left positioning depending on the browser\r\n// (used by Leaflet internally to position its layers).\r\nfunction setPosition(el, point) {\r\n\r\n\t/*eslint-disable */\r\n\tel._leaflet_pos = point;\r\n\t/* eslint-enable */\r\n\r\n\tif (any3d) {\r\n\t\tsetTransform(el, point);\r\n\t} else {\r\n\t\tel.style.left = point.x + 'px';\r\n\t\tel.style.top = point.y + 'px';\r\n\t}\r\n}\r\n\r\n// @function getPosition(el: HTMLElement): Point\r\n// Returns the coordinates of an element previously positioned with setPosition.\r\nfunction getPosition(el) {\r\n\t// this method is only used for elements previously positioned using setPosition,\r\n\t// so it's safe to cache the position for performance\r\n\r\n\treturn el._leaflet_pos || new Point(0, 0);\r\n}\r\n\r\n// @function disableTextSelection()\r\n// Prevents the user from generating `selectstart` DOM events, usually generated\r\n// when the user drags the mouse through a page with text. Used internally\r\n// by Leaflet to override the behaviour of any click-and-drag interaction on\r\n// the map. Affects drag interactions on the whole document.\r\n\r\n// @function enableTextSelection()\r\n// Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).\r\nvar disableTextSelection;\r\nvar enableTextSelection;\r\nvar _userSelect;\r\nif ('onselectstart' in document) {\r\n\tdisableTextSelection = function () {\r\n\t\ton(window, 'selectstart', preventDefault);\r\n\t};\r\n\tenableTextSelection = function () {\r\n\t\toff(window, 'selectstart', preventDefault);\r\n\t};\r\n} else {\r\n\tvar userSelectProperty = testProp(\r\n\t\t['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);\r\n\r\n\tdisableTextSelection = function () {\r\n\t\tif (userSelectProperty) {\r\n\t\t\tvar style = document.documentElement.style;\r\n\t\t\t_userSelect = style[userSelectProperty];\r\n\t\t\tstyle[userSelectProperty] = 'none';\r\n\t\t}\r\n\t};\r\n\tenableTextSelection = function () {\r\n\t\tif (userSelectProperty) {\r\n\t\t\tdocument.documentElement.style[userSelectProperty] = _userSelect;\r\n\t\t\t_userSelect = undefined;\r\n\t\t}\r\n\t};\r\n}\r\n\r\n// @function disableImageDrag()\r\n// As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but\r\n// for `dragstart` DOM events, usually generated when the user drags an image.\r\nfunction disableImageDrag() {\r\n\ton(window, 'dragstart', preventDefault);\r\n}\r\n\r\n// @function enableImageDrag()\r\n// Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).\r\nfunction enableImageDrag() {\r\n\toff(window, 'dragstart', preventDefault);\r\n}\r\n\r\nvar _outlineElement;\nvar _outlineStyle;\r\n// @function preventOutline(el: HTMLElement)\r\n// Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)\r\n// of the element `el` invisible. Used internally by Leaflet to prevent\r\n// focusable elements from displaying an outline when the user performs a\r\n// drag interaction on them.\r\nfunction preventOutline(element) {\r\n\twhile (element.tabIndex === -1) {\r\n\t\telement = element.parentNode;\r\n\t}\r\n\tif (!element.style) { return; }\r\n\trestoreOutline();\r\n\t_outlineElement = element;\r\n\t_outlineStyle = element.style.outline;\r\n\telement.style.outline = 'none';\r\n\ton(window, 'keydown', restoreOutline);\r\n}\r\n\r\n// @function restoreOutline()\r\n// Cancels the effects of a previous [`L.DomUtil.preventOutline`]().\r\nfunction restoreOutline() {\r\n\tif (!_outlineElement) { return; }\r\n\t_outlineElement.style.outline = _outlineStyle;\r\n\t_outlineElement = undefined;\r\n\t_outlineStyle = undefined;\r\n\toff(window, 'keydown', restoreOutline);\r\n}\r\n\r\n// @function getSizedParentNode(el: HTMLElement): HTMLElement\r\n// Finds the closest parent node which size (width and height) is not null.\r\nfunction getSizedParentNode(element) {\r\n\tdo {\r\n\t\telement = element.parentNode;\r\n\t} while ((!element.offsetWidth || !element.offsetHeight) && element !== document.body);\r\n\treturn element;\r\n}\r\n\r\n// @function getScale(el: HTMLElement): Object\r\n// Computes the CSS scale currently applied on the element.\r\n// Returns an object with `x` and `y` members as horizontal and vertical scales respectively,\r\n// and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).\r\nfunction getScale(element) {\r\n\tvar rect = element.getBoundingClientRect(); // Read-only in old browsers.\r\n\r\n\treturn {\r\n\t\tx: rect.width / element.offsetWidth || 1,\r\n\t\ty: rect.height / element.offsetHeight || 1,\r\n\t\tboundingClientRect: rect\r\n\t};\r\n}\r\n\n\nvar DomUtil = (Object.freeze || Object)({\n\tTRANSFORM: TRANSFORM,\n\tTRANSITION: TRANSITION,\n\tTRANSITION_END: TRANSITION_END,\n\tget: get,\n\tgetStyle: getStyle,\n\tcreate: create$1,\n\tremove: remove,\n\tempty: empty,\n\ttoFront: toFront,\n\ttoBack: toBack,\n\thasClass: hasClass,\n\taddClass: addClass,\n\tremoveClass: removeClass,\n\tsetClass: setClass,\n\tgetClass: getClass,\n\tsetOpacity: setOpacity,\n\ttestProp: testProp,\n\tsetTransform: setTransform,\n\tsetPosition: setPosition,\n\tgetPosition: getPosition,\n\tdisableTextSelection: disableTextSelection,\n\tenableTextSelection: enableTextSelection,\n\tdisableImageDrag: disableImageDrag,\n\tenableImageDrag: enableImageDrag,\n\tpreventOutline: preventOutline,\n\trestoreOutline: restoreOutline,\n\tgetSizedParentNode: getSizedParentNode,\n\tgetScale: getScale\n});\n\n/*\r\n * @namespace DomEvent\r\n * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.\r\n */\r\n\r\n// Inspired by John Resig, Dean Edwards and YUI addEvent implementations.\r\n\r\n// @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this\r\n// Adds a listener function (`fn`) to a particular DOM event type of the\r\n// element `el`. You can optionally specify the context of the listener\r\n// (object the `this` keyword will point to). You can also pass several\r\n// space-separated types (e.g. `'click dblclick'`).\r\n\r\n// @alternative\r\n// @function on(el: HTMLElement, eventMap: Object, context?: Object): this\r\n// Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`\r\nfunction on(obj, types, fn, context) {\r\n\r\n\tif (typeof types === 'object') {\r\n\t\tfor (var type in types) {\r\n\t\t\taddOne(obj, type, types[type], fn);\r\n\t\t}\r\n\t} else {\r\n\t\ttypes = splitWords(types);\r\n\r\n\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\taddOne(obj, types[i], fn, context);\r\n\t\t}\r\n\t}\r\n\r\n\treturn this;\r\n}\r\n\r\nvar eventsKey = '_leaflet_events';\r\n\r\n// @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this\r\n// Removes a previously added listener function.\r\n// Note that if you passed a custom context to on, you must pass the same\r\n// context to `off` in order to remove the listener.\r\n\r\n// @alternative\r\n// @function off(el: HTMLElement, eventMap: Object, context?: Object): this\r\n// Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`\r\nfunction off(obj, types, fn, context) {\r\n\r\n\tif (typeof types === 'object') {\r\n\t\tfor (var type in types) {\r\n\t\t\tremoveOne(obj, type, types[type], fn);\r\n\t\t}\r\n\t} else if (types) {\r\n\t\ttypes = splitWords(types);\r\n\r\n\t\tfor (var i = 0, len = types.length; i < len; i++) {\r\n\t\t\tremoveOne(obj, types[i], fn, context);\r\n\t\t}\r\n\t} else {\r\n\t\tfor (var j in obj[eventsKey]) {\r\n\t\t\tremoveOne(obj, j, obj[eventsKey][j]);\r\n\t\t}\r\n\t\tdelete obj[eventsKey];\r\n\t}\r\n\r\n\treturn this;\r\n}\r\n\r\nfunction addOne(obj, type, fn, context) {\r\n\tvar id = type + stamp(fn) + (context ? '_' + stamp(context) : '');\r\n\r\n\tif (obj[eventsKey] && obj[eventsKey][id]) { return this; }\r\n\r\n\tvar handler = function (e) {\r\n\t\treturn fn.call(context || obj, e || window.event);\r\n\t};\r\n\r\n\tvar originalHandler = handler;\r\n\r\n\tif (pointer && type.indexOf('touch') === 0) {\r\n\t\t// Needs DomEvent.Pointer.js\r\n\t\taddPointerListener(obj, type, handler, id);\r\n\r\n\t} else if (touch && (type === 'dblclick') && addDoubleTapListener &&\r\n\t !(pointer && chrome)) {\r\n\t\t// Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener\r\n\t\t// See #5180\r\n\t\taddDoubleTapListener(obj, handler, id);\r\n\r\n\t} else if ('addEventListener' in obj) {\r\n\r\n\t\tif (type === 'mousewheel') {\r\n\t\t\tobj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);\r\n\r\n\t\t} else if ((type === 'mouseenter') || (type === 'mouseleave')) {\r\n\t\t\thandler = function (e) {\r\n\t\t\t\te = e || window.event;\r\n\t\t\t\tif (isExternalTarget(obj, e)) {\r\n\t\t\t\t\toriginalHandler(e);\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\tobj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);\r\n\r\n\t\t} else {\r\n\t\t\tif (type === 'click' && android) {\r\n\t\t\t\thandler = function (e) {\r\n\t\t\t\t\tfilterClick(e, originalHandler);\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t\tobj.addEventListener(type, handler, false);\r\n\t\t}\r\n\r\n\t} else if ('attachEvent' in obj) {\r\n\t\tobj.attachEvent('on' + type, handler);\r\n\t}\r\n\r\n\tobj[eventsKey] = obj[eventsKey] || {};\r\n\tobj[eventsKey][id] = handler;\r\n}\r\n\r\nfunction removeOne(obj, type, fn, context) {\r\n\r\n\tvar id = type + stamp(fn) + (context ? '_' + stamp(context) : ''),\r\n\t handler = obj[eventsKey] && obj[eventsKey][id];\r\n\r\n\tif (!handler) { return this; }\r\n\r\n\tif (pointer && type.indexOf('touch') === 0) {\r\n\t\tremovePointerListener(obj, type, id);\r\n\r\n\t} else if (touch && (type === 'dblclick') && removeDoubleTapListener &&\r\n\t !(pointer && chrome)) {\r\n\t\tremoveDoubleTapListener(obj, id);\r\n\r\n\t} else if ('removeEventListener' in obj) {\r\n\r\n\t\tif (type === 'mousewheel') {\r\n\t\t\tobj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);\r\n\r\n\t\t} else {\r\n\t\t\tobj.removeEventListener(\r\n\t\t\t\ttype === 'mouseenter' ? 'mouseover' :\r\n\t\t\t\ttype === 'mouseleave' ? 'mouseout' : type, handler, false);\r\n\t\t}\r\n\r\n\t} else if ('detachEvent' in obj) {\r\n\t\tobj.detachEvent('on' + type, handler);\r\n\t}\r\n\r\n\tobj[eventsKey][id] = null;\r\n}\r\n\r\n// @function stopPropagation(ev: DOMEvent): this\r\n// Stop the given event from propagation to parent elements. Used inside the listener functions:\r\n// ```js\r\n// L.DomEvent.on(div, 'click', function (ev) {\r\n// \tL.DomEvent.stopPropagation(ev);\r\n// });\r\n// ```\r\nfunction stopPropagation(e) {\r\n\r\n\tif (e.stopPropagation) {\r\n\t\te.stopPropagation();\r\n\t} else if (e.originalEvent) { // In case of Leaflet event.\r\n\t\te.originalEvent._stopped = true;\r\n\t} else {\r\n\t\te.cancelBubble = true;\r\n\t}\r\n\tskipped(e);\r\n\r\n\treturn this;\r\n}\r\n\r\n// @function disableScrollPropagation(el: HTMLElement): this\r\n// Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).\r\nfunction disableScrollPropagation(el) {\r\n\taddOne(el, 'mousewheel', stopPropagation);\r\n\treturn this;\r\n}\r\n\r\n// @function disableClickPropagation(el: HTMLElement): this\r\n// Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,\r\n// `'mousedown'` and `'touchstart'` events (plus browser variants).\r\nfunction disableClickPropagation(el) {\r\n\ton(el, 'mousedown touchstart dblclick', stopPropagation);\r\n\taddOne(el, 'click', fakeStop);\r\n\treturn this;\r\n}\r\n\r\n// @function preventDefault(ev: DOMEvent): this\r\n// Prevents the default action of the DOM Event `ev` from happening (such as\r\n// following a link in the href of the a element, or doing a POST request\r\n// with page reload when a `` is submitted).\r\n// Use it inside listener functions.\r\nfunction preventDefault(e) {\r\n\tif (e.preventDefault) {\r\n\t\te.preventDefault();\r\n\t} else {\r\n\t\te.returnValue = false;\r\n\t}\r\n\treturn this;\r\n}\r\n\r\n// @function stop(ev: DOMEvent): this\r\n// Does `stopPropagation` and `preventDefault` at the same time.\r\nfunction stop(e) {\r\n\tpreventDefault(e);\r\n\tstopPropagation(e);\r\n\treturn this;\r\n}\r\n\r\n// @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point\r\n// Gets normalized mouse position from a DOM event relative to the\r\n// `container` (border excluded) or to the whole page if not specified.\r\nfunction getMousePosition(e, container) {\r\n\tif (!container) {\r\n\t\treturn new Point(e.clientX, e.clientY);\r\n\t}\r\n\r\n\tvar scale = getScale(container),\r\n\t offset = scale.boundingClientRect; // left and top values are in page scale (like the event clientX/Y)\r\n\r\n\treturn new Point(\r\n\t\t// offset.left/top values are in page scale (like clientX/Y),\r\n\t\t// whereas clientLeft/Top (border width) values are the original values (before CSS scale applies).\r\n\t\t(e.clientX - offset.left) / scale.x - container.clientLeft,\r\n\t\t(e.clientY - offset.top) / scale.y - container.clientTop\r\n\t);\r\n}\r\n\r\n// Chrome on Win scrolls double the pixels as in other platforms (see #4538),\r\n// and Firefox scrolls device pixels, not CSS pixels\r\nvar wheelPxFactor =\r\n\t(win && chrome) ? 2 * window.devicePixelRatio :\r\n\tgecko ? window.devicePixelRatio : 1;\r\n\r\n// @function getWheelDelta(ev: DOMEvent): Number\r\n// Gets normalized wheel delta from a mousewheel DOM event, in vertical\r\n// pixels scrolled (negative if scrolling down).\r\n// Events from pointing devices without precise scrolling are mapped to\r\n// a best guess of 60 pixels.\r\nfunction getWheelDelta(e) {\r\n\treturn (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta\r\n\t (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels\r\n\t (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines\r\n\t (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages\r\n\t (e.deltaX || e.deltaZ) ? 0 :\t// Skip horizontal/depth wheel events\r\n\t e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels\r\n\t (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines\r\n\t e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages\r\n\t 0;\r\n}\r\n\r\nvar skipEvents = {};\r\n\r\nfunction fakeStop(e) {\r\n\t// fakes stopPropagation by setting a special event flag, checked/reset with skipped(e)\r\n\tskipEvents[e.type] = true;\r\n}\r\n\r\nfunction skipped(e) {\r\n\tvar events = skipEvents[e.type];\r\n\t// reset when checking, as it's only used in map container and propagates outside of the map\r\n\tskipEvents[e.type] = false;\r\n\treturn events;\r\n}\r\n\r\n// check if element really left/entered the event target (for mouseenter/mouseleave)\r\nfunction isExternalTarget(el, e) {\r\n\r\n\tvar related = e.relatedTarget;\r\n\r\n\tif (!related) { return true; }\r\n\r\n\ttry {\r\n\t\twhile (related && (related !== el)) {\r\n\t\t\trelated = related.parentNode;\r\n\t\t}\r\n\t} catch (err) {\r\n\t\treturn false;\r\n\t}\r\n\treturn (related !== el);\r\n}\r\n\r\nvar lastClick;\r\n\r\n// this is a horrible workaround for a bug in Android where a single touch triggers two click events\r\nfunction filterClick(e, handler) {\r\n\tvar timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),\r\n\t elapsed = lastClick && (timeStamp - lastClick);\r\n\r\n\t// are they closer together than 500ms yet more than 100ms?\r\n\t// Android typically triggers them ~300ms apart while multiple listeners\r\n\t// on the same event should be triggered far faster;\r\n\t// or check if click is simulated on the element, and if it is, reject any non-simulated events\r\n\r\n\tif ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {\r\n\t\tstop(e);\r\n\t\treturn;\r\n\t}\r\n\tlastClick = timeStamp;\r\n\r\n\thandler(e);\r\n}\r\n\r\n\r\n\n\nvar DomEvent = (Object.freeze || Object)({\n\ton: on,\n\toff: off,\n\tstopPropagation: stopPropagation,\n\tdisableScrollPropagation: disableScrollPropagation,\n\tdisableClickPropagation: disableClickPropagation,\n\tpreventDefault: preventDefault,\n\tstop: stop,\n\tgetMousePosition: getMousePosition,\n\tgetWheelDelta: getWheelDelta,\n\tfakeStop: fakeStop,\n\tskipped: skipped,\n\tisExternalTarget: isExternalTarget,\n\taddListener: on,\n\tremoveListener: off\n});\n\n/*\n * @class PosAnimation\n * @aka L.PosAnimation\n * @inherits Evented\n * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.\n *\n * @example\n * ```js\n * var fx = new L.PosAnimation();\n * fx.run(el, [300, 500], 0.5);\n * ```\n *\n * @constructor L.PosAnimation()\n * Creates a `PosAnimation` object.\n *\n */\n\nvar PosAnimation = Evented.extend({\n\n\t// @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)\n\t// Run an animation of a given element to a new position, optionally setting\n\t// duration in seconds (`0.25` by default) and easing linearity factor (3rd\n\t// argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),\n\t// `0.5` by default).\n\trun: function (el, newPos, duration, easeLinearity) {\n\t\tthis.stop();\n\n\t\tthis._el = el;\n\t\tthis._inProgress = true;\n\t\tthis._duration = duration || 0.25;\n\t\tthis._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);\n\n\t\tthis._startPos = getPosition(el);\n\t\tthis._offset = newPos.subtract(this._startPos);\n\t\tthis._startTime = +new Date();\n\n\t\t// @event start: Event\n\t\t// Fired when the animation starts\n\t\tthis.fire('start');\n\n\t\tthis._animate();\n\t},\n\n\t// @method stop()\n\t// Stops the animation (if currently running).\n\tstop: function () {\n\t\tif (!this._inProgress) { return; }\n\n\t\tthis._step(true);\n\t\tthis._complete();\n\t},\n\n\t_animate: function () {\n\t\t// animation loop\n\t\tthis._animId = requestAnimFrame(this._animate, this);\n\t\tthis._step();\n\t},\n\n\t_step: function (round) {\n\t\tvar elapsed = (+new Date()) - this._startTime,\n\t\t duration = this._duration * 1000;\n\n\t\tif (elapsed < duration) {\n\t\t\tthis._runFrame(this._easeOut(elapsed / duration), round);\n\t\t} else {\n\t\t\tthis._runFrame(1);\n\t\t\tthis._complete();\n\t\t}\n\t},\n\n\t_runFrame: function (progress, round) {\n\t\tvar pos = this._startPos.add(this._offset.multiplyBy(progress));\n\t\tif (round) {\n\t\t\tpos._round();\n\t\t}\n\t\tsetPosition(this._el, pos);\n\n\t\t// @event step: Event\n\t\t// Fired continuously during the animation.\n\t\tthis.fire('step');\n\t},\n\n\t_complete: function () {\n\t\tcancelAnimFrame(this._animId);\n\n\t\tthis._inProgress = false;\n\t\t// @event end: Event\n\t\t// Fired when the animation ends.\n\t\tthis.fire('end');\n\t},\n\n\t_easeOut: function (t) {\n\t\treturn 1 - Math.pow(1 - t, this._easeOutPower);\n\t}\n});\n\n/*\r\n * @class Map\r\n * @aka L.Map\r\n * @inherits Evented\r\n *\r\n * The central class of the API — it is used to create a map on a page and manipulate it.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * // initialize the map on the \"map\" div with a given center and zoom\r\n * var map = L.map('map', {\r\n * \tcenter: [51.505, -0.09],\r\n * \tzoom: 13\r\n * });\r\n * ```\r\n *\r\n */\r\n\r\nvar Map = Evented.extend({\r\n\r\n\toptions: {\r\n\t\t// @section Map State Options\r\n\t\t// @option crs: CRS = L.CRS.EPSG3857\r\n\t\t// The [Coordinate Reference System](#crs) to use. Don't change this if you're not\r\n\t\t// sure what it means.\r\n\t\tcrs: EPSG3857,\r\n\r\n\t\t// @option center: LatLng = undefined\r\n\t\t// Initial geographic center of the map\r\n\t\tcenter: undefined,\r\n\r\n\t\t// @option zoom: Number = undefined\r\n\t\t// Initial map zoom level\r\n\t\tzoom: undefined,\r\n\r\n\t\t// @option minZoom: Number = *\r\n\t\t// Minimum zoom level of the map.\r\n\t\t// If not specified and at least one `GridLayer` or `TileLayer` is in the map,\r\n\t\t// the lowest of their `minZoom` options will be used instead.\r\n\t\tminZoom: undefined,\r\n\r\n\t\t// @option maxZoom: Number = *\r\n\t\t// Maximum zoom level of the map.\r\n\t\t// If not specified and at least one `GridLayer` or `TileLayer` is in the map,\r\n\t\t// the highest of their `maxZoom` options will be used instead.\r\n\t\tmaxZoom: undefined,\r\n\r\n\t\t// @option layers: Layer[] = []\r\n\t\t// Array of layers that will be added to the map initially\r\n\t\tlayers: [],\r\n\r\n\t\t// @option maxBounds: LatLngBounds = null\r\n\t\t// When this option is set, the map restricts the view to the given\r\n\t\t// geographical bounds, bouncing the user back if the user tries to pan\r\n\t\t// outside the view. To set the restriction dynamically, use\r\n\t\t// [`setMaxBounds`](#map-setmaxbounds) method.\r\n\t\tmaxBounds: undefined,\r\n\r\n\t\t// @option renderer: Renderer = *\r\n\t\t// The default method for drawing vector layers on the map. `L.SVG`\r\n\t\t// or `L.Canvas` by default depending on browser support.\r\n\t\trenderer: undefined,\r\n\r\n\r\n\t\t// @section Animation Options\r\n\t\t// @option zoomAnimation: Boolean = true\r\n\t\t// Whether the map zoom animation is enabled. By default it's enabled\r\n\t\t// in all browsers that support CSS3 Transitions except Android.\r\n\t\tzoomAnimation: true,\r\n\r\n\t\t// @option zoomAnimationThreshold: Number = 4\r\n\t\t// Won't animate zoom if the zoom difference exceeds this value.\r\n\t\tzoomAnimationThreshold: 4,\r\n\r\n\t\t// @option fadeAnimation: Boolean = true\r\n\t\t// Whether the tile fade animation is enabled. By default it's enabled\r\n\t\t// in all browsers that support CSS3 Transitions except Android.\r\n\t\tfadeAnimation: true,\r\n\r\n\t\t// @option markerZoomAnimation: Boolean = true\r\n\t\t// Whether markers animate their zoom with the zoom animation, if disabled\r\n\t\t// they will disappear for the length of the animation. By default it's\r\n\t\t// enabled in all browsers that support CSS3 Transitions except Android.\r\n\t\tmarkerZoomAnimation: true,\r\n\r\n\t\t// @option transform3DLimit: Number = 2^23\r\n\t\t// Defines the maximum size of a CSS translation transform. The default\r\n\t\t// value should not be changed unless a web browser positions layers in\r\n\t\t// the wrong place after doing a large `panBy`.\r\n\t\ttransform3DLimit: 8388608, // Precision limit of a 32-bit float\r\n\r\n\t\t// @section Interaction Options\r\n\t\t// @option zoomSnap: Number = 1\r\n\t\t// Forces the map's zoom level to always be a multiple of this, particularly\r\n\t\t// right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.\r\n\t\t// By default, the zoom level snaps to the nearest integer; lower values\r\n\t\t// (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`\r\n\t\t// means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.\r\n\t\tzoomSnap: 1,\r\n\r\n\t\t// @option zoomDelta: Number = 1\r\n\t\t// Controls how much the map's zoom level will change after a\r\n\t\t// [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`\r\n\t\t// or `-` on the keyboard, or using the [zoom controls](#control-zoom).\r\n\t\t// Values smaller than `1` (e.g. `0.5`) allow for greater granularity.\r\n\t\tzoomDelta: 1,\r\n\r\n\t\t// @option trackResize: Boolean = true\r\n\t\t// Whether the map automatically handles browser window resize to update itself.\r\n\t\ttrackResize: true\r\n\t},\r\n\r\n\tinitialize: function (id, options) { // (HTMLElement or String, Object)\r\n\t\toptions = setOptions(this, options);\r\n\r\n\t\t// Make sure to assign internal flags at the beginning,\r\n\t\t// to avoid inconsistent state in some edge cases.\r\n\t\tthis._handlers = [];\r\n\t\tthis._layers = {};\r\n\t\tthis._zoomBoundLayers = {};\r\n\t\tthis._sizeChanged = true;\r\n\r\n\t\tthis._initContainer(id);\r\n\t\tthis._initLayout();\r\n\r\n\t\t// hack for https://github.com/Leaflet/Leaflet/issues/1980\r\n\t\tthis._onResize = bind(this._onResize, this);\r\n\r\n\t\tthis._initEvents();\r\n\r\n\t\tif (options.maxBounds) {\r\n\t\t\tthis.setMaxBounds(options.maxBounds);\r\n\t\t}\r\n\r\n\t\tif (options.zoom !== undefined) {\r\n\t\t\tthis._zoom = this._limitZoom(options.zoom);\r\n\t\t}\r\n\r\n\t\tif (options.center && options.zoom !== undefined) {\r\n\t\t\tthis.setView(toLatLng(options.center), options.zoom, {reset: true});\r\n\t\t}\r\n\r\n\t\tthis.callInitHooks();\r\n\r\n\t\t// don't animate on browsers without hardware-accelerated transitions or old Android/Opera\r\n\t\tthis._zoomAnimated = TRANSITION && any3d && !mobileOpera &&\r\n\t\t\t\tthis.options.zoomAnimation;\r\n\r\n\t\t// zoom transitions run with the same duration for all layers, so if one of transitionend events\r\n\t\t// happens after starting zoom animation (propagating to the map pane), we know that it ended globally\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tthis._createAnimProxy();\r\n\t\t\ton(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);\r\n\t\t}\r\n\r\n\t\tthis._addLayers(this.options.layers);\r\n\t},\r\n\r\n\r\n\t// @section Methods for modifying map state\r\n\r\n\t// @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this\r\n\t// Sets the view of the map (geographical center and zoom) with the given\r\n\t// animation options.\r\n\tsetView: function (center, zoom, options) {\r\n\r\n\t\tzoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);\r\n\t\tcenter = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);\r\n\t\toptions = options || {};\r\n\r\n\t\tthis._stop();\r\n\r\n\t\tif (this._loaded && !options.reset && options !== true) {\r\n\r\n\t\t\tif (options.animate !== undefined) {\r\n\t\t\t\toptions.zoom = extend({animate: options.animate}, options.zoom);\r\n\t\t\t\toptions.pan = extend({animate: options.animate, duration: options.duration}, options.pan);\r\n\t\t\t}\r\n\r\n\t\t\t// try animating pan or zoom\r\n\t\t\tvar moved = (this._zoom !== zoom) ?\r\n\t\t\t\tthis._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :\r\n\t\t\t\tthis._tryAnimatedPan(center, options.pan);\r\n\r\n\t\t\tif (moved) {\r\n\t\t\t\t// prevent resize handler call, the view will refresh after animation anyway\r\n\t\t\t\tclearTimeout(this._sizeTimer);\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// animation didn't start, just reset the map view\r\n\t\tthis._resetView(center, zoom);\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setZoom(zoom: Number, options?: Zoom/pan options): this\r\n\t// Sets the zoom of the map.\r\n\tsetZoom: function (zoom, options) {\r\n\t\tif (!this._loaded) {\r\n\t\t\tthis._zoom = zoom;\r\n\t\t\treturn this;\r\n\t\t}\r\n\t\treturn this.setView(this.getCenter(), zoom, {zoom: options});\r\n\t},\r\n\r\n\t// @method zoomIn(delta?: Number, options?: Zoom options): this\r\n\t// Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).\r\n\tzoomIn: function (delta, options) {\r\n\t\tdelta = delta || (any3d ? this.options.zoomDelta : 1);\r\n\t\treturn this.setZoom(this._zoom + delta, options);\r\n\t},\r\n\r\n\t// @method zoomOut(delta?: Number, options?: Zoom options): this\r\n\t// Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).\r\n\tzoomOut: function (delta, options) {\r\n\t\tdelta = delta || (any3d ? this.options.zoomDelta : 1);\r\n\t\treturn this.setZoom(this._zoom - delta, options);\r\n\t},\r\n\r\n\t// @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this\r\n\t// Zooms the map while keeping a specified geographical point on the map\r\n\t// stationary (e.g. used internally for scroll zoom and double-click zoom).\r\n\t// @alternative\r\n\t// @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this\r\n\t// Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.\r\n\tsetZoomAround: function (latlng, zoom, options) {\r\n\t\tvar scale = this.getZoomScale(zoom),\r\n\t\t viewHalf = this.getSize().divideBy(2),\r\n\t\t containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),\r\n\r\n\t\t centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),\r\n\t\t newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));\r\n\r\n\t\treturn this.setView(newCenter, zoom, {zoom: options});\r\n\t},\r\n\r\n\t_getBoundsCenterZoom: function (bounds, options) {\r\n\r\n\t\toptions = options || {};\r\n\t\tbounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);\r\n\r\n\t\tvar paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),\r\n\t\t paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),\r\n\r\n\t\t zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));\r\n\r\n\t\tzoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;\r\n\r\n\t\tif (zoom === Infinity) {\r\n\t\t\treturn {\r\n\t\t\t\tcenter: bounds.getCenter(),\r\n\t\t\t\tzoom: zoom\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\tvar paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),\r\n\r\n\t\t swPoint = this.project(bounds.getSouthWest(), zoom),\r\n\t\t nePoint = this.project(bounds.getNorthEast(), zoom),\r\n\t\t center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);\r\n\r\n\t\treturn {\r\n\t\t\tcenter: center,\r\n\t\t\tzoom: zoom\r\n\t\t};\r\n\t},\r\n\r\n\t// @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this\r\n\t// Sets a map view that contains the given geographical bounds with the\r\n\t// maximum zoom level possible.\r\n\tfitBounds: function (bounds, options) {\r\n\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tif (!bounds.isValid()) {\r\n\t\t\tthrow new Error('Bounds are not valid.');\r\n\t\t}\r\n\r\n\t\tvar target = this._getBoundsCenterZoom(bounds, options);\r\n\t\treturn this.setView(target.center, target.zoom, options);\r\n\t},\r\n\r\n\t// @method fitWorld(options?: fitBounds options): this\r\n\t// Sets a map view that mostly contains the whole world with the maximum\r\n\t// zoom level possible.\r\n\tfitWorld: function (options) {\r\n\t\treturn this.fitBounds([[-90, -180], [90, 180]], options);\r\n\t},\r\n\r\n\t// @method panTo(latlng: LatLng, options?: Pan options): this\r\n\t// Pans the map to a given center.\r\n\tpanTo: function (center, options) { // (LatLng)\r\n\t\treturn this.setView(center, this._zoom, {pan: options});\r\n\t},\r\n\r\n\t// @method panBy(offset: Point, options?: Pan options): this\r\n\t// Pans the map by a given number of pixels (animated).\r\n\tpanBy: function (offset, options) {\r\n\t\toffset = toPoint(offset).round();\r\n\t\toptions = options || {};\r\n\r\n\t\tif (!offset.x && !offset.y) {\r\n\t\t\treturn this.fire('moveend');\r\n\t\t}\r\n\t\t// If we pan too far, Chrome gets issues with tiles\r\n\t\t// and makes them disappear or appear in the wrong place (slightly offset) #2602\r\n\t\tif (options.animate !== true && !this.getSize().contains(offset)) {\r\n\t\t\tthis._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tif (!this._panAnim) {\r\n\t\t\tthis._panAnim = new PosAnimation();\r\n\r\n\t\t\tthis._panAnim.on({\r\n\t\t\t\t'step': this._onPanTransitionStep,\r\n\t\t\t\t'end': this._onPanTransitionEnd\r\n\t\t\t}, this);\r\n\t\t}\r\n\r\n\t\t// don't fire movestart if animating inertia\r\n\t\tif (!options.noMoveStart) {\r\n\t\t\tthis.fire('movestart');\r\n\t\t}\r\n\r\n\t\t// animate pan unless animate: false specified\r\n\t\tif (options.animate !== false) {\r\n\t\t\taddClass(this._mapPane, 'leaflet-pan-anim');\r\n\r\n\t\t\tvar newPos = this._getMapPanePos().subtract(offset).round();\r\n\t\t\tthis._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);\r\n\t\t} else {\r\n\t\t\tthis._rawPanBy(offset);\r\n\t\t\tthis.fire('move').fire('moveend');\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this\r\n\t// Sets the view of the map (geographical center and zoom) performing a smooth\r\n\t// pan-zoom animation.\r\n\tflyTo: function (targetCenter, targetZoom, options) {\r\n\r\n\t\toptions = options || {};\r\n\t\tif (options.animate === false || !any3d) {\r\n\t\t\treturn this.setView(targetCenter, targetZoom, options);\r\n\t\t}\r\n\r\n\t\tthis._stop();\r\n\r\n\t\tvar from = this.project(this.getCenter()),\r\n\t\t to = this.project(targetCenter),\r\n\t\t size = this.getSize(),\r\n\t\t startZoom = this._zoom;\r\n\r\n\t\ttargetCenter = toLatLng(targetCenter);\r\n\t\ttargetZoom = targetZoom === undefined ? startZoom : targetZoom;\r\n\r\n\t\tvar w0 = Math.max(size.x, size.y),\r\n\t\t w1 = w0 * this.getZoomScale(startZoom, targetZoom),\r\n\t\t u1 = (to.distanceTo(from)) || 1,\r\n\t\t rho = 1.42,\r\n\t\t rho2 = rho * rho;\r\n\r\n\t\tfunction r(i) {\r\n\t\t\tvar s1 = i ? -1 : 1,\r\n\t\t\t s2 = i ? w1 : w0,\r\n\t\t\t t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,\r\n\t\t\t b1 = 2 * s2 * rho2 * u1,\r\n\t\t\t b = t1 / b1,\r\n\t\t\t sq = Math.sqrt(b * b + 1) - b;\r\n\r\n\t\t\t // workaround for floating point precision bug when sq = 0, log = -Infinite,\r\n\t\t\t // thus triggering an infinite loop in flyTo\r\n\t\t\t var log = sq < 0.000000001 ? -18 : Math.log(sq);\r\n\r\n\t\t\treturn log;\r\n\t\t}\r\n\r\n\t\tfunction sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }\r\n\t\tfunction cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }\r\n\t\tfunction tanh(n) { return sinh(n) / cosh(n); }\r\n\r\n\t\tvar r0 = r(0);\r\n\r\n\t\tfunction w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }\r\n\t\tfunction u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }\r\n\r\n\t\tfunction easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }\r\n\r\n\t\tvar start = Date.now(),\r\n\t\t S = (r(1) - r0) / rho,\r\n\t\t duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;\r\n\r\n\t\tfunction frame() {\r\n\t\t\tvar t = (Date.now() - start) / duration,\r\n\t\t\t s = easeOut(t) * S;\r\n\r\n\t\t\tif (t <= 1) {\r\n\t\t\t\tthis._flyToFrame = requestAnimFrame(frame, this);\r\n\r\n\t\t\t\tthis._move(\r\n\t\t\t\t\tthis.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),\r\n\t\t\t\t\tthis.getScaleZoom(w0 / w(s), startZoom),\r\n\t\t\t\t\t{flyTo: true});\r\n\r\n\t\t\t} else {\r\n\t\t\t\tthis\r\n\t\t\t\t\t._move(targetCenter, targetZoom)\r\n\t\t\t\t\t._moveEnd(true);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis._moveStart(true, options.noMoveStart);\r\n\r\n\t\tframe.call(this);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this\r\n\t// Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),\r\n\t// but takes a bounds parameter like [`fitBounds`](#map-fitbounds).\r\n\tflyToBounds: function (bounds, options) {\r\n\t\tvar target = this._getBoundsCenterZoom(bounds, options);\r\n\t\treturn this.flyTo(target.center, target.zoom, options);\r\n\t},\r\n\r\n\t// @method setMaxBounds(bounds: Bounds): this\r\n\t// Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).\r\n\tsetMaxBounds: function (bounds) {\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\r\n\t\tif (!bounds.isValid()) {\r\n\t\t\tthis.options.maxBounds = null;\r\n\t\t\treturn this.off('moveend', this._panInsideMaxBounds);\r\n\t\t} else if (this.options.maxBounds) {\r\n\t\t\tthis.off('moveend', this._panInsideMaxBounds);\r\n\t\t}\r\n\r\n\t\tthis.options.maxBounds = bounds;\r\n\r\n\t\tif (this._loaded) {\r\n\t\t\tthis._panInsideMaxBounds();\r\n\t\t}\r\n\r\n\t\treturn this.on('moveend', this._panInsideMaxBounds);\r\n\t},\r\n\r\n\t// @method setMinZoom(zoom: Number): this\r\n\t// Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).\r\n\tsetMinZoom: function (zoom) {\r\n\t\tvar oldZoom = this.options.minZoom;\r\n\t\tthis.options.minZoom = zoom;\r\n\r\n\t\tif (this._loaded && oldZoom !== zoom) {\r\n\t\t\tthis.fire('zoomlevelschange');\r\n\r\n\t\t\tif (this.getZoom() < this.options.minZoom) {\r\n\t\t\t\treturn this.setZoom(zoom);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setMaxZoom(zoom: Number): this\r\n\t// Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).\r\n\tsetMaxZoom: function (zoom) {\r\n\t\tvar oldZoom = this.options.maxZoom;\r\n\t\tthis.options.maxZoom = zoom;\r\n\r\n\t\tif (this._loaded && oldZoom !== zoom) {\r\n\t\t\tthis.fire('zoomlevelschange');\r\n\r\n\t\t\tif (this.getZoom() > this.options.maxZoom) {\r\n\t\t\t\treturn this.setZoom(zoom);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this\r\n\t// Pans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any.\r\n\tpanInsideBounds: function (bounds, options) {\r\n\t\tthis._enforcingBounds = true;\r\n\t\tvar center = this.getCenter(),\r\n\t\t newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));\r\n\r\n\t\tif (!center.equals(newCenter)) {\r\n\t\t\tthis.panTo(newCenter, options);\r\n\t\t}\r\n\r\n\t\tthis._enforcingBounds = false;\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method panInside(latlng: LatLng, options?: options): this\r\n\t// Pans the map the minimum amount to make the `latlng` visible. Use\r\n\t// `padding`, `paddingTopLeft` and `paddingTopRight` options to fit\r\n\t// the display to more restricted bounds, like [`fitBounds`](#map-fitbounds).\r\n\t// If `latlng` is already within the (optionally padded) display bounds,\r\n\t// the map will not be panned.\r\n\tpanInside: function (latlng, options) {\r\n\t\toptions = options || {};\r\n\r\n\t\tvar paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),\r\n\t\t paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),\r\n\t\t center = this.getCenter(),\r\n\t\t pixelCenter = this.project(center),\r\n\t\t pixelPoint = this.project(latlng),\r\n\t\t pixelBounds = this.getPixelBounds(),\r\n\t\t halfPixelBounds = pixelBounds.getSize().divideBy(2),\r\n\t\t paddedBounds = toBounds([pixelBounds.min.add(paddingTL), pixelBounds.max.subtract(paddingBR)]);\r\n\r\n\t\tif (!paddedBounds.contains(pixelPoint)) {\r\n\t\t\tthis._enforcingBounds = true;\r\n\t\t\tvar diff = pixelCenter.subtract(pixelPoint),\r\n\t\t\t newCenter = toPoint(pixelPoint.x + diff.x, pixelPoint.y + diff.y);\r\n\r\n\t\t\tif (pixelPoint.x < paddedBounds.min.x || pixelPoint.x > paddedBounds.max.x) {\r\n\t\t\t\tnewCenter.x = pixelCenter.x - diff.x;\r\n\t\t\t\tif (diff.x > 0) {\r\n\t\t\t\t\tnewCenter.x += halfPixelBounds.x - paddingTL.x;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tnewCenter.x -= halfPixelBounds.x - paddingBR.x;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (pixelPoint.y < paddedBounds.min.y || pixelPoint.y > paddedBounds.max.y) {\r\n\t\t\t\tnewCenter.y = pixelCenter.y - diff.y;\r\n\t\t\t\tif (diff.y > 0) {\r\n\t\t\t\t\tnewCenter.y += halfPixelBounds.y - paddingTL.y;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tnewCenter.y -= halfPixelBounds.y - paddingBR.y;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tthis.panTo(this.unproject(newCenter), options);\r\n\t\t\tthis._enforcingBounds = false;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method invalidateSize(options: Zoom/pan options): this\r\n\t// Checks if the map container size changed and updates the map if so —\r\n\t// call it after you've changed the map size dynamically, also animating\r\n\t// pan by default. If `options.pan` is `false`, panning will not occur.\r\n\t// If `options.debounceMoveend` is `true`, it will delay `moveend` event so\r\n\t// that it doesn't happen often even if the method is called many\r\n\t// times in a row.\r\n\r\n\t// @alternative\r\n\t// @method invalidateSize(animate: Boolean): this\r\n\t// Checks if the map container size changed and updates the map if so —\r\n\t// call it after you've changed the map size dynamically, also animating\r\n\t// pan by default.\r\n\tinvalidateSize: function (options) {\r\n\t\tif (!this._loaded) { return this; }\r\n\r\n\t\toptions = extend({\r\n\t\t\tanimate: false,\r\n\t\t\tpan: true\r\n\t\t}, options === true ? {animate: true} : options);\r\n\r\n\t\tvar oldSize = this.getSize();\r\n\t\tthis._sizeChanged = true;\r\n\t\tthis._lastCenter = null;\r\n\r\n\t\tvar newSize = this.getSize(),\r\n\t\t oldCenter = oldSize.divideBy(2).round(),\r\n\t\t newCenter = newSize.divideBy(2).round(),\r\n\t\t offset = oldCenter.subtract(newCenter);\r\n\r\n\t\tif (!offset.x && !offset.y) { return this; }\r\n\r\n\t\tif (options.animate && options.pan) {\r\n\t\t\tthis.panBy(offset);\r\n\r\n\t\t} else {\r\n\t\t\tif (options.pan) {\r\n\t\t\t\tthis._rawPanBy(offset);\r\n\t\t\t}\r\n\r\n\t\t\tthis.fire('move');\r\n\r\n\t\t\tif (options.debounceMoveend) {\r\n\t\t\t\tclearTimeout(this._sizeTimer);\r\n\t\t\t\tthis._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);\r\n\t\t\t} else {\r\n\t\t\t\tthis.fire('moveend');\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// @section Map state change events\r\n\t\t// @event resize: ResizeEvent\r\n\t\t// Fired when the map is resized.\r\n\t\treturn this.fire('resize', {\r\n\t\t\toldSize: oldSize,\r\n\t\t\tnewSize: newSize\r\n\t\t});\r\n\t},\r\n\r\n\t// @section Methods for modifying map state\r\n\t// @method stop(): this\r\n\t// Stops the currently running `panTo` or `flyTo` animation, if any.\r\n\tstop: function () {\r\n\t\tthis.setZoom(this._limitZoom(this._zoom));\r\n\t\tif (!this.options.zoomSnap) {\r\n\t\t\tthis.fire('viewreset');\r\n\t\t}\r\n\t\treturn this._stop();\r\n\t},\r\n\r\n\t// @section Geolocation methods\r\n\t// @method locate(options?: Locate options): this\r\n\t// Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)\r\n\t// event with location data on success or a [`locationerror`](#map-locationerror) event on failure,\r\n\t// and optionally sets the map view to the user's location with respect to\r\n\t// detection accuracy (or to the world view if geolocation failed).\r\n\t// Note that, if your page doesn't use HTTPS, this method will fail in\r\n\t// modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))\r\n\t// See `Locate options` for more details.\r\n\tlocate: function (options) {\r\n\r\n\t\toptions = this._locateOptions = extend({\r\n\t\t\ttimeout: 10000,\r\n\t\t\twatch: false\r\n\t\t\t// setView: false\r\n\t\t\t// maxZoom: \r\n\t\t\t// maximumAge: 0\r\n\t\t\t// enableHighAccuracy: false\r\n\t\t}, options);\r\n\r\n\t\tif (!('geolocation' in navigator)) {\r\n\t\t\tthis._handleGeolocationError({\r\n\t\t\t\tcode: 0,\r\n\t\t\t\tmessage: 'Geolocation not supported.'\r\n\t\t\t});\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tvar onResponse = bind(this._handleGeolocationResponse, this),\r\n\t\t onError = bind(this._handleGeolocationError, this);\r\n\r\n\t\tif (options.watch) {\r\n\t\t\tthis._locationWatchId =\r\n\t\t\t navigator.geolocation.watchPosition(onResponse, onError, options);\r\n\t\t} else {\r\n\t\t\tnavigator.geolocation.getCurrentPosition(onResponse, onError, options);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method stopLocate(): this\r\n\t// Stops watching location previously initiated by `map.locate({watch: true})`\r\n\t// and aborts resetting the map view if map.locate was called with\r\n\t// `{setView: true}`.\r\n\tstopLocate: function () {\r\n\t\tif (navigator.geolocation && navigator.geolocation.clearWatch) {\r\n\t\t\tnavigator.geolocation.clearWatch(this._locationWatchId);\r\n\t\t}\r\n\t\tif (this._locateOptions) {\r\n\t\t\tthis._locateOptions.setView = false;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_handleGeolocationError: function (error) {\r\n\t\tvar c = error.code,\r\n\t\t message = error.message ||\r\n\t\t (c === 1 ? 'permission denied' :\r\n\t\t (c === 2 ? 'position unavailable' : 'timeout'));\r\n\r\n\t\tif (this._locateOptions.setView && !this._loaded) {\r\n\t\t\tthis.fitWorld();\r\n\t\t}\r\n\r\n\t\t// @section Location events\r\n\t\t// @event locationerror: ErrorEvent\r\n\t\t// Fired when geolocation (using the [`locate`](#map-locate) method) failed.\r\n\t\tthis.fire('locationerror', {\r\n\t\t\tcode: c,\r\n\t\t\tmessage: 'Geolocation error: ' + message + '.'\r\n\t\t});\r\n\t},\r\n\r\n\t_handleGeolocationResponse: function (pos) {\r\n\t\tvar lat = pos.coords.latitude,\r\n\t\t lng = pos.coords.longitude,\r\n\t\t latlng = new LatLng(lat, lng),\r\n\t\t bounds = latlng.toBounds(pos.coords.accuracy * 2),\r\n\t\t options = this._locateOptions;\r\n\r\n\t\tif (options.setView) {\r\n\t\t\tvar zoom = this.getBoundsZoom(bounds);\r\n\t\t\tthis.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);\r\n\t\t}\r\n\r\n\t\tvar data = {\r\n\t\t\tlatlng: latlng,\r\n\t\t\tbounds: bounds,\r\n\t\t\ttimestamp: pos.timestamp\r\n\t\t};\r\n\r\n\t\tfor (var i in pos.coords) {\r\n\t\t\tif (typeof pos.coords[i] === 'number') {\r\n\t\t\t\tdata[i] = pos.coords[i];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// @event locationfound: LocationEvent\r\n\t\t// Fired when geolocation (using the [`locate`](#map-locate) method)\r\n\t\t// went successfully.\r\n\t\tthis.fire('locationfound', data);\r\n\t},\r\n\r\n\t// TODO Appropriate docs section?\r\n\t// @section Other Methods\r\n\t// @method addHandler(name: String, HandlerClass: Function): this\r\n\t// Adds a new `Handler` to the map, given its name and constructor function.\r\n\taddHandler: function (name, HandlerClass) {\r\n\t\tif (!HandlerClass) { return this; }\r\n\r\n\t\tvar handler = this[name] = new HandlerClass(this);\r\n\r\n\t\tthis._handlers.push(handler);\r\n\r\n\t\tif (this.options[name]) {\r\n\t\t\thandler.enable();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method remove(): this\r\n\t// Destroys the map and clears all related event listeners.\r\n\tremove: function () {\r\n\r\n\t\tthis._initEvents(true);\r\n\r\n\t\tif (this._containerId !== this._container._leaflet_id) {\r\n\t\t\tthrow new Error('Map container is being reused by another instance');\r\n\t\t}\r\n\r\n\t\ttry {\r\n\t\t\t// throws error in IE6-8\r\n\t\t\tdelete this._container._leaflet_id;\r\n\t\t\tdelete this._containerId;\r\n\t\t} catch (e) {\r\n\t\t\t/*eslint-disable */\r\n\t\t\tthis._container._leaflet_id = undefined;\r\n\t\t\t/* eslint-enable */\r\n\t\t\tthis._containerId = undefined;\r\n\t\t}\r\n\r\n\t\tif (this._locationWatchId !== undefined) {\r\n\t\t\tthis.stopLocate();\r\n\t\t}\r\n\r\n\t\tthis._stop();\r\n\r\n\t\tremove(this._mapPane);\r\n\r\n\t\tif (this._clearControlPos) {\r\n\t\t\tthis._clearControlPos();\r\n\t\t}\r\n\t\tif (this._resizeRequest) {\r\n\t\t\tcancelAnimFrame(this._resizeRequest);\r\n\t\t\tthis._resizeRequest = null;\r\n\t\t}\r\n\r\n\t\tthis._clearHandlers();\r\n\r\n\t\tif (this._loaded) {\r\n\t\t\t// @section Map state change events\r\n\t\t\t// @event unload: Event\r\n\t\t\t// Fired when the map is destroyed with [remove](#map-remove) method.\r\n\t\t\tthis.fire('unload');\r\n\t\t}\r\n\r\n\t\tvar i;\r\n\t\tfor (i in this._layers) {\r\n\t\t\tthis._layers[i].remove();\r\n\t\t}\r\n\t\tfor (i in this._panes) {\r\n\t\t\tremove(this._panes[i]);\r\n\t\t}\r\n\r\n\t\tthis._layers = [];\r\n\t\tthis._panes = [];\r\n\t\tdelete this._mapPane;\r\n\t\tdelete this._renderer;\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @section Other Methods\r\n\t// @method createPane(name: String, container?: HTMLElement): HTMLElement\r\n\t// Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,\r\n\t// then returns it. The pane is created as a child of `container`, or\r\n\t// as a child of the main map pane if not set.\r\n\tcreatePane: function (name, container) {\r\n\t\tvar className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),\r\n\t\t pane = create$1('div', className, container || this._mapPane);\r\n\r\n\t\tif (name) {\r\n\t\t\tthis._panes[name] = pane;\r\n\t\t}\r\n\t\treturn pane;\r\n\t},\r\n\r\n\t// @section Methods for Getting Map State\r\n\r\n\t// @method getCenter(): LatLng\r\n\t// Returns the geographical center of the map view\r\n\tgetCenter: function () {\r\n\t\tthis._checkIfLoaded();\r\n\r\n\t\tif (this._lastCenter && !this._moved()) {\r\n\t\t\treturn this._lastCenter;\r\n\t\t}\r\n\t\treturn this.layerPointToLatLng(this._getCenterLayerPoint());\r\n\t},\r\n\r\n\t// @method getZoom(): Number\r\n\t// Returns the current zoom level of the map view\r\n\tgetZoom: function () {\r\n\t\treturn this._zoom;\r\n\t},\r\n\r\n\t// @method getBounds(): LatLngBounds\r\n\t// Returns the geographical bounds visible in the current map view\r\n\tgetBounds: function () {\r\n\t\tvar bounds = this.getPixelBounds(),\r\n\t\t sw = this.unproject(bounds.getBottomLeft()),\r\n\t\t ne = this.unproject(bounds.getTopRight());\r\n\r\n\t\treturn new LatLngBounds(sw, ne);\r\n\t},\r\n\r\n\t// @method getMinZoom(): Number\r\n\t// Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default.\r\n\tgetMinZoom: function () {\r\n\t\treturn this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;\r\n\t},\r\n\r\n\t// @method getMaxZoom(): Number\r\n\t// Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).\r\n\tgetMaxZoom: function () {\r\n\t\treturn this.options.maxZoom === undefined ?\r\n\t\t\t(this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :\r\n\t\t\tthis.options.maxZoom;\r\n\t},\r\n\r\n\t// @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean, padding?: Point): Number\r\n\t// Returns the maximum zoom level on which the given bounds fit to the map\r\n\t// view in its entirety. If `inside` (optional) is set to `true`, the method\r\n\t// instead returns the minimum zoom level on which the map view fits into\r\n\t// the given bounds in its entirety.\r\n\tgetBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number\r\n\t\tbounds = toLatLngBounds(bounds);\r\n\t\tpadding = toPoint(padding || [0, 0]);\r\n\r\n\t\tvar zoom = this.getZoom() || 0,\r\n\t\t min = this.getMinZoom(),\r\n\t\t max = this.getMaxZoom(),\r\n\t\t nw = bounds.getNorthWest(),\r\n\t\t se = bounds.getSouthEast(),\r\n\t\t size = this.getSize().subtract(padding),\r\n\t\t boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),\r\n\t\t snap = any3d ? this.options.zoomSnap : 1,\r\n\t\t scalex = size.x / boundsSize.x,\r\n\t\t scaley = size.y / boundsSize.y,\r\n\t\t scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);\r\n\r\n\t\tzoom = this.getScaleZoom(scale, zoom);\r\n\r\n\t\tif (snap) {\r\n\t\t\tzoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level\r\n\t\t\tzoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;\r\n\t\t}\r\n\r\n\t\treturn Math.max(min, Math.min(max, zoom));\r\n\t},\r\n\r\n\t// @method getSize(): Point\r\n\t// Returns the current size of the map container (in pixels).\r\n\tgetSize: function () {\r\n\t\tif (!this._size || this._sizeChanged) {\r\n\t\t\tthis._size = new Point(\r\n\t\t\t\tthis._container.clientWidth || 0,\r\n\t\t\t\tthis._container.clientHeight || 0);\r\n\r\n\t\t\tthis._sizeChanged = false;\r\n\t\t}\r\n\t\treturn this._size.clone();\r\n\t},\r\n\r\n\t// @method getPixelBounds(): Bounds\r\n\t// Returns the bounds of the current map view in projected pixel\r\n\t// coordinates (sometimes useful in layer and overlay implementations).\r\n\tgetPixelBounds: function (center, zoom) {\r\n\t\tvar topLeftPoint = this._getTopLeftPoint(center, zoom);\r\n\t\treturn new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));\r\n\t},\r\n\r\n\t// TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to\r\n\t// the map pane? \"left point of the map layer\" can be confusing, specially\r\n\t// since there can be negative offsets.\r\n\t// @method getPixelOrigin(): Point\r\n\t// Returns the projected pixel coordinates of the top left point of\r\n\t// the map layer (useful in custom layer and overlay implementations).\r\n\tgetPixelOrigin: function () {\r\n\t\tthis._checkIfLoaded();\r\n\t\treturn this._pixelOrigin;\r\n\t},\r\n\r\n\t// @method getPixelWorldBounds(zoom?: Number): Bounds\r\n\t// Returns the world's bounds in pixel coordinates for zoom level `zoom`.\r\n\t// If `zoom` is omitted, the map's current zoom level is used.\r\n\tgetPixelWorldBounds: function (zoom) {\r\n\t\treturn this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);\r\n\t},\r\n\r\n\t// @section Other Methods\r\n\r\n\t// @method getPane(pane: String|HTMLElement): HTMLElement\r\n\t// Returns a [map pane](#map-pane), given its name or its HTML element (its identity).\r\n\tgetPane: function (pane) {\r\n\t\treturn typeof pane === 'string' ? this._panes[pane] : pane;\r\n\t},\r\n\r\n\t// @method getPanes(): Object\r\n\t// Returns a plain object containing the names of all [panes](#map-pane) as keys and\r\n\t// the panes as values.\r\n\tgetPanes: function () {\r\n\t\treturn this._panes;\r\n\t},\r\n\r\n\t// @method getContainer: HTMLElement\r\n\t// Returns the HTML element that contains the map.\r\n\tgetContainer: function () {\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\r\n\t// @section Conversion Methods\r\n\r\n\t// @method getZoomScale(toZoom: Number, fromZoom: Number): Number\r\n\t// Returns the scale factor to be applied to a map transition from zoom level\r\n\t// `fromZoom` to `toZoom`. Used internally to help with zoom animations.\r\n\tgetZoomScale: function (toZoom, fromZoom) {\r\n\t\t// TODO replace with universal implementation after refactoring projections\r\n\t\tvar crs = this.options.crs;\r\n\t\tfromZoom = fromZoom === undefined ? this._zoom : fromZoom;\r\n\t\treturn crs.scale(toZoom) / crs.scale(fromZoom);\r\n\t},\r\n\r\n\t// @method getScaleZoom(scale: Number, fromZoom: Number): Number\r\n\t// Returns the zoom level that the map would end up at, if it is at `fromZoom`\r\n\t// level and everything is scaled by a factor of `scale`. Inverse of\r\n\t// [`getZoomScale`](#map-getZoomScale).\r\n\tgetScaleZoom: function (scale, fromZoom) {\r\n\t\tvar crs = this.options.crs;\r\n\t\tfromZoom = fromZoom === undefined ? this._zoom : fromZoom;\r\n\t\tvar zoom = crs.zoom(scale * crs.scale(fromZoom));\r\n\t\treturn isNaN(zoom) ? Infinity : zoom;\r\n\t},\r\n\r\n\t// @method project(latlng: LatLng, zoom: Number): Point\r\n\t// Projects a geographical coordinate `LatLng` according to the projection\r\n\t// of the map's CRS, then scales it according to `zoom` and the CRS's\r\n\t// `Transformation`. The result is pixel coordinate relative to\r\n\t// the CRS origin.\r\n\tproject: function (latlng, zoom) {\r\n\t\tzoom = zoom === undefined ? this._zoom : zoom;\r\n\t\treturn this.options.crs.latLngToPoint(toLatLng(latlng), zoom);\r\n\t},\r\n\r\n\t// @method unproject(point: Point, zoom: Number): LatLng\r\n\t// Inverse of [`project`](#map-project).\r\n\tunproject: function (point, zoom) {\r\n\t\tzoom = zoom === undefined ? this._zoom : zoom;\r\n\t\treturn this.options.crs.pointToLatLng(toPoint(point), zoom);\r\n\t},\r\n\r\n\t// @method layerPointToLatLng(point: Point): LatLng\r\n\t// Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),\r\n\t// returns the corresponding geographical coordinate (for the current zoom level).\r\n\tlayerPointToLatLng: function (point) {\r\n\t\tvar projectedPoint = toPoint(point).add(this.getPixelOrigin());\r\n\t\treturn this.unproject(projectedPoint);\r\n\t},\r\n\r\n\t// @method latLngToLayerPoint(latlng: LatLng): Point\r\n\t// Given a geographical coordinate, returns the corresponding pixel coordinate\r\n\t// relative to the [origin pixel](#map-getpixelorigin).\r\n\tlatLngToLayerPoint: function (latlng) {\r\n\t\tvar projectedPoint = this.project(toLatLng(latlng))._round();\r\n\t\treturn projectedPoint._subtract(this.getPixelOrigin());\r\n\t},\r\n\r\n\t// @method wrapLatLng(latlng: LatLng): LatLng\r\n\t// Returns a `LatLng` where `lat` and `lng` has been wrapped according to the\r\n\t// map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the\r\n\t// CRS's bounds.\r\n\t// By default this means longitude is wrapped around the dateline so its\r\n\t// value is between -180 and +180 degrees.\r\n\twrapLatLng: function (latlng) {\r\n\t\treturn this.options.crs.wrapLatLng(toLatLng(latlng));\r\n\t},\r\n\r\n\t// @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds\r\n\t// Returns a `LatLngBounds` with the same size as the given one, ensuring that\r\n\t// its center is within the CRS's bounds.\r\n\t// By default this means the center longitude is wrapped around the dateline so its\r\n\t// value is between -180 and +180 degrees, and the majority of the bounds\r\n\t// overlaps the CRS's bounds.\r\n\twrapLatLngBounds: function (latlng) {\r\n\t\treturn this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));\r\n\t},\r\n\r\n\t// @method distance(latlng1: LatLng, latlng2: LatLng): Number\r\n\t// Returns the distance between two geographical coordinates according to\r\n\t// the map's CRS. By default this measures distance in meters.\r\n\tdistance: function (latlng1, latlng2) {\r\n\t\treturn this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));\r\n\t},\r\n\r\n\t// @method containerPointToLayerPoint(point: Point): Point\r\n\t// Given a pixel coordinate relative to the map container, returns the corresponding\r\n\t// pixel coordinate relative to the [origin pixel](#map-getpixelorigin).\r\n\tcontainerPointToLayerPoint: function (point) { // (Point)\r\n\t\treturn toPoint(point).subtract(this._getMapPanePos());\r\n\t},\r\n\r\n\t// @method layerPointToContainerPoint(point: Point): Point\r\n\t// Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),\r\n\t// returns the corresponding pixel coordinate relative to the map container.\r\n\tlayerPointToContainerPoint: function (point) { // (Point)\r\n\t\treturn toPoint(point).add(this._getMapPanePos());\r\n\t},\r\n\r\n\t// @method containerPointToLatLng(point: Point): LatLng\r\n\t// Given a pixel coordinate relative to the map container, returns\r\n\t// the corresponding geographical coordinate (for the current zoom level).\r\n\tcontainerPointToLatLng: function (point) {\r\n\t\tvar layerPoint = this.containerPointToLayerPoint(toPoint(point));\r\n\t\treturn this.layerPointToLatLng(layerPoint);\r\n\t},\r\n\r\n\t// @method latLngToContainerPoint(latlng: LatLng): Point\r\n\t// Given a geographical coordinate, returns the corresponding pixel coordinate\r\n\t// relative to the map container.\r\n\tlatLngToContainerPoint: function (latlng) {\r\n\t\treturn this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));\r\n\t},\r\n\r\n\t// @method mouseEventToContainerPoint(ev: MouseEvent): Point\r\n\t// Given a MouseEvent object, returns the pixel coordinate relative to the\r\n\t// map container where the event took place.\r\n\tmouseEventToContainerPoint: function (e) {\r\n\t\treturn getMousePosition(e, this._container);\r\n\t},\r\n\r\n\t// @method mouseEventToLayerPoint(ev: MouseEvent): Point\r\n\t// Given a MouseEvent object, returns the pixel coordinate relative to\r\n\t// the [origin pixel](#map-getpixelorigin) where the event took place.\r\n\tmouseEventToLayerPoint: function (e) {\r\n\t\treturn this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));\r\n\t},\r\n\r\n\t// @method mouseEventToLatLng(ev: MouseEvent): LatLng\r\n\t// Given a MouseEvent object, returns geographical coordinate where the\r\n\t// event took place.\r\n\tmouseEventToLatLng: function (e) { // (MouseEvent)\r\n\t\treturn this.layerPointToLatLng(this.mouseEventToLayerPoint(e));\r\n\t},\r\n\r\n\r\n\t// map initialization methods\r\n\r\n\t_initContainer: function (id) {\r\n\t\tvar container = this._container = get(id);\r\n\r\n\t\tif (!container) {\r\n\t\t\tthrow new Error('Map container not found.');\r\n\t\t} else if (container._leaflet_id) {\r\n\t\t\tthrow new Error('Map container is already initialized.');\r\n\t\t}\r\n\r\n\t\ton(container, 'scroll', this._onScroll, this);\r\n\t\tthis._containerId = stamp(container);\r\n\t},\r\n\r\n\t_initLayout: function () {\r\n\t\tvar container = this._container;\r\n\r\n\t\tthis._fadeAnimated = this.options.fadeAnimation && any3d;\r\n\r\n\t\taddClass(container, 'leaflet-container' +\r\n\t\t\t(touch ? ' leaflet-touch' : '') +\r\n\t\t\t(retina ? ' leaflet-retina' : '') +\r\n\t\t\t(ielt9 ? ' leaflet-oldie' : '') +\r\n\t\t\t(safari ? ' leaflet-safari' : '') +\r\n\t\t\t(this._fadeAnimated ? ' leaflet-fade-anim' : ''));\r\n\r\n\t\tvar position = getStyle(container, 'position');\r\n\r\n\t\tif (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {\r\n\t\t\tcontainer.style.position = 'relative';\r\n\t\t}\r\n\r\n\t\tthis._initPanes();\r\n\r\n\t\tif (this._initControlPos) {\r\n\t\t\tthis._initControlPos();\r\n\t\t}\r\n\t},\r\n\r\n\t_initPanes: function () {\r\n\t\tvar panes = this._panes = {};\r\n\t\tthis._paneRenderers = {};\r\n\r\n\t\t// @section\r\n\t\t//\r\n\t\t// Panes are DOM elements used to control the ordering of layers on the map. You\r\n\t\t// can access panes with [`map.getPane`](#map-getpane) or\r\n\t\t// [`map.getPanes`](#map-getpanes) methods. New panes can be created with the\r\n\t\t// [`map.createPane`](#map-createpane) method.\r\n\t\t//\r\n\t\t// Every map has the following default panes that differ only in zIndex.\r\n\t\t//\r\n\t\t// @pane mapPane: HTMLElement = 'auto'\r\n\t\t// Pane that contains all other map panes\r\n\r\n\t\tthis._mapPane = this.createPane('mapPane', this._container);\r\n\t\tsetPosition(this._mapPane, new Point(0, 0));\r\n\r\n\t\t// @pane tilePane: HTMLElement = 200\r\n\t\t// Pane for `GridLayer`s and `TileLayer`s\r\n\t\tthis.createPane('tilePane');\r\n\t\t// @pane overlayPane: HTMLElement = 400\r\n\t\t// Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s\r\n\t\tthis.createPane('shadowPane');\r\n\t\t// @pane shadowPane: HTMLElement = 500\r\n\t\t// Pane for overlay shadows (e.g. `Marker` shadows)\r\n\t\tthis.createPane('overlayPane');\r\n\t\t// @pane markerPane: HTMLElement = 600\r\n\t\t// Pane for `Icon`s of `Marker`s\r\n\t\tthis.createPane('markerPane');\r\n\t\t// @pane tooltipPane: HTMLElement = 650\r\n\t\t// Pane for `Tooltip`s.\r\n\t\tthis.createPane('tooltipPane');\r\n\t\t// @pane popupPane: HTMLElement = 700\r\n\t\t// Pane for `Popup`s.\r\n\t\tthis.createPane('popupPane');\r\n\r\n\t\tif (!this.options.markerZoomAnimation) {\r\n\t\t\taddClass(panes.markerPane, 'leaflet-zoom-hide');\r\n\t\t\taddClass(panes.shadowPane, 'leaflet-zoom-hide');\r\n\t\t}\r\n\t},\r\n\r\n\r\n\t// private methods that modify map state\r\n\r\n\t// @section Map state change events\r\n\t_resetView: function (center, zoom) {\r\n\t\tsetPosition(this._mapPane, new Point(0, 0));\r\n\r\n\t\tvar loading = !this._loaded;\r\n\t\tthis._loaded = true;\r\n\t\tzoom = this._limitZoom(zoom);\r\n\r\n\t\tthis.fire('viewprereset');\r\n\r\n\t\tvar zoomChanged = this._zoom !== zoom;\r\n\t\tthis\r\n\t\t\t._moveStart(zoomChanged, false)\r\n\t\t\t._move(center, zoom)\r\n\t\t\t._moveEnd(zoomChanged);\r\n\r\n\t\t// @event viewreset: Event\r\n\t\t// Fired when the map needs to redraw its content (this usually happens\r\n\t\t// on map zoom or load). Very useful for creating custom overlays.\r\n\t\tthis.fire('viewreset');\r\n\r\n\t\t// @event load: Event\r\n\t\t// Fired when the map is initialized (when its center and zoom are set\r\n\t\t// for the first time).\r\n\t\tif (loading) {\r\n\t\t\tthis.fire('load');\r\n\t\t}\r\n\t},\r\n\r\n\t_moveStart: function (zoomChanged, noMoveStart) {\r\n\t\t// @event zoomstart: Event\r\n\t\t// Fired when the map zoom is about to change (e.g. before zoom animation).\r\n\t\t// @event movestart: Event\r\n\t\t// Fired when the view of the map starts changing (e.g. user starts dragging the map).\r\n\t\tif (zoomChanged) {\r\n\t\t\tthis.fire('zoomstart');\r\n\t\t}\r\n\t\tif (!noMoveStart) {\r\n\t\t\tthis.fire('movestart');\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_move: function (center, zoom, data) {\r\n\t\tif (zoom === undefined) {\r\n\t\t\tzoom = this._zoom;\r\n\t\t}\r\n\t\tvar zoomChanged = this._zoom !== zoom;\r\n\r\n\t\tthis._zoom = zoom;\r\n\t\tthis._lastCenter = center;\r\n\t\tthis._pixelOrigin = this._getNewPixelOrigin(center);\r\n\r\n\t\t// @event zoom: Event\r\n\t\t// Fired repeatedly during any change in zoom level, including zoom\r\n\t\t// and fly animations.\r\n\t\tif (zoomChanged || (data && data.pinch)) {\t// Always fire 'zoom' if pinching because #3530\r\n\t\t\tthis.fire('zoom', data);\r\n\t\t}\r\n\r\n\t\t// @event move: Event\r\n\t\t// Fired repeatedly during any movement of the map, including pan and\r\n\t\t// fly animations.\r\n\t\treturn this.fire('move', data);\r\n\t},\r\n\r\n\t_moveEnd: function (zoomChanged) {\r\n\t\t// @event zoomend: Event\r\n\t\t// Fired when the map has changed, after any animations.\r\n\t\tif (zoomChanged) {\r\n\t\t\tthis.fire('zoomend');\r\n\t\t}\r\n\r\n\t\t// @event moveend: Event\r\n\t\t// Fired when the center of the map stops changing (e.g. user stopped\r\n\t\t// dragging the map).\r\n\t\treturn this.fire('moveend');\r\n\t},\r\n\r\n\t_stop: function () {\r\n\t\tcancelAnimFrame(this._flyToFrame);\r\n\t\tif (this._panAnim) {\r\n\t\t\tthis._panAnim.stop();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_rawPanBy: function (offset) {\r\n\t\tsetPosition(this._mapPane, this._getMapPanePos().subtract(offset));\r\n\t},\r\n\r\n\t_getZoomSpan: function () {\r\n\t\treturn this.getMaxZoom() - this.getMinZoom();\r\n\t},\r\n\r\n\t_panInsideMaxBounds: function () {\r\n\t\tif (!this._enforcingBounds) {\r\n\t\t\tthis.panInsideBounds(this.options.maxBounds);\r\n\t\t}\r\n\t},\r\n\r\n\t_checkIfLoaded: function () {\r\n\t\tif (!this._loaded) {\r\n\t\t\tthrow new Error('Set map center and zoom first.');\r\n\t\t}\r\n\t},\r\n\r\n\t// DOM event handling\r\n\r\n\t// @section Interaction events\r\n\t_initEvents: function (remove$$1) {\r\n\t\tthis._targets = {};\r\n\t\tthis._targets[stamp(this._container)] = this;\r\n\r\n\t\tvar onOff = remove$$1 ? off : on;\r\n\r\n\t\t// @event click: MouseEvent\r\n\t\t// Fired when the user clicks (or taps) the map.\r\n\t\t// @event dblclick: MouseEvent\r\n\t\t// Fired when the user double-clicks (or double-taps) the map.\r\n\t\t// @event mousedown: MouseEvent\r\n\t\t// Fired when the user pushes the mouse button on the map.\r\n\t\t// @event mouseup: MouseEvent\r\n\t\t// Fired when the user releases the mouse button on the map.\r\n\t\t// @event mouseover: MouseEvent\r\n\t\t// Fired when the mouse enters the map.\r\n\t\t// @event mouseout: MouseEvent\r\n\t\t// Fired when the mouse leaves the map.\r\n\t\t// @event mousemove: MouseEvent\r\n\t\t// Fired while the mouse moves over the map.\r\n\t\t// @event contextmenu: MouseEvent\r\n\t\t// Fired when the user pushes the right mouse button on the map, prevents\r\n\t\t// default browser context menu from showing if there are listeners on\r\n\t\t// this event. Also fired on mobile when the user holds a single touch\r\n\t\t// for a second (also called long press).\r\n\t\t// @event keypress: KeyboardEvent\r\n\t\t// Fired when the user presses a key from the keyboard that produces a character value while the map is focused.\r\n\t\t// @event keydown: KeyboardEvent\r\n\t\t// Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event,\r\n\t\t// the `keydown` event is fired for keys that produce a character value and for keys\r\n\t\t// that do not produce a character value.\r\n\t\t// @event keyup: KeyboardEvent\r\n\t\t// Fired when the user releases a key from the keyboard while the map is focused.\r\n\t\tonOff(this._container, 'click dblclick mousedown mouseup ' +\r\n\t\t\t'mouseover mouseout mousemove contextmenu keypress keydown keyup', this._handleDOMEvent, this);\r\n\r\n\t\tif (this.options.trackResize) {\r\n\t\t\tonOff(window, 'resize', this._onResize, this);\r\n\t\t}\r\n\r\n\t\tif (any3d && this.options.transform3DLimit) {\r\n\t\t\t(remove$$1 ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);\r\n\t\t}\r\n\t},\r\n\r\n\t_onResize: function () {\r\n\t\tcancelAnimFrame(this._resizeRequest);\r\n\t\tthis._resizeRequest = requestAnimFrame(\r\n\t\t function () { this.invalidateSize({debounceMoveend: true}); }, this);\r\n\t},\r\n\r\n\t_onScroll: function () {\r\n\t\tthis._container.scrollTop = 0;\r\n\t\tthis._container.scrollLeft = 0;\r\n\t},\r\n\r\n\t_onMoveEnd: function () {\r\n\t\tvar pos = this._getMapPanePos();\r\n\t\tif (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {\r\n\t\t\t// https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have\r\n\t\t\t// a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/\r\n\t\t\tthis._resetView(this.getCenter(), this.getZoom());\r\n\t\t}\r\n\t},\r\n\r\n\t_findEventTargets: function (e, type) {\r\n\t\tvar targets = [],\r\n\t\t target,\r\n\t\t isHover = type === 'mouseout' || type === 'mouseover',\r\n\t\t src = e.target || e.srcElement,\r\n\t\t dragging = false;\r\n\r\n\t\twhile (src) {\r\n\t\t\ttarget = this._targets[stamp(src)];\r\n\t\t\tif (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {\r\n\t\t\t\t// Prevent firing click after you just dragged an object.\r\n\t\t\t\tdragging = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (target && target.listens(type, true)) {\r\n\t\t\t\tif (isHover && !isExternalTarget(src, e)) { break; }\r\n\t\t\t\ttargets.push(target);\r\n\t\t\t\tif (isHover) { break; }\r\n\t\t\t}\r\n\t\t\tif (src === this._container) { break; }\r\n\t\t\tsrc = src.parentNode;\r\n\t\t}\r\n\t\tif (!targets.length && !dragging && !isHover && isExternalTarget(src, e)) {\r\n\t\t\ttargets = [this];\r\n\t\t}\r\n\t\treturn targets;\r\n\t},\r\n\r\n\t_handleDOMEvent: function (e) {\r\n\t\tif (!this._loaded || skipped(e)) { return; }\r\n\r\n\t\tvar type = e.type;\r\n\r\n\t\tif (type === 'mousedown' || type === 'keypress' || type === 'keyup' || type === 'keydown') {\r\n\t\t\t// prevents outline when clicking on keyboard-focusable element\r\n\t\t\tpreventOutline(e.target || e.srcElement);\r\n\t\t}\r\n\r\n\t\tthis._fireDOMEvent(e, type);\r\n\t},\r\n\r\n\t_mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],\r\n\r\n\t_fireDOMEvent: function (e, type, targets) {\r\n\r\n\t\tif (e.type === 'click') {\r\n\t\t\t// Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).\r\n\t\t\t// @event preclick: MouseEvent\r\n\t\t\t// Fired before mouse click on the map (sometimes useful when you\r\n\t\t\t// want something to happen on click before any existing click\r\n\t\t\t// handlers start running).\r\n\t\t\tvar synth = extend({}, e);\r\n\t\t\tsynth.type = 'preclick';\r\n\t\t\tthis._fireDOMEvent(synth, synth.type, targets);\r\n\t\t}\r\n\r\n\t\tif (e._stopped) { return; }\r\n\r\n\t\t// Find the layer the event is propagating from and its parents.\r\n\t\ttargets = (targets || []).concat(this._findEventTargets(e, type));\r\n\r\n\t\tif (!targets.length) { return; }\r\n\r\n\t\tvar target = targets[0];\r\n\t\tif (type === 'contextmenu' && target.listens(type, true)) {\r\n\t\t\tpreventDefault(e);\r\n\t\t}\r\n\r\n\t\tvar data = {\r\n\t\t\toriginalEvent: e\r\n\t\t};\r\n\r\n\t\tif (e.type !== 'keypress' && e.type !== 'keydown' && e.type !== 'keyup') {\r\n\t\t\tvar isMarker = target.getLatLng && (!target._radius || target._radius <= 10);\r\n\t\t\tdata.containerPoint = isMarker ?\r\n\t\t\t\tthis.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);\r\n\t\t\tdata.layerPoint = this.containerPointToLayerPoint(data.containerPoint);\r\n\t\t\tdata.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);\r\n\t\t}\r\n\r\n\t\tfor (var i = 0; i < targets.length; i++) {\r\n\t\t\ttargets[i].fire(type, data, true);\r\n\t\t\tif (data.originalEvent._stopped ||\r\n\t\t\t\t(targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }\r\n\t\t}\r\n\t},\r\n\r\n\t_draggableMoved: function (obj) {\r\n\t\tobj = obj.dragging && obj.dragging.enabled() ? obj : this;\r\n\t\treturn (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());\r\n\t},\r\n\r\n\t_clearHandlers: function () {\r\n\t\tfor (var i = 0, len = this._handlers.length; i < len; i++) {\r\n\t\t\tthis._handlers[i].disable();\r\n\t\t}\r\n\t},\r\n\r\n\t// @section Other Methods\r\n\r\n\t// @method whenReady(fn: Function, context?: Object): this\r\n\t// Runs the given function `fn` when the map gets initialized with\r\n\t// a view (center and zoom) and at least one layer, or immediately\r\n\t// if it's already initialized, optionally passing a function context.\r\n\twhenReady: function (callback, context) {\r\n\t\tif (this._loaded) {\r\n\t\t\tcallback.call(context || this, {target: this});\r\n\t\t} else {\r\n\t\t\tthis.on('load', callback, context);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\r\n\t// private methods for getting map state\r\n\r\n\t_getMapPanePos: function () {\r\n\t\treturn getPosition(this._mapPane) || new Point(0, 0);\r\n\t},\r\n\r\n\t_moved: function () {\r\n\t\tvar pos = this._getMapPanePos();\r\n\t\treturn pos && !pos.equals([0, 0]);\r\n\t},\r\n\r\n\t_getTopLeftPoint: function (center, zoom) {\r\n\t\tvar pixelOrigin = center && zoom !== undefined ?\r\n\t\t\tthis._getNewPixelOrigin(center, zoom) :\r\n\t\t\tthis.getPixelOrigin();\r\n\t\treturn pixelOrigin.subtract(this._getMapPanePos());\r\n\t},\r\n\r\n\t_getNewPixelOrigin: function (center, zoom) {\r\n\t\tvar viewHalf = this.getSize()._divideBy(2);\r\n\t\treturn this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();\r\n\t},\r\n\r\n\t_latLngToNewLayerPoint: function (latlng, zoom, center) {\r\n\t\tvar topLeft = this._getNewPixelOrigin(center, zoom);\r\n\t\treturn this.project(latlng, zoom)._subtract(topLeft);\r\n\t},\r\n\r\n\t_latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {\r\n\t\tvar topLeft = this._getNewPixelOrigin(center, zoom);\r\n\t\treturn toBounds([\r\n\t\t\tthis.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),\r\n\t\t\tthis.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),\r\n\t\t\tthis.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),\r\n\t\t\tthis.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)\r\n\t\t]);\r\n\t},\r\n\r\n\t// layer point of the current center\r\n\t_getCenterLayerPoint: function () {\r\n\t\treturn this.containerPointToLayerPoint(this.getSize()._divideBy(2));\r\n\t},\r\n\r\n\t// offset of the specified place to the current center in pixels\r\n\t_getCenterOffset: function (latlng) {\r\n\t\treturn this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());\r\n\t},\r\n\r\n\t// adjust center for view to get inside bounds\r\n\t_limitCenter: function (center, zoom, bounds) {\r\n\r\n\t\tif (!bounds) { return center; }\r\n\r\n\t\tvar centerPoint = this.project(center, zoom),\r\n\t\t viewHalf = this.getSize().divideBy(2),\r\n\t\t viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),\r\n\t\t offset = this._getBoundsOffset(viewBounds, bounds, zoom);\r\n\r\n\t\t// If offset is less than a pixel, ignore.\r\n\t\t// This prevents unstable projections from getting into\r\n\t\t// an infinite loop of tiny offsets.\r\n\t\tif (offset.round().equals([0, 0])) {\r\n\t\t\treturn center;\r\n\t\t}\r\n\r\n\t\treturn this.unproject(centerPoint.add(offset), zoom);\r\n\t},\r\n\r\n\t// adjust offset for view to get inside bounds\r\n\t_limitOffset: function (offset, bounds) {\r\n\t\tif (!bounds) { return offset; }\r\n\r\n\t\tvar viewBounds = this.getPixelBounds(),\r\n\t\t newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));\r\n\r\n\t\treturn offset.add(this._getBoundsOffset(newBounds, bounds));\r\n\t},\r\n\r\n\t// returns offset needed for pxBounds to get inside maxBounds at a specified zoom\r\n\t_getBoundsOffset: function (pxBounds, maxBounds, zoom) {\r\n\t\tvar projectedMaxBounds = toBounds(\r\n\t\t this.project(maxBounds.getNorthEast(), zoom),\r\n\t\t this.project(maxBounds.getSouthWest(), zoom)\r\n\t\t ),\r\n\t\t minOffset = projectedMaxBounds.min.subtract(pxBounds.min),\r\n\t\t maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),\r\n\r\n\t\t dx = this._rebound(minOffset.x, -maxOffset.x),\r\n\t\t dy = this._rebound(minOffset.y, -maxOffset.y);\r\n\r\n\t\treturn new Point(dx, dy);\r\n\t},\r\n\r\n\t_rebound: function (left, right) {\r\n\t\treturn left + right > 0 ?\r\n\t\t\tMath.round(left - right) / 2 :\r\n\t\t\tMath.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));\r\n\t},\r\n\r\n\t_limitZoom: function (zoom) {\r\n\t\tvar min = this.getMinZoom(),\r\n\t\t max = this.getMaxZoom(),\r\n\t\t snap = any3d ? this.options.zoomSnap : 1;\r\n\t\tif (snap) {\r\n\t\t\tzoom = Math.round(zoom / snap) * snap;\r\n\t\t}\r\n\t\treturn Math.max(min, Math.min(max, zoom));\r\n\t},\r\n\r\n\t_onPanTransitionStep: function () {\r\n\t\tthis.fire('move');\r\n\t},\r\n\r\n\t_onPanTransitionEnd: function () {\r\n\t\tremoveClass(this._mapPane, 'leaflet-pan-anim');\r\n\t\tthis.fire('moveend');\r\n\t},\r\n\r\n\t_tryAnimatedPan: function (center, options) {\r\n\t\t// difference between the new and current centers in pixels\r\n\t\tvar offset = this._getCenterOffset(center)._trunc();\r\n\r\n\t\t// don't animate too far unless animate: true specified in options\r\n\t\tif ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }\r\n\r\n\t\tthis.panBy(offset, options);\r\n\r\n\t\treturn true;\r\n\t},\r\n\r\n\t_createAnimProxy: function () {\r\n\r\n\t\tvar proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');\r\n\t\tthis._panes.mapPane.appendChild(proxy);\r\n\r\n\t\tthis.on('zoomanim', function (e) {\r\n\t\t\tvar prop = TRANSFORM,\r\n\t\t\t transform = this._proxy.style[prop];\r\n\r\n\t\t\tsetTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));\r\n\r\n\t\t\t// workaround for case when transform is the same and so transitionend event is not fired\r\n\t\t\tif (transform === this._proxy.style[prop] && this._animatingZoom) {\r\n\t\t\t\tthis._onZoomTransitionEnd();\r\n\t\t\t}\r\n\t\t}, this);\r\n\r\n\t\tthis.on('load moveend', function () {\r\n\t\t\tvar c = this.getCenter(),\r\n\t\t\t z = this.getZoom();\r\n\t\t\tsetTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));\r\n\t\t}, this);\r\n\r\n\t\tthis._on('unload', this._destroyAnimProxy, this);\r\n\t},\r\n\r\n\t_destroyAnimProxy: function () {\r\n\t\tremove(this._proxy);\r\n\t\tdelete this._proxy;\r\n\t},\r\n\r\n\t_catchTransitionEnd: function (e) {\r\n\t\tif (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {\r\n\t\t\tthis._onZoomTransitionEnd();\r\n\t\t}\r\n\t},\r\n\r\n\t_nothingToAnimate: function () {\r\n\t\treturn !this._container.getElementsByClassName('leaflet-zoom-animated').length;\r\n\t},\r\n\r\n\t_tryAnimatedZoom: function (center, zoom, options) {\r\n\r\n\t\tif (this._animatingZoom) { return true; }\r\n\r\n\t\toptions = options || {};\r\n\r\n\t\t// don't animate if disabled, not supported or zoom difference is too large\r\n\t\tif (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||\r\n\t\t Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }\r\n\r\n\t\t// offset is the pixel coords of the zoom origin relative to the current center\r\n\t\tvar scale = this.getZoomScale(zoom),\r\n\t\t offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);\r\n\r\n\t\t// don't animate if the zoom origin isn't within one screen from the current center, unless forced\r\n\t\tif (options.animate !== true && !this.getSize().contains(offset)) { return false; }\r\n\r\n\t\trequestAnimFrame(function () {\r\n\t\t\tthis\r\n\t\t\t ._moveStart(true, false)\r\n\t\t\t ._animateZoom(center, zoom, true);\r\n\t\t}, this);\r\n\r\n\t\treturn true;\r\n\t},\r\n\r\n\t_animateZoom: function (center, zoom, startAnim, noUpdate) {\r\n\t\tif (!this._mapPane) { return; }\r\n\r\n\t\tif (startAnim) {\r\n\t\t\tthis._animatingZoom = true;\r\n\r\n\t\t\t// remember what center/zoom to set after animation\r\n\t\t\tthis._animateToCenter = center;\r\n\t\t\tthis._animateToZoom = zoom;\r\n\r\n\t\t\taddClass(this._mapPane, 'leaflet-zoom-anim');\r\n\t\t}\r\n\r\n\t\t// @event zoomanim: ZoomAnimEvent\r\n\t\t// Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.\r\n\t\tthis.fire('zoomanim', {\r\n\t\t\tcenter: center,\r\n\t\t\tzoom: zoom,\r\n\t\t\tnoUpdate: noUpdate\r\n\t\t});\r\n\r\n\t\t// Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693\r\n\t\tsetTimeout(bind(this._onZoomTransitionEnd, this), 250);\r\n\t},\r\n\r\n\t_onZoomTransitionEnd: function () {\r\n\t\tif (!this._animatingZoom) { return; }\r\n\r\n\t\tif (this._mapPane) {\r\n\t\t\tremoveClass(this._mapPane, 'leaflet-zoom-anim');\r\n\t\t}\r\n\r\n\t\tthis._animatingZoom = false;\r\n\r\n\t\tthis._move(this._animateToCenter, this._animateToZoom);\r\n\r\n\t\t// This anim frame should prevent an obscure iOS webkit tile loading race condition.\r\n\t\trequestAnimFrame(function () {\r\n\t\t\tthis._moveEnd(true);\r\n\t\t}, this);\r\n\t}\r\n});\r\n\r\n// @section\r\n\r\n// @factory L.map(id: String, options?: Map options)\r\n// Instantiates a map object given the DOM ID of a `
    ` element\r\n// and optionally an object literal with `Map options`.\r\n//\r\n// @alternative\r\n// @factory L.map(el: HTMLElement, options?: Map options)\r\n// Instantiates a map object given an instance of a `
    ` HTML element\r\n// and optionally an object literal with `Map options`.\r\nfunction createMap(id, options) {\r\n\treturn new Map(id, options);\r\n}\n\n/*\r\n * @class Control\r\n * @aka L.Control\r\n * @inherits Class\r\n *\r\n * L.Control is a base class for implementing map controls. Handles positioning.\r\n * All other controls extend from this class.\r\n */\r\n\r\nvar Control = Class.extend({\r\n\t// @section\r\n\t// @aka Control options\r\n\toptions: {\r\n\t\t// @option position: String = 'topright'\r\n\t\t// The position of the control (one of the map corners). Possible values are `'topleft'`,\r\n\t\t// `'topright'`, `'bottomleft'` or `'bottomright'`\r\n\t\tposition: 'topright'\r\n\t},\r\n\r\n\tinitialize: function (options) {\r\n\t\tsetOptions(this, options);\r\n\t},\r\n\r\n\t/* @section\r\n\t * Classes extending L.Control will inherit the following methods:\r\n\t *\r\n\t * @method getPosition: string\r\n\t * Returns the position of the control.\r\n\t */\r\n\tgetPosition: function () {\r\n\t\treturn this.options.position;\r\n\t},\r\n\r\n\t// @method setPosition(position: string): this\r\n\t// Sets the position of the control.\r\n\tsetPosition: function (position) {\r\n\t\tvar map = this._map;\r\n\r\n\t\tif (map) {\r\n\t\t\tmap.removeControl(this);\r\n\t\t}\r\n\r\n\t\tthis.options.position = position;\r\n\r\n\t\tif (map) {\r\n\t\t\tmap.addControl(this);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getContainer: HTMLElement\r\n\t// Returns the HTMLElement that contains the control.\r\n\tgetContainer: function () {\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\t// @method addTo(map: Map): this\r\n\t// Adds the control to the given map.\r\n\taddTo: function (map) {\r\n\t\tthis.remove();\r\n\t\tthis._map = map;\r\n\r\n\t\tvar container = this._container = this.onAdd(map),\r\n\t\t pos = this.getPosition(),\r\n\t\t corner = map._controlCorners[pos];\r\n\r\n\t\taddClass(container, 'leaflet-control');\r\n\r\n\t\tif (pos.indexOf('bottom') !== -1) {\r\n\t\t\tcorner.insertBefore(container, corner.firstChild);\r\n\t\t} else {\r\n\t\t\tcorner.appendChild(container);\r\n\t\t}\r\n\r\n\t\tthis._map.on('unload', this.remove, this);\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method remove: this\r\n\t// Removes the control from the map it is currently active on.\r\n\tremove: function () {\r\n\t\tif (!this._map) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tremove(this._container);\r\n\r\n\t\tif (this.onRemove) {\r\n\t\t\tthis.onRemove(this._map);\r\n\t\t}\r\n\r\n\t\tthis._map.off('unload', this.remove, this);\r\n\t\tthis._map = null;\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_refocusOnMap: function (e) {\r\n\t\t// if map exists and event is not a keyboard event\r\n\t\tif (this._map && e && e.screenX > 0 && e.screenY > 0) {\r\n\t\t\tthis._map.getContainer().focus();\r\n\t\t}\r\n\t}\r\n});\r\n\r\nvar control = function (options) {\r\n\treturn new Control(options);\r\n};\r\n\r\n/* @section Extension methods\r\n * @uninheritable\r\n *\r\n * Every control should extend from `L.Control` and (re-)implement the following methods.\r\n *\r\n * @method onAdd(map: Map): HTMLElement\r\n * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).\r\n *\r\n * @method onRemove(map: Map)\r\n * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).\r\n */\r\n\r\n/* @namespace Map\r\n * @section Methods for Layers and Controls\r\n */\r\nMap.include({\r\n\t// @method addControl(control: Control): this\r\n\t// Adds the given control to the map\r\n\taddControl: function (control) {\r\n\t\tcontrol.addTo(this);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeControl(control: Control): this\r\n\t// Removes the given control from the map\r\n\tremoveControl: function (control) {\r\n\t\tcontrol.remove();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_initControlPos: function () {\r\n\t\tvar corners = this._controlCorners = {},\r\n\t\t l = 'leaflet-',\r\n\t\t container = this._controlContainer =\r\n\t\t create$1('div', l + 'control-container', this._container);\r\n\r\n\t\tfunction createCorner(vSide, hSide) {\r\n\t\t\tvar className = l + vSide + ' ' + l + hSide;\r\n\r\n\t\t\tcorners[vSide + hSide] = create$1('div', className, container);\r\n\t\t}\r\n\r\n\t\tcreateCorner('top', 'left');\r\n\t\tcreateCorner('top', 'right');\r\n\t\tcreateCorner('bottom', 'left');\r\n\t\tcreateCorner('bottom', 'right');\r\n\t},\r\n\r\n\t_clearControlPos: function () {\r\n\t\tfor (var i in this._controlCorners) {\r\n\t\t\tremove(this._controlCorners[i]);\r\n\t\t}\r\n\t\tremove(this._controlContainer);\r\n\t\tdelete this._controlCorners;\r\n\t\tdelete this._controlContainer;\r\n\t}\r\n});\n\n/*\r\n * @class Control.Layers\r\n * @aka L.Control.Layers\r\n * @inherits Control\r\n *\r\n * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](http://leafletjs.com/examples/layers-control/)). Extends `Control`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var baseLayers = {\r\n * \t\"Mapbox\": mapbox,\r\n * \t\"OpenStreetMap\": osm\r\n * };\r\n *\r\n * var overlays = {\r\n * \t\"Marker\": marker,\r\n * \t\"Roads\": roadsLayer\r\n * };\r\n *\r\n * L.control.layers(baseLayers, overlays).addTo(map);\r\n * ```\r\n *\r\n * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:\r\n *\r\n * ```js\r\n * {\r\n * \"\": layer1,\r\n * \"\": layer2\r\n * }\r\n * ```\r\n *\r\n * The layer names can contain HTML, which allows you to add additional styling to the items:\r\n *\r\n * ```js\r\n * {\" My Layer\": myLayer}\r\n * ```\r\n */\r\n\r\nvar Layers = Control.extend({\r\n\t// @section\r\n\t// @aka Control.Layers options\r\n\toptions: {\r\n\t\t// @option collapsed: Boolean = true\r\n\t\t// If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.\r\n\t\tcollapsed: true,\r\n\t\tposition: 'topright',\r\n\r\n\t\t// @option autoZIndex: Boolean = true\r\n\t\t// If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.\r\n\t\tautoZIndex: true,\r\n\r\n\t\t// @option hideSingleBase: Boolean = false\r\n\t\t// If `true`, the base layers in the control will be hidden when there is only one.\r\n\t\thideSingleBase: false,\r\n\r\n\t\t// @option sortLayers: Boolean = false\r\n\t\t// Whether to sort the layers. When `false`, layers will keep the order\r\n\t\t// in which they were added to the control.\r\n\t\tsortLayers: false,\r\n\r\n\t\t// @option sortFunction: Function = *\r\n\t\t// A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)\r\n\t\t// that will be used for sorting the layers, when `sortLayers` is `true`.\r\n\t\t// The function receives both the `L.Layer` instances and their names, as in\r\n\t\t// `sortFunction(layerA, layerB, nameA, nameB)`.\r\n\t\t// By default, it sorts layers alphabetically by their name.\r\n\t\tsortFunction: function (layerA, layerB, nameA, nameB) {\r\n\t\t\treturn nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);\r\n\t\t}\r\n\t},\r\n\r\n\tinitialize: function (baseLayers, overlays, options) {\r\n\t\tsetOptions(this, options);\r\n\r\n\t\tthis._layerControlInputs = [];\r\n\t\tthis._layers = [];\r\n\t\tthis._lastZIndex = 0;\r\n\t\tthis._handlingClick = false;\r\n\r\n\t\tfor (var i in baseLayers) {\r\n\t\t\tthis._addLayer(baseLayers[i], i);\r\n\t\t}\r\n\r\n\t\tfor (i in overlays) {\r\n\t\t\tthis._addLayer(overlays[i], i, true);\r\n\t\t}\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis._initLayout();\r\n\t\tthis._update();\r\n\r\n\t\tthis._map = map;\r\n\t\tmap.on('zoomend', this._checkDisabledLayers, this);\r\n\r\n\t\tfor (var i = 0; i < this._layers.length; i++) {\r\n\t\t\tthis._layers[i].layer.on('add remove', this._onLayerChange, this);\r\n\t\t}\r\n\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\taddTo: function (map) {\r\n\t\tControl.prototype.addTo.call(this, map);\r\n\t\t// Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.\r\n\t\treturn this._expandIfNotCollapsed();\r\n\t},\r\n\r\n\tonRemove: function () {\r\n\t\tthis._map.off('zoomend', this._checkDisabledLayers, this);\r\n\r\n\t\tfor (var i = 0; i < this._layers.length; i++) {\r\n\t\t\tthis._layers[i].layer.off('add remove', this._onLayerChange, this);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method addBaseLayer(layer: Layer, name: String): this\r\n\t// Adds a base layer (radio button entry) with the given name to the control.\r\n\taddBaseLayer: function (layer, name) {\r\n\t\tthis._addLayer(layer, name);\r\n\t\treturn (this._map) ? this._update() : this;\r\n\t},\r\n\r\n\t// @method addOverlay(layer: Layer, name: String): this\r\n\t// Adds an overlay (checkbox entry) with the given name to the control.\r\n\taddOverlay: function (layer, name) {\r\n\t\tthis._addLayer(layer, name, true);\r\n\t\treturn (this._map) ? this._update() : this;\r\n\t},\r\n\r\n\t// @method removeLayer(layer: Layer): this\r\n\t// Remove the given layer from the control.\r\n\tremoveLayer: function (layer) {\r\n\t\tlayer.off('add remove', this._onLayerChange, this);\r\n\r\n\t\tvar obj = this._getLayer(stamp(layer));\r\n\t\tif (obj) {\r\n\t\t\tthis._layers.splice(this._layers.indexOf(obj), 1);\r\n\t\t}\r\n\t\treturn (this._map) ? this._update() : this;\r\n\t},\r\n\r\n\t// @method expand(): this\r\n\t// Expand the control container if collapsed.\r\n\texpand: function () {\r\n\t\taddClass(this._container, 'leaflet-control-layers-expanded');\r\n\t\tthis._section.style.height = null;\r\n\t\tvar acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);\r\n\t\tif (acceptableHeight < this._section.clientHeight) {\r\n\t\t\taddClass(this._section, 'leaflet-control-layers-scrollbar');\r\n\t\t\tthis._section.style.height = acceptableHeight + 'px';\r\n\t\t} else {\r\n\t\t\tremoveClass(this._section, 'leaflet-control-layers-scrollbar');\r\n\t\t}\r\n\t\tthis._checkDisabledLayers();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method collapse(): this\r\n\t// Collapse the control container if expanded.\r\n\tcollapse: function () {\r\n\t\tremoveClass(this._container, 'leaflet-control-layers-expanded');\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_initLayout: function () {\r\n\t\tvar className = 'leaflet-control-layers',\r\n\t\t container = this._container = create$1('div', className),\r\n\t\t collapsed = this.options.collapsed;\r\n\r\n\t\t// makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released\r\n\t\tcontainer.setAttribute('aria-haspopup', true);\r\n\r\n\t\tdisableClickPropagation(container);\r\n\t\tdisableScrollPropagation(container);\r\n\r\n\t\tvar section = this._section = create$1('section', className + '-list');\r\n\r\n\t\tif (collapsed) {\r\n\t\t\tthis._map.on('click', this.collapse, this);\r\n\r\n\t\t\tif (!android) {\r\n\t\t\t\ton(container, {\r\n\t\t\t\t\tmouseenter: this.expand,\r\n\t\t\t\t\tmouseleave: this.collapse\r\n\t\t\t\t}, this);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvar link = this._layersLink = create$1('a', className + '-toggle', container);\r\n\t\tlink.href = '#';\r\n\t\tlink.title = 'Layers';\r\n\r\n\t\tif (touch) {\r\n\t\t\ton(link, 'click', stop);\r\n\t\t\ton(link, 'click', this.expand, this);\r\n\t\t} else {\r\n\t\t\ton(link, 'focus', this.expand, this);\r\n\t\t}\r\n\r\n\t\tif (!collapsed) {\r\n\t\t\tthis.expand();\r\n\t\t}\r\n\r\n\t\tthis._baseLayersList = create$1('div', className + '-base', section);\r\n\t\tthis._separator = create$1('div', className + '-separator', section);\r\n\t\tthis._overlaysList = create$1('div', className + '-overlays', section);\r\n\r\n\t\tcontainer.appendChild(section);\r\n\t},\r\n\r\n\t_getLayer: function (id) {\r\n\t\tfor (var i = 0; i < this._layers.length; i++) {\r\n\r\n\t\t\tif (this._layers[i] && stamp(this._layers[i].layer) === id) {\r\n\t\t\t\treturn this._layers[i];\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t_addLayer: function (layer, name, overlay) {\r\n\t\tif (this._map) {\r\n\t\t\tlayer.on('add remove', this._onLayerChange, this);\r\n\t\t}\r\n\r\n\t\tthis._layers.push({\r\n\t\t\tlayer: layer,\r\n\t\t\tname: name,\r\n\t\t\toverlay: overlay\r\n\t\t});\r\n\r\n\t\tif (this.options.sortLayers) {\r\n\t\t\tthis._layers.sort(bind(function (a, b) {\r\n\t\t\t\treturn this.options.sortFunction(a.layer, b.layer, a.name, b.name);\r\n\t\t\t}, this));\r\n\t\t}\r\n\r\n\t\tif (this.options.autoZIndex && layer.setZIndex) {\r\n\t\t\tthis._lastZIndex++;\r\n\t\t\tlayer.setZIndex(this._lastZIndex);\r\n\t\t}\r\n\r\n\t\tthis._expandIfNotCollapsed();\r\n\t},\r\n\r\n\t_update: function () {\r\n\t\tif (!this._container) { return this; }\r\n\r\n\t\tempty(this._baseLayersList);\r\n\t\tempty(this._overlaysList);\r\n\r\n\t\tthis._layerControlInputs = [];\r\n\t\tvar baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;\r\n\r\n\t\tfor (i = 0; i < this._layers.length; i++) {\r\n\t\t\tobj = this._layers[i];\r\n\t\t\tthis._addItem(obj);\r\n\t\t\toverlaysPresent = overlaysPresent || obj.overlay;\r\n\t\t\tbaseLayersPresent = baseLayersPresent || !obj.overlay;\r\n\t\t\tbaseLayersCount += !obj.overlay ? 1 : 0;\r\n\t\t}\r\n\r\n\t\t// Hide base layers section if there's only one layer.\r\n\t\tif (this.options.hideSingleBase) {\r\n\t\t\tbaseLayersPresent = baseLayersPresent && baseLayersCount > 1;\r\n\t\t\tthis._baseLayersList.style.display = baseLayersPresent ? '' : 'none';\r\n\t\t}\r\n\r\n\t\tthis._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_onLayerChange: function (e) {\r\n\t\tif (!this._handlingClick) {\r\n\t\t\tthis._update();\r\n\t\t}\r\n\r\n\t\tvar obj = this._getLayer(stamp(e.target));\r\n\r\n\t\t// @namespace Map\r\n\t\t// @section Layer events\r\n\t\t// @event baselayerchange: LayersControlEvent\r\n\t\t// Fired when the base layer is changed through the [layer control](#control-layers).\r\n\t\t// @event overlayadd: LayersControlEvent\r\n\t\t// Fired when an overlay is selected through the [layer control](#control-layers).\r\n\t\t// @event overlayremove: LayersControlEvent\r\n\t\t// Fired when an overlay is deselected through the [layer control](#control-layers).\r\n\t\t// @namespace Control.Layers\r\n\t\tvar type = obj.overlay ?\r\n\t\t\t(e.type === 'add' ? 'overlayadd' : 'overlayremove') :\r\n\t\t\t(e.type === 'add' ? 'baselayerchange' : null);\r\n\r\n\t\tif (type) {\r\n\t\t\tthis._map.fire(type, obj);\r\n\t\t}\r\n\t},\r\n\r\n\t// IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)\r\n\t_createRadioElement: function (name, checked) {\r\n\r\n\t\tvar radioHtml = '';\r\n\r\n\t\tvar radioFragment = document.createElement('div');\r\n\t\tradioFragment.innerHTML = radioHtml;\r\n\r\n\t\treturn radioFragment.firstChild;\r\n\t},\r\n\r\n\t_addItem: function (obj) {\r\n\t\tvar label = document.createElement('label'),\r\n\t\t checked = this._map.hasLayer(obj.layer),\r\n\t\t input;\r\n\r\n\t\tif (obj.overlay) {\r\n\t\t\tinput = document.createElement('input');\r\n\t\t\tinput.type = 'checkbox';\r\n\t\t\tinput.className = 'leaflet-control-layers-selector';\r\n\t\t\tinput.defaultChecked = checked;\r\n\t\t} else {\r\n\t\t\tinput = this._createRadioElement('leaflet-base-layers_' + stamp(this), checked);\r\n\t\t}\r\n\r\n\t\tthis._layerControlInputs.push(input);\r\n\t\tinput.layerId = stamp(obj.layer);\r\n\r\n\t\ton(input, 'click', this._onInputClick, this);\r\n\r\n\t\tvar name = document.createElement('span');\r\n\t\tname.innerHTML = ' ' + obj.name;\r\n\r\n\t\t// Helps from preventing layer control flicker when checkboxes are disabled\r\n\t\t// https://github.com/Leaflet/Leaflet/issues/2771\r\n\t\tvar holder = document.createElement('div');\r\n\r\n\t\tlabel.appendChild(holder);\r\n\t\tholder.appendChild(input);\r\n\t\tholder.appendChild(name);\r\n\r\n\t\tvar container = obj.overlay ? this._overlaysList : this._baseLayersList;\r\n\t\tcontainer.appendChild(label);\r\n\r\n\t\tthis._checkDisabledLayers();\r\n\t\treturn label;\r\n\t},\r\n\r\n\t_onInputClick: function () {\r\n\t\tvar inputs = this._layerControlInputs,\r\n\t\t input, layer;\r\n\t\tvar addedLayers = [],\r\n\t\t removedLayers = [];\r\n\r\n\t\tthis._handlingClick = true;\r\n\r\n\t\tfor (var i = inputs.length - 1; i >= 0; i--) {\r\n\t\t\tinput = inputs[i];\r\n\t\t\tlayer = this._getLayer(input.layerId).layer;\r\n\r\n\t\t\tif (input.checked) {\r\n\t\t\t\taddedLayers.push(layer);\r\n\t\t\t} else if (!input.checked) {\r\n\t\t\t\tremovedLayers.push(layer);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Bugfix issue 2318: Should remove all old layers before readding new ones\r\n\t\tfor (i = 0; i < removedLayers.length; i++) {\r\n\t\t\tif (this._map.hasLayer(removedLayers[i])) {\r\n\t\t\t\tthis._map.removeLayer(removedLayers[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (i = 0; i < addedLayers.length; i++) {\r\n\t\t\tif (!this._map.hasLayer(addedLayers[i])) {\r\n\t\t\t\tthis._map.addLayer(addedLayers[i]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis._handlingClick = false;\r\n\r\n\t\tthis._refocusOnMap();\r\n\t},\r\n\r\n\t_checkDisabledLayers: function () {\r\n\t\tvar inputs = this._layerControlInputs,\r\n\t\t input,\r\n\t\t layer,\r\n\t\t zoom = this._map.getZoom();\r\n\r\n\t\tfor (var i = inputs.length - 1; i >= 0; i--) {\r\n\t\t\tinput = inputs[i];\r\n\t\t\tlayer = this._getLayer(input.layerId).layer;\r\n\t\t\tinput.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||\r\n\t\t\t (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);\r\n\r\n\t\t}\r\n\t},\r\n\r\n\t_expandIfNotCollapsed: function () {\r\n\t\tif (this._map && !this.options.collapsed) {\r\n\t\t\tthis.expand();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_expand: function () {\r\n\t\t// Backward compatibility, remove me in 1.1.\r\n\t\treturn this.expand();\r\n\t},\r\n\r\n\t_collapse: function () {\r\n\t\t// Backward compatibility, remove me in 1.1.\r\n\t\treturn this.collapse();\r\n\t}\r\n\r\n});\r\n\r\n\r\n// @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)\r\n// Creates an attribution control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.\r\nvar layers = function (baseLayers, overlays, options) {\r\n\treturn new Layers(baseLayers, overlays, options);\r\n};\n\n/*\r\n * @class Control.Zoom\r\n * @aka L.Control.Zoom\r\n * @inherits Control\r\n *\r\n * A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its [`zoomControl` option](#map-zoomcontrol) to `false`. Extends `Control`.\r\n */\r\n\r\nvar Zoom = Control.extend({\r\n\t// @section\r\n\t// @aka Control.Zoom options\r\n\toptions: {\r\n\t\tposition: 'topleft',\r\n\r\n\t\t// @option zoomInText: String = '+'\r\n\t\t// The text set on the 'zoom in' button.\r\n\t\tzoomInText: '+',\r\n\r\n\t\t// @option zoomInTitle: String = 'Zoom in'\r\n\t\t// The title set on the 'zoom in' button.\r\n\t\tzoomInTitle: 'Zoom in',\r\n\r\n\t\t// @option zoomOutText: String = '−'\r\n\t\t// The text set on the 'zoom out' button.\r\n\t\tzoomOutText: '−',\r\n\r\n\t\t// @option zoomOutTitle: String = 'Zoom out'\r\n\t\t// The title set on the 'zoom out' button.\r\n\t\tzoomOutTitle: 'Zoom out'\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tvar zoomName = 'leaflet-control-zoom',\r\n\t\t container = create$1('div', zoomName + ' leaflet-bar'),\r\n\t\t options = this.options;\r\n\r\n\t\tthis._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,\r\n\t\t zoomName + '-in', container, this._zoomIn);\r\n\t\tthis._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,\r\n\t\t zoomName + '-out', container, this._zoomOut);\r\n\r\n\t\tthis._updateDisabled();\r\n\t\tmap.on('zoomend zoomlevelschange', this._updateDisabled, this);\r\n\r\n\t\treturn container;\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tmap.off('zoomend zoomlevelschange', this._updateDisabled, this);\r\n\t},\r\n\r\n\tdisable: function () {\r\n\t\tthis._disabled = true;\r\n\t\tthis._updateDisabled();\r\n\t\treturn this;\r\n\t},\r\n\r\n\tenable: function () {\r\n\t\tthis._disabled = false;\r\n\t\tthis._updateDisabled();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_zoomIn: function (e) {\r\n\t\tif (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {\r\n\t\t\tthis._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));\r\n\t\t}\r\n\t},\r\n\r\n\t_zoomOut: function (e) {\r\n\t\tif (!this._disabled && this._map._zoom > this._map.getMinZoom()) {\r\n\t\t\tthis._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));\r\n\t\t}\r\n\t},\r\n\r\n\t_createButton: function (html, title, className, container, fn) {\r\n\t\tvar link = create$1('a', className, container);\r\n\t\tlink.innerHTML = html;\r\n\t\tlink.href = '#';\r\n\t\tlink.title = title;\r\n\r\n\t\t/*\r\n\t\t * Will force screen readers like VoiceOver to read this as \"Zoom in - button\"\r\n\t\t */\r\n\t\tlink.setAttribute('role', 'button');\r\n\t\tlink.setAttribute('aria-label', title);\r\n\r\n\t\tdisableClickPropagation(link);\r\n\t\ton(link, 'click', stop);\r\n\t\ton(link, 'click', fn, this);\r\n\t\ton(link, 'click', this._refocusOnMap, this);\r\n\r\n\t\treturn link;\r\n\t},\r\n\r\n\t_updateDisabled: function () {\r\n\t\tvar map = this._map,\r\n\t\t className = 'leaflet-disabled';\r\n\r\n\t\tremoveClass(this._zoomInButton, className);\r\n\t\tremoveClass(this._zoomOutButton, className);\r\n\r\n\t\tif (this._disabled || map._zoom === map.getMinZoom()) {\r\n\t\t\taddClass(this._zoomOutButton, className);\r\n\t\t}\r\n\t\tif (this._disabled || map._zoom === map.getMaxZoom()) {\r\n\t\t\taddClass(this._zoomInButton, className);\r\n\t\t}\r\n\t}\r\n});\r\n\r\n// @namespace Map\r\n// @section Control options\r\n// @option zoomControl: Boolean = true\r\n// Whether a [zoom control](#control-zoom) is added to the map by default.\r\nMap.mergeOptions({\r\n\tzoomControl: true\r\n});\r\n\r\nMap.addInitHook(function () {\r\n\tif (this.options.zoomControl) {\r\n\t\t// @section Controls\r\n\t\t// @property zoomControl: Control.Zoom\r\n\t\t// The default zoom control (only available if the\r\n\t\t// [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).\r\n\t\tthis.zoomControl = new Zoom();\r\n\t\tthis.addControl(this.zoomControl);\r\n\t}\r\n});\r\n\r\n// @namespace Control.Zoom\r\n// @factory L.control.zoom(options: Control.Zoom options)\r\n// Creates a zoom control\r\nvar zoom = function (options) {\r\n\treturn new Zoom(options);\r\n};\n\n/*\n * @class Control.Scale\n * @aka L.Control.Scale\n * @inherits Control\n *\n * A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) systems. Extends `Control`.\n *\n * @example\n *\n * ```js\n * L.control.scale().addTo(map);\n * ```\n */\n\nvar Scale = Control.extend({\n\t// @section\n\t// @aka Control.Scale options\n\toptions: {\n\t\tposition: 'bottomleft',\n\n\t\t// @option maxWidth: Number = 100\n\t\t// Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).\n\t\tmaxWidth: 100,\n\n\t\t// @option metric: Boolean = True\n\t\t// Whether to show the metric scale line (m/km).\n\t\tmetric: true,\n\n\t\t// @option imperial: Boolean = True\n\t\t// Whether to show the imperial scale line (mi/ft).\n\t\timperial: true\n\n\t\t// @option updateWhenIdle: Boolean = false\n\t\t// If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).\n\t},\n\n\tonAdd: function (map) {\n\t\tvar className = 'leaflet-control-scale',\n\t\t container = create$1('div', className),\n\t\t options = this.options;\n\n\t\tthis._addScales(options, className + '-line', container);\n\n\t\tmap.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);\n\t\tmap.whenReady(this._update, this);\n\n\t\treturn container;\n\t},\n\n\tonRemove: function (map) {\n\t\tmap.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);\n\t},\n\n\t_addScales: function (options, className, container) {\n\t\tif (options.metric) {\n\t\t\tthis._mScale = create$1('div', className, container);\n\t\t}\n\t\tif (options.imperial) {\n\t\t\tthis._iScale = create$1('div', className, container);\n\t\t}\n\t},\n\n\t_update: function () {\n\t\tvar map = this._map,\n\t\t y = map.getSize().y / 2;\n\n\t\tvar maxMeters = map.distance(\n\t\t\tmap.containerPointToLatLng([0, y]),\n\t\t\tmap.containerPointToLatLng([this.options.maxWidth, y]));\n\n\t\tthis._updateScales(maxMeters);\n\t},\n\n\t_updateScales: function (maxMeters) {\n\t\tif (this.options.metric && maxMeters) {\n\t\t\tthis._updateMetric(maxMeters);\n\t\t}\n\t\tif (this.options.imperial && maxMeters) {\n\t\t\tthis._updateImperial(maxMeters);\n\t\t}\n\t},\n\n\t_updateMetric: function (maxMeters) {\n\t\tvar meters = this._getRoundNum(maxMeters),\n\t\t label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';\n\n\t\tthis._updateScale(this._mScale, label, meters / maxMeters);\n\t},\n\n\t_updateImperial: function (maxMeters) {\n\t\tvar maxFeet = maxMeters * 3.2808399,\n\t\t maxMiles, miles, feet;\n\n\t\tif (maxFeet > 5280) {\n\t\t\tmaxMiles = maxFeet / 5280;\n\t\t\tmiles = this._getRoundNum(maxMiles);\n\t\t\tthis._updateScale(this._iScale, miles + ' mi', miles / maxMiles);\n\n\t\t} else {\n\t\t\tfeet = this._getRoundNum(maxFeet);\n\t\t\tthis._updateScale(this._iScale, feet + ' ft', feet / maxFeet);\n\t\t}\n\t},\n\n\t_updateScale: function (scale, text, ratio) {\n\t\tscale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';\n\t\tscale.innerHTML = text;\n\t},\n\n\t_getRoundNum: function (num) {\n\t\tvar pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),\n\t\t d = num / pow10;\n\n\t\td = d >= 10 ? 10 :\n\t\t d >= 5 ? 5 :\n\t\t d >= 3 ? 3 :\n\t\t d >= 2 ? 2 : 1;\n\n\t\treturn pow10 * d;\n\t}\n});\n\n\n// @factory L.control.scale(options?: Control.Scale options)\n// Creates an scale control with the given options.\nvar scale = function (options) {\n\treturn new Scale(options);\n};\n\n/*\r\n * @class Control.Attribution\r\n * @aka L.Control.Attribution\r\n * @inherits Control\r\n *\r\n * The attribution control allows you to display attribution data in a small text box on a map. It is put on the map by default unless you set its [`attributionControl` option](#map-attributioncontrol) to `false`, and it fetches attribution texts from layers with the [`getAttribution` method](#layer-getattribution) automatically. Extends Control.\r\n */\r\n\r\nvar Attribution = Control.extend({\r\n\t// @section\r\n\t// @aka Control.Attribution options\r\n\toptions: {\r\n\t\tposition: 'bottomright',\r\n\r\n\t\t// @option prefix: String = 'Leaflet'\r\n\t\t// The HTML text shown before the attributions. Pass `false` to disable.\r\n\t\tprefix: 'Leaflet'\r\n\t},\r\n\r\n\tinitialize: function (options) {\r\n\t\tsetOptions(this, options);\r\n\r\n\t\tthis._attributions = {};\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tmap.attributionControl = this;\r\n\t\tthis._container = create$1('div', 'leaflet-control-attribution');\r\n\t\tdisableClickPropagation(this._container);\r\n\r\n\t\t// TODO ugly, refactor\r\n\t\tfor (var i in map._layers) {\r\n\t\t\tif (map._layers[i].getAttribution) {\r\n\t\t\t\tthis.addAttribution(map._layers[i].getAttribution());\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthis._update();\r\n\r\n\t\treturn this._container;\r\n\t},\r\n\r\n\t// @method setPrefix(prefix: String): this\r\n\t// Sets the text before the attributions.\r\n\tsetPrefix: function (prefix) {\r\n\t\tthis.options.prefix = prefix;\r\n\t\tthis._update();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method addAttribution(text: String): this\r\n\t// Adds an attribution text (e.g. `'Vector data © Mapbox'`).\r\n\taddAttribution: function (text) {\r\n\t\tif (!text) { return this; }\r\n\r\n\t\tif (!this._attributions[text]) {\r\n\t\t\tthis._attributions[text] = 0;\r\n\t\t}\r\n\t\tthis._attributions[text]++;\r\n\r\n\t\tthis._update();\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeAttribution(text: String): this\r\n\t// Removes an attribution text.\r\n\tremoveAttribution: function (text) {\r\n\t\tif (!text) { return this; }\r\n\r\n\t\tif (this._attributions[text]) {\r\n\t\t\tthis._attributions[text]--;\r\n\t\t\tthis._update();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_update: function () {\r\n\t\tif (!this._map) { return; }\r\n\r\n\t\tvar attribs = [];\r\n\r\n\t\tfor (var i in this._attributions) {\r\n\t\t\tif (this._attributions[i]) {\r\n\t\t\t\tattribs.push(i);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvar prefixAndAttribs = [];\r\n\r\n\t\tif (this.options.prefix) {\r\n\t\t\tprefixAndAttribs.push(this.options.prefix);\r\n\t\t}\r\n\t\tif (attribs.length) {\r\n\t\t\tprefixAndAttribs.push(attribs.join(', '));\r\n\t\t}\r\n\r\n\t\tthis._container.innerHTML = prefixAndAttribs.join(' | ');\r\n\t}\r\n});\r\n\r\n// @namespace Map\r\n// @section Control options\r\n// @option attributionControl: Boolean = true\r\n// Whether a [attribution control](#control-attribution) is added to the map by default.\r\nMap.mergeOptions({\r\n\tattributionControl: true\r\n});\r\n\r\nMap.addInitHook(function () {\r\n\tif (this.options.attributionControl) {\r\n\t\tnew Attribution().addTo(this);\r\n\t}\r\n});\r\n\r\n// @namespace Control.Attribution\r\n// @factory L.control.attribution(options: Control.Attribution options)\r\n// Creates an attribution control.\r\nvar attribution = function (options) {\r\n\treturn new Attribution(options);\r\n};\n\nControl.Layers = Layers;\nControl.Zoom = Zoom;\nControl.Scale = Scale;\nControl.Attribution = Attribution;\n\ncontrol.layers = layers;\ncontrol.zoom = zoom;\ncontrol.scale = scale;\ncontrol.attribution = attribution;\n\n/*\n\tL.Handler is a base class for handler classes that are used internally to inject\n\tinteraction features like dragging to classes like Map and Marker.\n*/\n\n// @class Handler\n// @aka L.Handler\n// Abstract class for map interaction handlers\n\nvar Handler = Class.extend({\n\tinitialize: function (map) {\n\t\tthis._map = map;\n\t},\n\n\t// @method enable(): this\n\t// Enables the handler\n\tenable: function () {\n\t\tif (this._enabled) { return this; }\n\n\t\tthis._enabled = true;\n\t\tthis.addHooks();\n\t\treturn this;\n\t},\n\n\t// @method disable(): this\n\t// Disables the handler\n\tdisable: function () {\n\t\tif (!this._enabled) { return this; }\n\n\t\tthis._enabled = false;\n\t\tthis.removeHooks();\n\t\treturn this;\n\t},\n\n\t// @method enabled(): Boolean\n\t// Returns `true` if the handler is enabled\n\tenabled: function () {\n\t\treturn !!this._enabled;\n\t}\n\n\t// @section Extension methods\n\t// Classes inheriting from `Handler` must implement the two following methods:\n\t// @method addHooks()\n\t// Called when the handler is enabled, should add event hooks.\n\t// @method removeHooks()\n\t// Called when the handler is disabled, should remove the event hooks added previously.\n});\n\n// @section There is static function which can be called without instantiating L.Handler:\n// @function addTo(map: Map, name: String): this\n// Adds a new Handler to the given map with the given name.\nHandler.addTo = function (map, name) {\n\tmap.addHandler(name, this);\n\treturn this;\n};\n\nvar Mixin = {Events: Events};\n\n/*\r\n * @class Draggable\r\n * @aka L.Draggable\r\n * @inherits Evented\r\n *\r\n * A class for making DOM elements draggable (including touch support).\r\n * Used internally for map and marker dragging. Only works for elements\r\n * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).\r\n *\r\n * @example\r\n * ```js\r\n * var draggable = new L.Draggable(elementToDrag);\r\n * draggable.enable();\r\n * ```\r\n */\r\n\r\nvar START = touch ? 'touchstart mousedown' : 'mousedown';\r\nvar END = {\r\n\tmousedown: 'mouseup',\r\n\ttouchstart: 'touchend',\r\n\tpointerdown: 'touchend',\r\n\tMSPointerDown: 'touchend'\r\n};\r\nvar MOVE = {\r\n\tmousedown: 'mousemove',\r\n\ttouchstart: 'touchmove',\r\n\tpointerdown: 'touchmove',\r\n\tMSPointerDown: 'touchmove'\r\n};\r\n\r\n\r\nvar Draggable = Evented.extend({\r\n\r\n\toptions: {\r\n\t\t// @section\r\n\t\t// @aka Draggable options\r\n\t\t// @option clickTolerance: Number = 3\r\n\t\t// The max number of pixels a user can shift the mouse pointer during a click\r\n\t\t// for it to be considered a valid click (as opposed to a mouse drag).\r\n\t\tclickTolerance: 3\r\n\t},\r\n\r\n\t// @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)\r\n\t// Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).\r\n\tinitialize: function (element, dragStartTarget, preventOutline$$1, options) {\r\n\t\tsetOptions(this, options);\r\n\r\n\t\tthis._element = element;\r\n\t\tthis._dragStartTarget = dragStartTarget || element;\r\n\t\tthis._preventOutline = preventOutline$$1;\r\n\t},\r\n\r\n\t// @method enable()\r\n\t// Enables the dragging ability\r\n\tenable: function () {\r\n\t\tif (this._enabled) { return; }\r\n\r\n\t\ton(this._dragStartTarget, START, this._onDown, this);\r\n\r\n\t\tthis._enabled = true;\r\n\t},\r\n\r\n\t// @method disable()\r\n\t// Disables the dragging ability\r\n\tdisable: function () {\r\n\t\tif (!this._enabled) { return; }\r\n\r\n\t\t// If we're currently dragging this draggable,\r\n\t\t// disabling it counts as first ending the drag.\r\n\t\tif (Draggable._dragging === this) {\r\n\t\t\tthis.finishDrag();\r\n\t\t}\r\n\r\n\t\toff(this._dragStartTarget, START, this._onDown, this);\r\n\r\n\t\tthis._enabled = false;\r\n\t\tthis._moved = false;\r\n\t},\r\n\r\n\t_onDown: function (e) {\r\n\t\t// Ignore simulated events, since we handle both touch and\r\n\t\t// mouse explicitly; otherwise we risk getting duplicates of\r\n\t\t// touch events, see #4315.\r\n\t\t// Also ignore the event if disabled; this happens in IE11\r\n\t\t// under some circumstances, see #3666.\r\n\t\tif (e._simulated || !this._enabled) { return; }\r\n\r\n\t\tthis._moved = false;\r\n\r\n\t\tif (hasClass(this._element, 'leaflet-zoom-anim')) { return; }\r\n\r\n\t\tif (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }\r\n\t\tDraggable._dragging = this; // Prevent dragging multiple objects at once.\r\n\r\n\t\tif (this._preventOutline) {\r\n\t\t\tpreventOutline(this._element);\r\n\t\t}\r\n\r\n\t\tdisableImageDrag();\r\n\t\tdisableTextSelection();\r\n\r\n\t\tif (this._moving) { return; }\r\n\r\n\t\t// @event down: Event\r\n\t\t// Fired when a drag is about to start.\r\n\t\tthis.fire('down');\r\n\r\n\t\tvar first = e.touches ? e.touches[0] : e,\r\n\t\t sizedParent = getSizedParentNode(this._element);\r\n\r\n\t\tthis._startPoint = new Point(first.clientX, first.clientY);\r\n\r\n\t\t// Cache the scale, so that we can continuously compensate for it during drag (_onMove).\r\n\t\tthis._parentScale = getScale(sizedParent);\r\n\r\n\t\ton(document, MOVE[e.type], this._onMove, this);\r\n\t\ton(document, END[e.type], this._onUp, this);\r\n\t},\r\n\r\n\t_onMove: function (e) {\r\n\t\t// Ignore simulated events, since we handle both touch and\r\n\t\t// mouse explicitly; otherwise we risk getting duplicates of\r\n\t\t// touch events, see #4315.\r\n\t\t// Also ignore the event if disabled; this happens in IE11\r\n\t\t// under some circumstances, see #3666.\r\n\t\tif (e._simulated || !this._enabled) { return; }\r\n\r\n\t\tif (e.touches && e.touches.length > 1) {\r\n\t\t\tthis._moved = true;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),\r\n\t\t offset = new Point(first.clientX, first.clientY)._subtract(this._startPoint);\r\n\r\n\t\tif (!offset.x && !offset.y) { return; }\r\n\t\tif (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }\r\n\r\n\t\t// We assume that the parent container's position, border and scale do not change for the duration of the drag.\r\n\t\t// Therefore there is no need to account for the position and border (they are eliminated by the subtraction)\r\n\t\t// and we can use the cached value for the scale.\r\n\t\toffset.x /= this._parentScale.x;\r\n\t\toffset.y /= this._parentScale.y;\r\n\r\n\t\tpreventDefault(e);\r\n\r\n\t\tif (!this._moved) {\r\n\t\t\t// @event dragstart: Event\r\n\t\t\t// Fired when a drag starts\r\n\t\t\tthis.fire('dragstart');\r\n\r\n\t\t\tthis._moved = true;\r\n\t\t\tthis._startPos = getPosition(this._element).subtract(offset);\r\n\r\n\t\t\taddClass(document.body, 'leaflet-dragging');\r\n\r\n\t\t\tthis._lastTarget = e.target || e.srcElement;\r\n\t\t\t// IE and Edge do not give the element, so fetch it\r\n\t\t\t// if necessary\r\n\t\t\tif ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {\r\n\t\t\t\tthis._lastTarget = this._lastTarget.correspondingUseElement;\r\n\t\t\t}\r\n\t\t\taddClass(this._lastTarget, 'leaflet-drag-target');\r\n\t\t}\r\n\r\n\t\tthis._newPos = this._startPos.add(offset);\r\n\t\tthis._moving = true;\r\n\r\n\t\tcancelAnimFrame(this._animRequest);\r\n\t\tthis._lastEvent = e;\r\n\t\tthis._animRequest = requestAnimFrame(this._updatePosition, this, true);\r\n\t},\r\n\r\n\t_updatePosition: function () {\r\n\t\tvar e = {originalEvent: this._lastEvent};\r\n\r\n\t\t// @event predrag: Event\r\n\t\t// Fired continuously during dragging *before* each corresponding\r\n\t\t// update of the element's position.\r\n\t\tthis.fire('predrag', e);\r\n\t\tsetPosition(this._element, this._newPos);\r\n\r\n\t\t// @event drag: Event\r\n\t\t// Fired continuously during dragging.\r\n\t\tthis.fire('drag', e);\r\n\t},\r\n\r\n\t_onUp: function (e) {\r\n\t\t// Ignore simulated events, since we handle both touch and\r\n\t\t// mouse explicitly; otherwise we risk getting duplicates of\r\n\t\t// touch events, see #4315.\r\n\t\t// Also ignore the event if disabled; this happens in IE11\r\n\t\t// under some circumstances, see #3666.\r\n\t\tif (e._simulated || !this._enabled) { return; }\r\n\t\tthis.finishDrag();\r\n\t},\r\n\r\n\tfinishDrag: function () {\r\n\t\tremoveClass(document.body, 'leaflet-dragging');\r\n\r\n\t\tif (this._lastTarget) {\r\n\t\t\tremoveClass(this._lastTarget, 'leaflet-drag-target');\r\n\t\t\tthis._lastTarget = null;\r\n\t\t}\r\n\r\n\t\tfor (var i in MOVE) {\r\n\t\t\toff(document, MOVE[i], this._onMove, this);\r\n\t\t\toff(document, END[i], this._onUp, this);\r\n\t\t}\r\n\r\n\t\tenableImageDrag();\r\n\t\tenableTextSelection();\r\n\r\n\t\tif (this._moved && this._moving) {\r\n\t\t\t// ensure drag is not fired after dragend\r\n\t\t\tcancelAnimFrame(this._animRequest);\r\n\r\n\t\t\t// @event dragend: DragEndEvent\r\n\t\t\t// Fired when the drag ends.\r\n\t\t\tthis.fire('dragend', {\r\n\t\t\t\tdistance: this._newPos.distanceTo(this._startPos)\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tthis._moving = false;\r\n\t\tDraggable._dragging = false;\r\n\t}\r\n\r\n});\n\n/*\r\n * @namespace LineUtil\r\n *\r\n * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.\r\n */\r\n\r\n// Simplify polyline with vertex reduction and Douglas-Peucker simplification.\r\n// Improves rendering performance dramatically by lessening the number of points to draw.\r\n\r\n// @function simplify(points: Point[], tolerance: Number): Point[]\r\n// Dramatically reduces the number of points in a polyline while retaining\r\n// its shape and returns a new array of simplified points, using the\r\n// [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).\r\n// Used for a huge performance boost when processing/displaying Leaflet polylines for\r\n// each zoom level and also reducing visual noise. tolerance affects the amount of\r\n// simplification (lesser value means higher quality but slower and with more points).\r\n// Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).\r\nfunction simplify(points, tolerance) {\r\n\tif (!tolerance || !points.length) {\r\n\t\treturn points.slice();\r\n\t}\r\n\r\n\tvar sqTolerance = tolerance * tolerance;\r\n\r\n\t // stage 1: vertex reduction\r\n\t points = _reducePoints(points, sqTolerance);\r\n\r\n\t // stage 2: Douglas-Peucker simplification\r\n\t points = _simplifyDP(points, sqTolerance);\r\n\r\n\treturn points;\r\n}\r\n\r\n// @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number\r\n// Returns the distance between point `p` and segment `p1` to `p2`.\r\nfunction pointToSegmentDistance(p, p1, p2) {\r\n\treturn Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));\r\n}\r\n\r\n// @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number\r\n// Returns the closest point from a point `p` on a segment `p1` to `p2`.\r\nfunction closestPointOnSegment(p, p1, p2) {\r\n\treturn _sqClosestPointOnSegment(p, p1, p2);\r\n}\r\n\r\n// Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm\r\nfunction _simplifyDP(points, sqTolerance) {\r\n\r\n\tvar len = points.length,\r\n\t ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,\r\n\t markers = new ArrayConstructor(len);\r\n\r\n\t markers[0] = markers[len - 1] = 1;\r\n\r\n\t_simplifyDPStep(points, markers, sqTolerance, 0, len - 1);\r\n\r\n\tvar i,\r\n\t newPoints = [];\r\n\r\n\tfor (i = 0; i < len; i++) {\r\n\t\tif (markers[i]) {\r\n\t\t\tnewPoints.push(points[i]);\r\n\t\t}\r\n\t}\r\n\r\n\treturn newPoints;\r\n}\r\n\r\nfunction _simplifyDPStep(points, markers, sqTolerance, first, last) {\r\n\r\n\tvar maxSqDist = 0,\r\n\tindex, i, sqDist;\r\n\r\n\tfor (i = first + 1; i <= last - 1; i++) {\r\n\t\tsqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);\r\n\r\n\t\tif (sqDist > maxSqDist) {\r\n\t\t\tindex = i;\r\n\t\t\tmaxSqDist = sqDist;\r\n\t\t}\r\n\t}\r\n\r\n\tif (maxSqDist > sqTolerance) {\r\n\t\tmarkers[index] = 1;\r\n\r\n\t\t_simplifyDPStep(points, markers, sqTolerance, first, index);\r\n\t\t_simplifyDPStep(points, markers, sqTolerance, index, last);\r\n\t}\r\n}\r\n\r\n// reduce points that are too close to each other to a single point\r\nfunction _reducePoints(points, sqTolerance) {\r\n\tvar reducedPoints = [points[0]];\r\n\r\n\tfor (var i = 1, prev = 0, len = points.length; i < len; i++) {\r\n\t\tif (_sqDist(points[i], points[prev]) > sqTolerance) {\r\n\t\t\treducedPoints.push(points[i]);\r\n\t\t\tprev = i;\r\n\t\t}\r\n\t}\r\n\tif (prev < len - 1) {\r\n\t\treducedPoints.push(points[len - 1]);\r\n\t}\r\n\treturn reducedPoints;\r\n}\r\n\r\nvar _lastCode;\r\n\r\n// @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean\r\n// Clips the segment a to b by rectangular bounds with the\r\n// [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)\r\n// (modifying the segment points directly!). Used by Leaflet to only show polyline\r\n// points that are on the screen or near, increasing performance.\r\nfunction clipSegment(a, b, bounds, useLastCode, round) {\r\n\tvar codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),\r\n\t codeB = _getBitCode(b, bounds),\r\n\r\n\t codeOut, p, newCode;\r\n\r\n\t // save 2nd code to avoid calculating it on the next segment\r\n\t _lastCode = codeB;\r\n\r\n\twhile (true) {\r\n\t\t// if a,b is inside the clip window (trivial accept)\r\n\t\tif (!(codeA | codeB)) {\r\n\t\t\treturn [a, b];\r\n\t\t}\r\n\r\n\t\t// if a,b is outside the clip window (trivial reject)\r\n\t\tif (codeA & codeB) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t// other cases\r\n\t\tcodeOut = codeA || codeB;\r\n\t\tp = _getEdgeIntersection(a, b, codeOut, bounds, round);\r\n\t\tnewCode = _getBitCode(p, bounds);\r\n\r\n\t\tif (codeOut === codeA) {\r\n\t\t\ta = p;\r\n\t\t\tcodeA = newCode;\r\n\t\t} else {\r\n\t\t\tb = p;\r\n\t\t\tcodeB = newCode;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunction _getEdgeIntersection(a, b, code, bounds, round) {\r\n\tvar dx = b.x - a.x,\r\n\t dy = b.y - a.y,\r\n\t min = bounds.min,\r\n\t max = bounds.max,\r\n\t x, y;\r\n\r\n\tif (code & 8) { // top\r\n\t\tx = a.x + dx * (max.y - a.y) / dy;\r\n\t\ty = max.y;\r\n\r\n\t} else if (code & 4) { // bottom\r\n\t\tx = a.x + dx * (min.y - a.y) / dy;\r\n\t\ty = min.y;\r\n\r\n\t} else if (code & 2) { // right\r\n\t\tx = max.x;\r\n\t\ty = a.y + dy * (max.x - a.x) / dx;\r\n\r\n\t} else if (code & 1) { // left\r\n\t\tx = min.x;\r\n\t\ty = a.y + dy * (min.x - a.x) / dx;\r\n\t}\r\n\r\n\treturn new Point(x, y, round);\r\n}\r\n\r\nfunction _getBitCode(p, bounds) {\r\n\tvar code = 0;\r\n\r\n\tif (p.x < bounds.min.x) { // left\r\n\t\tcode |= 1;\r\n\t} else if (p.x > bounds.max.x) { // right\r\n\t\tcode |= 2;\r\n\t}\r\n\r\n\tif (p.y < bounds.min.y) { // bottom\r\n\t\tcode |= 4;\r\n\t} else if (p.y > bounds.max.y) { // top\r\n\t\tcode |= 8;\r\n\t}\r\n\r\n\treturn code;\r\n}\r\n\r\n// square distance (to avoid unnecessary Math.sqrt calls)\r\nfunction _sqDist(p1, p2) {\r\n\tvar dx = p2.x - p1.x,\r\n\t dy = p2.y - p1.y;\r\n\treturn dx * dx + dy * dy;\r\n}\r\n\r\n// return closest point on segment or distance to that point\r\nfunction _sqClosestPointOnSegment(p, p1, p2, sqDist) {\r\n\tvar x = p1.x,\r\n\t y = p1.y,\r\n\t dx = p2.x - x,\r\n\t dy = p2.y - y,\r\n\t dot = dx * dx + dy * dy,\r\n\t t;\r\n\r\n\tif (dot > 0) {\r\n\t\tt = ((p.x - x) * dx + (p.y - y) * dy) / dot;\r\n\r\n\t\tif (t > 1) {\r\n\t\t\tx = p2.x;\r\n\t\t\ty = p2.y;\r\n\t\t} else if (t > 0) {\r\n\t\t\tx += dx * t;\r\n\t\t\ty += dy * t;\r\n\t\t}\r\n\t}\r\n\r\n\tdx = p.x - x;\r\n\tdy = p.y - y;\r\n\r\n\treturn sqDist ? dx * dx + dy * dy : new Point(x, y);\r\n}\r\n\r\n\r\n// @function isFlat(latlngs: LatLng[]): Boolean\r\n// Returns true if `latlngs` is a flat array, false is nested.\r\nfunction isFlat(latlngs) {\r\n\treturn !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');\r\n}\r\n\r\nfunction _flat(latlngs) {\r\n\tconsole.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');\r\n\treturn isFlat(latlngs);\r\n}\r\n\n\nvar LineUtil = (Object.freeze || Object)({\n\tsimplify: simplify,\n\tpointToSegmentDistance: pointToSegmentDistance,\n\tclosestPointOnSegment: closestPointOnSegment,\n\tclipSegment: clipSegment,\n\t_getEdgeIntersection: _getEdgeIntersection,\n\t_getBitCode: _getBitCode,\n\t_sqClosestPointOnSegment: _sqClosestPointOnSegment,\n\tisFlat: isFlat,\n\t_flat: _flat\n});\n\n/*\r\n * @namespace PolyUtil\r\n * Various utility functions for polygon geometries.\r\n */\r\n\r\n/* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]\r\n * Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)).\r\n * Used by Leaflet to only show polygon points that are on the screen or near, increasing\r\n * performance. Note that polygon points needs different algorithm for clipping\r\n * than polyline, so there's a separate method for it.\r\n */\r\nfunction clipPolygon(points, bounds, round) {\r\n\tvar clippedPoints,\r\n\t edges = [1, 4, 2, 8],\r\n\t i, j, k,\r\n\t a, b,\r\n\t len, edge, p;\r\n\r\n\tfor (i = 0, len = points.length; i < len; i++) {\r\n\t\tpoints[i]._code = _getBitCode(points[i], bounds);\r\n\t}\r\n\r\n\t// for each edge (left, bottom, right, top)\r\n\tfor (k = 0; k < 4; k++) {\r\n\t\tedge = edges[k];\r\n\t\tclippedPoints = [];\r\n\r\n\t\tfor (i = 0, len = points.length, j = len - 1; i < len; j = i++) {\r\n\t\t\ta = points[i];\r\n\t\t\tb = points[j];\r\n\r\n\t\t\t// if a is inside the clip window\r\n\t\t\tif (!(a._code & edge)) {\r\n\t\t\t\t// if b is outside the clip window (a->b goes out of screen)\r\n\t\t\t\tif (b._code & edge) {\r\n\t\t\t\t\tp = _getEdgeIntersection(b, a, edge, bounds, round);\r\n\t\t\t\t\tp._code = _getBitCode(p, bounds);\r\n\t\t\t\t\tclippedPoints.push(p);\r\n\t\t\t\t}\r\n\t\t\t\tclippedPoints.push(a);\r\n\r\n\t\t\t// else if b is inside the clip window (a->b enters the screen)\r\n\t\t\t} else if (!(b._code & edge)) {\r\n\t\t\t\tp = _getEdgeIntersection(b, a, edge, bounds, round);\r\n\t\t\t\tp._code = _getBitCode(p, bounds);\r\n\t\t\t\tclippedPoints.push(p);\r\n\t\t\t}\r\n\t\t}\r\n\t\tpoints = clippedPoints;\r\n\t}\r\n\r\n\treturn points;\r\n}\r\n\n\nvar PolyUtil = (Object.freeze || Object)({\n\tclipPolygon: clipPolygon\n});\n\n/*\r\n * @namespace Projection\r\n * @section\r\n * Leaflet comes with a set of already defined Projections out of the box:\r\n *\r\n * @projection L.Projection.LonLat\r\n *\r\n * Equirectangular, or Plate Carree projection — the most simple projection,\r\n * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as\r\n * latitude. Also suitable for flat worlds, e.g. game maps. Used by the\r\n * `EPSG:4326` and `Simple` CRS.\r\n */\r\n\r\nvar LonLat = {\r\n\tproject: function (latlng) {\r\n\t\treturn new Point(latlng.lng, latlng.lat);\r\n\t},\r\n\r\n\tunproject: function (point) {\r\n\t\treturn new LatLng(point.y, point.x);\r\n\t},\r\n\r\n\tbounds: new Bounds([-180, -90], [180, 90])\r\n};\n\n/*\r\n * @namespace Projection\r\n * @projection L.Projection.Mercator\r\n *\r\n * Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS.\r\n */\r\n\r\nvar Mercator = {\r\n\tR: 6378137,\r\n\tR_MINOR: 6356752.314245179,\r\n\r\n\tbounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),\r\n\r\n\tproject: function (latlng) {\r\n\t\tvar d = Math.PI / 180,\r\n\t\t r = this.R,\r\n\t\t y = latlng.lat * d,\r\n\t\t tmp = this.R_MINOR / r,\r\n\t\t e = Math.sqrt(1 - tmp * tmp),\r\n\t\t con = e * Math.sin(y);\r\n\r\n\t\tvar ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);\r\n\t\ty = -r * Math.log(Math.max(ts, 1E-10));\r\n\r\n\t\treturn new Point(latlng.lng * d * r, y);\r\n\t},\r\n\r\n\tunproject: function (point) {\r\n\t\tvar d = 180 / Math.PI,\r\n\t\t r = this.R,\r\n\t\t tmp = this.R_MINOR / r,\r\n\t\t e = Math.sqrt(1 - tmp * tmp),\r\n\t\t ts = Math.exp(-point.y / r),\r\n\t\t phi = Math.PI / 2 - 2 * Math.atan(ts);\r\n\r\n\t\tfor (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {\r\n\t\t\tcon = e * Math.sin(phi);\r\n\t\t\tcon = Math.pow((1 - con) / (1 + con), e / 2);\r\n\t\t\tdphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;\r\n\t\t\tphi += dphi;\r\n\t\t}\r\n\r\n\t\treturn new LatLng(phi * d, point.x * d / r);\r\n\t}\r\n};\n\n/*\n * @class Projection\n\n * An object with methods for projecting geographical coordinates of the world onto\n * a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection).\n\n * @property bounds: Bounds\n * The bounds (specified in CRS units) where the projection is valid\n\n * @method project(latlng: LatLng): Point\n * Projects geographical coordinates into a 2D point.\n * Only accepts actual `L.LatLng` instances, not arrays.\n\n * @method unproject(point: Point): LatLng\n * The inverse of `project`. Projects a 2D point into a geographical location.\n * Only accepts actual `L.Point` instances, not arrays.\n\n * Note that the projection instances do not inherit from Leafet's `Class` object,\n * and can't be instantiated. Also, new classes can't inherit from them,\n * and methods can't be added to them with the `include` function.\n\n */\n\n\n\n\nvar index = (Object.freeze || Object)({\n\tLonLat: LonLat,\n\tMercator: Mercator,\n\tSphericalMercator: SphericalMercator\n});\n\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.EPSG3395\r\n *\r\n * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.\r\n */\r\nvar EPSG3395 = extend({}, Earth, {\r\n\tcode: 'EPSG:3395',\r\n\tprojection: Mercator,\r\n\r\n\ttransformation: (function () {\r\n\t\tvar scale = 0.5 / (Math.PI * Mercator.R);\r\n\t\treturn toTransformation(scale, 0.5, -scale, 0.5);\r\n\t}())\r\n});\n\n/*\r\n * @namespace CRS\r\n * @crs L.CRS.EPSG4326\r\n *\r\n * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.\r\n *\r\n * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),\r\n * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`\r\n * with this CRS, ensure that there are two 256x256 pixel tiles covering the\r\n * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),\r\n * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.\r\n */\r\n\r\nvar EPSG4326 = extend({}, Earth, {\r\n\tcode: 'EPSG:4326',\r\n\tprojection: LonLat,\r\n\ttransformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)\r\n});\n\n/*\n * @namespace CRS\n * @crs L.CRS.Simple\n *\n * A simple CRS that maps longitude and latitude into `x` and `y` directly.\n * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`\n * axis should still be inverted (going from bottom to top). `distance()` returns\n * simple euclidean distance.\n */\n\nvar Simple = extend({}, CRS, {\n\tprojection: LonLat,\n\ttransformation: toTransformation(1, 0, -1, 0),\n\n\tscale: function (zoom) {\n\t\treturn Math.pow(2, zoom);\n\t},\n\n\tzoom: function (scale) {\n\t\treturn Math.log(scale) / Math.LN2;\n\t},\n\n\tdistance: function (latlng1, latlng2) {\n\t\tvar dx = latlng2.lng - latlng1.lng,\n\t\t dy = latlng2.lat - latlng1.lat;\n\n\t\treturn Math.sqrt(dx * dx + dy * dy);\n\t},\n\n\tinfinite: true\n});\n\nCRS.Earth = Earth;\nCRS.EPSG3395 = EPSG3395;\nCRS.EPSG3857 = EPSG3857;\nCRS.EPSG900913 = EPSG900913;\nCRS.EPSG4326 = EPSG4326;\nCRS.Simple = Simple;\n\n/*\n * @class Layer\n * @inherits Evented\n * @aka L.Layer\n * @aka ILayer\n *\n * A set of methods from the Layer base class that all Leaflet layers use.\n * Inherits all methods, options and events from `L.Evented`.\n *\n * @example\n *\n * ```js\n * var layer = L.marker(latlng).addTo(map);\n * layer.addTo(map);\n * layer.remove();\n * ```\n *\n * @event add: Event\n * Fired after the layer is added to a map\n *\n * @event remove: Event\n * Fired after the layer is removed from a map\n */\n\n\nvar Layer = Evented.extend({\n\n\t// Classes extending `L.Layer` will inherit the following options:\n\toptions: {\n\t\t// @option pane: String = 'overlayPane'\n\t\t// By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default.\n\t\tpane: 'overlayPane',\n\n\t\t// @option attribution: String = null\n\t\t// String to be shown in the attribution control, e.g. \"© OpenStreetMap contributors\". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.\n\t\tattribution: null,\n\n\t\tbubblingMouseEvents: true\n\t},\n\n\t/* @section\n\t * Classes extending `L.Layer` will inherit the following methods:\n\t *\n\t * @method addTo(map: Map|LayerGroup): this\n\t * Adds the layer to the given map or layer group.\n\t */\n\taddTo: function (map) {\n\t\tmap.addLayer(this);\n\t\treturn this;\n\t},\n\n\t// @method remove: this\n\t// Removes the layer from the map it is currently active on.\n\tremove: function () {\n\t\treturn this.removeFrom(this._map || this._mapToAdd);\n\t},\n\n\t// @method removeFrom(map: Map): this\n\t// Removes the layer from the given map\n\tremoveFrom: function (obj) {\n\t\tif (obj) {\n\t\t\tobj.removeLayer(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method getPane(name? : String): HTMLElement\n\t// Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.\n\tgetPane: function (name) {\n\t\treturn this._map.getPane(name ? (this.options[name] || name) : this.options.pane);\n\t},\n\n\taddInteractiveTarget: function (targetEl) {\n\t\tthis._map._targets[stamp(targetEl)] = this;\n\t\treturn this;\n\t},\n\n\tremoveInteractiveTarget: function (targetEl) {\n\t\tdelete this._map._targets[stamp(targetEl)];\n\t\treturn this;\n\t},\n\n\t// @method getAttribution: String\n\t// Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).\n\tgetAttribution: function () {\n\t\treturn this.options.attribution;\n\t},\n\n\t_layerAdd: function (e) {\n\t\tvar map = e.target;\n\n\t\t// check in case layer gets added and then removed before the map is ready\n\t\tif (!map.hasLayer(this)) { return; }\n\n\t\tthis._map = map;\n\t\tthis._zoomAnimated = map._zoomAnimated;\n\n\t\tif (this.getEvents) {\n\t\t\tvar events = this.getEvents();\n\t\t\tmap.on(events, this);\n\t\t\tthis.once('remove', function () {\n\t\t\t\tmap.off(events, this);\n\t\t\t}, this);\n\t\t}\n\n\t\tthis.onAdd(map);\n\n\t\tif (this.getAttribution && map.attributionControl) {\n\t\t\tmap.attributionControl.addAttribution(this.getAttribution());\n\t\t}\n\n\t\tthis.fire('add');\n\t\tmap.fire('layeradd', {layer: this});\n\t}\n});\n\n/* @section Extension methods\n * @uninheritable\n *\n * Every layer should extend from `L.Layer` and (re-)implement the following methods.\n *\n * @method onAdd(map: Map): this\n * Should contain code that creates DOM elements for the layer, adds them to `map panes` where they should belong and puts listeners on relevant map events. Called on [`map.addLayer(layer)`](#map-addlayer).\n *\n * @method onRemove(map: Map): this\n * Should contain all clean up code that removes the layer's elements from the DOM and removes listeners previously added in [`onAdd`](#layer-onadd). Called on [`map.removeLayer(layer)`](#map-removelayer).\n *\n * @method getEvents(): Object\n * This optional method should return an object like `{ viewreset: this._reset }` for [`addEventListener`](#evented-addeventlistener). The event handlers in this object will be automatically added and removed from the map with your layer.\n *\n * @method getAttribution(): String\n * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.\n *\n * @method beforeAdd(map: Map): this\n * Optional method. Called on [`map.addLayer(layer)`](#map-addlayer), before the layer is added to the map, before events are initialized, without waiting until the map is in a usable state. Use for early initialization only.\n */\n\n\n/* @namespace Map\n * @section Layer events\n *\n * @event layeradd: LayerEvent\n * Fired when a new layer is added to the map.\n *\n * @event layerremove: LayerEvent\n * Fired when some layer is removed from the map\n *\n * @section Methods for Layers and Controls\n */\nMap.include({\n\t// @method addLayer(layer: Layer): this\n\t// Adds the given layer to the map\n\taddLayer: function (layer) {\n\t\tif (!layer._layerAdd) {\n\t\t\tthrow new Error('The provided object is not a Layer.');\n\t\t}\n\n\t\tvar id = stamp(layer);\n\t\tif (this._layers[id]) { return this; }\n\t\tthis._layers[id] = layer;\n\n\t\tlayer._mapToAdd = this;\n\n\t\tif (layer.beforeAdd) {\n\t\t\tlayer.beforeAdd(this);\n\t\t}\n\n\t\tthis.whenReady(layer._layerAdd, layer);\n\n\t\treturn this;\n\t},\n\n\t// @method removeLayer(layer: Layer): this\n\t// Removes the given layer from the map.\n\tremoveLayer: function (layer) {\n\t\tvar id = stamp(layer);\n\n\t\tif (!this._layers[id]) { return this; }\n\n\t\tif (this._loaded) {\n\t\t\tlayer.onRemove(this);\n\t\t}\n\n\t\tif (layer.getAttribution && this.attributionControl) {\n\t\t\tthis.attributionControl.removeAttribution(layer.getAttribution());\n\t\t}\n\n\t\tdelete this._layers[id];\n\n\t\tif (this._loaded) {\n\t\t\tthis.fire('layerremove', {layer: layer});\n\t\t\tlayer.fire('remove');\n\t\t}\n\n\t\tlayer._map = layer._mapToAdd = null;\n\n\t\treturn this;\n\t},\n\n\t// @method hasLayer(layer: Layer): Boolean\n\t// Returns `true` if the given layer is currently added to the map\n\thasLayer: function (layer) {\n\t\treturn !!layer && (stamp(layer) in this._layers);\n\t},\n\n\t/* @method eachLayer(fn: Function, context?: Object): this\n\t * Iterates over the layers of the map, optionally specifying context of the iterator function.\n\t * ```\n\t * map.eachLayer(function(layer){\n\t * layer.bindPopup('Hello');\n\t * });\n\t * ```\n\t */\n\teachLayer: function (method, context) {\n\t\tfor (var i in this._layers) {\n\t\t\tmethod.call(context, this._layers[i]);\n\t\t}\n\t\treturn this;\n\t},\n\n\t_addLayers: function (layers) {\n\t\tlayers = layers ? (isArray(layers) ? layers : [layers]) : [];\n\n\t\tfor (var i = 0, len = layers.length; i < len; i++) {\n\t\t\tthis.addLayer(layers[i]);\n\t\t}\n\t},\n\n\t_addZoomLimit: function (layer) {\n\t\tif (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {\n\t\t\tthis._zoomBoundLayers[stamp(layer)] = layer;\n\t\t\tthis._updateZoomLevels();\n\t\t}\n\t},\n\n\t_removeZoomLimit: function (layer) {\n\t\tvar id = stamp(layer);\n\n\t\tif (this._zoomBoundLayers[id]) {\n\t\t\tdelete this._zoomBoundLayers[id];\n\t\t\tthis._updateZoomLevels();\n\t\t}\n\t},\n\n\t_updateZoomLevels: function () {\n\t\tvar minZoom = Infinity,\n\t\t maxZoom = -Infinity,\n\t\t oldZoomSpan = this._getZoomSpan();\n\n\t\tfor (var i in this._zoomBoundLayers) {\n\t\t\tvar options = this._zoomBoundLayers[i].options;\n\n\t\t\tminZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);\n\t\t\tmaxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);\n\t\t}\n\n\t\tthis._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;\n\t\tthis._layersMinZoom = minZoom === Infinity ? undefined : minZoom;\n\n\t\t// @section Map state change events\n\t\t// @event zoomlevelschange: Event\n\t\t// Fired when the number of zoomlevels on the map is changed due\n\t\t// to adding or removing a layer.\n\t\tif (oldZoomSpan !== this._getZoomSpan()) {\n\t\t\tthis.fire('zoomlevelschange');\n\t\t}\n\n\t\tif (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {\n\t\t\tthis.setZoom(this._layersMaxZoom);\n\t\t}\n\t\tif (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {\n\t\t\tthis.setZoom(this._layersMinZoom);\n\t\t}\n\t}\n});\n\n/*\r\n * @class LayerGroup\r\n * @aka L.LayerGroup\r\n * @inherits Layer\r\n *\r\n * Used to group several layers and handle them as one. If you add it to the map,\r\n * any layers added or removed from the group will be added/removed on the map as\r\n * well. Extends `Layer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.layerGroup([marker1, marker2])\r\n * \t.addLayer(polyline)\r\n * \t.addTo(map);\r\n * ```\r\n */\r\n\r\nvar LayerGroup = Layer.extend({\r\n\r\n\tinitialize: function (layers, options) {\r\n\t\tsetOptions(this, options);\r\n\r\n\t\tthis._layers = {};\r\n\r\n\t\tvar i, len;\r\n\r\n\t\tif (layers) {\r\n\t\t\tfor (i = 0, len = layers.length; i < len; i++) {\r\n\t\t\t\tthis.addLayer(layers[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t// @method addLayer(layer: Layer): this\r\n\t// Adds the given layer to the group.\r\n\taddLayer: function (layer) {\r\n\t\tvar id = this.getLayerId(layer);\r\n\r\n\t\tthis._layers[id] = layer;\r\n\r\n\t\tif (this._map) {\r\n\t\t\tthis._map.addLayer(layer);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method removeLayer(layer: Layer): this\r\n\t// Removes the given layer from the group.\r\n\t// @alternative\r\n\t// @method removeLayer(id: Number): this\r\n\t// Removes the layer with the given internal ID from the group.\r\n\tremoveLayer: function (layer) {\r\n\t\tvar id = layer in this._layers ? layer : this.getLayerId(layer);\r\n\r\n\t\tif (this._map && this._layers[id]) {\r\n\t\t\tthis._map.removeLayer(this._layers[id]);\r\n\t\t}\r\n\r\n\t\tdelete this._layers[id];\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method hasLayer(layer: Layer): Boolean\r\n\t// Returns `true` if the given layer is currently added to the group.\r\n\t// @alternative\r\n\t// @method hasLayer(id: Number): Boolean\r\n\t// Returns `true` if the given internal ID is currently added to the group.\r\n\thasLayer: function (layer) {\r\n\t\treturn !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);\r\n\t},\r\n\r\n\t// @method clearLayers(): this\r\n\t// Removes all the layers from the group.\r\n\tclearLayers: function () {\r\n\t\treturn this.eachLayer(this.removeLayer, this);\r\n\t},\r\n\r\n\t// @method invoke(methodName: String, …): this\r\n\t// Calls `methodName` on every layer contained in this group, passing any\r\n\t// additional parameters. Has no effect if the layers contained do not\r\n\t// implement `methodName`.\r\n\tinvoke: function (methodName) {\r\n\t\tvar args = Array.prototype.slice.call(arguments, 1),\r\n\t\t i, layer;\r\n\r\n\t\tfor (i in this._layers) {\r\n\t\t\tlayer = this._layers[i];\r\n\r\n\t\t\tif (layer[methodName]) {\r\n\t\t\t\tlayer[methodName].apply(layer, args);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis.eachLayer(map.addLayer, map);\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tthis.eachLayer(map.removeLayer, map);\r\n\t},\r\n\r\n\t// @method eachLayer(fn: Function, context?: Object): this\r\n\t// Iterates over the layers of the group, optionally specifying context of the iterator function.\r\n\t// ```js\r\n\t// group.eachLayer(function (layer) {\r\n\t// \tlayer.bindPopup('Hello');\r\n\t// });\r\n\t// ```\r\n\teachLayer: function (method, context) {\r\n\t\tfor (var i in this._layers) {\r\n\t\t\tmethod.call(context, this._layers[i]);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getLayer(id: Number): Layer\r\n\t// Returns the layer with the given internal ID.\r\n\tgetLayer: function (id) {\r\n\t\treturn this._layers[id];\r\n\t},\r\n\r\n\t// @method getLayers(): Layer[]\r\n\t// Returns an array of all the layers added to the group.\r\n\tgetLayers: function () {\r\n\t\tvar layers = [];\r\n\t\tthis.eachLayer(layers.push, layers);\r\n\t\treturn layers;\r\n\t},\r\n\r\n\t// @method setZIndex(zIndex: Number): this\r\n\t// Calls `setZIndex` on every layer contained in this group, passing the z-index.\r\n\tsetZIndex: function (zIndex) {\r\n\t\treturn this.invoke('setZIndex', zIndex);\r\n\t},\r\n\r\n\t// @method getLayerId(layer: Layer): Number\r\n\t// Returns the internal ID for a layer\r\n\tgetLayerId: function (layer) {\r\n\t\treturn stamp(layer);\r\n\t}\r\n});\r\n\r\n\r\n// @factory L.layerGroup(layers?: Layer[], options?: Object)\r\n// Create a layer group, optionally given an initial set of layers and an `options` object.\r\nvar layerGroup = function (layers, options) {\r\n\treturn new LayerGroup(layers, options);\r\n};\n\n/*\r\n * @class FeatureGroup\r\n * @aka L.FeatureGroup\r\n * @inherits LayerGroup\r\n *\r\n * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:\r\n * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))\r\n * * Events are propagated to the `FeatureGroup`, so if the group has an event\r\n * handler, it will handle events from any of the layers. This includes mouse events\r\n * and custom events.\r\n * * Has `layeradd` and `layerremove` events\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.featureGroup([marker1, marker2, polyline])\r\n * \t.bindPopup('Hello world!')\r\n * \t.on('click', function() { alert('Clicked on a member of the group!'); })\r\n * \t.addTo(map);\r\n * ```\r\n */\r\n\r\nvar FeatureGroup = LayerGroup.extend({\r\n\r\n\taddLayer: function (layer) {\r\n\t\tif (this.hasLayer(layer)) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tlayer.addEventParent(this);\r\n\r\n\t\tLayerGroup.prototype.addLayer.call(this, layer);\r\n\r\n\t\t// @event layeradd: LayerEvent\r\n\t\t// Fired when a layer is added to this `FeatureGroup`\r\n\t\treturn this.fire('layeradd', {layer: layer});\r\n\t},\r\n\r\n\tremoveLayer: function (layer) {\r\n\t\tif (!this.hasLayer(layer)) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\t\tif (layer in this._layers) {\r\n\t\t\tlayer = this._layers[layer];\r\n\t\t}\r\n\r\n\t\tlayer.removeEventParent(this);\r\n\r\n\t\tLayerGroup.prototype.removeLayer.call(this, layer);\r\n\r\n\t\t// @event layerremove: LayerEvent\r\n\t\t// Fired when a layer is removed from this `FeatureGroup`\r\n\t\treturn this.fire('layerremove', {layer: layer});\r\n\t},\r\n\r\n\t// @method setStyle(style: Path options): this\r\n\t// Sets the given path options to each layer of the group that has a `setStyle` method.\r\n\tsetStyle: function (style) {\r\n\t\treturn this.invoke('setStyle', style);\r\n\t},\r\n\r\n\t// @method bringToFront(): this\r\n\t// Brings the layer group to the top of all other layers\r\n\tbringToFront: function () {\r\n\t\treturn this.invoke('bringToFront');\r\n\t},\r\n\r\n\t// @method bringToBack(): this\r\n\t// Brings the layer group to the back of all other layers\r\n\tbringToBack: function () {\r\n\t\treturn this.invoke('bringToBack');\r\n\t},\r\n\r\n\t// @method getBounds(): LatLngBounds\r\n\t// Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).\r\n\tgetBounds: function () {\r\n\t\tvar bounds = new LatLngBounds();\r\n\r\n\t\tfor (var id in this._layers) {\r\n\t\t\tvar layer = this._layers[id];\r\n\t\t\tbounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());\r\n\t\t}\r\n\t\treturn bounds;\r\n\t}\r\n});\r\n\r\n// @factory L.featureGroup(layers: Layer[])\r\n// Create a feature group, optionally given an initial set of layers.\r\nvar featureGroup = function (layers) {\r\n\treturn new FeatureGroup(layers);\r\n};\n\n/*\r\n * @class Icon\r\n * @aka L.Icon\r\n *\r\n * Represents an icon to provide when creating a marker.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var myIcon = L.icon({\r\n * iconUrl: 'my-icon.png',\r\n * iconRetinaUrl: 'my-icon@2x.png',\r\n * iconSize: [38, 95],\r\n * iconAnchor: [22, 94],\r\n * popupAnchor: [-3, -76],\r\n * shadowUrl: 'my-icon-shadow.png',\r\n * shadowRetinaUrl: 'my-icon-shadow@2x.png',\r\n * shadowSize: [68, 95],\r\n * shadowAnchor: [22, 94]\r\n * });\r\n *\r\n * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);\r\n * ```\r\n *\r\n * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.\r\n *\r\n */\r\n\r\nvar Icon = Class.extend({\r\n\r\n\t/* @section\r\n\t * @aka Icon options\r\n\t *\r\n\t * @option iconUrl: String = null\r\n\t * **(required)** The URL to the icon image (absolute or relative to your script path).\r\n\t *\r\n\t * @option iconRetinaUrl: String = null\r\n\t * The URL to a retina sized version of the icon image (absolute or relative to your\r\n\t * script path). Used for Retina screen devices.\r\n\t *\r\n\t * @option iconSize: Point = null\r\n\t * Size of the icon image in pixels.\r\n\t *\r\n\t * @option iconAnchor: Point = null\r\n\t * The coordinates of the \"tip\" of the icon (relative to its top left corner). The icon\r\n\t * will be aligned so that this point is at the marker's geographical location. Centered\r\n\t * by default if size is specified, also can be set in CSS with negative margins.\r\n\t *\r\n\t * @option popupAnchor: Point = [0, 0]\r\n\t * The coordinates of the point from which popups will \"open\", relative to the icon anchor.\r\n\t *\r\n\t * @option tooltipAnchor: Point = [0, 0]\r\n\t * The coordinates of the point from which tooltips will \"open\", relative to the icon anchor.\r\n\t *\r\n\t * @option shadowUrl: String = null\r\n\t * The URL to the icon shadow image. If not specified, no shadow image will be created.\r\n\t *\r\n\t * @option shadowRetinaUrl: String = null\r\n\t *\r\n\t * @option shadowSize: Point = null\r\n\t * Size of the shadow image in pixels.\r\n\t *\r\n\t * @option shadowAnchor: Point = null\r\n\t * The coordinates of the \"tip\" of the shadow (relative to its top left corner) (the same\r\n\t * as iconAnchor if not specified).\r\n\t *\r\n\t * @option className: String = ''\r\n\t * A custom class name to assign to both icon and shadow images. Empty by default.\r\n\t */\r\n\r\n\toptions: {\r\n\t\tpopupAnchor: [0, 0],\r\n\t\ttooltipAnchor: [0, 0]\r\n\t},\r\n\r\n\tinitialize: function (options) {\r\n\t\tsetOptions(this, options);\r\n\t},\r\n\r\n\t// @method createIcon(oldIcon?: HTMLElement): HTMLElement\r\n\t// Called internally when the icon has to be shown, returns a `` HTML element\r\n\t// styled according to the options.\r\n\tcreateIcon: function (oldIcon) {\r\n\t\treturn this._createIcon('icon', oldIcon);\r\n\t},\r\n\r\n\t// @method createShadow(oldIcon?: HTMLElement): HTMLElement\r\n\t// As `createIcon`, but for the shadow beneath it.\r\n\tcreateShadow: function (oldIcon) {\r\n\t\treturn this._createIcon('shadow', oldIcon);\r\n\t},\r\n\r\n\t_createIcon: function (name, oldIcon) {\r\n\t\tvar src = this._getIconUrl(name);\r\n\r\n\t\tif (!src) {\r\n\t\t\tif (name === 'icon') {\r\n\t\t\t\tthrow new Error('iconUrl not set in Icon options (see the docs).');\r\n\t\t\t}\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tvar img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);\r\n\t\tthis._setIconStyles(img, name);\r\n\r\n\t\treturn img;\r\n\t},\r\n\r\n\t_setIconStyles: function (img, name) {\r\n\t\tvar options = this.options;\r\n\t\tvar sizeOption = options[name + 'Size'];\r\n\r\n\t\tif (typeof sizeOption === 'number') {\r\n\t\t\tsizeOption = [sizeOption, sizeOption];\r\n\t\t}\r\n\r\n\t\tvar size = toPoint(sizeOption),\r\n\t\t anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||\r\n\t\t size && size.divideBy(2, true));\r\n\r\n\t\timg.className = 'leaflet-marker-' + name + ' ' + (options.className || '');\r\n\r\n\t\tif (anchor) {\r\n\t\t\timg.style.marginLeft = (-anchor.x) + 'px';\r\n\t\t\timg.style.marginTop = (-anchor.y) + 'px';\r\n\t\t}\r\n\r\n\t\tif (size) {\r\n\t\t\timg.style.width = size.x + 'px';\r\n\t\t\timg.style.height = size.y + 'px';\r\n\t\t}\r\n\t},\r\n\r\n\t_createImg: function (src, el) {\r\n\t\tel = el || document.createElement('img');\r\n\t\tel.src = src;\r\n\t\treturn el;\r\n\t},\r\n\r\n\t_getIconUrl: function (name) {\r\n\t\treturn retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];\r\n\t}\r\n});\r\n\r\n\r\n// @factory L.icon(options: Icon options)\r\n// Creates an icon instance with the given options.\r\nfunction icon(options) {\r\n\treturn new Icon(options);\r\n}\n\n/*\n * @miniclass Icon.Default (Icon)\n * @aka L.Icon.Default\n * @section\n *\n * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when\n * no icon is specified. Points to the blue marker image distributed with Leaflet\n * releases.\n *\n * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`\n * (which is a set of `Icon options`).\n *\n * If you want to _completely_ replace the default icon, override the\n * `L.Marker.prototype.options.icon` with your own icon instead.\n */\n\nvar IconDefault = Icon.extend({\n\n\toptions: {\n\t\ticonUrl: 'marker-icon.png',\n\t\ticonRetinaUrl: 'marker-icon-2x.png',\n\t\tshadowUrl: 'marker-shadow.png',\n\t\ticonSize: [25, 41],\n\t\ticonAnchor: [12, 41],\n\t\tpopupAnchor: [1, -34],\n\t\ttooltipAnchor: [16, -28],\n\t\tshadowSize: [41, 41]\n\t},\n\n\t_getIconUrl: function (name) {\n\t\tif (!IconDefault.imagePath) {\t// Deprecated, backwards-compatibility only\n\t\t\tIconDefault.imagePath = this._detectIconPath();\n\t\t}\n\n\t\t// @option imagePath: String\n\t\t// `Icon.Default` will try to auto-detect the location of the\n\t\t// blue icon images. If you are placing these images in a non-standard\n\t\t// way, set this option to point to the right path.\n\t\treturn (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);\n\t},\n\n\t_detectIconPath: function () {\n\t\tvar el = create$1('div', 'leaflet-default-icon-path', document.body);\n\t\tvar path = getStyle(el, 'background-image') ||\n\t\t getStyle(el, 'backgroundImage');\t// IE8\n\n\t\tdocument.body.removeChild(el);\n\n\t\tif (path === null || path.indexOf('url') !== 0) {\n\t\t\tpath = '';\n\t\t} else {\n\t\t\tpath = path.replace(/^url\\([\"']?/, '').replace(/marker-icon\\.png[\"']?\\)$/, '');\n\t\t}\n\n\t\treturn path;\n\t}\n});\n\n/*\n * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.\n */\n\n\n/* @namespace Marker\n * @section Interaction handlers\n *\n * Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see `Handler` methods). Example:\n *\n * ```js\n * marker.dragging.disable();\n * ```\n *\n * @property dragging: Handler\n * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).\n */\n\nvar MarkerDrag = Handler.extend({\n\tinitialize: function (marker) {\n\t\tthis._marker = marker;\n\t},\n\n\taddHooks: function () {\n\t\tvar icon = this._marker._icon;\n\n\t\tif (!this._draggable) {\n\t\t\tthis._draggable = new Draggable(icon, icon, true);\n\t\t}\n\n\t\tthis._draggable.on({\n\t\t\tdragstart: this._onDragStart,\n\t\t\tpredrag: this._onPreDrag,\n\t\t\tdrag: this._onDrag,\n\t\t\tdragend: this._onDragEnd\n\t\t}, this).enable();\n\n\t\taddClass(icon, 'leaflet-marker-draggable');\n\t},\n\n\tremoveHooks: function () {\n\t\tthis._draggable.off({\n\t\t\tdragstart: this._onDragStart,\n\t\t\tpredrag: this._onPreDrag,\n\t\t\tdrag: this._onDrag,\n\t\t\tdragend: this._onDragEnd\n\t\t}, this).disable();\n\n\t\tif (this._marker._icon) {\n\t\t\tremoveClass(this._marker._icon, 'leaflet-marker-draggable');\n\t\t}\n\t},\n\n\tmoved: function () {\n\t\treturn this._draggable && this._draggable._moved;\n\t},\n\n\t_adjustPan: function (e) {\n\t\tvar marker = this._marker,\n\t\t map = marker._map,\n\t\t speed = this._marker.options.autoPanSpeed,\n\t\t padding = this._marker.options.autoPanPadding,\n\t\t iconPos = getPosition(marker._icon),\n\t\t bounds = map.getPixelBounds(),\n\t\t origin = map.getPixelOrigin();\n\n\t\tvar panBounds = toBounds(\n\t\t\tbounds.min._subtract(origin).add(padding),\n\t\t\tbounds.max._subtract(origin).subtract(padding)\n\t\t);\n\n\t\tif (!panBounds.contains(iconPos)) {\n\t\t\t// Compute incremental movement\n\t\t\tvar movement = toPoint(\n\t\t\t\t(Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -\n\t\t\t\t(Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),\n\n\t\t\t\t(Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -\n\t\t\t\t(Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)\n\t\t\t).multiplyBy(speed);\n\n\t\t\tmap.panBy(movement, {animate: false});\n\n\t\t\tthis._draggable._newPos._add(movement);\n\t\t\tthis._draggable._startPos._add(movement);\n\n\t\t\tsetPosition(marker._icon, this._draggable._newPos);\n\t\t\tthis._onDrag(e);\n\n\t\t\tthis._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));\n\t\t}\n\t},\n\n\t_onDragStart: function () {\n\t\t// @section Dragging events\n\t\t// @event dragstart: Event\n\t\t// Fired when the user starts dragging the marker.\n\n\t\t// @event movestart: Event\n\t\t// Fired when the marker starts moving (because of dragging).\n\n\t\tthis._oldLatLng = this._marker.getLatLng();\n\t\tthis._marker\n\t\t .closePopup()\n\t\t .fire('movestart')\n\t\t .fire('dragstart');\n\t},\n\n\t_onPreDrag: function (e) {\n\t\tif (this._marker.options.autoPan) {\n\t\t\tcancelAnimFrame(this._panRequest);\n\t\t\tthis._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));\n\t\t}\n\t},\n\n\t_onDrag: function (e) {\n\t\tvar marker = this._marker,\n\t\t shadow = marker._shadow,\n\t\t iconPos = getPosition(marker._icon),\n\t\t latlng = marker._map.layerPointToLatLng(iconPos);\n\n\t\t// update shadow position\n\t\tif (shadow) {\n\t\t\tsetPosition(shadow, iconPos);\n\t\t}\n\n\t\tmarker._latlng = latlng;\n\t\te.latlng = latlng;\n\t\te.oldLatLng = this._oldLatLng;\n\n\t\t// @event drag: Event\n\t\t// Fired repeatedly while the user drags the marker.\n\t\tmarker\n\t\t .fire('move', e)\n\t\t .fire('drag', e);\n\t},\n\n\t_onDragEnd: function (e) {\n\t\t// @event dragend: DragEndEvent\n\t\t// Fired when the user stops dragging the marker.\n\n\t\t cancelAnimFrame(this._panRequest);\n\n\t\t// @event moveend: Event\n\t\t// Fired when the marker stops moving (because of dragging).\n\t\tdelete this._oldLatLng;\n\t\tthis._marker\n\t\t .fire('moveend')\n\t\t .fire('dragend', e);\n\t}\n});\n\n/*\r\n * @class Marker\r\n * @inherits Interactive layer\r\n * @aka L.Marker\r\n * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.marker([50.5, 30.5]).addTo(map);\r\n * ```\r\n */\r\n\r\nvar Marker = Layer.extend({\r\n\r\n\t// @section\r\n\t// @aka Marker options\r\n\toptions: {\r\n\t\t// @option icon: Icon = *\r\n\t\t// Icon instance to use for rendering the marker.\r\n\t\t// See [Icon documentation](#L.Icon) for details on how to customize the marker icon.\r\n\t\t// If not specified, a common instance of `L.Icon.Default` is used.\r\n\t\ticon: new IconDefault(),\r\n\r\n\t\t// Option inherited from \"Interactive layer\" abstract class\r\n\t\tinteractive: true,\r\n\r\n\t\t// @option keyboard: Boolean = true\r\n\t\t// Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.\r\n\t\tkeyboard: true,\r\n\r\n\t\t// @option title: String = ''\r\n\t\t// Text for the browser tooltip that appear on marker hover (no tooltip by default).\r\n\t\ttitle: '',\r\n\r\n\t\t// @option alt: String = ''\r\n\t\t// Text for the `alt` attribute of the icon image (useful for accessibility).\r\n\t\talt: '',\r\n\r\n\t\t// @option zIndexOffset: Number = 0\r\n\t\t// By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like `1000` (or high negative value, respectively).\r\n\t\tzIndexOffset: 0,\r\n\r\n\t\t// @option opacity: Number = 1.0\r\n\t\t// The opacity of the marker.\r\n\t\topacity: 1,\r\n\r\n\t\t// @option riseOnHover: Boolean = false\r\n\t\t// If `true`, the marker will get on top of others when you hover the mouse over it.\r\n\t\triseOnHover: false,\r\n\r\n\t\t// @option riseOffset: Number = 250\r\n\t\t// The z-index offset used for the `riseOnHover` feature.\r\n\t\triseOffset: 250,\r\n\r\n\t\t// @option pane: String = 'markerPane'\r\n\t\t// `Map pane` where the markers icon will be added.\r\n\t\tpane: 'markerPane',\r\n\r\n\t\t// @option pane: String = 'shadowPane'\r\n\t\t// `Map pane` where the markers shadow will be added.\r\n\t\tshadowPane: 'shadowPane',\r\n\r\n\t\t// @option bubblingMouseEvents: Boolean = false\r\n\t\t// When `true`, a mouse event on this marker will trigger the same event on the map\r\n\t\t// (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).\r\n\t\tbubblingMouseEvents: false,\r\n\r\n\t\t// @section Draggable marker options\r\n\t\t// @option draggable: Boolean = false\r\n\t\t// Whether the marker is draggable with mouse/touch or not.\r\n\t\tdraggable: false,\r\n\r\n\t\t// @option autoPan: Boolean = false\r\n\t\t// Whether to pan the map when dragging this marker near its edge or not.\r\n\t\tautoPan: false,\r\n\r\n\t\t// @option autoPanPadding: Point = Point(50, 50)\r\n\t\t// Distance (in pixels to the left/right and to the top/bottom) of the\r\n\t\t// map edge to start panning the map.\r\n\t\tautoPanPadding: [50, 50],\r\n\r\n\t\t// @option autoPanSpeed: Number = 10\r\n\t\t// Number of pixels the map should pan by.\r\n\t\tautoPanSpeed: 10\r\n\t},\r\n\r\n\t/* @section\r\n\t *\r\n\t * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:\r\n\t */\r\n\r\n\tinitialize: function (latlng, options) {\r\n\t\tsetOptions(this, options);\r\n\t\tthis._latlng = toLatLng(latlng);\r\n\t},\r\n\r\n\tonAdd: function (map) {\r\n\t\tthis._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tmap.on('zoomanim', this._animateZoom, this);\r\n\t\t}\r\n\r\n\t\tthis._initIcon();\r\n\t\tthis.update();\r\n\t},\r\n\r\n\tonRemove: function (map) {\r\n\t\tif (this.dragging && this.dragging.enabled()) {\r\n\t\t\tthis.options.draggable = true;\r\n\t\t\tthis.dragging.removeHooks();\r\n\t\t}\r\n\t\tdelete this.dragging;\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tmap.off('zoomanim', this._animateZoom, this);\r\n\t\t}\r\n\r\n\t\tthis._removeIcon();\r\n\t\tthis._removeShadow();\r\n\t},\r\n\r\n\tgetEvents: function () {\r\n\t\treturn {\r\n\t\t\tzoom: this.update,\r\n\t\t\tviewreset: this.update\r\n\t\t};\r\n\t},\r\n\r\n\t// @method getLatLng: LatLng\r\n\t// Returns the current geographical position of the marker.\r\n\tgetLatLng: function () {\r\n\t\treturn this._latlng;\r\n\t},\r\n\r\n\t// @method setLatLng(latlng: LatLng): this\r\n\t// Changes the marker position to the given point.\r\n\tsetLatLng: function (latlng) {\r\n\t\tvar oldLatLng = this._latlng;\r\n\t\tthis._latlng = toLatLng(latlng);\r\n\t\tthis.update();\r\n\r\n\t\t// @event move: Event\r\n\t\t// Fired when the marker is moved via [`setLatLng`](#marker-setlatlng) or by [dragging](#marker-dragging). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`.\r\n\t\treturn this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});\r\n\t},\r\n\r\n\t// @method setZIndexOffset(offset: Number): this\r\n\t// Changes the [zIndex offset](#marker-zindexoffset) of the marker.\r\n\tsetZIndexOffset: function (offset) {\r\n\t\tthis.options.zIndexOffset = offset;\r\n\t\treturn this.update();\r\n\t},\r\n\r\n\t// @method getIcon: Icon\r\n\t// Returns the current icon used by the marker\r\n\tgetIcon: function () {\r\n\t\treturn this.options.icon;\r\n\t},\r\n\r\n\t// @method setIcon(icon: Icon): this\r\n\t// Changes the marker icon.\r\n\tsetIcon: function (icon) {\r\n\r\n\t\tthis.options.icon = icon;\r\n\r\n\t\tif (this._map) {\r\n\t\t\tthis._initIcon();\r\n\t\t\tthis.update();\r\n\t\t}\r\n\r\n\t\tif (this._popup) {\r\n\t\t\tthis.bindPopup(this._popup, this._popup.options);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\tgetElement: function () {\r\n\t\treturn this._icon;\r\n\t},\r\n\r\n\tupdate: function () {\r\n\r\n\t\tif (this._icon && this._map) {\r\n\t\t\tvar pos = this._map.latLngToLayerPoint(this._latlng).round();\r\n\t\t\tthis._setPos(pos);\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_initIcon: function () {\r\n\t\tvar options = this.options,\r\n\t\t classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');\r\n\r\n\t\tvar icon = options.icon.createIcon(this._icon),\r\n\t\t addIcon = false;\r\n\r\n\t\t// if we're not reusing the icon, remove the old one and init new one\r\n\t\tif (icon !== this._icon) {\r\n\t\t\tif (this._icon) {\r\n\t\t\t\tthis._removeIcon();\r\n\t\t\t}\r\n\t\t\taddIcon = true;\r\n\r\n\t\t\tif (options.title) {\r\n\t\t\t\ticon.title = options.title;\r\n\t\t\t}\r\n\r\n\t\t\tif (icon.tagName === 'IMG') {\r\n\t\t\t\ticon.alt = options.alt || '';\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\taddClass(icon, classToAdd);\r\n\r\n\t\tif (options.keyboard) {\r\n\t\t\ticon.tabIndex = '0';\r\n\t\t}\r\n\r\n\t\tthis._icon = icon;\r\n\r\n\t\tif (options.riseOnHover) {\r\n\t\t\tthis.on({\r\n\t\t\t\tmouseover: this._bringToFront,\r\n\t\t\t\tmouseout: this._resetZIndex\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tvar newShadow = options.icon.createShadow(this._shadow),\r\n\t\t addShadow = false;\r\n\r\n\t\tif (newShadow !== this._shadow) {\r\n\t\t\tthis._removeShadow();\r\n\t\t\taddShadow = true;\r\n\t\t}\r\n\r\n\t\tif (newShadow) {\r\n\t\t\taddClass(newShadow, classToAdd);\r\n\t\t\tnewShadow.alt = '';\r\n\t\t}\r\n\t\tthis._shadow = newShadow;\r\n\r\n\r\n\t\tif (options.opacity < 1) {\r\n\t\t\tthis._updateOpacity();\r\n\t\t}\r\n\r\n\r\n\t\tif (addIcon) {\r\n\t\t\tthis.getPane().appendChild(this._icon);\r\n\t\t}\r\n\t\tthis._initInteraction();\r\n\t\tif (newShadow && addShadow) {\r\n\t\t\tthis.getPane(options.shadowPane).appendChild(this._shadow);\r\n\t\t}\r\n\t},\r\n\r\n\t_removeIcon: function () {\r\n\t\tif (this.options.riseOnHover) {\r\n\t\t\tthis.off({\r\n\t\t\t\tmouseover: this._bringToFront,\r\n\t\t\t\tmouseout: this._resetZIndex\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tremove(this._icon);\r\n\t\tthis.removeInteractiveTarget(this._icon);\r\n\r\n\t\tthis._icon = null;\r\n\t},\r\n\r\n\t_removeShadow: function () {\r\n\t\tif (this._shadow) {\r\n\t\t\tremove(this._shadow);\r\n\t\t}\r\n\t\tthis._shadow = null;\r\n\t},\r\n\r\n\t_setPos: function (pos) {\r\n\t\tsetPosition(this._icon, pos);\r\n\r\n\t\tif (this._shadow) {\r\n\t\t\tsetPosition(this._shadow, pos);\r\n\t\t}\r\n\r\n\t\tthis._zIndex = pos.y + this.options.zIndexOffset;\r\n\r\n\t\tthis._resetZIndex();\r\n\t},\r\n\r\n\t_updateZIndex: function (offset) {\r\n\t\tthis._icon.style.zIndex = this._zIndex + offset;\r\n\t},\r\n\r\n\t_animateZoom: function (opt) {\r\n\t\tvar pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();\r\n\r\n\t\tthis._setPos(pos);\r\n\t},\r\n\r\n\t_initInteraction: function () {\r\n\r\n\t\tif (!this.options.interactive) { return; }\r\n\r\n\t\taddClass(this._icon, 'leaflet-interactive');\r\n\r\n\t\tthis.addInteractiveTarget(this._icon);\r\n\r\n\t\tif (MarkerDrag) {\r\n\t\t\tvar draggable = this.options.draggable;\r\n\t\t\tif (this.dragging) {\r\n\t\t\t\tdraggable = this.dragging.enabled();\r\n\t\t\t\tthis.dragging.disable();\r\n\t\t\t}\r\n\r\n\t\t\tthis.dragging = new MarkerDrag(this);\r\n\r\n\t\t\tif (draggable) {\r\n\t\t\t\tthis.dragging.enable();\r\n\t\t\t}\r\n\t\t}\r\n\t},\r\n\r\n\t// @method setOpacity(opacity: Number): this\r\n\t// Changes the opacity of the marker.\r\n\tsetOpacity: function (opacity) {\r\n\t\tthis.options.opacity = opacity;\r\n\t\tif (this._map) {\r\n\t\t\tthis._updateOpacity();\r\n\t\t}\r\n\r\n\t\treturn this;\r\n\t},\r\n\r\n\t_updateOpacity: function () {\r\n\t\tvar opacity = this.options.opacity;\r\n\r\n\t\tif (this._icon) {\r\n\t\t\tsetOpacity(this._icon, opacity);\r\n\t\t}\r\n\r\n\t\tif (this._shadow) {\r\n\t\t\tsetOpacity(this._shadow, opacity);\r\n\t\t}\r\n\t},\r\n\r\n\t_bringToFront: function () {\r\n\t\tthis._updateZIndex(this.options.riseOffset);\r\n\t},\r\n\r\n\t_resetZIndex: function () {\r\n\t\tthis._updateZIndex(0);\r\n\t},\r\n\r\n\t_getPopupAnchor: function () {\r\n\t\treturn this.options.icon.options.popupAnchor;\r\n\t},\r\n\r\n\t_getTooltipAnchor: function () {\r\n\t\treturn this.options.icon.options.tooltipAnchor;\r\n\t}\r\n});\r\n\r\n\r\n// factory L.marker(latlng: LatLng, options? : Marker options)\r\n\r\n// @factory L.marker(latlng: LatLng, options? : Marker options)\r\n// Instantiates a Marker object given a geographical point and optionally an options object.\r\nfunction marker(latlng, options) {\r\n\treturn new Marker(latlng, options);\r\n}\n\n/*\n * @class Path\n * @aka L.Path\n * @inherits Interactive layer\n *\n * An abstract class that contains options and constants shared between vector\n * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.\n */\n\nvar Path = Layer.extend({\n\n\t// @section\n\t// @aka Path options\n\toptions: {\n\t\t// @option stroke: Boolean = true\n\t\t// Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.\n\t\tstroke: true,\n\n\t\t// @option color: String = '#3388ff'\n\t\t// Stroke color\n\t\tcolor: '#3388ff',\n\n\t\t// @option weight: Number = 3\n\t\t// Stroke width in pixels\n\t\tweight: 3,\n\n\t\t// @option opacity: Number = 1.0\n\t\t// Stroke opacity\n\t\topacity: 1,\n\n\t\t// @option lineCap: String= 'round'\n\t\t// A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.\n\t\tlineCap: 'round',\n\n\t\t// @option lineJoin: String = 'round'\n\t\t// A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.\n\t\tlineJoin: 'round',\n\n\t\t// @option dashArray: String = null\n\t\t// A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).\n\t\tdashArray: null,\n\n\t\t// @option dashOffset: String = null\n\t\t// A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on `Canvas`-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility).\n\t\tdashOffset: null,\n\n\t\t// @option fill: Boolean = depends\n\t\t// Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.\n\t\tfill: false,\n\n\t\t// @option fillColor: String = *\n\t\t// Fill color. Defaults to the value of the [`color`](#path-color) option\n\t\tfillColor: null,\n\n\t\t// @option fillOpacity: Number = 0.2\n\t\t// Fill opacity.\n\t\tfillOpacity: 0.2,\n\n\t\t// @option fillRule: String = 'evenodd'\n\t\t// A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.\n\t\tfillRule: 'evenodd',\n\n\t\t// className: '',\n\n\t\t// Option inherited from \"Interactive layer\" abstract class\n\t\tinteractive: true,\n\n\t\t// @option bubblingMouseEvents: Boolean = true\n\t\t// When `true`, a mouse event on this path will trigger the same event on the map\n\t\t// (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).\n\t\tbubblingMouseEvents: true\n\t},\n\n\tbeforeAdd: function (map) {\n\t\t// Renderer is set here because we need to call renderer.getEvents\n\t\t// before this.getEvents.\n\t\tthis._renderer = map.getRenderer(this);\n\t},\n\n\tonAdd: function () {\n\t\tthis._renderer._initPath(this);\n\t\tthis._reset();\n\t\tthis._renderer._addPath(this);\n\t},\n\n\tonRemove: function () {\n\t\tthis._renderer._removePath(this);\n\t},\n\n\t// @method redraw(): this\n\t// Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.\n\tredraw: function () {\n\t\tif (this._map) {\n\t\t\tthis._renderer._updatePath(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method setStyle(style: Path options): this\n\t// Changes the appearance of a Path based on the options in the `Path options` object.\n\tsetStyle: function (style) {\n\t\tsetOptions(this, style);\n\t\tif (this._renderer) {\n\t\t\tthis._renderer._updateStyle(this);\n\t\t\tif (this.options.stroke && style.hasOwnProperty('weight')) {\n\t\t\t\tthis._updateBounds();\n\t\t\t}\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method bringToFront(): this\n\t// Brings the layer to the top of all path layers.\n\tbringToFront: function () {\n\t\tif (this._renderer) {\n\t\t\tthis._renderer._bringToFront(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\t// @method bringToBack(): this\n\t// Brings the layer to the bottom of all path layers.\n\tbringToBack: function () {\n\t\tif (this._renderer) {\n\t\t\tthis._renderer._bringToBack(this);\n\t\t}\n\t\treturn this;\n\t},\n\n\tgetElement: function () {\n\t\treturn this._path;\n\t},\n\n\t_reset: function () {\n\t\t// defined in child classes\n\t\tthis._project();\n\t\tthis._update();\n\t},\n\n\t_clickTolerance: function () {\n\t\t// used when doing hit detection for Canvas layers\n\t\treturn (this.options.stroke ? this.options.weight / 2 : 0) + this._renderer.options.tolerance;\n\t}\n});\n\n/*\n * @class CircleMarker\n * @aka L.CircleMarker\n * @inherits Path\n *\n * A circle of a fixed size with radius specified in pixels. Extends `Path`.\n */\n\nvar CircleMarker = Path.extend({\n\n\t// @section\n\t// @aka CircleMarker options\n\toptions: {\n\t\tfill: true,\n\n\t\t// @option radius: Number = 10\n\t\t// Radius of the circle marker, in pixels\n\t\tradius: 10\n\t},\n\n\tinitialize: function (latlng, options) {\n\t\tsetOptions(this, options);\n\t\tthis._latlng = toLatLng(latlng);\n\t\tthis._radius = this.options.radius;\n\t},\n\n\t// @method setLatLng(latLng: LatLng): this\n\t// Sets the position of a circle marker to a new location.\n\tsetLatLng: function (latlng) {\n\t\tthis._latlng = toLatLng(latlng);\n\t\tthis.redraw();\n\t\treturn this.fire('move', {latlng: this._latlng});\n\t},\n\n\t// @method getLatLng(): LatLng\n\t// Returns the current geographical position of the circle marker\n\tgetLatLng: function () {\n\t\treturn this._latlng;\n\t},\n\n\t// @method setRadius(radius: Number): this\n\t// Sets the radius of a circle marker. Units are in pixels.\n\tsetRadius: function (radius) {\n\t\tthis.options.radius = this._radius = radius;\n\t\treturn this.redraw();\n\t},\n\n\t// @method getRadius(): Number\n\t// Returns the current radius of the circle\n\tgetRadius: function () {\n\t\treturn this._radius;\n\t},\n\n\tsetStyle : function (options) {\n\t\tvar radius = options && options.radius || this._radius;\n\t\tPath.prototype.setStyle.call(this, options);\n\t\tthis.setRadius(radius);\n\t\treturn this;\n\t},\n\n\t_project: function () {\n\t\tthis._point = this._map.latLngToLayerPoint(this._latlng);\n\t\tthis._updateBounds();\n\t},\n\n\t_updateBounds: function () {\n\t\tvar r = this._radius,\n\t\t r2 = this._radiusY || r,\n\t\t w = this._clickTolerance(),\n\t\t p = [r + w, r2 + w];\n\t\tthis._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));\n\t},\n\n\t_update: function () {\n\t\tif (this._map) {\n\t\t\tthis._updatePath();\n\t\t}\n\t},\n\n\t_updatePath: function () {\n\t\tthis._renderer._updateCircle(this);\n\t},\n\n\t_empty: function () {\n\t\treturn this._radius && !this._renderer._bounds.intersects(this._pxBounds);\n\t},\n\n\t// Needed by the `Canvas` renderer for interactivity\n\t_containsPoint: function (p) {\n\t\treturn p.distanceTo(this._point) <= this._radius + this._clickTolerance();\n\t}\n});\n\n\n// @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)\n// Instantiates a circle marker object given a geographical point, and an optional options object.\nfunction circleMarker(latlng, options) {\n\treturn new CircleMarker(latlng, options);\n}\n\n/*\n * @class Circle\n * @aka L.Circle\n * @inherits CircleMarker\n *\n * A class for drawing circle overlays on a map. Extends `CircleMarker`.\n *\n * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).\n *\n * @example\n *\n * ```js\n * L.circle([50.5, 30.5], {radius: 200}).addTo(map);\n * ```\n */\n\nvar Circle = CircleMarker.extend({\n\n\tinitialize: function (latlng, options, legacyOptions) {\n\t\tif (typeof options === 'number') {\n\t\t\t// Backwards compatibility with 0.7.x factory (latlng, radius, options?)\n\t\t\toptions = extend({}, legacyOptions, {radius: options});\n\t\t}\n\t\tsetOptions(this, options);\n\t\tthis._latlng = toLatLng(latlng);\n\n\t\tif (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }\n\n\t\t// @section\n\t\t// @aka Circle options\n\t\t// @option radius: Number; Radius of the circle, in meters.\n\t\tthis._mRadius = this.options.radius;\n\t},\n\n\t// @method setRadius(radius: Number): this\n\t// Sets the radius of a circle. Units are in meters.\n\tsetRadius: function (radius) {\n\t\tthis._mRadius = radius;\n\t\treturn this.redraw();\n\t},\n\n\t// @method getRadius(): Number\n\t// Returns the current radius of a circle. Units are in meters.\n\tgetRadius: function () {\n\t\treturn this._mRadius;\n\t},\n\n\t// @method getBounds(): LatLngBounds\n\t// Returns the `LatLngBounds` of the path.\n\tgetBounds: function () {\n\t\tvar half = [this._radius, this._radiusY || this._radius];\n\n\t\treturn new LatLngBounds(\n\t\t\tthis._map.layerPointToLatLng(this._point.subtract(half)),\n\t\t\tthis._map.layerPointToLatLng(this._point.add(half)));\n\t},\n\n\tsetStyle: Path.prototype.setStyle,\n\n\t_project: function () {\n\n\t\tvar lng = this._latlng.lng,\n\t\t lat = this._latlng.lat,\n\t\t map = this._map,\n\t\t crs = map.options.crs;\n\n\t\tif (crs.distance === Earth.distance) {\n\t\t\tvar d = Math.PI / 180,\n\t\t\t latR = (this._mRadius / Earth.R) / d,\n\t\t\t top = map.project([lat + latR, lng]),\n\t\t\t bottom = map.project([lat - latR, lng]),\n\t\t\t p = top.add(bottom).divideBy(2),\n\t\t\t lat2 = map.unproject(p).lat,\n\t\t\t lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /\n\t\t\t (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;\n\n\t\t\tif (isNaN(lngR) || lngR === 0) {\n\t\t\t\tlngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425\n\t\t\t}\n\n\t\t\tthis._point = p.subtract(map.getPixelOrigin());\n\t\t\tthis._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;\n\t\t\tthis._radiusY = p.y - top.y;\n\n\t\t} else {\n\t\t\tvar latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));\n\n\t\t\tthis._point = map.latLngToLayerPoint(this._latlng);\n\t\t\tthis._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;\n\t\t}\n\n\t\tthis._updateBounds();\n\t}\n});\n\n// @factory L.circle(latlng: LatLng, options?: Circle options)\n// Instantiates a circle object given a geographical point, and an options object\n// which contains the circle radius.\n// @alternative\n// @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)\n// Obsolete way of instantiating a circle, for compatibility with 0.7.x code.\n// Do not use in new applications or plugins.\nfunction circle(latlng, options, legacyOptions) {\n\treturn new Circle(latlng, options, legacyOptions);\n}\n\n/*\n * @class Polyline\n * @aka L.Polyline\n * @inherits Path\n *\n * A class for drawing polyline overlays on a map. Extends `Path`.\n *\n * @example\n *\n * ```js\n * // create a red polyline from an array of LatLng points\n * var latlngs = [\n * \t[45.51, -122.68],\n * \t[37.77, -122.43],\n * \t[34.04, -118.2]\n * ];\n *\n * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);\n *\n * // zoom the map to the polyline\n * map.fitBounds(polyline.getBounds());\n * ```\n *\n * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:\n *\n * ```js\n * // create a red polyline from an array of arrays of LatLng points\n * var latlngs = [\n * \t[[45.51, -122.68],\n * \t [37.77, -122.43],\n * \t [34.04, -118.2]],\n * \t[[40.78, -73.91],\n * \t [41.83, -87.62],\n * \t [32.76, -96.72]]\n * ];\n * ```\n */\n\n\nvar Polyline = Path.extend({\n\n\t// @section\n\t// @aka Polyline options\n\toptions: {\n\t\t// @option smoothFactor: Number = 1.0\n\t\t// How much to simplify the polyline on each zoom level. More means\n\t\t// better performance and smoother look, and less means more accurate representation.\n\t\tsmoothFactor: 1.0,\n\n\t\t// @option noClip: Boolean = false\n\t\t// Disable polyline clipping.\n\t\tnoClip: false\n\t},\n\n\tinitialize: function (latlngs, options) {\n\t\tsetOptions(this, options);\n\t\tthis._setLatLngs(latlngs);\n\t},\n\n\t// @method getLatLngs(): LatLng[]\n\t// Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.\n\tgetLatLngs: function () {\n\t\treturn this._latlngs;\n\t},\n\n\t// @method setLatLngs(latlngs: LatLng[]): this\n\t// Replaces all the points in the polyline with the given array of geographical points.\n\tsetLatLngs: function (latlngs) {\n\t\tthis._setLatLngs(latlngs);\n\t\treturn this.redraw();\n\t},\n\n\t// @method isEmpty(): Boolean\n\t// Returns `true` if the Polyline has no LatLngs.\n\tisEmpty: function () {\n\t\treturn !this._latlngs.length;\n\t},\n\n\t// @method closestLayerPoint(p: Point): Point\n\t// Returns the point closest to `p` on the Polyline.\n\tclosestLayerPoint: function (p) {\n\t\tvar minDistance = Infinity,\n\t\t minPoint = null,\n\t\t closest = _sqClosestPointOnSegment,\n\t\t p1, p2;\n\n\t\tfor (var j = 0, jLen = this._parts.length; j < jLen; j++) {\n\t\t\tvar points = this._parts[j];\n\n\t\t\tfor (var i = 1, len = points.length; i < len; i++) {\n\t\t\t\tp1 = points[i - 1];\n\t\t\t\tp2 = points[i];\n\n\t\t\t\tvar sqDist = closest(p, p1, p2, true);\n\n\t\t\t\tif (sqDist < minDistance) {\n\t\t\t\t\tminDistance = sqDist;\n\t\t\t\t\tminPoint = closest(p, p1, p2);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (minPoint) {\n\t\t\tminPoint.distance = Math.sqrt(minDistance);\n\t\t}\n\t\treturn minPoint;\n\t},\n\n\t// @method getCenter(): LatLng\n\t// Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.\n\tgetCenter: function () {\n\t\t// throws error when not yet added to map as this center calculation requires projected coordinates\n\t\tif (!this._map) {\n\t\t\tthrow new Error('Must add layer to map before using getCenter()');\n\t\t}\n\n\t\tvar i, halfDist, segDist, dist, p1, p2, ratio,\n\t\t points = this._rings[0],\n\t\t len = points.length;\n\n\t\tif (!len) { return null; }\n\n\t\t// polyline centroid algorithm; only uses the first ring if there are multiple\n\n\t\tfor (i = 0, halfDist = 0; i < len - 1; i++) {\n\t\t\thalfDist += points[i].distanceTo(points[i + 1]) / 2;\n\t\t}\n\n\t\t// The line is so small in the current view that all points are on the same pixel.\n\t\tif (halfDist === 0) {\n\t\t\treturn this._map.layerPointToLatLng(points[0]);\n\t\t}\n\n\t\tfor (i = 0, dist = 0; i < len - 1; i++) {\n\t\t\tp1 = points[i];\n\t\t\tp2 = points[i + 1];\n\t\t\tsegDist = p1.distanceTo(p2);\n\t\t\tdist += segDist;\n\n\t\t\tif (dist > halfDist) {\n\t\t\t\tratio = (dist - halfDist) / segDist;\n\t\t\t\treturn this._map.layerPointToLatLng([\n\t\t\t\t\tp2.x - ratio * (p2.x - p1.x),\n\t\t\t\t\tp2.y - ratio * (p2.y - p1.y)\n\t\t\t\t]);\n\t\t\t}\n\t\t}\n\t},\n\n\t// @method getBounds(): LatLngBounds\n\t// Returns the `LatLngBounds` of the path.\n\tgetBounds: function () {\n\t\treturn this._bounds;\n\t},\n\n\t// @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this\n\t// Adds a given point to the polyline. By default, adds to the first ring of\n\t// the polyline in case of a multi-polyline, but can be overridden by passing\n\t// a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).\n\taddLatLng: function (latlng, latlngs) {\n\t\tlatlngs = latlngs || this._defaultShape();\n\t\tlatlng = toLatLng(latlng);\n\t\tlatlngs.push(latlng);\n\t\tthis._bounds.extend(latlng);\n\t\treturn this.redraw();\n\t},\n\n\t_setLatLngs: function (latlngs) {\n\t\tthis._bounds = new LatLngBounds();\n\t\tthis._latlngs = this._convertLatLngs(latlngs);\n\t},\n\n\t_defaultShape: function () {\n\t\treturn isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];\n\t},\n\n\t// recursively convert latlngs input into actual LatLng instances; calculate bounds along the way\n\t_convertLatLngs: function (latlngs) {\n\t\tvar result = [],\n\t\t flat = isFlat(latlngs);\n\n\t\tfor (var i = 0, len = latlngs.length; i < len; i++) {\n\t\t\tif (flat) {\n\t\t\t\tresult[i] = toLatLng(latlngs[i]);\n\t\t\t\tthis._bounds.extend(result[i]);\n\t\t\t} else {\n\t\t\t\tresult[i] = this._convertLatLngs(latlngs[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t},\n\n\t_project: function () {\n\t\tvar pxBounds = new Bounds();\n\t\tthis._rings = [];\n\t\tthis._projectLatlngs(this._latlngs, this._rings, pxBounds);\n\n\t\tif (this._bounds.isValid() && pxBounds.isValid()) {\n\t\t\tthis._rawPxBounds = pxBounds;\n\t\t\tthis._updateBounds();\n\t\t}\n\t},\n\n\t_updateBounds: function () {\n\t\tvar w = this._clickTolerance(),\n\t\t p = new Point(w, w);\n\t\tthis._pxBounds = new Bounds([\n\t\t\tthis._rawPxBounds.min.subtract(p),\n\t\t\tthis._rawPxBounds.max.add(p)\n\t\t]);\n\t},\n\n\t// recursively turns latlngs into a set of rings with projected coordinates\n\t_projectLatlngs: function (latlngs, result, projectedBounds) {\n\t\tvar flat = latlngs[0] instanceof LatLng,\n\t\t len = latlngs.length,\n\t\t i, ring;\n\n\t\tif (flat) {\n\t\t\tring = [];\n\t\t\tfor (i = 0; i < len; i++) {\n\t\t\t\tring[i] = this._map.latLngToLayerPoint(latlngs[i]);\n\t\t\t\tprojectedBounds.extend(ring[i]);\n\t\t\t}\n\t\t\tresult.push(ring);\n\t\t} else {\n\t\t\tfor (i = 0; i < len; i++) {\n\t\t\t\tthis._projectLatlngs(latlngs[i], result, projectedBounds);\n\t\t\t}\n\t\t}\n\t},\n\n\t// clip polyline by renderer bounds so that we have less to render for performance\n\t_clipPoints: function () {\n\t\tvar bounds = this._renderer._bounds;\n\n\t\tthis._parts = [];\n\t\tif (!this._pxBounds || !this._pxBounds.intersects(bounds)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.options.noClip) {\n\t\t\tthis._parts = this._rings;\n\t\t\treturn;\n\t\t}\n\n\t\tvar parts = this._parts,\n\t\t i, j, k, len, len2, segment, points;\n\n\t\tfor (i = 0, k = 0, len = this._rings.length; i < len; i++) {\n\t\t\tpoints = this._rings[i];\n\n\t\t\tfor (j = 0, len2 = points.length; j < len2 - 1; j++) {\n\t\t\t\tsegment = clipSegment(points[j], points[j + 1], bounds, j, true);\n\n\t\t\t\tif (!segment) { continue; }\n\n\t\t\t\tparts[k] = parts[k] || [];\n\t\t\t\tparts[k].push(segment[0]);\n\n\t\t\t\t// if segment goes out of screen, or it's the last one, it's the end of the line part\n\t\t\t\tif ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {\n\t\t\t\t\tparts[k].push(segment[1]);\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n\n\t// simplify each clipped part of the polyline for performance\n\t_simplifyPoints: function () {\n\t\tvar parts = this._parts,\n\t\t tolerance = this.options.smoothFactor;\n\n\t\tfor (var i = 0, len = parts.length; i < len; i++) {\n\t\t\tparts[i] = simplify(parts[i], tolerance);\n\t\t}\n\t},\n\n\t_update: function () {\n\t\tif (!this._map) { return; }\n\n\t\tthis._clipPoints();\n\t\tthis._simplifyPoints();\n\t\tthis._updatePath();\n\t},\n\n\t_updatePath: function () {\n\t\tthis._renderer._updatePoly(this);\n\t},\n\n\t// Needed by the `Canvas` renderer for interactivity\n\t_containsPoint: function (p, closed) {\n\t\tvar i, j, k, len, len2, part,\n\t\t w = this._clickTolerance();\n\n\t\tif (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }\n\n\t\t// hit detection for polylines\n\t\tfor (i = 0, len = this._parts.length; i < len; i++) {\n\t\t\tpart = this._parts[i];\n\n\t\t\tfor (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {\n\t\t\t\tif (!closed && (j === 0)) { continue; }\n\n\t\t\t\tif (pointToSegmentDistance(p, part[k], part[j]) <= w) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n});\n\n// @factory L.polyline(latlngs: LatLng[], options?: Polyline options)\n// Instantiates a polyline object given an array of geographical points and\n// optionally an options object. You can create a `Polyline` object with\n// multiple separate lines (`MultiPolyline`) by passing an array of arrays\n// of geographic points.\nfunction polyline(latlngs, options) {\n\treturn new Polyline(latlngs, options);\n}\n\n// Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.\nPolyline._flat = _flat;\n\n/*\n * @class Polygon\n * @aka L.Polygon\n * @inherits Polyline\n *\n * A class for drawing polygon overlays on a map. Extends `Polyline`.\n *\n * Note that points you pass when creating a polygon shouldn't have an additional last point equal to the first one — it's better to filter out such points.\n *\n *\n * @example\n *\n * ```js\n * // create a red polygon from an array of LatLng points\n * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];\n *\n * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);\n *\n * // zoom the map to the polygon\n * map.fitBounds(polygon.getBounds());\n * ```\n *\n * You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape:\n *\n * ```js\n * var latlngs = [\n * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring\n * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole\n * ];\n * ```\n *\n * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.\n *\n * ```js\n * var latlngs = [\n * [ // first polygon\n * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring\n * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole\n * ],\n * [ // second polygon\n * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]\n * ]\n * ];\n * ```\n */\n\nvar Polygon = Polyline.extend({\n\n\toptions: {\n\t\tfill: true\n\t},\n\n\tisEmpty: function () {\n\t\treturn !this._latlngs.length || !this._latlngs[0].length;\n\t},\n\n\tgetCenter: function () {\n\t\t// throws error when not yet added to map as this center calculation requires projected coordinates\n\t\tif (!this._map) {\n\t\t\tthrow new Error('Must add layer to map before using getCenter()');\n\t\t}\n\n\t\tvar i, j, p1, p2, f, area, x, y, center,\n\t\t points = this._rings[0],\n\t\t len = points.length;\n\n\t\tif (!len) { return null; }\n\n\t\t// polygon centroid algorithm; only uses the first ring if there are multiple\n\n\t\tarea = x = y = 0;\n\n\t\tfor (i = 0, j = len - 1; i < len; j = i++) {\n\t\t\tp1 = points[i];\n\t\t\tp2 = points[j];\n\n\t\t\tf = p1.y * p2.x - p2.y * p1.x;\n\t\t\tx += (p1.x + p2.x) * f;\n\t\t\ty += (p1.y + p2.y) * f;\n\t\t\tarea += f * 3;\n\t\t}\n\n\t\tif (area === 0) {\n\t\t\t// Polygon is so small that all points are on same pixel.\n\t\t\tcenter = points[0];\n\t\t} else {\n\t\t\tcenter = [x / area, y / area];\n\t\t}\n\t\treturn this._map.layerPointToLatLng(center);\n\t},\n\n\t_convertLatLngs: function (latlngs) {\n\t\tvar result = Polyline.prototype._convertLatLngs.call(this, latlngs),\n\t\t len = result.length;\n\n\t\t// remove last point if it equals first one\n\t\tif (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {\n\t\t\tresult.pop();\n\t\t}\n\t\treturn result;\n\t},\n\n\t_setLatLngs: function (latlngs) {\n\t\tPolyline.prototype._setLatLngs.call(this, latlngs);\n\t\tif (isFlat(this._latlngs)) {\n\t\t\tthis._latlngs = [this._latlngs];\n\t\t}\n\t},\n\n\t_defaultShape: function () {\n\t\treturn isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];\n\t},\n\n\t_clipPoints: function () {\n\t\t// polygons need a different clipping algorithm so we redefine that\n\n\t\tvar bounds = this._renderer._bounds,\n\t\t w = this.options.weight,\n\t\t p = new Point(w, w);\n\n\t\t// increase clip padding by stroke width to avoid stroke on clip edges\n\t\tbounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));\n\n\t\tthis._parts = [];\n\t\tif (!this._pxBounds || !this._pxBounds.intersects(bounds)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.options.noClip) {\n\t\t\tthis._parts = this._rings;\n\t\t\treturn;\n\t\t}\n\n\t\tfor (var i = 0, len = this._rings.length, clipped; i < len; i++) {\n\t\t\tclipped = clipPolygon(this._rings[i], bounds, true);\n\t\t\tif (clipped.length) {\n\t\t\t\tthis._parts.push(clipped);\n\t\t\t}\n\t\t}\n\t},\n\n\t_updatePath: function () {\n\t\tthis._renderer._updatePoly(this, true);\n\t},\n\n\t// Needed by the `Canvas` renderer for interactivity\n\t_containsPoint: function (p) {\n\t\tvar inside = false,\n\t\t part, p1, p2, i, j, k, len, len2;\n\n\t\tif (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }\n\n\t\t// ray casting algorithm for detecting if point is in polygon\n\t\tfor (i = 0, len = this._parts.length; i < len; i++) {\n\t\t\tpart = this._parts[i];\n\n\t\t\tfor (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {\n\t\t\t\tp1 = part[j];\n\t\t\t\tp2 = part[k];\n\n\t\t\t\tif (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {\n\t\t\t\t\tinside = !inside;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// also check if it's on polygon stroke\n\t\treturn inside || Polyline.prototype._containsPoint.call(this, p, true);\n\t}\n\n});\n\n\n// @factory L.polygon(latlngs: LatLng[], options?: Polyline options)\nfunction polygon(latlngs, options) {\n\treturn new Polygon(latlngs, options);\n}\n\n/*\r\n * @class GeoJSON\r\n * @aka L.GeoJSON\r\n * @inherits FeatureGroup\r\n *\r\n * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse\r\n * GeoJSON data and display it on the map. Extends `FeatureGroup`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * L.geoJSON(data, {\r\n * \tstyle: function (feature) {\r\n * \t\treturn {color: feature.properties.color};\r\n * \t}\r\n * }).bindPopup(function (layer) {\r\n * \treturn layer.feature.properties.description;\r\n * }).addTo(map);\r\n * ```\r\n */\r\n\r\nvar GeoJSON = FeatureGroup.extend({\r\n\r\n\t/* @section\r\n\t * @aka GeoJSON options\r\n\t *\r\n\t * @option pointToLayer: Function = *\r\n\t * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally\r\n\t * called when data is added, passing the GeoJSON point feature and its `LatLng`.\r\n\t * The default is to spawn a default `Marker`:\r\n\t * ```js\r\n\t * function(geoJsonPoint, latlng) {\r\n\t * \treturn L.marker(latlng);\r\n\t * }\r\n\t * ```\r\n\t *\r\n\t * @option style: Function = *\r\n\t * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,\r\n\t * called internally when data is added.\r\n\t * The default value is to not override any defaults:\r\n\t * ```js\r\n\t * function (geoJsonFeature) {\r\n\t * \treturn {}\r\n\t * }\r\n\t * ```\r\n\t *\r\n\t * @option onEachFeature: Function = *\r\n\t * A `Function` that will be called once for each created `Feature`, after it has\r\n\t * been created and styled. Useful for attaching events and popups to features.\r\n\t * The default is to do nothing with the newly created layers:\r\n\t * ```js\r\n\t * function (feature, layer) {}\r\n\t * ```\r\n\t *\r\n\t * @option filter: Function = *\r\n\t * A `Function` that will be used to decide whether to include a feature or not.\r\n\t * The default is to include all features:\r\n\t * ```js\r\n\t * function (geoJsonFeature) {\r\n\t * \treturn true;\r\n\t * }\r\n\t * ```\r\n\t * Note: dynamically changing the `filter` option will have effect only on newly\r\n\t * added data. It will _not_ re-evaluate already included features.\r\n\t *\r\n\t * @option coordsToLatLng: Function = *\r\n\t * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.\r\n\t * The default is the `coordsToLatLng` static method.\r\n\t */\r\n\r\n\tinitialize: function (geojson, options) {\r\n\t\tsetOptions(this, options);\r\n\r\n\t\tthis._layers = {};\r\n\r\n\t\tif (geojson) {\r\n\t\t\tthis.addData(geojson);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method addData( data ): this\r\n\t// Adds a GeoJSON object to the layer.\r\n\taddData: function (geojson) {\r\n\t\tvar features = isArray(geojson) ? geojson : geojson.features,\r\n\t\t i, len, feature;\r\n\r\n\t\tif (features) {\r\n\t\t\tfor (i = 0, len = features.length; i < len; i++) {\r\n\t\t\t\t// only add this if geometry or geometries are set and not null\r\n\t\t\t\tfeature = features[i];\r\n\t\t\t\tif (feature.geometries || feature.geometry || feature.features || feature.coordinates) {\r\n\t\t\t\t\tthis.addData(feature);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn this;\r\n\t\t}\r\n\r\n\t\tvar options = this.options;\r\n\r\n\t\tif (options.filter && !options.filter(geojson)) { return this; }\r\n\r\n\t\tvar layer = geometryToLayer(geojson, options);\r\n\t\tif (!layer) {\r\n\t\t\treturn this;\r\n\t\t}\r\n\t\tlayer.feature = asFeature(geojson);\r\n\r\n\t\tlayer.defaultOptions = layer.options;\r\n\t\tthis.resetStyle(layer);\r\n\r\n\t\tif (options.onEachFeature) {\r\n\t\t\toptions.onEachFeature(geojson, layer);\r\n\t\t}\r\n\r\n\t\treturn this.addLayer(layer);\r\n\t},\r\n\r\n\t// @method resetStyle( layer ): this\r\n\t// Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.\r\n\tresetStyle: function (layer) {\r\n\t\t// reset any custom styles\r\n\t\tlayer.options = extend({}, layer.defaultOptions);\r\n\t\tthis._setLayerStyle(layer, this.options.style);\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setStyle( style ): this\r\n\t// Changes styles of GeoJSON vector layers with the given style function.\r\n\tsetStyle: function (style) {\r\n\t\treturn this.eachLayer(function (layer) {\r\n\t\t\tthis._setLayerStyle(layer, style);\r\n\t\t}, this);\r\n\t},\r\n\r\n\t_setLayerStyle: function (layer, style) {\r\n\t\tif (layer.setStyle) {\r\n\t\t\tif (typeof style === 'function') {\r\n\t\t\t\tstyle = style(layer.feature);\r\n\t\t\t}\r\n\t\t\tlayer.setStyle(style);\r\n\t\t}\r\n\t}\r\n});\r\n\r\n// @section\r\n// There are several static functions which can be called without instantiating L.GeoJSON:\r\n\r\n// @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer\r\n// Creates a `Layer` from a given GeoJSON feature. Can use a custom\r\n// [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)\r\n// functions if provided as options.\r\nfunction geometryToLayer(geojson, options) {\r\n\r\n\tvar geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,\r\n\t coords = geometry ? geometry.coordinates : null,\r\n\t layers = [],\r\n\t pointToLayer = options && options.pointToLayer,\r\n\t _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,\r\n\t latlng, latlngs, i, len;\r\n\r\n\tif (!coords && !geometry) {\r\n\t\treturn null;\r\n\t}\r\n\r\n\tswitch (geometry.type) {\r\n\tcase 'Point':\r\n\t\tlatlng = _coordsToLatLng(coords);\r\n\t\treturn pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng);\r\n\r\n\tcase 'MultiPoint':\r\n\t\tfor (i = 0, len = coords.length; i < len; i++) {\r\n\t\t\tlatlng = _coordsToLatLng(coords[i]);\r\n\t\t\tlayers.push(pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng));\r\n\t\t}\r\n\t\treturn new FeatureGroup(layers);\r\n\r\n\tcase 'LineString':\r\n\tcase 'MultiLineString':\r\n\t\tlatlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);\r\n\t\treturn new Polyline(latlngs, options);\r\n\r\n\tcase 'Polygon':\r\n\tcase 'MultiPolygon':\r\n\t\tlatlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);\r\n\t\treturn new Polygon(latlngs, options);\r\n\r\n\tcase 'GeometryCollection':\r\n\t\tfor (i = 0, len = geometry.geometries.length; i < len; i++) {\r\n\t\t\tvar layer = geometryToLayer({\r\n\t\t\t\tgeometry: geometry.geometries[i],\r\n\t\t\t\ttype: 'Feature',\r\n\t\t\t\tproperties: geojson.properties\r\n\t\t\t}, options);\r\n\r\n\t\t\tif (layer) {\r\n\t\t\t\tlayers.push(layer);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn new FeatureGroup(layers);\r\n\r\n\tdefault:\r\n\t\tthrow new Error('Invalid GeoJSON object.');\r\n\t}\r\n}\r\n\r\n// @function coordsToLatLng(coords: Array): LatLng\r\n// Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)\r\n// or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.\r\nfunction coordsToLatLng(coords) {\r\n\treturn new LatLng(coords[1], coords[0], coords[2]);\r\n}\r\n\r\n// @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array\r\n// Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.\r\n// `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).\r\n// Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.\r\nfunction coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {\r\n\tvar latlngs = [];\r\n\r\n\tfor (var i = 0, len = coords.length, latlng; i < len; i++) {\r\n\t\tlatlng = levelsDeep ?\r\n\t\t\tcoordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :\r\n\t\t\t(_coordsToLatLng || coordsToLatLng)(coords[i]);\r\n\r\n\t\tlatlngs.push(latlng);\r\n\t}\r\n\r\n\treturn latlngs;\r\n}\r\n\r\n// @function latLngToCoords(latlng: LatLng, precision?: Number): Array\r\n// Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)\r\nfunction latLngToCoords(latlng, precision) {\r\n\tprecision = typeof precision === 'number' ? precision : 6;\r\n\treturn latlng.alt !== undefined ?\r\n\t\t[formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :\r\n\t\t[formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];\r\n}\r\n\r\n// @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array\r\n// Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)\r\n// `closed` determines whether the first point should be appended to the end of the array to close the feature, only used when `levelsDeep` is 0. False by default.\r\nfunction latLngsToCoords(latlngs, levelsDeep, closed, precision) {\r\n\tvar coords = [];\r\n\r\n\tfor (var i = 0, len = latlngs.length; i < len; i++) {\r\n\t\tcoords.push(levelsDeep ?\r\n\t\t\tlatLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) :\r\n\t\t\tlatLngToCoords(latlngs[i], precision));\r\n\t}\r\n\r\n\tif (!levelsDeep && closed) {\r\n\t\tcoords.push(coords[0]);\r\n\t}\r\n\r\n\treturn coords;\r\n}\r\n\r\nfunction getFeature(layer, newGeometry) {\r\n\treturn layer.feature ?\r\n\t\textend({}, layer.feature, {geometry: newGeometry}) :\r\n\t\tasFeature(newGeometry);\r\n}\r\n\r\n// @function asFeature(geojson: Object): Object\r\n// Normalize GeoJSON geometries/features into GeoJSON features.\r\nfunction asFeature(geojson) {\r\n\tif (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {\r\n\t\treturn geojson;\r\n\t}\r\n\r\n\treturn {\r\n\t\ttype: 'Feature',\r\n\t\tproperties: {},\r\n\t\tgeometry: geojson\r\n\t};\r\n}\r\n\r\nvar PointToGeoJSON = {\r\n\ttoGeoJSON: function (precision) {\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: 'Point',\r\n\t\t\tcoordinates: latLngToCoords(this.getLatLng(), precision)\r\n\t\t});\r\n\t}\r\n};\r\n\r\n// @namespace Marker\r\n// @method toGeoJSON(precision?: Number): Object\r\n// `precision` is the number of decimal places for coordinates.\r\n// The default value is 6 places.\r\n// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).\r\nMarker.include(PointToGeoJSON);\r\n\r\n// @namespace CircleMarker\r\n// @method toGeoJSON(precision?: Number): Object\r\n// `precision` is the number of decimal places for coordinates.\r\n// The default value is 6 places.\r\n// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).\r\nCircle.include(PointToGeoJSON);\r\nCircleMarker.include(PointToGeoJSON);\r\n\r\n\r\n// @namespace Polyline\r\n// @method toGeoJSON(precision?: Number): Object\r\n// `precision` is the number of decimal places for coordinates.\r\n// The default value is 6 places.\r\n// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).\r\nPolyline.include({\r\n\ttoGeoJSON: function (precision) {\r\n\t\tvar multi = !isFlat(this._latlngs);\r\n\r\n\t\tvar coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);\r\n\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: (multi ? 'Multi' : '') + 'LineString',\r\n\t\t\tcoordinates: coords\r\n\t\t});\r\n\t}\r\n});\r\n\r\n// @namespace Polygon\r\n// @method toGeoJSON(precision?: Number): Object\r\n// `precision` is the number of decimal places for coordinates.\r\n// The default value is 6 places.\r\n// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).\r\nPolygon.include({\r\n\ttoGeoJSON: function (precision) {\r\n\t\tvar holes = !isFlat(this._latlngs),\r\n\t\t multi = holes && !isFlat(this._latlngs[0]);\r\n\r\n\t\tvar coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);\r\n\r\n\t\tif (!holes) {\r\n\t\t\tcoords = [coords];\r\n\t\t}\r\n\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: (multi ? 'Multi' : '') + 'Polygon',\r\n\t\t\tcoordinates: coords\r\n\t\t});\r\n\t}\r\n});\r\n\r\n\r\n// @namespace LayerGroup\r\nLayerGroup.include({\r\n\ttoMultiPoint: function (precision) {\r\n\t\tvar coords = [];\r\n\r\n\t\tthis.eachLayer(function (layer) {\r\n\t\t\tcoords.push(layer.toGeoJSON(precision).geometry.coordinates);\r\n\t\t});\r\n\r\n\t\treturn getFeature(this, {\r\n\t\t\ttype: 'MultiPoint',\r\n\t\t\tcoordinates: coords\r\n\t\t});\r\n\t},\r\n\r\n\t// @method toGeoJSON(precision?: Number): Object\r\n\t// `precision` is the number of decimal places for coordinates.\r\n\t// The default value is 6 places.\r\n\t// Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).\r\n\ttoGeoJSON: function (precision) {\r\n\r\n\t\tvar type = this.feature && this.feature.geometry && this.feature.geometry.type;\r\n\r\n\t\tif (type === 'MultiPoint') {\r\n\t\t\treturn this.toMultiPoint(precision);\r\n\t\t}\r\n\r\n\t\tvar isGeometryCollection = type === 'GeometryCollection',\r\n\t\t jsons = [];\r\n\r\n\t\tthis.eachLayer(function (layer) {\r\n\t\t\tif (layer.toGeoJSON) {\r\n\t\t\t\tvar json = layer.toGeoJSON(precision);\r\n\t\t\t\tif (isGeometryCollection) {\r\n\t\t\t\t\tjsons.push(json.geometry);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tvar feature = asFeature(json);\r\n\t\t\t\t\t// Squash nested feature collections\r\n\t\t\t\t\tif (feature.type === 'FeatureCollection') {\r\n\t\t\t\t\t\tjsons.push.apply(jsons, feature.features);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tjsons.push(feature);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tif (isGeometryCollection) {\r\n\t\t\treturn getFeature(this, {\r\n\t\t\t\tgeometries: jsons,\r\n\t\t\t\ttype: 'GeometryCollection'\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\treturn {\r\n\t\t\ttype: 'FeatureCollection',\r\n\t\t\tfeatures: jsons\r\n\t\t};\r\n\t}\r\n});\r\n\r\n// @namespace GeoJSON\r\n// @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)\r\n// Creates a GeoJSON layer. Optionally accepts an object in\r\n// [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map\r\n// (you can alternatively add it later with `addData` method) and an `options` object.\r\nfunction geoJSON(geojson, options) {\r\n\treturn new GeoJSON(geojson, options);\r\n}\r\n\r\n// Backward compatibility.\r\nvar geoJson = geoJSON;\n\n/*\r\n * @class ImageOverlay\r\n * @aka L.ImageOverlay\r\n * @inherits Interactive layer\r\n *\r\n * Used to load and display a single image over specific bounds of the map. Extends `Layer`.\r\n *\r\n * @example\r\n *\r\n * ```js\r\n * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',\r\n * \timageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];\r\n * L.imageOverlay(imageUrl, imageBounds).addTo(map);\r\n * ```\r\n */\r\n\r\nvar ImageOverlay = Layer.extend({\r\n\r\n\t// @section\r\n\t// @aka ImageOverlay options\r\n\toptions: {\r\n\t\t// @option opacity: Number = 1.0\r\n\t\t// The opacity of the image overlay.\r\n\t\topacity: 1,\r\n\r\n\t\t// @option alt: String = ''\r\n\t\t// Text for the `alt` attribute of the image (useful for accessibility).\r\n\t\talt: '',\r\n\r\n\t\t// @option interactive: Boolean = false\r\n\t\t// If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.\r\n\t\tinteractive: false,\r\n\r\n\t\t// @option crossOrigin: Boolean|String = false\r\n\t\t// Whether the crossOrigin attribute will be added to the image.\r\n\t\t// If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data.\r\n\t\t// Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values.\r\n\t\tcrossOrigin: false,\r\n\r\n\t\t// @option errorOverlayUrl: String = ''\r\n\t\t// URL to the overlay image to show in place of the overlay that failed to load.\r\n\t\terrorOverlayUrl: '',\r\n\r\n\t\t// @option zIndex: Number = 1\r\n\t\t// The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer.\r\n\t\tzIndex: 1,\r\n\r\n\t\t// @option className: String = ''\r\n\t\t// A custom class name to assign to the image. Empty by default.\r\n\t\tclassName: ''\r\n\t},\r\n\r\n\tinitialize: function (url, bounds, options) { // (String, LatLngBounds, Object)\r\n\t\tthis._url = url;\r\n\t\tthis._bounds = toLatLngBounds(bounds);\r\n\r\n\t\tsetOptions(this, options);\r\n\t},\r\n\r\n\tonAdd: function () {\r\n\t\tif (!this._image) {\r\n\t\t\tthis._initImage();\r\n\r\n\t\t\tif (this.options.opacity < 1) {\r\n\t\t\t\tthis._updateOpacity();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (this.options.interactive) {\r\n\t\t\taddClass(this._image, 'leaflet-interactive');\r\n\t\t\tthis.addInteractiveTarget(this._image);\r\n\t\t}\r\n\r\n\t\tthis.getPane().appendChild(this._image);\r\n\t\tthis._reset();\r\n\t},\r\n\r\n\tonRemove: function () {\r\n\t\tremove(this._image);\r\n\t\tif (this.options.interactive) {\r\n\t\t\tthis.removeInteractiveTarget(this._image);\r\n\t\t}\r\n\t},\r\n\r\n\t// @method setOpacity(opacity: Number): this\r\n\t// Sets the opacity of the overlay.\r\n\tsetOpacity: function (opacity) {\r\n\t\tthis.options.opacity = opacity;\r\n\r\n\t\tif (this._image) {\r\n\t\t\tthis._updateOpacity();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\tsetStyle: function (styleOpts) {\r\n\t\tif (styleOpts.opacity) {\r\n\t\t\tthis.setOpacity(styleOpts.opacity);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method bringToFront(): this\r\n\t// Brings the layer to the top of all overlays.\r\n\tbringToFront: function () {\r\n\t\tif (this._map) {\r\n\t\t\ttoFront(this._image);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method bringToBack(): this\r\n\t// Brings the layer to the bottom of all overlays.\r\n\tbringToBack: function () {\r\n\t\tif (this._map) {\r\n\t\t\ttoBack(this._image);\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setUrl(url: String): this\r\n\t// Changes the URL of the image.\r\n\tsetUrl: function (url) {\r\n\t\tthis._url = url;\r\n\r\n\t\tif (this._image) {\r\n\t\t\tthis._image.src = url;\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method setBounds(bounds: LatLngBounds): this\r\n\t// Update the bounds that this ImageOverlay covers\r\n\tsetBounds: function (bounds) {\r\n\t\tthis._bounds = toLatLngBounds(bounds);\r\n\r\n\t\tif (this._map) {\r\n\t\t\tthis._reset();\r\n\t\t}\r\n\t\treturn this;\r\n\t},\r\n\r\n\tgetEvents: function () {\r\n\t\tvar events = {\r\n\t\t\tzoom: this._reset,\r\n\t\t\tviewreset: this._reset\r\n\t\t};\r\n\r\n\t\tif (this._zoomAnimated) {\r\n\t\t\tevents.zoomanim = this._animateZoom;\r\n\t\t}\r\n\r\n\t\treturn events;\r\n\t},\r\n\r\n\t// @method setZIndex(value: Number): this\r\n\t// Changes the [zIndex](#imageoverlay-zindex) of the image overlay.\r\n\tsetZIndex: function (value) {\r\n\t\tthis.options.zIndex = value;\r\n\t\tthis._updateZIndex();\r\n\t\treturn this;\r\n\t},\r\n\r\n\t// @method getBounds(): LatLngBounds\r\n\t// Get the bounds that this ImageOverlay covers\r\n\tgetBounds: function () {\r\n\t\treturn this._bounds;\r\n\t},\r\n\r\n\t// @method getElement(): HTMLElement\r\n\t// Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)\r\n\t// used by this overlay.\r\n\tgetElement: function () {\r\n\t\treturn this._image;\r\n\t},\r\n\r\n\t_initImage: function () {\r\n\t\tvar wasElementSupplied = this._url.tagName === 'IMG';\r\n\t\tvar img = this._image = wasElementSupplied ? this._url : create$1('img');\r\n\r\n\t\taddClass(img, 'leaflet-image-layer');\r\n\t\tif (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }\r\n\t\tif (this.options.className) { addClass(img, this.options.className); }\r\n\r\n\t\timg.onselectstart = falseFn;\r\n\t\timg.onmousemove = falseFn;\r\n\r\n\t\t// @event load: Event\r\n\t\t// Fired when the ImageOverlay layer has loaded its image\r\n\t\timg.onload = bind(this.fire, this, 'load');\r\n\t\timg.onerror = bind(this._overlayOnError, this, 'error');\r\n\r\n\t\tif (this.options.crossOrigin || this.options.crossOrigin === '') {\r\n\t\t\timg.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;\r\n\t\t}\r\n\r\n\t\tif (this.options.zIndex) {\r\n\t\t\tthis._updateZIndex();\r\n\t\t}\r\n\r\n\t\tif (wasElementSupplied) {\r\n\t\t\tthis._url = img.src;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\timg.src = this._url;\r\n\t\timg.alt = this.options.alt;\r\n\t},\r\n\r\n\t_animateZoom: function (e) {\r\n\t\tvar scale = this._map.getZoomScale(e.zoom),\r\n\t\t offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;\r\n\r\n\t\tsetTransform(this._image, offset, scale);\r\n\t},\r\n\r\n\t_reset: function () {\r\n\t\tvar image = this._image,\r\n\t\t bounds = new Bounds(\r\n\t\t this._map.latLngToLayerPoint(this._bounds.getNorthWest()),\r\n\t\t this._map.latLngToLayerPoint(this._bounds.getSouthEast())),\r\n\t\t size = bounds.getSize();\r\n\r\n\t\tsetPosition(image, bounds.min);\r\n\r\n\t\timage.style.width = size.x + 'px';\r\n\t\timage.style.height = size.y + 'px';\r\n\t},\r\n\r\n\t_updateOpacity: function () {\r\n\t\tsetOpacity(this._image, this.options.opacity);\r\n\t},\r\n\r\n\t_updateZIndex: function () {\r\n\t\tif (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {\r\n\t\t\tthis._image.style.zIndex = this.options.zIndex;\r\n\t\t}\r\n\t},\r\n\r\n\t_overlayOnError: function () {\r\n\t\t// @event error: Event\r\n\t\t// Fired when the ImageOverlay layer fails to load its image\r\n\t\tthis.fire('error');\r\n\r\n\t\tvar errorUrl = this.options.errorOverlayUrl;\r\n\t\tif (errorUrl && this._url !== errorUrl) {\r\n\t\t\tthis._url = errorUrl;\r\n\t\t\tthis._image.src = errorUrl;\r\n\t\t}\r\n\t}\r\n});\r\n\r\n// @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)\r\n// Instantiates an image overlay object given the URL of the image and the\r\n// geographical bounds it is tied to.\r\nvar imageOverlay = function (url, bounds, options) {\r\n\treturn new ImageOverlay(url, bounds, options);\r\n};\n\n/*\r\n * @class VideoOverlay\r\n * @aka L.VideoOverlay\r\n * @inherits ImageOverlay\r\n *\r\n * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.\r\n *\r\n * A video overlay uses the [`