Gemfile 🔗
@@ -4,6 +4,7 @@ source "https://rubygems.org"
gem "blather"
gem "braintree"
+gem "countries"
gem "dhall", ">= 0.5.3.fixed"
gem "em-http-request"
gem "em_promise.rb"
Stephen Paul Weber created
Gemfile | 1
assets/css/loader/loader.scss | 39
assets/css/tom_select/_dropdown.scss | 104
assets/css/tom_select/_items.scss | 115
assets/css/tom_select/plugins/_dropdown_input.scss | 37
assets/css/tom_select/tom_select.scss | 169
assets/js/htmx/htmx.js | 2751 +++++++++
assets/js/section_list/section_list.js | 51
assets/js/tom_select/tom_select.js | 4806 ++++++++++++++++
config.ru | 280
views/braintree.slim | 15
views/esim_adapter.slim | 160
views/layout.slim | 1
views/receipt.slim | 36
views/total.slim | 17
15 files changed, 8,535 insertions(+), 47 deletions(-)
@@ -4,6 +4,7 @@ source "https://rubygems.org"
gem "blather"
gem "braintree"
+gem "countries"
gem "dhall", ">= 0.5.3.fixed"
gem "em-http-request"
gem "em_promise.rb"
@@ -0,0 +1,39 @@
+.lds-ring,
+.lds-ring div {
+ box-sizing: border-box;
+}
+.lds-ring {
+ display: inline-block;
+ position: relative;
+ width: 80px;
+ height: 80px;
+}
+.lds-ring div {
+ box-sizing: border-box;
+ display: block;
+ position: absolute;
+ width: 64px;
+ height: 64px;
+ margin: 8px;
+ border: 8px solid currentColor;
+ border-radius: 50%;
+ animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
+ border-color: currentColor transparent transparent transparent;
+}
+.lds-ring div:nth-child(1) {
+ animation-delay: -0.45s;
+}
+.lds-ring div:nth-child(2) {
+ animation-delay: -0.3s;
+}
+.lds-ring div:nth-child(3) {
+ animation-delay: -0.15s;
+}
+@keyframes lds-ring {
+ 0% {
+ transform: rotate(0deg);
+ }
+ 100% {
+ transform: rotate(360deg);
+ }
+}
@@ -0,0 +1,104 @@
+
+
+.#{$select-ns}-dropdown {
+ position: absolute;
+ top: 100%;
+ left: 0;
+ width: 100%;
+ z-index: 10;
+
+ border: $select-dropdown-border;
+ background: $select-color-dropdown;
+ margin: 0.25rem 0 0 0;
+ border-top: 0 none;
+ box-sizing: border-box;
+ box-shadow: 0 1px 3px rgba(0,0,0,0.1);
+ border-radius: 0 0 $select-border-radius $select-border-radius;
+
+
+ [data-selectable] {
+ cursor: pointer;
+ overflow: hidden;
+ .highlight {
+ background: $select-color-highlight;
+ border-radius: 1px;
+ }
+ }
+
+ .option,
+ .optgroup-header,
+ .no-results,
+ .create {
+ padding: $select-padding-dropdown-item-y $select-padding-dropdown-item-x;
+ }
+
+ .option, [data-disabled], [data-disabled] [data-selectable].option {
+ cursor: inherit;
+ opacity: 0.5;
+ }
+
+ [data-selectable].option {
+ opacity: 1;
+ cursor: pointer;
+ }
+
+ .optgroup:first-child .optgroup-header {
+ border-top: 0 none;
+ }
+
+ .optgroup-header {
+ color: $select-color-optgroup-text;
+ background: $select-color-optgroup;
+ cursor: default;
+ }
+
+ .create:hover,
+ .option:hover,
+ .active {
+ background-color: $select-color-dropdown-item-active;
+ color: $select-color-dropdown-item-active-text;
+ &.create {
+ color: $select-color-dropdown-item-create-active-text;
+ }
+ }
+
+ .create {
+ color: $select-color-dropdown-item-create-text;
+ }
+
+ .spinner{
+ display: inline-block;
+ width: $select-spinner-size;
+ height: $select-spinner-size;
+ margin: $select-padding-dropdown-item-y $select-padding-dropdown-item-x;
+
+
+ &:after {
+ content: " ";
+ display: block;
+ width: $select-spinner-size * .8;
+ height: $select-spinner-size * .8;
+ margin: $select-spinner-size * .1;
+ border-radius: 50%;
+ border: $select-spinner-border-size solid $select-spinner-border-color;
+ border-color: $select-spinner-border-color transparent $select-spinner-border-color transparent;
+ animation: lds-dual-ring 1.2s linear infinite;
+ }
+ @keyframes lds-dual-ring {
+ 0% {
+ transform: rotate(0deg);
+ }
+ 100% {
+ transform: rotate(360deg);
+ }
+ }
+ }
+}
+
+.#{$select-ns}-dropdown-content {
+ overflow-y: auto;
+ overflow-x: hidden;
+ max-height: $select-max-height-dropdown;
+ overflow-scrolling: touch;
+ scroll-behavior: smooth;
+}
@@ -0,0 +1,115 @@
+
+
+.#{$select-ns}-control {
+
+ border: $select-border;
+ padding: $select-padding-y $select-padding-x;
+ width: 100%;
+ overflow: hidden;
+ position: relative;
+ z-index: 1;
+ box-sizing: border-box;
+ box-shadow: $select-shadow-input;
+ border-radius: $select-border-radius;
+ display: flex;
+ flex-wrap: wrap;
+
+ .#{$select-ns}-wrapper.multi.has-items & {
+ $padding-x: $select-padding-x;
+ $padding-top: calc( #{$select-padding-y} - #{$select-padding-item-y} - #{$select-width-item-border});
+ $padding-bottom: calc( #{$select-padding-y} - #{$select-padding-item-y} - #{$select-margin-item-y} - #{$select-width-item-border});
+ padding: $padding-top $padding-x $padding-bottom;
+ }
+
+ .full & {
+ background-color: $select-color-input-full;
+ }
+
+ .disabled &,
+ .disabled & * {
+ cursor: default !important;
+ }
+
+ .focus & {
+ box-shadow: $select-shadow-input-focus;
+ }
+
+ > * {
+ vertical-align: baseline;
+ display: inline-block;
+ }
+
+ .#{$select-ns}-wrapper.multi & > div {
+ cursor: pointer;
+ margin: 0 $select-margin-item-x $select-margin-item-y 0;
+ padding: $select-padding-item-y $select-padding-item-x;
+ background: $select-color-item;
+ color: $select-color-item-text;
+ border: $select-width-item-border solid $select-color-item-border;
+
+ &.active {
+ background: $select-color-item-active;
+ color: $select-color-item-active-text;
+ border: $select-width-item-border solid $select-color-item-active-border;
+ }
+ }
+
+ .#{$select-ns}-wrapper.multi.disabled & > div {
+ &, &.active {
+ color: lighten(desaturate($select-color-item-text, 100%), $select-lighten-disabled-item-text);
+ background: lighten(desaturate($select-color-item, 100%), $select-lighten-disabled-item);
+ border: $select-width-item-border solid lighten(desaturate($select-color-item-border, 100%), $select-lighten-disabled-item-border);
+ }
+ }
+
+ > input {
+ &::-ms-clear {
+ display: none;
+ }
+
+ flex: 1 1 auto;
+ min-width: 7rem;
+ display: inline-block !important;
+ padding: 0 !important;
+ min-height: 0 !important;
+ max-height: none !important;
+ max-width: 100% !important;
+ margin: 0 !important;
+ text-indent: 0 !important;
+ border: 0 none !important;
+ background: none !important;
+ line-height: inherit !important;
+ user-select: auto !important;
+ box-shadow: none !important;
+ &:focus { outline: none !important; }
+ }
+
+ .has-items & > input{
+ margin: $select-caret-margin !important;
+ }
+
+ &.rtl {
+ text-align: right;
+ &.single .#{$select-ns}-control:after {
+ left: $select-arrow-offset;
+ right: auto;
+ }
+ .#{$select-ns}-control > input {
+ margin: $select-caret-margin-rtl !important;
+ }
+ }
+
+ .disabled & {
+ opacity: $select-opacity-disabled;
+ background-color: $select-color-disabled;
+ }
+
+ // hide input, while retaining its focus, and maintain layout so users can still click on the space to bring the display back
+ // visibility:hidden can prevent the input from receiving focus
+ .input-hidden & > input{
+ opacity: 0;
+ position: absolute;
+ left: -10000px;
+ }
+
+}
@@ -0,0 +1,37 @@
+
+.plugin-dropdown_input{
+
+ &.focus.dropdown-active .#{$select-ns}-control{
+ box-shadow: none;
+ border: $select-border;
+ @if variable-exists(input-box-shadow) {
+ box-shadow: $input-box-shadow;
+ }
+ }
+
+ .dropdown-input {
+ border: 1px solid $select-color-border;
+ border-width: 0 0 1px 0;
+ display: block;
+ padding: $select-padding-y $select-padding-x;
+ box-shadow: $select-shadow-input;
+ width: 100%;
+ background: transparent;
+ }
+
+ &.focus ~ .#{$select-ns}-dropdown .dropdown-input{
+ @if variable-exists(input-focus-border-color) {
+ border-color: $input-focus-border-color;
+
+ outline: 0;
+ @if $enable-shadows {
+ box-shadow: $input-box-shadow, $input-focus-box-shadow;
+ } @else {
+ box-shadow: $input-focus-box-shadow;
+ }
+
+ }
+
+ }
+
+}
@@ -0,0 +1,169 @@
+/**
+ * tom-select.css (v2.0.0)
+ * Copyright (c) contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+
+
+// base styles
+$select-ns: 'ts' !default;
+$select-font-family: inherit !default;
+$select-font-smoothing: inherit !default;
+$select-font-size: 1.2em !default;
+$select-line-height: 1.1 !default;
+
+$select-color-text: #303030 !default;
+$select-color-border: #d0d0d0 !default;
+$select-color-highlight: rgba(125,168,208,0.2) !default;
+$select-color-input: #fff !default;
+$select-color-input-full: $select-color-input !default;
+$select-color-disabled: #fafafa !default;
+$select-color-item: #f2f2f2 !default;
+$select-color-item-text: $select-color-text !default;
+$select-color-item-border: #d0d0d0 !default;
+$select-color-item-active: #e8e8e8 !default;
+$select-color-item-active-text: $select-color-text !default;
+$select-color-item-active-border: #cacaca !default;
+$select-color-dropdown: #fff !default;
+$select-color-dropdown-border: $select-color-border !default;
+$select-color-dropdown-border-top: #f0f0f0 !default;
+$select-color-dropdown-item-active: #f5fafd !default;
+$select-color-dropdown-item-active-text: #495c68 !default;
+$select-color-dropdown-item-create-text: rgba(red($select-color-text), green($select-color-text), blue($select-color-text), 0.5) !default;
+$select-color-dropdown-item-create-active-text: $select-color-dropdown-item-active-text !default;
+$select-color-optgroup: $select-color-dropdown !default;
+$select-color-optgroup-text: $select-color-text !default;
+$select-lighten-disabled-item: 30% !default;
+$select-lighten-disabled-item-text: 30% !default;
+$select-lighten-disabled-item-border: 30% !default;
+$select-opacity-disabled: 0.5 !default;
+
+$select-shadow-input: none !default;
+$select-shadow-input-focus: none !default;
+$select-border: 1px solid $select-color-border !default;
+$select-dropdown-border: 1px solid $select-color-dropdown-border !default;
+$select-border-radius: 3px !default;
+
+$select-width-item-border: 0 !default;
+$select-max-height-dropdown: 200px !default;
+
+$select-padding-x: 8px !default;
+$select-padding-y: 8px !default;
+$select-padding-item-x: 6px !default;
+$select-padding-item-y: 2px !default;
+$select-padding-dropdown-item-x: $select-padding-x !default;
+$select-padding-dropdown-item-y: 5px !default;
+$select-margin-item-x: 3px !default;
+$select-margin-item-y: 3px !default;
+
+$select-arrow-size: 5px !default;
+$select-arrow-color: #808080 !default;
+$select-arrow-offset: 15px !default;
+
+$select-caret-margin: 0 4px !default;
+$select-caret-margin-rtl: 0 4px 0 -2px !default;
+
+$select-spinner-size: 30px !default;
+$select-spinner-border-size: 5px !default;
+$select-spinner-border-color: $select-color-border !default;
+
+@mixin selectize-vertical-gradient($color-top, $color-bottom) {
+ background-color: mix($color-top, $color-bottom, 60%);
+ background-image: linear-gradient(to bottom, $color-top, $color-bottom);
+ background-repeat: repeat-x;
+}
+
+
+@mixin ts-caret(){
+
+ .#{$select-ns}-wrapper.single{
+
+ .#{$select-ns}-control {
+ padding-right: 2rem;
+
+ &, input {
+ cursor: pointer;
+ }
+
+ &:after {
+ content: ' ';
+ display: block;
+ position: absolute;
+ top: 50%;
+ right: $select-arrow-offset;
+ margin-top: round((-1 * $select-arrow-size / 2));
+ width: 0;
+ height: 0;
+ border-style: solid;
+ border-width: $select-arrow-size $select-arrow-size 0 $select-arrow-size;
+ border-color: $select-arrow-color transparent transparent transparent;
+ }
+ }
+
+ &.dropdown-active .#{$select-ns}-control::after {
+ margin-top: $select-arrow-size * -0.8;
+ border-width: 0 $select-arrow-size $select-arrow-size $select-arrow-size;
+ border-color: transparent transparent $select-arrow-color transparent;
+ }
+
+ &.input-active .#{$select-ns}-control,
+ &.input-active .#{$select-ns}-control input {
+ cursor: text;
+ }
+
+ }
+}
+
+//@import "./plugins/drag_drop.scss";
+//@import "./plugins/checkbox_options.scss";
+//@import "./plugins/clear_button.scss";
+//@import "./plugins/dropdown_header.scss";
+@import "./plugins/dropdown_input";
+//@import "./plugins/input_autogrow.scss";
+//@import "./plugins/optgroup_columns.scss";
+//@import "./plugins/remove_button.scss";
+
+
+.#{$select-ns}-wrapper {
+ position: relative;
+}
+
+.#{$select-ns}-dropdown,
+.#{$select-ns}-control,
+.#{$select-ns}-control input {
+ color: $select-color-text;
+ font-family: $select-font-family;
+ font-size: $select-font-size;
+ line-height: $select-line-height;
+ font-smoothing: $select-font-smoothing;
+}
+
+.#{$select-ns}-control,
+.#{$select-ns}-wrapper.single.input-active .#{$select-ns}-control {
+ background: $select-color-input;
+ cursor: text;
+}
+
+@import 'items';
+@import 'dropdown';
+
+.ts-hidden-accessible{
+ border: 0 !important;
+ clip: rect(0 0 0 0) !important;
+ clip-path: inset(50%) !important;
+ height: 1px !important;
+ overflow: hidden !important;
+ padding: 0 !important;
+ position: absolute !important;
+ width: 1px !important;
+ white-space: nowrap !important;
+}
@@ -0,0 +1,2751 @@
+//AMD insanity
+(function (root, factory) {
+ //@ts-ignore
+ if (typeof define === 'function' && define.amd) {
+ // AMD. Register as an anonymous module.
+ //@ts-ignore
+ define([], factory);
+ } else {
+ // Browser globals
+ root.htmx = factory();
+ }
+}(typeof self !== 'undefined' ? self : this, function () {
+return (function () {
+ 'use strict';
+
+ // Public API
+ var htmx = {
+ onLoad: onLoadHelper,
+ process: processNode,
+ on: addEventListenerImpl,
+ off: removeEventListenerImpl,
+ trigger : triggerEvent,
+ ajax : ajaxHelper,
+ find : find,
+ findAll : findAll,
+ closest : closest,
+ values : function(elt, type){
+ var inputValues = getInputValues(elt, type || "post");
+ return inputValues.values;
+ },
+ remove : removeElement,
+ addClass : addClassToElement,
+ removeClass : removeClassFromElement,
+ toggleClass : toggleClassOnElement,
+ takeClass : takeClassForElement,
+ defineExtension : defineExtension,
+ removeExtension : removeExtension,
+ logAll : logAll,
+ logger : null,
+ config : {
+ historyEnabled:true,
+ historyCacheSize:10,
+ refreshOnHistoryMiss:false,
+ defaultSwapStyle:'innerHTML',
+ defaultSwapDelay:0,
+ defaultSettleDelay:20,
+ includeIndicatorStyles:true,
+ indicatorClass:'htmx-indicator',
+ requestClass:'htmx-request',
+ addedClass:'htmx-added',
+ settlingClass:'htmx-settling',
+ swappingClass:'htmx-swapping',
+ allowEval:true,
+ attributesToSettle:["class", "style", "width", "height"],
+ withCredentials:false,
+ timeout:0,
+ wsReconnectDelay: 'full-jitter',
+ disableSelector: "[hx-disable], [data-hx-disable]",
+ useTemplateFragments: false,
+ scrollBehavior: 'smooth',
+ },
+ parseInterval:parseInterval,
+ _:internalEval,
+ createEventSource: function(url){
+ return new EventSource(url, {withCredentials:true})
+ },
+ createWebSocket: function(url){
+ return new WebSocket(url, []);
+ },
+ version: "1.6.1"
+ };
+
+ var VERBS = ['get', 'post', 'put', 'delete', 'patch'];
+ var VERB_SELECTOR = VERBS.map(function(verb){
+ return "[hx-" + verb + "], [data-hx-" + verb + "]"
+ }).join(", ");
+
+ //====================================================================
+ // Utilities
+ //====================================================================
+
+ function parseInterval(str) {
+ if (str == undefined) {
+ return undefined
+ }
+ if (str.slice(-2) == "ms") {
+ return parseFloat(str.slice(0,-2)) || undefined
+ }
+ if (str.slice(-1) == "s") {
+ return (parseFloat(str.slice(0,-1)) * 1000) || undefined
+ }
+ return parseFloat(str) || undefined
+ }
+
+ function getRawAttribute(elt, name) {
+ return elt.getAttribute && elt.getAttribute(name);
+ }
+
+ // resolve with both hx and data-hx prefixes
+ function hasAttribute(elt, qualifiedName) {
+ return elt.hasAttribute && (elt.hasAttribute(qualifiedName) ||
+ elt.hasAttribute("data-" + qualifiedName));
+ }
+
+ function getAttributeValue(elt, qualifiedName) {
+ return getRawAttribute(elt, qualifiedName) || getRawAttribute(elt, "data-" + qualifiedName);
+ }
+
+ function parentElt(elt) {
+ return elt.parentElement;
+ }
+
+ function getDocument() {
+ return document;
+ }
+
+ function getClosestMatch(elt, condition) {
+ if (condition(elt)) {
+ return elt;
+ } else if (parentElt(elt)) {
+ return getClosestMatch(parentElt(elt), condition);
+ } else {
+ return null;
+ }
+ }
+
+ function getClosestAttributeValue(elt, attributeName) {
+ var closestAttr = null;
+ getClosestMatch(elt, function (e) {
+ return closestAttr = getAttributeValue(e, attributeName);
+ });
+ if (closestAttr !== "unset") {
+ return closestAttr;
+ }
+ }
+
+ function matches(elt, selector) {
+ // noinspection JSUnresolvedVariable
+ var matchesFunction = elt.matches ||
+ elt.matchesSelector || elt.msMatchesSelector || elt.mozMatchesSelector
+ || elt.webkitMatchesSelector || elt.oMatchesSelector;
+ return matchesFunction && matchesFunction.call(elt, selector);
+ }
+
+ function getStartTag(str) {
+ var tagMatcher = /<([a-z][^\/\0>\x20\t\r\n\f]*)/i
+ var match = tagMatcher.exec( str );
+ if (match) {
+ return match[1].toLowerCase();
+ } else {
+ return "";
+ }
+ }
+
+ function parseHTML(resp, depth) {
+ var parser = new DOMParser();
+ var responseDoc = parser.parseFromString(resp, "text/html");
+ var responseNode = responseDoc.body;
+ while (depth > 0) {
+ depth--;
+ // @ts-ignore
+ responseNode = responseNode.firstChild;
+ }
+ if (responseNode == null) {
+ // @ts-ignore
+ responseNode = getDocument().createDocumentFragment();
+ }
+ return responseNode;
+ }
+
+ function makeFragment(resp) {
+ if (htmx.config.useTemplateFragments) {
+ var documentFragment = parseHTML("<body><template>" + resp + "</template></body>", 0);
+ return documentFragment.querySelector('template').content;
+ } else {
+ var startTag = getStartTag(resp);
+ switch (startTag) {
+ case "thead":
+ case "tbody":
+ case "tfoot":
+ case "colgroup":
+ case "caption":
+ return parseHTML("<table>" + resp + "</table>", 1);
+ case "col":
+ return parseHTML("<table><colgroup>" + resp + "</colgroup></table>", 2);
+ case "tr":
+ return parseHTML("<table><tbody>" + resp + "</tbody></table>", 2);
+ case "td":
+ case "th":
+ return parseHTML("<table><tbody><tr>" + resp + "</tr></tbody></table>", 3);
+ case "script":
+ return parseHTML("<div>" + resp + "</div>", 1);
+ default:
+ return parseHTML(resp, 0);
+ }
+ }
+ }
+
+ function maybeCall(func){
+ if(func) {
+ func();
+ }
+ }
+
+ function isType(o, type) {
+ return Object.prototype.toString.call(o) === "[object " + type + "]";
+ }
+
+ function isFunction(o) {
+ return isType(o, "Function");
+ }
+
+ function isRawObject(o) {
+ return isType(o, "Object");
+ }
+
+ function getInternalData(elt) {
+ var dataProp = 'htmx-internal-data';
+ var data = elt[dataProp];
+ if (!data) {
+ data = elt[dataProp] = {};
+ }
+ return data;
+ }
+
+ function toArray(arr) {
+ var returnArr = [];
+ if (arr) {
+ for (var i = 0; i < arr.length; i++) {
+ returnArr.push(arr[i]);
+ }
+ }
+ return returnArr
+ }
+
+ function forEach(arr, func) {
+ if (arr) {
+ for (var i = 0; i < arr.length; i++) {
+ func(arr[i]);
+ }
+ }
+ }
+
+ function isScrolledIntoView(el) {
+ var rect = el.getBoundingClientRect();
+ var elemTop = rect.top;
+ var elemBottom = rect.bottom;
+ return elemTop < window.innerHeight && elemBottom >= 0;
+ }
+
+ function bodyContains(elt) {
+ if (elt.getRootNode() instanceof ShadowRoot) {
+ return getDocument().body.contains(elt.getRootNode().host);
+ } else {
+ return getDocument().body.contains(elt);
+ }
+ }
+
+ function splitOnWhitespace(trigger) {
+ return trigger.trim().split(/\s+/);
+ }
+
+ function mergeObjects(obj1, obj2) {
+ for (var key in obj2) {
+ if (obj2.hasOwnProperty(key)) {
+ obj1[key] = obj2[key];
+ }
+ }
+ return obj1;
+ }
+
+ function parseJSON(jString) {
+ try {
+ return JSON.parse(jString);
+ } catch(error) {
+ logError(error);
+ return null;
+ }
+ }
+
+ //==========================================================================================
+ // public API
+ //==========================================================================================
+
+ function internalEval(str){
+ return maybeEval(getDocument().body, function () {
+ return eval(str);
+ });
+ }
+
+ function onLoadHelper(callback) {
+ var value = htmx.on("htmx:load", function(evt) {
+ callback(evt.detail.elt);
+ });
+ return value;
+ }
+
+ function logAll(){
+ htmx.logger = function(elt, event, data) {
+ if(console) {
+ console.log(event, elt, data);
+ }
+ }
+ }
+
+ function find(eltOrSelector, selector) {
+ if (selector) {
+ return eltOrSelector.querySelector(selector);
+ } else {
+ return find(getDocument(), eltOrSelector);
+ }
+ }
+
+ function findAll(eltOrSelector, selector) {
+ if (selector) {
+ return eltOrSelector.querySelectorAll(selector);
+ } else {
+ return findAll(getDocument(), eltOrSelector);
+ }
+ }
+
+ function removeElement(elt, delay) {
+ elt = resolveTarget(elt);
+ if (delay) {
+ setTimeout(function(){removeElement(elt);}, delay)
+ } else {
+ elt.parentElement.removeChild(elt);
+ }
+ }
+
+ function addClassToElement(elt, clazz, delay) {
+ elt = resolveTarget(elt);
+ if (delay) {
+ setTimeout(function(){addClassToElement(elt, clazz);}, delay)
+ } else {
+ elt.classList && elt.classList.add(clazz);
+ }
+ }
+
+ function removeClassFromElement(elt, clazz, delay) {
+ elt = resolveTarget(elt);
+ if (delay) {
+ setTimeout(function(){removeClassFromElement(elt, clazz);}, delay)
+ } else {
+ if (elt.classList) {
+ elt.classList.remove(clazz);
+ // if there are no classes left, remove the class attribute
+ if (elt.classList.length === 0) {
+ elt.removeAttribute("class");
+ }
+ }
+ }
+ }
+
+ function toggleClassOnElement(elt, clazz) {
+ elt = resolveTarget(elt);
+ elt.classList.toggle(clazz);
+ }
+
+ function takeClassForElement(elt, clazz) {
+ elt = resolveTarget(elt);
+ forEach(elt.parentElement.children, function(child){
+ removeClassFromElement(child, clazz);
+ })
+ addClassToElement(elt, clazz);
+ }
+
+ function closest(elt, selector) {
+ elt = resolveTarget(elt);
+ if (elt.closest) {
+ return elt.closest(selector);
+ } else {
+ do{
+ if (elt == null || matches(elt, selector)){
+ return elt;
+ }
+ }
+ while (elt = elt && parentElt(elt));
+ }
+ }
+
+ function querySelectorAllExt(elt, selector) {
+ if (selector.indexOf("closest ") === 0) {
+ return [closest(elt, selector.substr(8))];
+ } else if (selector.indexOf("find ") === 0) {
+ return [find(elt, selector.substr(5))];
+ } else if (selector === 'document') {
+ return [document];
+ } else if (selector === 'window') {
+ return [window];
+ } else {
+ return getDocument().querySelectorAll(selector);
+ }
+ }
+
+ function querySelectorExt(eltOrSelector, selector) {
+ if (selector) {
+ return querySelectorAllExt(eltOrSelector, selector)[0];
+ } else {
+ return querySelectorAllExt(getDocument().body, eltOrSelector)[0];
+ }
+ }
+
+ function resolveTarget(arg2) {
+ if (isType(arg2, 'String')) {
+ return find(arg2);
+ } else {
+ return arg2;
+ }
+ }
+
+ function processEventArgs(arg1, arg2, arg3) {
+ if (isFunction(arg2)) {
+ return {
+ target: getDocument().body,
+ event: arg1,
+ listener: arg2
+ }
+ } else {
+ return {
+ target: resolveTarget(arg1),
+ event: arg2,
+ listener: arg3
+ }
+ }
+
+ }
+
+ function addEventListenerImpl(arg1, arg2, arg3) {
+ ready(function(){
+ var eventArgs = processEventArgs(arg1, arg2, arg3);
+ eventArgs.target.addEventListener(eventArgs.event, eventArgs.listener);
+ })
+ var b = isFunction(arg2);
+ return b ? arg2 : arg3;
+ }
+
+ function removeEventListenerImpl(arg1, arg2, arg3) {
+ ready(function(){
+ var eventArgs = processEventArgs(arg1, arg2, arg3);
+ eventArgs.target.removeEventListener(eventArgs.event, eventArgs.listener);
+ })
+ return isFunction(arg2) ? arg2 : arg3;
+ }
+
+ //====================================================================
+ // Node processing
+ //====================================================================
+
+ function getTarget(elt) {
+ var explicitTarget = getClosestMatch(elt, function(e){return getAttributeValue(e,"hx-target") !== null});
+ if (explicitTarget) {
+ var targetStr = getAttributeValue(explicitTarget, "hx-target");
+ if (targetStr === "this") {
+ return explicitTarget;
+ } else {
+ return querySelectorExt(elt, targetStr)
+ }
+ } else {
+ var data = getInternalData(elt);
+ if (data.boosted) {
+ return getDocument().body;
+ } else {
+ return elt;
+ }
+ }
+ }
+
+ function shouldSettleAttribute(name) {
+ var attributesToSettle = htmx.config.attributesToSettle;
+ for (var i = 0; i < attributesToSettle.length; i++) {
+ if (name === attributesToSettle[i]) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function cloneAttributes(mergeTo, mergeFrom) {
+ forEach(mergeTo.attributes, function (attr) {
+ if (!mergeFrom.hasAttribute(attr.name) && shouldSettleAttribute(attr.name)) {
+ mergeTo.removeAttribute(attr.name)
+ }
+ });
+ forEach(mergeFrom.attributes, function (attr) {
+ if (shouldSettleAttribute(attr.name)) {
+ mergeTo.setAttribute(attr.name, attr.value);
+ }
+ });
+ }
+
+ function isInlineSwap(swapStyle, target) {
+ var extensions = getExtensions(target);
+ for (var i = 0; i < extensions.length; i++) {
+ var extension = extensions[i];
+ try {
+ if (extension.isInlineSwap(swapStyle)) {
+ return true;
+ }
+ } catch(e) {
+ logError(e);
+ }
+ }
+ return swapStyle === "outerHTML";
+ }
+
+ function oobSwap(oobValue, oobElement, settleInfo) {
+ var selector = "#" + oobElement.id;
+ var swapStyle = "outerHTML";
+ if (oobValue === "true") {
+ // do nothing
+ } else if (oobValue.indexOf(":") > 0) {
+ swapStyle = oobValue.substr(0, oobValue.indexOf(":"));
+ selector = oobValue.substr(oobValue.indexOf(":") + 1, oobValue.length);
+ } else {
+ swapStyle = oobValue;
+ }
+
+ var target = getDocument().querySelector(selector);
+ if (target) {
+ var fragment;
+ fragment = getDocument().createDocumentFragment();
+ fragment.appendChild(oobElement); // pulls the child out of the existing fragment
+ if (!isInlineSwap(swapStyle, target)) {
+ fragment = oobElement; // if this is not an inline swap, we use the content of the node, not the node itself
+ }
+ swap(swapStyle, target, target, fragment, settleInfo);
+ } else {
+ oobElement.parentNode.removeChild(oobElement);
+ triggerErrorEvent(getDocument().body, "htmx:oobErrorNoTarget", {content: oobElement})
+ }
+ return oobValue;
+ }
+
+ function handleOutOfBandSwaps(fragment, settleInfo) {
+ forEach(findAll(fragment, '[hx-swap-oob], [data-hx-swap-oob]'), function (oobElement) {
+ var oobValue = getAttributeValue(oobElement, "hx-swap-oob");
+ if (oobValue != null) {
+ oobSwap(oobValue, oobElement, settleInfo);
+ }
+ });
+ }
+
+ function handlePreservedElements(fragment) {
+ forEach(findAll(fragment, '[hx-preserve], [data-hx-preserve]'), function (preservedElt) {
+ var id = getAttributeValue(preservedElt, "id");
+ var oldElt = getDocument().getElementById(id);
+ if (oldElt != null) {
+ preservedElt.parentNode.replaceChild(oldElt, preservedElt);
+ }
+ });
+ }
+
+ function handleAttributes(parentNode, fragment, settleInfo) {
+ forEach(fragment.querySelectorAll("[id]"), function (newNode) {
+ if (newNode.id && newNode.id.length > 0) {
+ var oldNode = parentNode.querySelector(newNode.tagName + "[id='" + newNode.id + "']");
+ if (oldNode && oldNode !== parentNode) {
+ var newAttributes = newNode.cloneNode();
+ cloneAttributes(newNode, oldNode);
+ settleInfo.tasks.push(function () {
+ cloneAttributes(newNode, newAttributes);
+ });
+ }
+ }
+ });
+ }
+
+ function makeAjaxLoadTask(child) {
+ return function () {
+ removeClassFromElement(child, htmx.config.addedClass);
+ processNode(child);
+ processScripts(child);
+ processFocus(child)
+ triggerEvent(child, 'htmx:load');
+ };
+ }
+
+ function processFocus(child) {
+ var autofocus = "[autofocus]";
+ var autoFocusedElt = matches(child, autofocus) ? child : child.querySelector(autofocus)
+ if (autoFocusedElt != null) {
+ autoFocusedElt.focus();
+ }
+ }
+
+ function insertNodesBefore(parentNode, insertBefore, fragment, settleInfo) {
+ handleAttributes(parentNode, fragment, settleInfo);
+ while(fragment.childNodes.length > 0){
+ var child = fragment.firstChild;
+ addClassToElement(child, htmx.config.addedClass);
+ parentNode.insertBefore(child, insertBefore);
+ if (child.nodeType !== Node.TEXT_NODE && child.nodeType !== Node.COMMENT_NODE) {
+ settleInfo.tasks.push(makeAjaxLoadTask(child));
+ }
+ }
+ }
+
+ function cleanUpElement(element) {
+ var internalData = getInternalData(element);
+ if (internalData.webSocket) {
+ internalData.webSocket.close();
+ }
+ if (internalData.sseEventSource) {
+ internalData.sseEventSource.close();
+ }
+ if (internalData.listenerInfos) {
+ forEach(internalData.listenerInfos, function(info) {
+ if (element !== info.on) {
+ info.on.removeEventListener(info.trigger, info.listener);
+ }
+ });
+ }
+ if (element.children) { // IE
+ forEach(element.children, function(child) { cleanUpElement(child) });
+ }
+ }
+
+ function swapOuterHTML(target, fragment, settleInfo) {
+ if (target.tagName === "BODY") {
+ return swapInnerHTML(target, fragment, settleInfo);
+ } else {
+ var eltBeforeNewContent = target.previousSibling;
+ insertNodesBefore(parentElt(target), target, fragment, settleInfo);
+ if (eltBeforeNewContent == null) {
+ var newElt = parentElt(target).firstChild;
+ } else {
+ var newElt = eltBeforeNewContent.nextSibling;
+ }
+ getInternalData(target).replacedWith = newElt; // tuck away so we can fire events on it later
+ settleInfo.elts = [] // clear existing elements
+ while(newElt && newElt !== target) {
+ if (newElt.nodeType === Node.ELEMENT_NODE) {
+ settleInfo.elts.push(newElt);
+ }
+ newElt = newElt.nextElementSibling;
+ }
+ cleanUpElement(target);
+ parentElt(target).removeChild(target);
+ }
+ }
+
+ function swapAfterBegin(target, fragment, settleInfo) {
+ return insertNodesBefore(target, target.firstChild, fragment, settleInfo);
+ }
+
+ function swapBeforeBegin(target, fragment, settleInfo) {
+ return insertNodesBefore(parentElt(target), target, fragment, settleInfo);
+ }
+
+ function swapBeforeEnd(target, fragment, settleInfo) {
+ return insertNodesBefore(target, null, fragment, settleInfo);
+ }
+
+ function swapAfterEnd(target, fragment, settleInfo) {
+ return insertNodesBefore(parentElt(target), target.nextSibling, fragment, settleInfo);
+ }
+
+ function swapInnerHTML(target, fragment, settleInfo) {
+ var firstChild = target.firstChild;
+ insertNodesBefore(target, firstChild, fragment, settleInfo);
+ if (firstChild) {
+ while (firstChild.nextSibling) {
+ cleanUpElement(firstChild.nextSibling)
+ target.removeChild(firstChild.nextSibling);
+ }
+ cleanUpElement(firstChild)
+ target.removeChild(firstChild);
+ }
+ }
+
+ function maybeSelectFromResponse(elt, fragment) {
+ var selector = getClosestAttributeValue(elt, "hx-select");
+ if (selector) {
+ var newFragment = getDocument().createDocumentFragment();
+ forEach(fragment.querySelectorAll(selector), function (node) {
+ newFragment.appendChild(node);
+ });
+ fragment = newFragment;
+ }
+ return fragment;
+ }
+
+ function swap(swapStyle, elt, target, fragment, settleInfo) {
+ switch (swapStyle) {
+ case "none":
+ return;
+ case "outerHTML":
+ swapOuterHTML(target, fragment, settleInfo);
+ return;
+ case "afterbegin":
+ swapAfterBegin(target, fragment, settleInfo);
+ return;
+ case "beforebegin":
+ swapBeforeBegin(target, fragment, settleInfo);
+ return;
+ case "beforeend":
+ swapBeforeEnd(target, fragment, settleInfo);
+ return;
+ case "afterend":
+ swapAfterEnd(target, fragment, settleInfo);
+ return;
+ default:
+ var extensions = getExtensions(elt);
+ for (var i = 0; i < extensions.length; i++) {
+ var ext = extensions[i];
+ try {
+ var newElements = ext.handleSwap(swapStyle, target, fragment, settleInfo);
+ if (newElements) {
+ if (typeof newElements.length !== 'undefined') {
+ // if handleSwap returns an array (like) of elements, we handle them
+ for (var j = 0; j < newElements.length; j++) {
+ var child = newElements[j];
+ if (child.nodeType !== Node.TEXT_NODE && child.nodeType !== Node.COMMENT_NODE) {
+ settleInfo.tasks.push(makeAjaxLoadTask(child));
+ }
+ }
+ }
+ return;
+ }
+ } catch (e) {
+ logError(e);
+ }
+ }
+ swapInnerHTML(target, fragment, settleInfo);
+ }
+ }
+
+ function findTitle(content) {
+ if (content.indexOf('<title') > -1) {
+ var contentWithSvgsRemoved = content.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim, '');
+ var result = contentWithSvgsRemoved.match(/<title(\s[^>]*>|>)([\s\S]*?)<\/title>/im);
+
+ if (result) {
+ return result[2];
+ }
+ }
+ }
+
+ function selectAndSwap(swapStyle, target, elt, responseText, settleInfo) {
+ var title = findTitle(responseText);
+ if(title) {
+ var titleElt = find("title");
+ if(titleElt) {
+ titleElt.innerHTML = title;
+ } else {
+ window.document.title = title;
+ }
+ }
+ var fragment = makeFragment(responseText);
+ if (fragment) {
+ handleOutOfBandSwaps(fragment, settleInfo);
+ fragment = maybeSelectFromResponse(elt, fragment);
+ handlePreservedElements(fragment);
+ return swap(swapStyle, elt, target, fragment, settleInfo);
+ }
+ }
+
+ function handleTrigger(xhr, header, elt) {
+ var triggerBody = xhr.getResponseHeader(header);
+ if (triggerBody.indexOf("{") === 0) {
+ var triggers = parseJSON(triggerBody);
+ for (var eventName in triggers) {
+ if (triggers.hasOwnProperty(eventName)) {
+ var detail = triggers[eventName];
+ if (!isRawObject(detail)) {
+ detail = {"value": detail}
+ }
+ triggerEvent(elt, eventName, detail);
+ }
+ }
+ } else {
+ triggerEvent(elt, triggerBody, []);
+ }
+ }
+
+ var WHITESPACE = /\s/;
+ var WHITESPACE_OR_COMMA = /[\s,]/;
+ var SYMBOL_START = /[_$a-zA-Z]/;
+ var SYMBOL_CONT = /[_$a-zA-Z0-9]/;
+ var STRINGISH_START = ['"', "'", "/"];
+ var NOT_WHITESPACE = /[^\s]/;
+ function tokenizeString(str) {
+ var tokens = [];
+ var position = 0;
+ while (position < str.length) {
+ if(SYMBOL_START.exec(str.charAt(position))) {
+ var startPosition = position;
+ while (SYMBOL_CONT.exec(str.charAt(position + 1))) {
+ position++;
+ }
+ tokens.push(str.substr(startPosition, position - startPosition + 1));
+ } else if (STRINGISH_START.indexOf(str.charAt(position)) !== -1) {
+ var startChar = str.charAt(position);
+ var startPosition = position;
+ position++;
+ while (position < str.length && str.charAt(position) !== startChar ) {
+ if (str.charAt(position) === "\\") {
+ position++;
+ }
+ position++;
+ }
+ tokens.push(str.substr(startPosition, position - startPosition + 1));
+ } else {
+ var symbol = str.charAt(position);
+ tokens.push(symbol);
+ }
+ position++;
+ }
+ return tokens;
+ }
+
+ function isPossibleRelativeReference(token, last, paramName) {
+ return SYMBOL_START.exec(token.charAt(0)) &&
+ token !== "true" &&
+ token !== "false" &&
+ token !== "this" &&
+ token !== paramName &&
+ last !== ".";
+ }
+
+ function maybeGenerateConditional(elt, tokens, paramName) {
+ if (tokens[0] === '[') {
+ tokens.shift();
+ var bracketCount = 1;
+ var conditionalSource = " return (function(" + paramName + "){ return (";
+ var last = null;
+ while (tokens.length > 0) {
+ var token = tokens[0];
+ if (token === "]") {
+ bracketCount--;
+ if (bracketCount === 0) {
+ if (last === null) {
+ conditionalSource = conditionalSource + "true";
+ }
+ tokens.shift();
+ conditionalSource += ")})";
+ try {
+ var conditionFunction = maybeEval(elt,function () {
+ return Function(conditionalSource)();
+ },
+ function(){return true})
+ conditionFunction.source = conditionalSource;
+ return conditionFunction;
+ } catch (e) {
+ triggerErrorEvent(getDocument().body, "htmx:syntax:error", {error:e, source:conditionalSource})
+ return null;
+ }
+ }
+ } else if (token === "[") {
+ bracketCount++;
+ }
+ if (isPossibleRelativeReference(token, last, paramName)) {
+ conditionalSource += "((" + paramName + "." + token + ") ? (" + paramName + "." + token + ") : (window." + token + "))";
+ } else {
+ conditionalSource = conditionalSource + token;
+ }
+ last = tokens.shift();
+ }
+ }
+ }
+
+ function consumeUntil(tokens, match) {
+ var result = "";
+ while (tokens.length > 0 && !tokens[0].match(match)) {
+ result += tokens.shift();
+ }
+ return result;
+ }
+
+ var INPUT_SELECTOR = 'input, textarea, select';
+ function getTriggerSpecs(elt) {
+ var explicitTrigger = getAttributeValue(elt, 'hx-trigger');
+ var triggerSpecs = [];
+ if (explicitTrigger) {
+ var tokens = tokenizeString(explicitTrigger);
+ do {
+ consumeUntil(tokens, NOT_WHITESPACE);
+ var initialLength = tokens.length;
+ var trigger = consumeUntil(tokens, /[,\[\s]/);
+ if (trigger !== "") {
+ if (trigger === "every") {
+ var every = {trigger: 'every'};
+ consumeUntil(tokens, NOT_WHITESPACE);
+ every.pollInterval = parseInterval(consumeUntil(tokens, /[,\[\s]/));
+ consumeUntil(tokens, NOT_WHITESPACE);
+ var eventFilter = maybeGenerateConditional(elt, tokens, "event");
+ if (eventFilter) {
+ every.eventFilter = eventFilter;
+ }
+ triggerSpecs.push(every);
+ } else if (trigger.indexOf("sse:") === 0) {
+ triggerSpecs.push({trigger: 'sse', sseEvent: trigger.substr(4)});
+ } else {
+ var triggerSpec = {trigger: trigger};
+ var eventFilter = maybeGenerateConditional(elt, tokens, "event");
+ if (eventFilter) {
+ triggerSpec.eventFilter = eventFilter;
+ }
+ while (tokens.length > 0 && tokens[0] !== ",") {
+ consumeUntil(tokens, NOT_WHITESPACE)
+ var token = tokens.shift();
+ if (token === "changed") {
+ triggerSpec.changed = true;
+ } else if (token === "once") {
+ triggerSpec.once = true;
+ } else if (token === "consume") {
+ triggerSpec.consume = true;
+ } else if (token === "delay" && tokens[0] === ":") {
+ tokens.shift();
+ triggerSpec.delay = parseInterval(consumeUntil(tokens, WHITESPACE_OR_COMMA));
+ } else if (token === "from" && tokens[0] === ":") {
+ tokens.shift();
+ var from_arg = consumeUntil(tokens, WHITESPACE_OR_COMMA);
+ if (from_arg === "closest" || from_arg === "find") {
+ tokens.shift();
+ from_arg +=
+ " " +
+ consumeUntil(
+ tokens,
+ WHITESPACE_OR_COMMA
+ );
+ }
+ triggerSpec.from = from_arg;
+ } else if (token === "target" && tokens[0] === ":") {
+ tokens.shift();
+ triggerSpec.target = consumeUntil(tokens, WHITESPACE_OR_COMMA);
+ } else if (token === "throttle" && tokens[0] === ":") {
+ tokens.shift();
+ triggerSpec.throttle = parseInterval(consumeUntil(tokens, WHITESPACE_OR_COMMA));
+ } else if (token === "queue" && tokens[0] === ":") {
+ tokens.shift();
+ triggerSpec.queue = consumeUntil(tokens, WHITESPACE_OR_COMMA);
+ } else if ((token === "root" || token === "threshold") && tokens[0] === ":") {
+ tokens.shift();
+ triggerSpec[token] = consumeUntil(tokens, WHITESPACE_OR_COMMA);
+ } else {
+ triggerErrorEvent(elt, "htmx:syntax:error", {token:tokens.shift()});
+ }
+ }
+ triggerSpecs.push(triggerSpec);
+ }
+ }
+ if (tokens.length === initialLength) {
+ triggerErrorEvent(elt, "htmx:syntax:error", {token:tokens.shift()});
+ }
+ consumeUntil(tokens, NOT_WHITESPACE);
+ } while (tokens[0] === "," && tokens.shift())
+ }
+
+ if (triggerSpecs.length > 0) {
+ return triggerSpecs;
+ } else if (matches(elt, 'form')) {
+ return [{trigger: 'submit'}];
+ } else if (matches(elt, INPUT_SELECTOR)) {
+ return [{trigger: 'change'}];
+ } else {
+ return [{trigger: 'click'}];
+ }
+ }
+
+ function cancelPolling(elt) {
+ getInternalData(elt).cancelled = true;
+ }
+
+ function processPolling(elt, verb, path, spec) {
+ var nodeData = getInternalData(elt);
+ nodeData.timeout = setTimeout(function () {
+ if (bodyContains(elt) && nodeData.cancelled !== true) {
+ if (!maybeFilterEvent(spec, makeEvent('hx:poll:trigger', {triggerSpec:spec}))) {
+ issueAjaxRequest(verb, path, elt);
+ }
+ processPolling(elt, verb, getAttributeValue(elt, "hx-" + verb), spec);
+ }
+ }, spec.pollInterval);
+ }
+
+ function isLocalLink(elt) {
+ return location.hostname === elt.hostname &&
+ getRawAttribute(elt,'href') &&
+ getRawAttribute(elt,'href').indexOf("#") !== 0;
+ }
+
+ function boostElement(elt, nodeData, triggerSpecs) {
+ if ((elt.tagName === "A" && isLocalLink(elt) && elt.target === "") || elt.tagName === "FORM") {
+ nodeData.boosted = true;
+ var verb, path;
+ if (elt.tagName === "A") {
+ verb = "get";
+ path = getRawAttribute(elt, 'href');
+ nodeData.pushURL = true;
+ } else {
+ var rawAttribute = getRawAttribute(elt, "method");
+ verb = rawAttribute ? rawAttribute.toLowerCase() : "get";
+ if (verb === "get") {
+ nodeData.pushURL = true;
+ }
+ path = getRawAttribute(elt, 'action');
+ }
+ triggerSpecs.forEach(function(triggerSpec) {
+ addEventListener(elt, verb, path, nodeData, triggerSpec, true);
+ });
+ }
+ }
+
+ function shouldCancel(evt, elt) {
+ if (evt.type === "submit" || evt.type === "click") {
+ if (elt.tagName === "FORM") {
+ return true;
+ }
+ if (matches(elt, 'input[type="submit"], button') && closest(elt, 'form') !== null) {
+ return true;
+ }
+ if (elt.tagName === "A" && elt.href &&
+ (elt.getAttribute('href') === '#' || elt.getAttribute('href').indexOf("#") !== 0)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function ignoreBoostedAnchorCtrlClick(elt, evt) {
+ return getInternalData(elt).boosted && elt.tagName === "A" && evt.type === "click" && (evt.ctrlKey || evt.metaKey);
+ }
+
+ function maybeFilterEvent(triggerSpec, evt) {
+ var eventFilter = triggerSpec.eventFilter;
+ if(eventFilter){
+ try {
+ return eventFilter(evt) !== true;
+ } catch(e) {
+ triggerErrorEvent(getDocument().body, "htmx:eventFilter:error", {error: e, source:eventFilter.source});
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function addEventListener(elt, verb, path, nodeData, triggerSpec, explicitCancel) {
+ var eltsToListenOn;
+ if (triggerSpec.from) {
+ eltsToListenOn = querySelectorAllExt(elt, triggerSpec.from);
+ } else {
+ eltsToListenOn = [elt];
+ }
+ forEach(eltsToListenOn, function (eltToListenOn) {
+ var eventListener = function (evt) {
+ if (!bodyContains(elt)) {
+ eltToListenOn.removeEventListener(triggerSpec.trigger, eventListener);
+ return;
+ }
+ if (ignoreBoostedAnchorCtrlClick(elt, evt)) {
+ return;
+ }
+ if (explicitCancel || shouldCancel(evt, elt)) {
+ evt.preventDefault();
+ }
+ if (maybeFilterEvent(triggerSpec, evt)) {
+ return;
+ }
+ var eventData = getInternalData(evt);
+ eventData.triggerSpec = triggerSpec;
+ if (eventData.handledFor == null) {
+ eventData.handledFor = [];
+ }
+ var elementData = getInternalData(elt);
+ if (eventData.handledFor.indexOf(elt) < 0) {
+ eventData.handledFor.push(elt);
+ if (triggerSpec.consume) {
+ evt.stopPropagation();
+ }
+ if (triggerSpec.target && evt.target) {
+ if (!matches(evt.target, triggerSpec.target)) {
+ return;
+ }
+ }
+ if (triggerSpec.once) {
+ if (elementData.triggeredOnce) {
+ return;
+ } else {
+ elementData.triggeredOnce = true;
+ }
+ }
+ if (triggerSpec.changed) {
+ if (elementData.lastValue === elt.value) {
+ return;
+ } else {
+ elementData.lastValue = elt.value;
+ }
+ }
+ if (elementData.delayed) {
+ clearTimeout(elementData.delayed);
+ }
+ if (elementData.throttle) {
+ return;
+ }
+
+ if (triggerSpec.throttle) {
+ if (!elementData.throttle) {
+ issueAjaxRequest(verb, path, elt, evt);
+ elementData.throttle = setTimeout(function () {
+ elementData.throttle = null;
+ }, triggerSpec.throttle);
+ }
+ } else if (triggerSpec.delay) {
+ elementData.delayed = setTimeout(function () {
+ issueAjaxRequest(verb, path, elt, evt);
+ }, triggerSpec.delay);
+ } else {
+ issueAjaxRequest(verb, path, elt, evt);
+ }
+ }
+ };
+ if (nodeData.listenerInfos == null) {
+ nodeData.listenerInfos = [];
+ }
+ nodeData.listenerInfos.push({
+ trigger: triggerSpec.trigger,
+ listener: eventListener,
+ on: eltToListenOn
+ })
+ eltToListenOn.addEventListener(triggerSpec.trigger, eventListener);
+ })
+ }
+
+ var windowIsScrolling = false // used by initScrollHandler
+ var scrollHandler = null;
+ function initScrollHandler() {
+ if (!scrollHandler) {
+ scrollHandler = function() {
+ windowIsScrolling = true
+ };
+ window.addEventListener("scroll", scrollHandler)
+ setInterval(function() {
+ if (windowIsScrolling) {
+ windowIsScrolling = false;
+ forEach(getDocument().querySelectorAll("[hx-trigger='revealed'],[data-hx-trigger='revealed']"), function (elt) {
+ maybeReveal(elt);
+ })
+ }
+ }, 200);
+ }
+ }
+
+ function maybeReveal(elt) {
+ if (!hasAttribute(elt,'data-hx-revealed') && isScrolledIntoView(elt)) {
+ elt.setAttribute('data-hx-revealed', 'true');
+ var nodeData = getInternalData(elt);
+ if (nodeData.initialized) {
+ issueAjaxRequest(nodeData.verb, nodeData.path, elt);
+ } else {
+ // if the node isn't initialized, wait for it before triggering the request
+ elt.addEventListener("htmx:afterProcessNode",
+ function () {
+ issueAjaxRequest(nodeData.verb, nodeData.path, elt);
+ }, {once: true});
+ }
+ }
+ }
+
+ function processWebSocketInfo(elt, nodeData, info) {
+ var values = splitOnWhitespace(info);
+ for (var i = 0; i < values.length; i++) {
+ var value = values[i].split(/:(.+)/);
+ if (value[0] === "connect") {
+ ensureWebSocket(elt, value[1], 0);
+ }
+ if (value[0] === "send") {
+ processWebSocketSend(elt);
+ }
+ }
+ }
+
+ function ensureWebSocket(elt, wssSource, retryCount) {
+ if (!bodyContains(elt)) {
+ return; // stop ensuring websocket connection when socket bearing element ceases to exist
+ }
+
+ if (wssSource.indexOf("/") == 0) { // complete absolute paths only
+ var base_part = location.hostname + (location.port ? ':'+location.port: '');
+ if (location.protocol == 'https:') {
+ wssSource = "wss://" + base_part + wssSource;
+ } else if (location.protocol == 'http:') {
+ wssSource = "ws://" + base_part + wssSource;
+ }
+ }
+ var socket = htmx.createWebSocket(wssSource);
+ socket.onerror = function (e) {
+ triggerErrorEvent(elt, "htmx:wsError", {error:e, socket:socket});
+ maybeCloseWebSocketSource(elt);
+ };
+
+ socket.onclose = function (e) {
+ if ([1006, 1012, 1013].indexOf(e.code) >= 0) { // Abnormal Closure/Service Restart/Try Again Later
+ var delay = getWebSocketReconnectDelay(retryCount);
+ setTimeout(function() {
+ ensureWebSocket(elt, wssSource, retryCount+1); // creates a websocket with a new timeout
+ }, delay);
+ }
+ };
+ socket.onopen = function (e) {
+ retryCount = 0;
+ }
+
+ getInternalData(elt).webSocket = socket;
+ socket.addEventListener('message', function (event) {
+ if (maybeCloseWebSocketSource(elt)) {
+ return;
+ }
+
+ var response = event.data;
+ withExtensions(elt, function(extension){
+ response = extension.transformResponse(response, null, elt);
+ });
+
+ var settleInfo = makeSettleInfo(elt);
+ var fragment = makeFragment(response);
+ var children = toArray(fragment.children);
+ for (var i = 0; i < children.length; i++) {
+ var child = children[i];
+ oobSwap(getAttributeValue(child, "hx-swap-oob") || "true", child, settleInfo);
+ }
+
+ settleImmediately(settleInfo.tasks);
+ });
+ }
+
+ function maybeCloseWebSocketSource(elt) {
+ if (!bodyContains(elt)) {
+ getInternalData(elt).webSocket.close();
+ return true;
+ }
+ }
+
+ function processWebSocketSend(elt) {
+ var webSocketSourceElt = getClosestMatch(elt, function (parent) {
+ return getInternalData(parent).webSocket != null;
+ });
+ if (webSocketSourceElt) {
+ elt.addEventListener(getTriggerSpecs(elt)[0].trigger, function (evt) {
+ var webSocket = getInternalData(webSocketSourceElt).webSocket;
+ var headers = getHeaders(elt, webSocketSourceElt);
+ var results = getInputValues(elt, 'post');
+ var errors = results.errors;
+ var rawParameters = results.values;
+ var expressionVars = getExpressionVars(elt);
+ var allParameters = mergeObjects(rawParameters, expressionVars);
+ var filteredParameters = filterValues(allParameters, elt);
+ filteredParameters['HEADERS'] = headers;
+ if (errors && errors.length > 0) {
+ triggerEvent(elt, 'htmx:validation:halted', errors);
+ return;
+ }
+ webSocket.send(JSON.stringify(filteredParameters));
+ if(shouldCancel(evt, elt)){
+ evt.preventDefault();
+ }
+ });
+ } else {
+ triggerErrorEvent(elt, "htmx:noWebSocketSourceError");
+ }
+ }
+
+ function getWebSocketReconnectDelay(retryCount) {
+ var delay = htmx.config.wsReconnectDelay;
+ if (typeof delay === 'function') {
+ // @ts-ignore
+ return delay(retryCount);
+ }
+ if (delay === 'full-jitter') {
+ var exp = Math.min(retryCount, 6);
+ var maxDelay = 1000 * Math.pow(2, exp);
+ return maxDelay * Math.random();
+ }
+ logError('htmx.config.wsReconnectDelay must either be a function or the string "full-jitter"');
+ }
+
+ //====================================================================
+ // Server Sent Events
+ //====================================================================
+
+ function processSSEInfo(elt, nodeData, info) {
+ var values = splitOnWhitespace(info);
+ for (var i = 0; i < values.length; i++) {
+ var value = values[i].split(/:(.+)/);
+ if (value[0] === "connect") {
+ processSSESource(elt, value[1]);
+ }
+
+ if ((value[0] === "swap")) {
+ processSSESwap(elt, value[1])
+ }
+ }
+ }
+
+ function processSSESource(elt, sseSrc) {
+ var source = htmx.createEventSource(sseSrc);
+ source.onerror = function (e) {
+ triggerErrorEvent(elt, "htmx:sseError", {error:e, source:source});
+ maybeCloseSSESource(elt);
+ };
+ getInternalData(elt).sseEventSource = source;
+ }
+
+ function processSSESwap(elt, sseEventName) {
+ var sseSourceElt = getClosestMatch(elt, hasEventSource);
+ if (sseSourceElt) {
+ var sseEventSource = getInternalData(sseSourceElt).sseEventSource;
+ var sseListener = function (event) {
+ if (maybeCloseSSESource(sseSourceElt)) {
+ sseEventSource.removeEventListener(sseEventName, sseListener);
+ return;
+ }
+
+ ///////////////////////////
+ // TODO: merge this code with AJAX and WebSockets code in the future.
+
+ var response = event.data;
+ withExtensions(elt, function(extension){
+ response = extension.transformResponse(response, null, elt);
+ });
+
+ var swapSpec = getSwapSpecification(elt)
+ var target = getTarget(elt)
+ var settleInfo = makeSettleInfo(elt);
+
+ selectAndSwap(swapSpec.swapStyle, elt, target, response, settleInfo)
+ settleImmediately(settleInfo.tasks)
+ triggerEvent(elt, "htmx:sseMessage", event)
+ };
+
+ getInternalData(elt).sseListener = sseListener;
+ sseEventSource.addEventListener(sseEventName, sseListener);
+ } else {
+ triggerErrorEvent(elt, "htmx:noSSESourceError");
+ }
+ }
+
+ function processSSETrigger(elt, verb, path, sseEventName) {
+ var sseSourceElt = getClosestMatch(elt, hasEventSource);
+ if (sseSourceElt) {
+ var sseEventSource = getInternalData(sseSourceElt).sseEventSource;
+ var sseListener = function () {
+ if (!maybeCloseSSESource(sseSourceElt)) {
+ if (bodyContains(elt)) {
+ issueAjaxRequest(verb, path, elt);
+ } else {
+ sseEventSource.removeEventListener(sseEventName, sseListener);
+ }
+ }
+ };
+ getInternalData(elt).sseListener = sseListener;
+ sseEventSource.addEventListener(sseEventName, sseListener);
+ } else {
+ triggerErrorEvent(elt, "htmx:noSSESourceError");
+ }
+ }
+
+ function maybeCloseSSESource(elt) {
+ if (!bodyContains(elt)) {
+ getInternalData(elt).sseEventSource.close();
+ return true;
+ }
+ }
+
+ function hasEventSource(node) {
+ return getInternalData(node).sseEventSource != null;
+ }
+
+ //====================================================================
+
+ function loadImmediately(elt, verb, path, nodeData, delay) {
+ var load = function(){
+ if (!nodeData.loaded) {
+ nodeData.loaded = true;
+ issueAjaxRequest(verb, path, elt);
+ }
+ }
+ if (delay) {
+ setTimeout(load, delay);
+ } else {
+ load();
+ }
+ }
+
+ function processVerbs(elt, nodeData, triggerSpecs) {
+ var explicitAction = false;
+ forEach(VERBS, function (verb) {
+ if (hasAttribute(elt,'hx-' + verb)) {
+ var path = getAttributeValue(elt, 'hx-' + verb);
+ explicitAction = true;
+ nodeData.path = path;
+ nodeData.verb = verb;
+ triggerSpecs.forEach(function(triggerSpec) {
+ if (triggerSpec.sseEvent) {
+ processSSETrigger(elt, verb, path, triggerSpec.sseEvent);
+ } else if (triggerSpec.trigger === "revealed") {
+ initScrollHandler();
+ maybeReveal(elt);
+ } else if (triggerSpec.trigger === "intersect") {
+ var observerOptions = {};
+ if (triggerSpec.root) {
+ observerOptions.root = querySelectorExt(elt, triggerSpec.root)
+ }
+ if (triggerSpec.threshold) {
+ observerOptions.threshold = parseFloat(triggerSpec.threshold);
+ }
+ var observer = new IntersectionObserver(function (entries) {
+ for (var i = 0; i < entries.length; i++) {
+ var entry = entries[i];
+ if (entry.isIntersecting) {
+ triggerEvent(elt, "intersect");
+ break;
+ }
+ }
+ }, observerOptions);
+ observer.observe(elt);
+ addEventListener(elt, verb, path, nodeData, triggerSpec);
+ } else if (triggerSpec.trigger === "load") {
+ loadImmediately(elt, verb, path, nodeData, triggerSpec.delay);
+ } else if (triggerSpec.pollInterval) {
+ nodeData.polling = true;
+ processPolling(elt, verb, path, triggerSpec);
+ } else {
+ addEventListener(elt, verb, path, nodeData, triggerSpec);
+ }
+ });
+ }
+ });
+ return explicitAction;
+ }
+
+ function evalScript(script) {
+ if (script.type === "text/javascript" || script.type === "module" || script.type === "") {
+ var newScript = getDocument().createElement("script");
+ forEach(script.attributes, function (attr) {
+ newScript.setAttribute(attr.name, attr.value);
+ });
+ newScript.textContent = script.textContent;
+ newScript.async = false;
+ var parent = script.parentElement;
+
+ try {
+ parent.insertBefore(newScript, script);
+ } catch (e) {
+ logError(e);
+ } finally {
+ parent.removeChild(script);
+ }
+ }
+ }
+
+ function processScripts(elt) {
+ if (matches(elt, "script")) {
+ evalScript(elt);
+ }
+ forEach(findAll(elt, "script"), function (script) {
+ evalScript(script);
+ });
+ }
+
+ function isBoosted() {
+ return document.querySelector("[hx-boost], [data-hx-boost]");
+ }
+
+ function findElementsToProcess(elt) {
+ if (elt.querySelectorAll) {
+ var boostedElts = isBoosted() ? ", a, form" : "";
+ var results = elt.querySelectorAll(VERB_SELECTOR + boostedElts + ", [hx-sse], [data-hx-sse], [hx-ws]," +
+ " [data-hx-ws], [hx-ext], [hx-data-ext]");
+ return results;
+ } else {
+ return [];
+ }
+ }
+
+ function initButtonTracking(form){
+ var maybeSetLastButtonClicked = function(evt){
+ if (matches(evt.target, "button, input[type='submit']")) {
+ var internalData = getInternalData(form);
+ internalData.lastButtonClicked = evt.target;
+ }
+ };
+
+ // need to handle both click and focus in:
+ // focusin - in case someone tabs in to a button and hits the space bar
+ // click - on OSX buttons do not focus on click see https://bugs.webkit.org/show_bug.cgi?id=13724
+
+ form.addEventListener('click', maybeSetLastButtonClicked)
+ form.addEventListener('focusin', maybeSetLastButtonClicked)
+ form.addEventListener('focusout', function(evt){
+ var internalData = getInternalData(form);
+ internalData.lastButtonClicked = null;
+ })
+ }
+
+ function initNode(elt) {
+ if (elt.closest && elt.closest(htmx.config.disableSelector)) {
+ return;
+ }
+ var nodeData = getInternalData(elt);
+ if (!nodeData.initialized) {
+ nodeData.initialized = true;
+ triggerEvent(elt, "htmx:beforeProcessNode")
+
+ if (elt.value) {
+ nodeData.lastValue = elt.value;
+ }
+
+ var triggerSpecs = getTriggerSpecs(elt);
+ var explicitAction = processVerbs(elt, nodeData, triggerSpecs);
+
+ if (!explicitAction && getClosestAttributeValue(elt, "hx-boost") === "true") {
+ boostElement(elt, nodeData, triggerSpecs);
+ }
+
+ if (elt.tagName === "FORM") {
+ initButtonTracking(elt);
+ }
+
+ var sseInfo = getAttributeValue(elt, 'hx-sse');
+ if (sseInfo) {
+ processSSEInfo(elt, nodeData, sseInfo);
+ }
+
+ var wsInfo = getAttributeValue(elt, 'hx-ws');
+ if (wsInfo) {
+ processWebSocketInfo(elt, nodeData, wsInfo);
+ }
+ triggerEvent(elt, "htmx:afterProcessNode");
+ }
+ }
+
+ function processNode(elt) {
+ elt = resolveTarget(elt);
+ initNode(elt);
+ forEach(findElementsToProcess(elt), function(child) { initNode(child) });
+ }
+
+ //====================================================================
+ // Event/Log Support
+ //====================================================================
+
+ function kebabEventName(str) {
+ return str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
+ }
+
+ function makeEvent(eventName, detail) {
+ var evt;
+ if (window.CustomEvent && typeof window.CustomEvent === 'function') {
+ evt = new CustomEvent(eventName, {bubbles: true, cancelable: true, detail: detail});
+ } else {
+ evt = getDocument().createEvent('CustomEvent');
+ evt.initCustomEvent(eventName, true, true, detail);
+ }
+ return evt;
+ }
+
+ function triggerErrorEvent(elt, eventName, detail) {
+ triggerEvent(elt, eventName, mergeObjects({error:eventName}, detail));
+ }
+
+ function ignoreEventForLogging(eventName) {
+ return eventName === "htmx:afterProcessNode"
+ }
+
+ function withExtensions(elt, toDo) {
+ forEach(getExtensions(elt), function(extension){
+ try {
+ toDo(extension);
+ } catch (e) {
+ logError(e);
+ }
+ });
+ }
+
+ function logError(msg) {
+ if(console.error) {
+ console.error(msg);
+ } else if (console.log) {
+ console.log("ERROR: ", msg);
+ }
+ }
+
+ function triggerEvent(elt, eventName, detail) {
+ elt = resolveTarget(elt);
+ if (detail == null) {
+ detail = {};
+ }
+ detail["elt"] = elt;
+ var event = makeEvent(eventName, detail);
+ if (htmx.logger && !ignoreEventForLogging(eventName)) {
+ htmx.logger(elt, eventName, detail);
+ }
+ if (detail.error) {
+ logError(detail.error);
+ triggerEvent(elt, "htmx:error", {errorInfo:detail})
+ }
+ var eventResult = elt.dispatchEvent(event);
+ var kebabName = kebabEventName(eventName);
+ if (eventResult && kebabName !== eventName) {
+ var kebabedEvent = makeEvent(kebabName, event.detail);
+ eventResult = eventResult && elt.dispatchEvent(kebabedEvent)
+ }
+ withExtensions(elt, function (extension) {
+ eventResult = eventResult && (extension.onEvent(eventName, event) !== false)
+ });
+ return eventResult;
+ }
+
+ //====================================================================
+ // History Support
+ //====================================================================
+ var currentPathForHistory = location.pathname+location.search;
+
+ function getHistoryElement() {
+ var historyElt = getDocument().querySelector('[hx-history-elt],[data-hx-history-elt]');
+ return historyElt || getDocument().body;
+ }
+
+ function saveToHistoryCache(url, content, title, scroll) {
+ var historyCache = parseJSON(localStorage.getItem("htmx-history-cache")) || [];
+ for (var i = 0; i < historyCache.length; i++) {
+ if (historyCache[i].url === url) {
+ historyCache.splice(i, 1);
+ break;
+ }
+ }
+ historyCache.push({url:url, content: content, title:title, scroll:scroll})
+ while (historyCache.length > htmx.config.historyCacheSize) {
+ historyCache.shift();
+ }
+ while(historyCache.length > 0){
+ try {
+ localStorage.setItem("htmx-history-cache", JSON.stringify(historyCache));
+ break;
+ } catch (e) {
+ triggerErrorEvent(getDocument().body, "htmx:historyCacheError", {cause:e, cache: historyCache})
+ historyCache.shift(); // shrink the cache and retry
+ }
+ }
+ }
+
+ function getCachedHistory(url) {
+ var historyCache = parseJSON(localStorage.getItem("htmx-history-cache")) || [];
+ for (var i = 0; i < historyCache.length; i++) {
+ if (historyCache[i].url === url) {
+ return historyCache[i];
+ }
+ }
+ return null;
+ }
+
+ function cleanInnerHtmlForHistory(elt) {
+ var className = htmx.config.requestClass;
+ var clone = elt.cloneNode(true);
+ forEach(findAll(clone, "." + className), function(child){
+ removeClassFromElement(child, className);
+ });
+ return clone.innerHTML;
+ }
+
+ function saveHistory() {
+ var elt = getHistoryElement();
+ var path = currentPathForHistory || location.pathname+location.search;
+ triggerEvent(getDocument().body, "htmx:beforeHistorySave", {path:path, historyElt:elt});
+ if(htmx.config.historyEnabled) history.replaceState({htmx:true}, getDocument().title, window.location.href);
+ saveToHistoryCache(path, cleanInnerHtmlForHistory(elt), getDocument().title, window.scrollY);
+ }
+
+ function pushUrlIntoHistory(path) {
+ if(htmx.config.historyEnabled) history.pushState({htmx:true}, "", path);
+ currentPathForHistory = path;
+ }
+
+ function settleImmediately(tasks) {
+ forEach(tasks, function (task) {
+ task.call();
+ });
+ }
+
+ function loadHistoryFromServer(path) {
+ var request = new XMLHttpRequest();
+ var details = {path: path, xhr:request};
+ triggerEvent(getDocument().body, "htmx:historyCacheMiss", details);
+ request.open('GET', path, true);
+ request.setRequestHeader("HX-History-Restore-Request", "true");
+ request.onload = function () {
+ if (this.status >= 200 && this.status < 400) {
+ triggerEvent(getDocument().body, "htmx:historyCacheMissLoad", details);
+ var fragment = makeFragment(this.response);
+ // @ts-ignore
+ fragment = fragment.querySelector('[hx-history-elt],[data-hx-history-elt]') || fragment;
+ var historyElement = getHistoryElement();
+ var settleInfo = makeSettleInfo(historyElement);
+ // @ts-ignore
+ swapInnerHTML(historyElement, fragment, settleInfo)
+ settleImmediately(settleInfo.tasks);
+ currentPathForHistory = path;
+ triggerEvent(getDocument().body, "htmx:historyRestore", {path:path});
+ } else {
+ triggerErrorEvent(getDocument().body, "htmx:historyCacheMissLoadError", details);
+ }
+ };
+ request.send();
+ }
+
+ function restoreHistory(path) {
+ saveHistory();
+ path = path || location.pathname+location.search;
+ var cached = getCachedHistory(path);
+ if (cached) {
+ var fragment = makeFragment(cached.content);
+ var historyElement = getHistoryElement();
+ var settleInfo = makeSettleInfo(historyElement);
+ swapInnerHTML(historyElement, fragment, settleInfo)
+ settleImmediately(settleInfo.tasks);
+ document.title = cached.title;
+ window.scrollTo(0, cached.scroll);
+ currentPathForHistory = path;
+ triggerEvent(getDocument().body, "htmx:historyRestore", {path:path});
+ } else {
+ if (htmx.config.refreshOnHistoryMiss) {
+ window.location.reload(true);
+ } else {
+ loadHistoryFromServer(path);
+ }
+ }
+ }
+
+ function shouldPush(elt) {
+ var pushUrl = getClosestAttributeValue(elt, "hx-push-url");
+ return (pushUrl && pushUrl !== "false") ||
+ (getInternalData(elt).boosted && getInternalData(elt).pushURL);
+ }
+
+ function getPushUrl(elt) {
+ var pushUrl = getClosestAttributeValue(elt, "hx-push-url");
+ return (pushUrl === "true" || pushUrl === "false") ? null : pushUrl;
+ }
+
+ function addRequestIndicatorClasses(elt) {
+ var indicator = getClosestAttributeValue(elt, 'hx-indicator');
+ if (indicator) {
+ var indicators = querySelectorAllExt(elt, indicator);
+ } else {
+ indicators = [elt];
+ }
+ forEach(indicators, function (ic) {
+ ic.classList["add"].call(ic.classList, htmx.config.requestClass);
+ });
+ return indicators;
+ }
+
+ function removeRequestIndicatorClasses(indicators) {
+ forEach(indicators, function (ic) {
+ ic.classList["remove"].call(ic.classList, htmx.config.requestClass);
+ });
+ }
+
+ //====================================================================
+ // Input Value Processing
+ //====================================================================
+
+ function haveSeenNode(processed, elt) {
+ for (var i = 0; i < processed.length; i++) {
+ var node = processed[i];
+ if (node.isSameNode(elt)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function shouldInclude(elt) {
+ if(elt.name === "" || elt.name == null || elt.disabled) {
+ return false;
+ }
+ // ignore "submitter" types (see jQuery src/serialize.js)
+ if (elt.type === "button" || elt.type === "submit" || elt.tagName === "image" || elt.tagName === "reset" || elt.tagName === "file" ) {
+ return false;
+ }
+ if (elt.type === "checkbox" || elt.type === "radio" ) {
+ return elt.checked;
+ }
+ return true;
+ }
+
+ function processInputValue(processed, values, errors, elt, validate) {
+ if (elt == null || haveSeenNode(processed, elt)) {
+ return;
+ } else {
+ processed.push(elt);
+ }
+ if (shouldInclude(elt)) {
+ var name = getRawAttribute(elt,"name");
+ var value = elt.value;
+ if (elt.multiple) {
+ value = toArray(elt.querySelectorAll("option:checked")).map(function (e) { return e.value });
+ }
+ // include file inputs
+ if (elt.files) {
+ value = toArray(elt.files);
+ }
+ // This is a little ugly because both the current value of the named value in the form
+ // and the new value could be arrays, so we have to handle all four cases :/
+ if (name != null && value != null) {
+ var current = values[name];
+ if(current) {
+ if (Array.isArray(current)) {
+ if (Array.isArray(value)) {
+ values[name] = current.concat(value);
+ } else {
+ current.push(value);
+ }
+ } else {
+ if (Array.isArray(value)) {
+ values[name] = [current].concat(value);
+ } else {
+ values[name] = [current, value];
+ }
+ }
+ } else {
+ values[name] = value;
+ }
+ }
+ if (validate) {
+ validateElement(elt, errors);
+ }
+ }
+ if (matches(elt, 'form')) {
+ var inputs = elt.elements;
+ forEach(inputs, function(input) {
+ processInputValue(processed, values, errors, input, validate);
+ });
+ }
+ }
+
+ function validateElement(element, errors) {
+ if (element.willValidate) {
+ triggerEvent(element, "htmx:validation:validate")
+ if (!element.checkValidity()) {
+ errors.push({elt: element, message:element.validationMessage, validity:element.validity});
+ triggerEvent(element, "htmx:validation:failed", {message:element.validationMessage, validity:element.validity})
+ }
+ }
+ }
+
+ function getInputValues(elt, verb) {
+ var processed = [];
+ var values = {};
+ var formValues = {};
+ var errors = [];
+
+ // only validate when form is directly submitted and novalidate is not set
+ var validate = matches(elt, 'form') && elt.noValidate !== true;
+
+ // for a non-GET include the closest form
+ if (verb !== 'get') {
+ processInputValue(processed, formValues, errors, closest(elt, 'form'), validate);
+ }
+
+ // include the element itself
+ processInputValue(processed, values, errors, elt, validate);
+
+ // if a button or submit was clicked last, include its value
+ var internalData = getInternalData(elt);
+ if (internalData.lastButtonClicked) {
+ var name = getRawAttribute(internalData.lastButtonClicked,"name");
+ if (name) {
+ values[name] = internalData.lastButtonClicked.value;
+ }
+ }
+
+ // include any explicit includes
+ var includes = getClosestAttributeValue(elt, "hx-include");
+ if (includes) {
+ var nodes = querySelectorAllExt(elt, includes);
+ forEach(nodes, function(node) {
+ processInputValue(processed, values, errors, node, validate);
+ // if a non-form is included, include any input values within it
+ if (!matches(node, 'form')) {
+ forEach(node.querySelectorAll(INPUT_SELECTOR), function (descendant) {
+ processInputValue(processed, values, errors, descendant, validate);
+ })
+ }
+ });
+ }
+
+ // form values take precedence, overriding the regular values
+ values = mergeObjects(values, formValues);
+
+ return {errors:errors, values:values};
+ }
+
+ function appendParam(returnStr, name, realValue) {
+ if (returnStr !== "") {
+ returnStr += "&";
+ }
+ returnStr += encodeURIComponent(name) + "=" + encodeURIComponent(realValue);
+ return returnStr;
+ }
+
+ function urlEncode(values) {
+ var returnStr = "";
+ for (var name in values) {
+ if (values.hasOwnProperty(name)) {
+ var value = values[name];
+ if (Array.isArray(value)) {
+ forEach(value, function(v) {
+ returnStr = appendParam(returnStr, name, v);
+ });
+ } else {
+ returnStr = appendParam(returnStr, name, value);
+ }
+ }
+ }
+ return returnStr;
+ }
+
+ function makeFormData(values) {
+ var formData = new FormData();
+ for (var name in values) {
+ if (values.hasOwnProperty(name)) {
+ var value = values[name];
+ if (Array.isArray(value)) {
+ forEach(value, function(v) {
+ formData.append(name, v);
+ });
+ } else {
+ formData.append(name, value);
+ }
+ }
+ }
+ return formData;
+ }
+
+ //====================================================================
+ // Ajax
+ //====================================================================
+
+ function getHeaders(elt, target, prompt) {
+ var headers = {
+ "HX-Request" : "true",
+ "HX-Trigger" : getRawAttribute(elt, "id"),
+ "HX-Trigger-Name" : getRawAttribute(elt, "name"),
+ "HX-Target" : getAttributeValue(target, "id"),
+ "HX-Current-URL" : getDocument().location.href,
+ }
+ getValuesForElement(elt, "hx-headers", false, headers)
+ if (prompt !== undefined) {
+ headers["HX-Prompt"] = prompt;
+ }
+ if (getInternalData(elt).boosted) {
+ headers["HX-Boosted"] = "true";
+ }
+ return headers;
+ }
+
+ function filterValues(inputValues, elt) {
+ var paramsValue = getClosestAttributeValue(elt, "hx-params");
+ if (paramsValue) {
+ if (paramsValue === "none") {
+ return {};
+ } else if (paramsValue === "*") {
+ return inputValues;
+ } else if(paramsValue.indexOf("not ") === 0) {
+ forEach(paramsValue.substr(4).split(","), function (name) {
+ name = name.trim();
+ delete inputValues[name];
+ });
+ return inputValues;
+ } else {
+ var newValues = {}
+ forEach(paramsValue.split(","), function (name) {
+ name = name.trim();
+ newValues[name] = inputValues[name];
+ });
+ return newValues;
+ }
+ } else {
+ return inputValues;
+ }
+ }
+
+ function isAnchorLink(elt) {
+ return getRawAttribute(elt, 'href') && getRawAttribute(elt, 'href').indexOf("#") >=0
+ }
+
+ function getSwapSpecification(elt) {
+ var swapInfo = getClosestAttributeValue(elt, "hx-swap");
+ var swapSpec = {
+ "swapStyle" : getInternalData(elt).boosted ? 'innerHTML' : htmx.config.defaultSwapStyle,
+ "swapDelay" : htmx.config.defaultSwapDelay,
+ "settleDelay" : htmx.config.defaultSettleDelay
+ }
+ if (getInternalData(elt).boosted && !isAnchorLink(elt)) {
+ swapSpec["show"] = "top"
+ }
+ if (swapInfo) {
+ var split = splitOnWhitespace(swapInfo);
+ if (split.length > 0) {
+ swapSpec["swapStyle"] = split[0];
+ for (var i = 1; i < split.length; i++) {
+ var modifier = split[i];
+ if (modifier.indexOf("swap:") === 0) {
+ swapSpec["swapDelay"] = parseInterval(modifier.substr(5));
+ }
+ if (modifier.indexOf("settle:") === 0) {
+ swapSpec["settleDelay"] = parseInterval(modifier.substr(7));
+ }
+ if (modifier.indexOf("scroll:") === 0) {
+ var scrollSpec = modifier.substr(7);
+ var splitSpec = scrollSpec.split(":");
+ var scrollVal = splitSpec.pop();
+ var selectorVal = splitSpec.length > 0 ? splitSpec.join(":") : null;
+ swapSpec["scroll"] = scrollVal;
+ swapSpec["scrollTarget"] = selectorVal;
+ }
+ if (modifier.indexOf("show:") === 0) {
+ var showSpec = modifier.substr(5);
+ var splitSpec = showSpec.split(":");
+ var showVal = splitSpec.pop();
+ var selectorVal = splitSpec.length > 0 ? splitSpec.join(":") : null;
+ swapSpec["show"] = showVal;
+ swapSpec["showTarget"] = selectorVal;
+ }
+ }
+ }
+ }
+ return swapSpec;
+ }
+
+ function encodeParamsForBody(xhr, elt, filteredParameters) {
+ var encodedParameters = null;
+ withExtensions(elt, function (extension) {
+ if (encodedParameters == null) {
+ encodedParameters = extension.encodeParameters(xhr, filteredParameters, elt);
+ }
+ });
+ if (encodedParameters != null) {
+ return encodedParameters;
+ } else {
+ if (getClosestAttributeValue(elt, "hx-encoding") === "multipart/form-data" ||
+ (matches(elt, "form") && getRawAttribute(elt, 'enctype') === "multipart/form-data")) {
+ return makeFormData(filteredParameters);
+ } else {
+ return urlEncode(filteredParameters);
+ }
+ }
+ }
+
+ function makeSettleInfo(target) {
+ return {tasks: [], elts: [target]};
+ }
+
+ function updateScrollState(content, swapSpec) {
+ var first = content[0];
+ var last = content[content.length - 1];
+ if (swapSpec.scroll) {
+ var target = null;
+ if (swapSpec.scrollTarget) {
+ target = querySelectorExt(first, swapSpec.scrollTarget);
+ }
+ if (swapSpec.scroll === "top" && (first || target)) {
+ target = target || first;
+ target.scrollTop = 0;
+ }
+ if (swapSpec.scroll === "bottom" && (last || target)) {
+ target = target || last;
+ target.scrollTop = target.scrollHeight;
+ }
+ }
+ if (swapSpec.show) {
+ var target = null;
+ if (swapSpec.showTarget) {
+ var targetStr = swapSpec.showTarget;
+ if (swapSpec.showTarget === "window") {
+ targetStr = "body";
+ }
+ target = querySelectorExt(first, targetStr);
+ }
+ if (swapSpec.show === "top" && (first || target)) {
+ target = target || first;
+ target.scrollIntoView({block:'start', behavior: htmx.config.scrollBehavior});
+ }
+ if (swapSpec.show === "bottom" && (last || target)) {
+ target = target || last;
+ target.scrollIntoView({block:'end', behavior: htmx.config.scrollBehavior});
+ }
+ }
+ }
+
+ function getValuesForElement(elt, attr, evalAsDefault, values) {
+ if (values == null) {
+ values = {};
+ }
+ if (elt == null) {
+ return values;
+ }
+ var attributeValue = getAttributeValue(elt, attr);
+ if (attributeValue) {
+ var str = attributeValue.trim();
+ var evaluateValue = evalAsDefault;
+ if (str.indexOf("javascript:") === 0) {
+ str = str.substr(11);
+ evaluateValue = true;
+ } else if (str.indexOf("js:") === 0) {
+ str = str.substr(3);
+ evaluateValue = true;
+ }
+ if (str.indexOf('{') !== 0) {
+ str = "{" + str + "}";
+ }
+ var varsValues;
+ if (evaluateValue) {
+ varsValues = maybeEval(elt,function () {return Function("return (" + str + ")")();}, {});
+ } else {
+ varsValues = parseJSON(str);
+ }
+ for (var key in varsValues) {
+ if (varsValues.hasOwnProperty(key)) {
+ if (values[key] == null) {
+ values[key] = varsValues[key];
+ }
+ }
+ }
+ }
+ return getValuesForElement(parentElt(elt), attr, evalAsDefault, values);
+ }
+
+ function maybeEval(elt, toEval, defaultVal) {
+ if (htmx.config.allowEval) {
+ return toEval();
+ } else {
+ triggerErrorEvent(elt, 'htmx:evalDisallowedError');
+ return defaultVal;
+ }
+ }
+
+ function getHXVarsForElement(elt, expressionVars) {
+ return getValuesForElement(elt, "hx-vars", true, expressionVars);
+ }
+
+ function getHXValsForElement(elt, expressionVars) {
+ return getValuesForElement(elt, "hx-vals", false, expressionVars);
+ }
+
+ function getExpressionVars(elt) {
+ return mergeObjects(getHXVarsForElement(elt), getHXValsForElement(elt));
+ }
+
+ function safelySetHeaderValue(xhr, header, headerValue) {
+ if (headerValue !== null) {
+ try {
+ xhr.setRequestHeader(header, headerValue);
+ } catch (e) {
+ // On an exception, try to set the header URI encoded instead
+ xhr.setRequestHeader(header, encodeURIComponent(headerValue));
+ xhr.setRequestHeader(header + "-URI-AutoEncoded", "true");
+ }
+ }
+ }
+
+ function getResponseURL(xhr) {
+ // NB: IE11 does not support this stuff
+ if (xhr.responseURL && typeof(URL) !== "undefined") {
+ try {
+ var url = new URL(xhr.responseURL);
+ return url.pathname + url.search;
+ } catch (e) {
+ triggerErrorEvent(getDocument().body, "htmx:badResponseUrl", {url: xhr.responseURL});
+ }
+ }
+ }
+
+ function hasHeader(xhr, regexp) {
+ return xhr.getAllResponseHeaders().match(regexp);
+ }
+
+ function ajaxHelper(verb, path, context) {
+ verb = verb.toLowerCase();
+ if (context) {
+ if (context instanceof Element || isType(context, 'String')) {
+ return issueAjaxRequest(verb, path, null, null, {
+ targetOverride: resolveTarget(context),
+ returnPromise: true
+ });
+ } else {
+ return issueAjaxRequest(verb, path, resolveTarget(context.source), context.event,
+ {
+ handler : context.handler,
+ headers : context.headers,
+ values : context.values,
+ targetOverride: resolveTarget(context.target),
+ returnPromise: true
+ });
+ }
+ } else {
+ return issueAjaxRequest(verb, path, null, null, {
+ returnPromise: true
+ });
+ }
+ }
+
+ function hierarchyForElt(elt) {
+ var arr = [];
+ while (elt) {
+ arr.push(elt);
+ elt = elt.parentElement;
+ }
+ return arr;
+ }
+
+ function issueAjaxRequest(verb, path, elt, event, etc) {
+ var resolve = null;
+ var reject = null;
+ etc = etc != null ? etc : {};
+ if(etc.returnPromise && typeof Promise !== "undefined"){
+ var promise = new Promise(function (_resolve, _reject) {
+ resolve = _resolve;
+ reject = _reject;
+ });
+ }
+ if(elt == null) {
+ elt = getDocument().body;
+ }
+ var responseHandler = etc.handler || handleAjaxResponse;
+
+ if (!bodyContains(elt)) {
+ return; // do not issue requests for elements removed from the DOM
+ }
+ var target = etc.targetOverride || getTarget(elt);
+ if (target == null) {
+ triggerErrorEvent(elt, 'htmx:targetError', {target: getAttributeValue(elt, "hx-target")});
+ return;
+ }
+ var eltData = getInternalData(elt);
+ if (eltData.requestInFlight) {
+ var queueStrategy = 'last';
+ if (event) {
+ var eventData = getInternalData(event);
+ if (eventData && eventData.triggerSpec && eventData.triggerSpec.queue) {
+ queueStrategy = eventData.triggerSpec.queue;
+ }
+ }
+ if (eltData.queuedRequests == null) {
+ eltData.queuedRequests = [];
+ }
+ if (queueStrategy === "first" && eltData.queuedRequests.length === 0) {
+ eltData.queuedRequests.push(function () {
+ issueAjaxRequest(verb, path, elt, event, etc)
+ });
+ } else if (queueStrategy === "all") {
+ eltData.queuedRequests.push(function () {
+ issueAjaxRequest(verb, path, elt, event, etc)
+ });
+ } else if (queueStrategy === "last") {
+ eltData.queuedRequests = []; // dump existing queue
+ eltData.queuedRequests.push(function () {
+ issueAjaxRequest(verb, path, elt, event, etc)
+ });
+ }
+ return;
+ } else {
+ eltData.requestInFlight = true;
+ }
+ var endRequestLock = function(){
+ eltData.requestInFlight = false
+ if (eltData.queuedRequests != null &&
+ eltData.queuedRequests.length > 0) {
+ var queuedRequest = eltData.queuedRequests.shift();
+ queuedRequest();
+ }
+ }
+ var promptQuestion = getClosestAttributeValue(elt, "hx-prompt");
+ if (promptQuestion) {
+ var promptResponse = prompt(promptQuestion);
+ // prompt returns null if cancelled and empty string if accepted with no entry
+ if (promptResponse === null ||
+ !triggerEvent(elt, 'htmx:prompt', {prompt: promptResponse, target:target})) {
+ maybeCall(resolve);
+ endRequestLock();
+ return promise;
+ }
+ }
+
+ var confirmQuestion = getClosestAttributeValue(elt, "hx-confirm");
+ if (confirmQuestion) {
+ if(!confirm(confirmQuestion)) {
+ maybeCall(resolve);
+ endRequestLock()
+ return promise;
+ }
+ }
+
+ var xhr = new XMLHttpRequest();
+
+ var headers = getHeaders(elt, target, promptResponse);
+ if (etc.headers) {
+ headers = mergeObjects(headers, etc.headers);
+ }
+ var results = getInputValues(elt, verb);
+ var errors = results.errors;
+ var rawParameters = results.values;
+ if (etc.values) {
+ rawParameters = mergeObjects(rawParameters, etc.values);
+ }
+ var expressionVars = getExpressionVars(elt);
+ var allParameters = mergeObjects(rawParameters, expressionVars);
+ var filteredParameters = filterValues(allParameters, elt);
+
+ if (verb !== 'get' && getClosestAttributeValue(elt, "hx-encoding") == null) {
+ headers['Content-Type'] = 'application/x-www-form-urlencoded';
+ }
+
+ // behavior of anchors w/ empty href is to use the current URL
+ if (path == null || path === "") {
+ path = getDocument().location.href;
+ }
+
+ var requestAttrValues = getValuesForElement(elt, 'hx-request');
+
+ var requestConfig = {
+ parameters: filteredParameters,
+ unfilteredParameters: allParameters,
+ headers:headers,
+ target:target,
+ verb:verb,
+ errors:errors,
+ withCredentials: etc.credentials || requestAttrValues.credentials || htmx.config.withCredentials,
+ timeout: etc.timeout || requestAttrValues.timeout || htmx.config.timeout,
+ path:path,
+ triggeringEvent:event
+ };
+
+ if(!triggerEvent(elt, 'htmx:configRequest', requestConfig)){
+ maybeCall(resolve);
+ endRequestLock();
+ return promise;
+ }
+
+ // copy out in case the object was overwritten
+ path = requestConfig.path;
+ verb = requestConfig.verb;
+ headers = requestConfig.headers;
+ filteredParameters = requestConfig.parameters;
+ errors = requestConfig.errors;
+
+ if(errors && errors.length > 0){
+ triggerEvent(elt, 'htmx:validation:halted', requestConfig)
+ maybeCall(resolve);
+ endRequestLock();
+ return promise;
+ }
+
+ var splitPath = path.split("#");
+ var pathNoAnchor = splitPath[0];
+ var anchor = splitPath[1];
+ if (verb === 'get') {
+ var finalPathForGet = pathNoAnchor;
+ var values = Object.keys(filteredParameters).length !== 0;
+ if (values) {
+ if (finalPathForGet.indexOf("?") < 0) {
+ finalPathForGet += "?";
+ } else {
+ finalPathForGet += "&";
+ }
+ finalPathForGet += urlEncode(filteredParameters);
+ if (anchor) {
+ finalPathForGet += "#" + anchor;
+ }
+ }
+ xhr.open('GET', finalPathForGet, true);
+ } else {
+ xhr.open(verb.toUpperCase(), path, true);
+ }
+
+ xhr.overrideMimeType("text/html");
+ xhr.withCredentials = requestConfig.withCredentials;
+ xhr.timeout = requestConfig.timeout;
+
+ // request headers
+ if (requestAttrValues.noHeaders) {
+ // ignore all headers
+ } else {
+ for (var header in headers) {
+ if (headers.hasOwnProperty(header)) {
+ var headerValue = headers[header];
+ safelySetHeaderValue(xhr, header, headerValue);
+ }
+ }
+ }
+
+ var responseInfo = {xhr: xhr, target: target, requestConfig: requestConfig, pathInfo:{
+ path:path, finalPath:finalPathForGet, anchor:anchor
+ }
+ };
+
+ xhr.onload = function () {
+ try {
+ var hierarchy = hierarchyForElt(elt);
+ responseHandler(elt, responseInfo);
+ removeRequestIndicatorClasses(indicators);
+ triggerEvent(elt, 'htmx:afterRequest', responseInfo);
+ triggerEvent(elt, 'htmx:afterOnLoad', responseInfo);
+ // if the body no longer contains the element, trigger the even on the closest parent
+ // remaining in the DOM
+ if (!bodyContains(elt)) {
+ var secondaryTriggerElt = null;
+ while (hierarchy.length > 0 && secondaryTriggerElt == null) {
+ var parentEltInHierarchy = hierarchy.shift();
+ if (bodyContains(parentEltInHierarchy)) {
+ secondaryTriggerElt = parentEltInHierarchy;
+ }
+ }
+ if (secondaryTriggerElt) {
+ triggerEvent(secondaryTriggerElt, 'htmx:afterRequest', responseInfo);
+ triggerEvent(secondaryTriggerElt, 'htmx:afterOnLoad', responseInfo);
+ }
+ }
+ maybeCall(resolve);
+ endRequestLock();
+ } catch (e) {
+ triggerErrorEvent(elt, 'htmx:onLoadError', mergeObjects({error:e}, responseInfo));
+ throw e;
+ }
+ }
+ xhr.onerror = function () {
+ removeRequestIndicatorClasses(indicators);
+ triggerErrorEvent(elt, 'htmx:afterRequest', responseInfo);
+ triggerErrorEvent(elt, 'htmx:sendError', responseInfo);
+ maybeCall(reject);
+ endRequestLock();
+ }
+ xhr.onabort = function() {
+ removeRequestIndicatorClasses(indicators);
+ triggerErrorEvent(elt, 'htmx:afterRequest', responseInfo);
+ triggerErrorEvent(elt, 'htmx:sendAbort', responseInfo);
+ maybeCall(reject);
+ endRequestLock();
+ }
+ xhr.ontimeout = function() {
+ removeRequestIndicatorClasses(indicators);
+ triggerErrorEvent(elt, 'htmx:afterRequest', responseInfo);
+ triggerErrorEvent(elt, 'htmx:timeout', responseInfo);
+ maybeCall(reject);
+ endRequestLock();
+ }
+ if(!triggerEvent(elt, 'htmx:beforeRequest', responseInfo)){
+ maybeCall(resolve);
+ endRequestLock()
+ return promise
+ }
+ var indicators = addRequestIndicatorClasses(elt);
+
+ forEach(['loadstart', 'loadend', 'progress', 'abort'], function(eventName) {
+ forEach([xhr, xhr.upload], function (target) {
+ target.addEventListener(eventName, function(event){
+ triggerEvent(elt, "htmx:xhr:" + eventName, {
+ lengthComputable:event.lengthComputable,
+ loaded:event.loaded,
+ total:event.total
+ });
+ })
+ });
+ });
+ triggerEvent(elt, 'htmx:beforeSend', responseInfo);
+ xhr.send(verb === 'get' ? null : encodeParamsForBody(xhr, elt, filteredParameters));
+ return promise;
+ }
+
+ function handleAjaxResponse(elt, responseInfo) {
+ var xhr = responseInfo.xhr;
+ var target = responseInfo.target;
+
+ if (!triggerEvent(elt, 'htmx:beforeOnLoad', responseInfo)) return;
+
+ if (hasHeader(xhr, /HX-Trigger:/i)) {
+ handleTrigger(xhr, "HX-Trigger", elt);
+ }
+
+ if (hasHeader(xhr,/HX-Push:/i)) {
+ var pushedUrl = xhr.getResponseHeader("HX-Push");
+ }
+
+ if (hasHeader(xhr, /HX-Redirect:/i)) {
+ window.location.href = xhr.getResponseHeader("HX-Redirect");
+ return;
+ }
+
+ if (hasHeader(xhr,/HX-Refresh:/i)) {
+ if ("true" === xhr.getResponseHeader("HX-Refresh")) {
+ location.reload();
+ return;
+ }
+ }
+
+ if (hasHeader(xhr,/HX-Retarget:/i)) {
+ responseInfo.target = getDocument().querySelector(xhr.getResponseHeader("HX-Retarget"));
+ }
+
+ var shouldSaveHistory = shouldPush(elt) || pushedUrl;
+
+ // by default htmx only swaps on 200 return codes and does not swap
+ // on 204 'No Content'
+ // this can be ovverriden by responding to the htmx:beforeSwap event and
+ // overriding the detail.shouldSwap property
+ var shouldSwap = xhr.status >= 200 && xhr.status < 400 && xhr.status !== 204;
+ var serverResponse = xhr.response;
+ var isError = xhr.status >= 400;
+ var beforeSwapDetails = mergeObjects({shouldSwap: shouldSwap, serverResponse:serverResponse, isError:isError}, responseInfo);
+ if (!triggerEvent(target, 'htmx:beforeSwap', beforeSwapDetails)) return;
+
+ target = beforeSwapDetails.target; // allow re-targeting
+ serverResponse = beforeSwapDetails.serverResponse; // allow updating content
+ isError = beforeSwapDetails.isError; // allow updating error
+
+ responseInfo.failed = isError; // Make failed property available to response events
+ responseInfo.successful = !isError; // Make successful property available to response events
+
+ if (beforeSwapDetails.shouldSwap) {
+ if (xhr.status === 286) {
+ cancelPolling(elt);
+ }
+
+ withExtensions(elt, function (extension) {
+ serverResponse = extension.transformResponse(serverResponse, xhr, elt);
+ });
+
+ // Save current page
+ if (shouldSaveHistory) {
+ saveHistory();
+ }
+
+ var swapSpec = getSwapSpecification(elt);
+
+ target.classList.add(htmx.config.swappingClass);
+ var doSwap = function () {
+ try {
+
+ var activeElt = document.activeElement;
+ var selectionInfo = {};
+ try {
+ selectionInfo = {
+ elt: activeElt,
+ // @ts-ignore
+ start: activeElt ? activeElt.selectionStart : null,
+ // @ts-ignore
+ end: activeElt ? activeElt.selectionEnd : null
+ };
+ } catch (e) {
+ // safari issue - see https://github.com/microsoft/playwright/issues/5894
+ }
+
+ var settleInfo = makeSettleInfo(target);
+ selectAndSwap(swapSpec.swapStyle, target, elt, serverResponse, settleInfo);
+
+ if (selectionInfo.elt &&
+ !bodyContains(selectionInfo.elt) &&
+ selectionInfo.elt.id) {
+ var newActiveElt = document.getElementById(selectionInfo.elt.id);
+ if (newActiveElt) {
+ // @ts-ignore
+ if (selectionInfo.start && newActiveElt.setSelectionRange) {
+ // @ts-ignore
+ newActiveElt.setSelectionRange(selectionInfo.start, selectionInfo.end);
+ }
+ newActiveElt.focus();
+ }
+ }
+
+ target.classList.remove(htmx.config.swappingClass);
+ forEach(settleInfo.elts, function (elt) {
+ if (elt.classList) {
+ elt.classList.add(htmx.config.settlingClass);
+ }
+ triggerEvent(elt, 'htmx:afterSwap', responseInfo);
+ });
+ if (responseInfo.pathInfo.anchor) {
+ location.hash = responseInfo.pathInfo.anchor;
+ }
+
+ if (hasHeader(xhr, /HX-Trigger-After-Swap:/i)) {
+ var finalElt = elt;
+ if (!bodyContains(elt)) {
+ finalElt = getDocument().body;
+ }
+ handleTrigger(xhr, "HX-Trigger-After-Swap", finalElt);
+ }
+
+ var doSettle = function () {
+ forEach(settleInfo.tasks, function (task) {
+ task.call();
+ });
+ forEach(settleInfo.elts, function (elt) {
+ if (elt.classList) {
+ elt.classList.remove(htmx.config.settlingClass);
+ }
+ triggerEvent(elt, 'htmx:afterSettle', responseInfo);
+ });
+ // push URL and save new page
+ if (shouldSaveHistory) {
+ var pathToPush = pushedUrl || getPushUrl(elt) || getResponseURL(xhr) || responseInfo.pathInfo.finalPath || responseInfo.pathInfo.path;
+ pushUrlIntoHistory(pathToPush);
+ triggerEvent(getDocument().body, 'htmx:pushedIntoHistory', {path: pathToPush});
+ }
+ updateScrollState(settleInfo.elts, swapSpec);
+
+ if (hasHeader(xhr, /HX-Trigger-After-Settle:/i)) {
+ var finalElt = elt;
+ if (!bodyContains(elt)) {
+ finalElt = getDocument().body;
+ }
+ handleTrigger(xhr, "HX-Trigger-After-Settle", finalElt);
+ }
+ }
+
+ if (swapSpec.settleDelay > 0) {
+ setTimeout(doSettle, swapSpec.settleDelay)
+ } else {
+ doSettle();
+ }
+ } catch (e) {
+ triggerErrorEvent(elt, 'htmx:swapError', responseInfo);
+ throw e;
+ }
+ };
+
+ if (swapSpec.swapDelay > 0) {
+ setTimeout(doSwap, swapSpec.swapDelay)
+ } else {
+ doSwap();
+ }
+ }
+ if (isError) {
+ triggerErrorEvent(elt, 'htmx:responseError', mergeObjects({error: "Response Status Error Code " + xhr.status + " from " + responseInfo.pathInfo.path}, responseInfo));
+ }
+ }
+
+ //====================================================================
+ // Extensions API
+ //====================================================================
+ var extensions = {};
+ function extensionBase() {
+ return {
+ onEvent : function(name, evt) {return true;},
+ transformResponse : function(text, xhr, elt) {return text;},
+ isInlineSwap : function(swapStyle) {return false;},
+ handleSwap : function(swapStyle, target, fragment, settleInfo) {return false;},
+ encodeParameters : function(xhr, parameters, elt) {return null;}
+ }
+ }
+
+ function defineExtension(name, extension) {
+ extensions[name] = mergeObjects(extensionBase(), extension);
+ }
+
+ function removeExtension(name) {
+ delete extensions[name];
+ }
+
+ function getExtensions(elt, extensionsToReturn, extensionsToIgnore) {
+ if (elt == undefined) {
+ return extensionsToReturn;
+ }
+ if (extensionsToReturn == undefined) {
+ extensionsToReturn = [];
+ }
+ if (extensionsToIgnore == undefined) {
+ extensionsToIgnore = [];
+ }
+ var extensionsForElement = getAttributeValue(elt, "hx-ext");
+ if (extensionsForElement) {
+ forEach(extensionsForElement.split(","), function(extensionName){
+ extensionName = extensionName.replace(/ /g, '');
+ if (extensionName.slice(0, 7) == "ignore:") {
+ extensionsToIgnore.push(extensionName.slice(7));
+ return;
+ }
+ if (extensionsToIgnore.indexOf(extensionName) < 0) {
+ var extension = extensions[extensionName];
+ if (extension && extensionsToReturn.indexOf(extension) < 0) {
+ extensionsToReturn.push(extension);
+ }
+ }
+ });
+ }
+ return getExtensions(parentElt(elt), extensionsToReturn, extensionsToIgnore);
+ }
+
+ //====================================================================
+ // Initialization
+ //====================================================================
+
+ function ready(fn) {
+ if (getDocument().readyState !== 'loading') {
+ fn();
+ } else {
+ getDocument().addEventListener('DOMContentLoaded', fn);
+ }
+ }
+
+ function insertIndicatorStyles() {
+ if (htmx.config.includeIndicatorStyles !== false) {
+ getDocument().head.insertAdjacentHTML("beforeend",
+ "<style>\
+ ." + htmx.config.indicatorClass + "{opacity:0;transition: opacity 200ms ease-in;}\
+ ." + htmx.config.requestClass + " ." + htmx.config.indicatorClass + "{opacity:1}\
+ ." + htmx.config.requestClass + "." + htmx.config.indicatorClass + "{opacity:1}\
+ </style>");
+ }
+ }
+
+ function getMetaConfig() {
+ var element = getDocument().querySelector('meta[name="htmx-config"]');
+ if (element) {
+ // @ts-ignore
+ return parseJSON(element.content);
+ } else {
+ return null;
+ }
+ }
+
+ function mergeMetaConfig() {
+ var metaConfig = getMetaConfig();
+ if (metaConfig) {
+ htmx.config = mergeObjects(htmx.config , metaConfig)
+ }
+ }
+
+ // initialize the document
+ ready(function () {
+ mergeMetaConfig();
+ insertIndicatorStyles();
+ var body = getDocument().body;
+ processNode(body);
+ window.onpopstate = function (event) {
+ if (event.state && event.state.htmx) {
+ restoreHistory();
+ }
+ };
+ setTimeout(function () {
+ triggerEvent(body, 'htmx:load', {}); // give ready handlers a chance to load up before firing this event
+ }, 0);
+ })
+
+ return htmx;
+ }
+)()
+}));
@@ -0,0 +1,51 @@
+function section_list(sections, selectAfter, def) {
+ var group = document.createElement("div");
+ group.id = "section-list";
+ var select = document.createElement("select");
+
+ var showall = document.createElement("button");
+ group.appendChild(showall);
+ showall.textContent = "all";
+ showall.addEventListener("click", function() {
+ sections.forEach(function(section) {
+ section.querySelector("h1").style.display = "block";
+ section.style.display = "block";
+ });
+ group.style.display = "none";
+ select = null;
+ });
+
+ sections.forEach(function(section) {
+ section.querySelector("h1").style.display = "none";
+ select[select.options.length] = new Option(
+ section.querySelector("h1").textContent,
+ section.id,
+ section.id == def,
+ window.location.hash ?
+ "#" + section.id == window.location.hash :
+ section.id == def
+ );
+ });
+
+ group.appendChild(select);
+ selectAfter.insertAdjacentElement("afterend", group);
+
+ window.addEventListener("hashchange", function() {
+ if(!select) return;
+
+ sections.forEach(function(section) { section.style.display = "none"; });
+ if(window.location.hash) {
+ document.querySelector(window.location.hash).style.display = "block";
+ }
+ select.value = window.location.hash.replace(/^#/, "");
+ var event = document.createEvent("HTMLEvents");
+ event.initEvent("change", false, true);
+ select.dispatchEvent(event);
+ });
+
+ window.location.hash = "";
+ window.location.hash = "#" + select.value;
+ select.addEventListener("change", function() {
+ window.location.hash = "#" + select.value;
+ });
+}
@@ -0,0 +1,4806 @@
+/**
+* Tom Select v2.0.0
+* Licensed under the Apache License, Version 2.0 (the "License");
+*/
+
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+ typeof define === 'function' && define.amd ? define(factory) :
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.TomSelect = factory());
+}(this, (function () { 'use strict';
+
+ /**
+ * MicroEvent - to make any js object an event emitter
+ *
+ * - pure javascript - server compatible, browser compatible
+ * - dont rely on the browser doms
+ * - super simple - you get it immediatly, no mistery, no magic involved
+ *
+ * @author Jerome Etienne (https://github.com/jeromeetienne)
+ */
+
+ /**
+ * Execute callback for each event in space separated list of event names
+ *
+ */
+ function forEvents(events, callback) {
+ events.split(/\s+/).forEach(event => {
+ callback(event);
+ });
+ }
+
+ class MicroEvent {
+ constructor() {
+ this._events = {};
+ }
+
+ on(events, fct) {
+ forEvents(events, event => {
+ this._events[event] = this._events[event] || [];
+
+ this._events[event].push(fct);
+ });
+ }
+
+ off(events, fct) {
+ var n = arguments.length;
+
+ if (n === 0) {
+ this._events = {};
+ return;
+ }
+
+ forEvents(events, event => {
+ if (n === 1) return delete this._events[event];
+ if (event in this._events === false) return;
+
+ this._events[event].splice(this._events[event].indexOf(fct), 1);
+ });
+ }
+
+ trigger(events, ...args) {
+ var self = this;
+ forEvents(events, event => {
+ if (event in self._events === false) return;
+
+ for (let fct of self._events[event]) {
+ fct.apply(self, args);
+ }
+ });
+ }
+
+ }
+
+ /**
+ * microplugin.js
+ * Copyright (c) 2013 Brian Reavis & contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ * @author Brian Reavis <brian@thirdroute.com>
+ */
+ function MicroPlugin(Interface) {
+ Interface.plugins = {};
+ return class extends Interface {
+ constructor(...args) {
+ super(...args);
+ this.plugins = {
+ names: [],
+ settings: {},
+ requested: {},
+ loaded: {}
+ };
+ }
+
+ /**
+ * Registers a plugin.
+ *
+ * @param {function} fn
+ */
+ static define(name, fn) {
+ Interface.plugins[name] = {
+ 'name': name,
+ 'fn': fn
+ };
+ }
+ /**
+ * Initializes the listed plugins (with options).
+ * Acceptable formats:
+ *
+ * List (without options):
+ * ['a', 'b', 'c']
+ *
+ * List (with options):
+ * [{'name': 'a', options: {}}, {'name': 'b', options: {}}]
+ *
+ * Hash (with options):
+ * {'a': { ... }, 'b': { ... }, 'c': { ... }}
+ *
+ * @param {array|object} plugins
+ */
+
+
+ initializePlugins(plugins) {
+ var key, name;
+ const self = this;
+ const queue = [];
+
+ if (Array.isArray(plugins)) {
+ plugins.forEach(plugin => {
+ if (typeof plugin === 'string') {
+ queue.push(plugin);
+ } else {
+ self.plugins.settings[plugin.name] = plugin.options;
+ queue.push(plugin.name);
+ }
+ });
+ } else if (plugins) {
+ for (key in plugins) {
+ if (plugins.hasOwnProperty(key)) {
+ self.plugins.settings[key] = plugins[key];
+ queue.push(key);
+ }
+ }
+ }
+
+ while (name = queue.shift()) {
+ self.require(name);
+ }
+ }
+
+ loadPlugin(name) {
+ var self = this;
+ var plugins = self.plugins;
+ var plugin = Interface.plugins[name];
+
+ if (!Interface.plugins.hasOwnProperty(name)) {
+ throw new Error('Unable to find "' + name + '" plugin');
+ }
+
+ plugins.requested[name] = true;
+ plugins.loaded[name] = plugin.fn.apply(self, [self.plugins.settings[name] || {}]);
+ plugins.names.push(name);
+ }
+ /**
+ * Initializes a plugin.
+ *
+ */
+
+
+ require(name) {
+ var self = this;
+ var plugins = self.plugins;
+
+ if (!self.plugins.loaded.hasOwnProperty(name)) {
+ if (plugins.requested[name]) {
+ throw new Error('Plugin has circular dependency ("' + name + '")');
+ }
+
+ self.loadPlugin(name);
+ }
+
+ return plugins.loaded[name];
+ }
+
+ };
+ }
+
+ // https://github.com/andrewrk/node-diacritics/blob/master/index.js
+ var latin_pat;
+ const accent_pat = '[\u0300-\u036F\u{b7}\u{2be}]'; // \u{2bc}
+
+ const accent_reg = new RegExp(accent_pat, 'g');
+ var diacritic_patterns;
+ const latin_convert = {
+ 'æ': 'ae',
+ 'ⱥ': 'a',
+ 'ø': 'o'
+ };
+ const convert_pat = new RegExp(Object.keys(latin_convert).join('|'), 'g');
+ /**
+ * code points generated from toCodePoints();
+ * removed 65339 to 65345
+ */
+
+ const code_points = [[67, 67], [160, 160], [192, 438], [452, 652], [961, 961], [1019, 1019], [1083, 1083], [1281, 1289], [1984, 1984], [5095, 5095], [7429, 7441], [7545, 7549], [7680, 7935], [8580, 8580], [9398, 9449], [11360, 11391], [42792, 42793], [42802, 42851], [42873, 42897], [42912, 42922], [64256, 64260], [65313, 65338], [65345, 65370]];
+ /**
+ * Remove accents
+ * via https://github.com/krisk/Fuse/issues/133#issuecomment-318692703
+ *
+ */
+
+ const asciifold = str => {
+ return str.normalize('NFKD').replace(accent_reg, '').toLowerCase().replace(convert_pat, function (foreignletter) {
+ return latin_convert[foreignletter];
+ });
+ };
+ /**
+ * Convert array of strings to a regular expression
+ * ex ['ab','a'] => (?:ab|a)
+ * ex ['a','b'] => [ab]
+ *
+ */
+
+
+ const arrayToPattern = (chars, glue = '|') => {
+ if (chars.length == 1) {
+ return chars[0];
+ }
+
+ var longest = 1;
+ chars.forEach(a => {
+ longest = Math.max(longest, a.length);
+ });
+
+ if (longest == 1) {
+ return '[' + chars.join('') + ']';
+ }
+
+ return '(?:' + chars.join(glue) + ')';
+ };
+ /**
+ * Get all possible combinations of substrings that add up to the given string
+ * https://stackoverflow.com/questions/30169587/find-all-the-combination-of-substrings-that-add-up-to-the-given-string
+ *
+ */
+
+ const allSubstrings = input => {
+ if (input.length === 1) return [[input]];
+ var result = [];
+ allSubstrings(input.substring(1)).forEach(function (subresult) {
+ var tmp = subresult.slice(0);
+ tmp[0] = input.charAt(0) + tmp[0];
+ result.push(tmp);
+ tmp = subresult.slice(0);
+ tmp.unshift(input.charAt(0));
+ result.push(tmp);
+ });
+ return result;
+ };
+ /**
+ * Generate a list of diacritics from the list of code points
+ *
+ */
+
+ const generateDiacritics = () => {
+ var diacritics = {};
+ code_points.forEach(code_range => {
+ for (let i = code_range[0]; i <= code_range[1]; i++) {
+ let diacritic = String.fromCharCode(i);
+ let latin = asciifold(diacritic);
+
+ if (latin == diacritic.toLowerCase()) {
+ continue;
+ }
+
+ if (!(latin in diacritics)) {
+ diacritics[latin] = [latin];
+ }
+
+ var patt = new RegExp(arrayToPattern(diacritics[latin]), 'iu');
+
+ if (diacritic.match(patt)) {
+ continue;
+ }
+
+ diacritics[latin].push(diacritic);
+ }
+ });
+ var latin_chars = Object.keys(diacritics); // latin character pattern
+ // match longer substrings first
+
+ latin_chars = latin_chars.sort((a, b) => b.length - a.length);
+ latin_pat = new RegExp('(' + arrayToPattern(latin_chars) + accent_pat + '*)', 'g'); // build diacritic patterns
+ // ae needs:
+ // (?:(?:ae|Æ|Ǽ|Ǣ)|(?:A|Ⓐ|A...)(?:E|ɛ|Ⓔ...))
+
+ var diacritic_patterns = {};
+ latin_chars.sort((a, b) => a.length - b.length).forEach(latin => {
+ var substrings = allSubstrings(latin);
+ var pattern = substrings.map(sub_pat => {
+ sub_pat = sub_pat.map(l => {
+ if (diacritics.hasOwnProperty(l)) {
+ return arrayToPattern(diacritics[l]);
+ }
+
+ return l;
+ });
+ return arrayToPattern(sub_pat, '');
+ });
+ diacritic_patterns[latin] = arrayToPattern(pattern);
+ });
+ return diacritic_patterns;
+ };
+ /**
+ * Expand a regular expression pattern to include diacritics
+ * eg /a/ becomes /aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐɑAⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄȺⱯ/
+ *
+ */
+
+ const diacriticRegexPoints = regex => {
+ if (diacritic_patterns === undefined) {
+ diacritic_patterns = generateDiacritics();
+ }
+
+ const decomposed = regex.normalize('NFKD').toLowerCase();
+ return decomposed.split(latin_pat).map(part => {
+ if (part == '') {
+ return '';
+ } // "ffl" or "ffl"
+
+
+ const no_accent = asciifold(part);
+
+ if (diacritic_patterns.hasOwnProperty(no_accent)) {
+ return diacritic_patterns[no_accent];
+ } // 'أهلا' (\u{623}\u{647}\u{644}\u{627}) or 'أهلا' (\u{627}\u{654}\u{647}\u{644}\u{627})
+
+
+ const composed_part = part.normalize('NFC');
+
+ if (composed_part != part) {
+ return arrayToPattern([part, composed_part]);
+ }
+
+ return part;
+ }).join('');
+ };
+
+ // @ts-ignore TS2691 "An import path cannot end with a '.ts' extension"
+
+ /**
+ * A property getter resolving dot-notation
+ * @param {Object} obj The root object to fetch property on
+ * @param {String} name The optionally dotted property name to fetch
+ * @return {Object} The resolved property value
+ */
+ const getAttr = (obj, name) => {
+ if (!obj) return;
+ return obj[name];
+ };
+ /**
+ * A property getter resolving dot-notation
+ * @param {Object} obj The root object to fetch property on
+ * @param {String} name The optionally dotted property name to fetch
+ * @return {Object} The resolved property value
+ */
+
+ const getAttrNesting = (obj, name) => {
+ if (!obj) return;
+ var part,
+ names = name.split(".");
+
+ while ((part = names.shift()) && (obj = obj[part]));
+
+ return obj;
+ };
+ /**
+ * Calculates how close of a match the
+ * given value is against a search token.
+ *
+ */
+
+ const scoreValue = (value, token, weight) => {
+ var score, pos;
+ if (!value) return 0;
+ value = value + '';
+ pos = value.search(token.regex);
+ if (pos === -1) return 0;
+ score = token.string.length / value.length;
+ if (pos === 0) score += 0.5;
+ return score * weight;
+ };
+ /**
+ *
+ * https://stackoverflow.com/questions/63006601/why-does-u-throw-an-invalid-escape-error
+ */
+
+ const escape_regex = str => {
+ return (str + '').replace(/([\$\(-\+\.\?\[-\^\{-\}])/g, '\\$1');
+ };
+ /**
+ * Cast object property to an array if it exists and has a value
+ *
+ */
+
+ const propToArray = (obj, key) => {
+ var value = obj[key];
+ if (typeof value == 'function') return value;
+
+ if (value && !Array.isArray(value)) {
+ obj[key] = [value];
+ }
+ };
+ /**
+ * Iterates over arrays and hashes.
+ *
+ * ```
+ * iterate(this.items, function(item, id) {
+ * // invoked for each item
+ * });
+ * ```
+ *
+ */
+
+ const iterate = (object, callback) => {
+ if (Array.isArray(object)) {
+ object.forEach(callback);
+ } else {
+ for (var key in object) {
+ if (object.hasOwnProperty(key)) {
+ callback(object[key], key);
+ }
+ }
+ }
+ };
+ const cmp = (a, b) => {
+ if (typeof a === 'number' && typeof b === 'number') {
+ return a > b ? 1 : a < b ? -1 : 0;
+ }
+
+ a = asciifold(a + '').toLowerCase();
+ b = asciifold(b + '').toLowerCase();
+ if (a > b) return 1;
+ if (b > a) return -1;
+ return 0;
+ };
+
+ /**
+ * sifter.js
+ * Copyright (c) 2013–2020 Brian Reavis & contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ * @author Brian Reavis <brian@thirdroute.com>
+ */
+
+ class Sifter {
+ // []|{};
+
+ /**
+ * Textually searches arrays and hashes of objects
+ * by property (or multiple properties). Designed
+ * specifically for autocomplete.
+ *
+ */
+ constructor(items, settings) {
+ this.items = items;
+ this.settings = settings || {
+ diacritics: true
+ };
+ }
+
+ /**
+ * Splits a search string into an array of individual
+ * regexps to be used to match results.
+ *
+ */
+ tokenize(query, respect_word_boundaries, weights) {
+ if (!query || !query.length) return [];
+ const tokens = [];
+ const words = query.split(/\s+/);
+ var field_regex;
+
+ if (weights) {
+ field_regex = new RegExp('^(' + Object.keys(weights).map(escape_regex).join('|') + ')\:(.*)$');
+ }
+
+ words.forEach(word => {
+ let field_match;
+ let field = null;
+ let regex = null; // look for "field:query" tokens
+
+ if (field_regex && (field_match = word.match(field_regex))) {
+ field = field_match[1];
+ word = field_match[2];
+ }
+
+ if (word.length > 0) {
+ regex = escape_regex(word);
+
+ if (this.settings.diacritics) {
+ regex = diacriticRegexPoints(regex);
+ }
+
+ if (respect_word_boundaries) regex = "\\b" + regex;
+ }
+
+ tokens.push({
+ string: word,
+ regex: regex ? new RegExp(regex, 'iu') : null,
+ field: field
+ });
+ });
+ return tokens;
+ }
+
+ /**
+ * Returns a function to be used to score individual results.
+ *
+ * Good matches will have a higher score than poor matches.
+ * If an item is not a match, 0 will be returned by the function.
+ *
+ * @returns {function}
+ */
+ getScoreFunction(query, options) {
+ var search = this.prepareSearch(query, options);
+ return this._getScoreFunction(search);
+ }
+
+ _getScoreFunction(search) {
+ const tokens = search.tokens,
+ token_count = tokens.length;
+
+ if (!token_count) {
+ return function () {
+ return 0;
+ };
+ }
+
+ const fields = search.options.fields,
+ weights = search.weights,
+ field_count = fields.length,
+ getAttrFn = search.getAttrFn;
+
+ if (!field_count) {
+ return function () {
+ return 1;
+ };
+ }
+ /**
+ * Calculates the score of an object
+ * against the search query.
+ *
+ */
+
+
+ const scoreObject = function () {
+ if (field_count === 1) {
+ return function (token, data) {
+ const field = fields[0].field;
+ return scoreValue(getAttrFn(data, field), token, weights[field]);
+ };
+ }
+
+ return function (token, data) {
+ var sum = 0; // is the token specific to a field?
+
+ if (token.field) {
+ const value = getAttrFn(data, token.field);
+
+ if (!token.regex && value) {
+ sum += 1 / field_count;
+ } else {
+ sum += scoreValue(value, token, 1);
+ }
+ } else {
+ iterate(weights, (weight, field) => {
+ sum += scoreValue(getAttrFn(data, field), token, weight);
+ });
+ }
+
+ return sum / field_count;
+ };
+ }();
+
+ if (token_count === 1) {
+ return function (data) {
+ return scoreObject(tokens[0], data);
+ };
+ }
+
+ if (search.options.conjunction === 'and') {
+ return function (data) {
+ var i = 0,
+ score,
+ sum = 0;
+
+ for (; i < token_count; i++) {
+ score = scoreObject(tokens[i], data);
+ if (score <= 0) return 0;
+ sum += score;
+ }
+
+ return sum / token_count;
+ };
+ } else {
+ return function (data) {
+ var sum = 0;
+ iterate(tokens, token => {
+ sum += scoreObject(token, data);
+ });
+ return sum / token_count;
+ };
+ }
+ }
+
+ /**
+ * Returns a function that can be used to compare two
+ * results, for sorting purposes. If no sorting should
+ * be performed, `null` will be returned.
+ *
+ * @return function(a,b)
+ */
+ getSortFunction(query, options) {
+ var search = this.prepareSearch(query, options);
+ return this._getSortFunction(search);
+ }
+
+ _getSortFunction(search) {
+ var i, n, implicit_score;
+ const self = this,
+ options = search.options,
+ sort = !search.query && options.sort_empty ? options.sort_empty : options.sort,
+ sort_flds = [],
+ multipliers = [];
+
+ if (typeof sort == 'function') {
+ return sort.bind(this);
+ }
+ /**
+ * Fetches the specified sort field value
+ * from a search result item.
+ *
+ */
+
+
+ const get_field = function get_field(name, result) {
+ if (name === '$score') return result.score;
+ return search.getAttrFn(self.items[result.id], name);
+ }; // parse options
+
+
+ if (sort) {
+ for (i = 0, n = sort.length; i < n; i++) {
+ if (search.query || sort[i].field !== '$score') {
+ sort_flds.push(sort[i]);
+ }
+ }
+ } // the "$score" field is implied to be the primary
+ // sort field, unless it's manually specified
+
+
+ if (search.query) {
+ implicit_score = true;
+
+ for (i = 0, n = sort_flds.length; i < n; i++) {
+ if (sort_flds[i].field === '$score') {
+ implicit_score = false;
+ break;
+ }
+ }
+
+ if (implicit_score) {
+ sort_flds.unshift({
+ field: '$score',
+ direction: 'desc'
+ });
+ }
+ } else {
+ for (i = 0, n = sort_flds.length; i < n; i++) {
+ if (sort_flds[i].field === '$score') {
+ sort_flds.splice(i, 1);
+ break;
+ }
+ }
+ }
+
+ for (i = 0, n = sort_flds.length; i < n; i++) {
+ multipliers.push(sort_flds[i].direction === 'desc' ? -1 : 1);
+ } // build function
+
+
+ const sort_flds_count = sort_flds.length;
+
+ if (!sort_flds_count) {
+ return null;
+ } else if (sort_flds_count === 1) {
+ const sort_fld = sort_flds[0].field;
+ const multiplier = multipliers[0];
+ return function (a, b) {
+ return multiplier * cmp(get_field(sort_fld, a), get_field(sort_fld, b));
+ };
+ } else {
+ return function (a, b) {
+ var i, result, field;
+
+ for (i = 0; i < sort_flds_count; i++) {
+ field = sort_flds[i].field;
+ result = multipliers[i] * cmp(get_field(field, a), get_field(field, b));
+ if (result) return result;
+ }
+
+ return 0;
+ };
+ }
+ }
+
+ /**
+ * Parses a search query and returns an object
+ * with tokens and fields ready to be populated
+ * with results.
+ *
+ */
+ prepareSearch(query, optsUser) {
+ const weights = {};
+ var options = Object.assign({}, optsUser);
+ propToArray(options, 'sort');
+ propToArray(options, 'sort_empty'); // convert fields to new format
+
+ if (options.fields) {
+ propToArray(options, 'fields');
+ const fields = [];
+ options.fields.forEach(field => {
+ if (typeof field == 'string') {
+ field = {
+ field: field,
+ weight: 1
+ };
+ }
+
+ fields.push(field);
+ weights[field.field] = 'weight' in field ? field.weight : 1;
+ });
+ options.fields = fields;
+ }
+
+ return {
+ options: options,
+ query: query.toLowerCase().trim(),
+ tokens: this.tokenize(query, options.respect_word_boundaries, weights),
+ total: 0,
+ items: [],
+ weights: weights,
+ getAttrFn: options.nesting ? getAttrNesting : getAttr
+ };
+ }
+
+ /**
+ * Searches through all items and returns a sorted array of matches.
+ *
+ */
+ search(query, options) {
+ var self = this,
+ score,
+ search;
+ search = this.prepareSearch(query, options);
+ options = search.options;
+ query = search.query; // generate result scoring function
+
+ const fn_score = options.score || self._getScoreFunction(search); // perform search and sort
+
+
+ if (query.length) {
+ iterate(self.items, (item, id) => {
+ score = fn_score(item);
+
+ if (options.filter === false || score > 0) {
+ search.items.push({
+ 'score': score,
+ 'id': id
+ });
+ }
+ });
+ } else {
+ iterate(self.items, (item, id) => {
+ search.items.push({
+ 'score': 1,
+ 'id': id
+ });
+ });
+ }
+
+ const fn_sort = self._getSortFunction(search);
+
+ if (fn_sort) search.items.sort(fn_sort); // apply limits
+
+ search.total = search.items.length;
+
+ if (typeof options.limit === 'number') {
+ search.items = search.items.slice(0, options.limit);
+ }
+
+ return search;
+ }
+
+ }
+
+ /**
+ * Return a dom element from either a dom query string, jQuery object, a dom element or html string
+ * https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518
+ *
+ * param query should be {}
+ */
+
+ const getDom = query => {
+ if (query.jquery) {
+ return query[0];
+ }
+
+ if (query instanceof HTMLElement) {
+ return query;
+ }
+
+ if (isHtmlString(query)) {
+ let div = document.createElement('div');
+ div.innerHTML = query.trim(); // Never return a text node of whitespace as the result
+
+ return div.firstChild;
+ }
+
+ return document.querySelector(query);
+ };
+ const isHtmlString = arg => {
+ if (typeof arg === 'string' && arg.indexOf('<') > -1) {
+ return true;
+ }
+
+ return false;
+ };
+ const escapeQuery = query => {
+ return query.replace(/['"\\]/g, '\\$&');
+ };
+ /**
+ * Dispatch an event
+ *
+ */
+
+ const triggerEvent = (dom_el, event_name) => {
+ var event = document.createEvent('HTMLEvents');
+ event.initEvent(event_name, true, false);
+ dom_el.dispatchEvent(event);
+ };
+ /**
+ * Apply CSS rules to a dom element
+ *
+ */
+
+ const applyCSS = (dom_el, css) => {
+ Object.assign(dom_el.style, css);
+ };
+ /**
+ * Add css classes
+ *
+ */
+
+ const addClasses = (elmts, ...classes) => {
+ var norm_classes = classesArray(classes);
+ elmts = castAsArray(elmts);
+ elmts.map(el => {
+ norm_classes.map(cls => {
+ el.classList.add(cls);
+ });
+ });
+ };
+ /**
+ * Remove css classes
+ *
+ */
+
+ const removeClasses = (elmts, ...classes) => {
+ var norm_classes = classesArray(classes);
+ elmts = castAsArray(elmts);
+ elmts.map(el => {
+ norm_classes.map(cls => {
+ el.classList.remove(cls);
+ });
+ });
+ };
+ /**
+ * Return arguments
+ *
+ */
+
+ const classesArray = args => {
+ var classes = [];
+ iterate(args, _classes => {
+ if (typeof _classes === 'string') {
+ _classes = _classes.trim().split(/[\11\12\14\15\40]/);
+ }
+
+ if (Array.isArray(_classes)) {
+ classes = classes.concat(_classes);
+ }
+ });
+ return classes.filter(Boolean);
+ };
+ /**
+ * Create an array from arg if it's not already an array
+ *
+ */
+
+ const castAsArray = arg => {
+ if (!Array.isArray(arg)) {
+ arg = [arg];
+ }
+
+ return arg;
+ };
+ /**
+ * Get the closest node to the evt.target matching the selector
+ * Stops at wrapper
+ *
+ */
+
+ const parentMatch = (target, selector, wrapper) => {
+ if (wrapper && !wrapper.contains(target)) {
+ return;
+ }
+
+ while (target && target.matches) {
+ if (target.matches(selector)) {
+ return target;
+ }
+
+ target = target.parentNode;
+ }
+ };
+ /**
+ * Get the first or last item from an array
+ *
+ * > 0 - right (last)
+ * <= 0 - left (first)
+ *
+ */
+
+ const getTail = (list, direction = 0) => {
+ if (direction > 0) {
+ return list[list.length - 1];
+ }
+
+ return list[0];
+ };
+ /**
+ * Return true if an object is empty
+ *
+ */
+
+ const isEmptyObject = obj => {
+ return Object.keys(obj).length === 0;
+ };
+ /**
+ * Get the index of an element amongst sibling nodes of the same type
+ *
+ */
+
+ const nodeIndex = (el, amongst) => {
+ if (!el) return -1;
+ amongst = amongst || el.nodeName;
+ var i = 0;
+
+ while (el = el.previousElementSibling) {
+ if (el.matches(amongst)) {
+ i++;
+ }
+ }
+
+ return i;
+ };
+ /**
+ * Set attributes of an element
+ *
+ */
+
+ const setAttr = (el, attrs) => {
+ iterate(attrs, (val, attr) => {
+ if (val == null) {
+ el.removeAttribute(attr);
+ } else {
+ el.setAttribute(attr, '' + val);
+ }
+ });
+ };
+ /**
+ * Replace a node
+ */
+
+ const replaceNode = (existing, replacement) => {
+ if (existing.parentNode) existing.parentNode.replaceChild(replacement, existing);
+ };
+
+ /**
+ * highlight v3 | MIT license | Johann Burkard <jb@eaio.com>
+ * Highlights arbitrary terms in a node.
+ *
+ * - Modified by Marshal <beatgates@gmail.com> 2011-6-24 (added regex)
+ * - Modified by Brian Reavis <brian@thirdroute.com> 2012-8-27 (cleanup)
+ */
+ const highlight = (element, regex) => {
+ if (regex === null) return; // convet string to regex
+
+ if (typeof regex === 'string') {
+ if (!regex.length) return;
+ regex = new RegExp(regex, 'i');
+ } // Wrap matching part of text node with highlighting <span>, e.g.
+ // Soccer -> <span class="highlight">Soc</span>cer for regex = /soc/i
+
+
+ const highlightText = node => {
+ var match = node.data.match(regex);
+
+ if (match && node.data.length > 0) {
+ var spannode = document.createElement('span');
+ spannode.className = 'highlight';
+ var middlebit = node.splitText(match.index);
+ middlebit.splitText(match[0].length);
+ var middleclone = middlebit.cloneNode(true);
+ spannode.appendChild(middleclone);
+ replaceNode(middlebit, spannode);
+ return 1;
+ }
+
+ return 0;
+ }; // Recurse element node, looking for child text nodes to highlight, unless element
+ // is childless, <script>, <style>, or already highlighted: <span class="hightlight">
+
+
+ const highlightChildren = node => {
+ if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName) && (node.className !== 'highlight' || node.tagName !== 'SPAN')) {
+ for (var i = 0; i < node.childNodes.length; ++i) {
+ i += highlightRecursive(node.childNodes[i]);
+ }
+ }
+ };
+
+ const highlightRecursive = node => {
+ if (node.nodeType === 3) {
+ return highlightText(node);
+ }
+
+ highlightChildren(node);
+ return 0;
+ };
+
+ highlightRecursive(element);
+ };
+ /**
+ * removeHighlight fn copied from highlight v5 and
+ * edited to remove with(), pass js strict mode, and use without jquery
+ */
+
+ const removeHighlight = el => {
+ var elements = el.querySelectorAll("span.highlight");
+ Array.prototype.forEach.call(elements, function (el) {
+ var parent = el.parentNode;
+ parent.replaceChild(el.firstChild, el);
+ parent.normalize();
+ });
+ };
+
+ const KEY_A = 65;
+ const KEY_RETURN = 13;
+ const KEY_ESC = 27;
+ const KEY_LEFT = 37;
+ const KEY_UP = 38;
+ const KEY_RIGHT = 39;
+ const KEY_DOWN = 40;
+ const KEY_BACKSPACE = 8;
+ const KEY_DELETE = 46;
+ const KEY_TAB = 9;
+ const IS_MAC = typeof navigator === 'undefined' ? false : /Mac/.test(navigator.userAgent);
+ const KEY_SHORTCUT = IS_MAC ? 'metaKey' : 'ctrlKey'; // ctrl key or apple key for ma
+
+ var defaults = {
+ options: [],
+ optgroups: [],
+ plugins: [],
+ delimiter: ',',
+ splitOn: null,
+ // regexp or string for splitting up values from a paste command
+ persist: true,
+ diacritics: true,
+ create: null,
+ createOnBlur: false,
+ createFilter: null,
+ highlight: true,
+ openOnFocus: true,
+ shouldOpen: null,
+ maxOptions: 50,
+ maxItems: null,
+ hideSelected: null,
+ duplicates: false,
+ addPrecedence: false,
+ selectOnTab: false,
+ preload: null,
+ allowEmptyOption: false,
+ //closeAfterSelect: false,
+ loadThrottle: 300,
+ loadingClass: 'loading',
+ dataAttr: null,
+ //'data-data',
+ optgroupField: 'optgroup',
+ valueField: 'value',
+ labelField: 'text',
+ disabledField: 'disabled',
+ optgroupLabelField: 'label',
+ optgroupValueField: 'value',
+ lockOptgroupOrder: false,
+ sortField: '$order',
+ searchField: ['text'],
+ searchConjunction: 'and',
+ mode: null,
+ wrapperClass: 'ts-wrapper',
+ controlClass: 'ts-control',
+ dropdownClass: 'ts-dropdown',
+ dropdownContentClass: 'ts-dropdown-content',
+ itemClass: 'item',
+ optionClass: 'option',
+ dropdownParent: null,
+ controlInput: '<input type="text" autocomplete="off" size="1" />',
+ copyClassesToDropdown: false,
+ placeholder: null,
+ hidePlaceholder: null,
+ shouldLoad: function (query) {
+ return query.length > 0;
+ },
+
+ /*
+ load : null, // function(query, callback) { ... }
+ score : null, // function(search) { ... }
+ onInitialize : null, // function() { ... }
+ onChange : null, // function(value) { ... }
+ onItemAdd : null, // function(value, $item) { ... }
+ onItemRemove : null, // function(value) { ... }
+ onClear : null, // function() { ... }
+ onOptionAdd : null, // function(value, data) { ... }
+ onOptionRemove : null, // function(value) { ... }
+ onOptionClear : null, // function() { ... }
+ onOptionGroupAdd : null, // function(id, data) { ... }
+ onOptionGroupRemove : null, // function(id) { ... }
+ onOptionGroupClear : null, // function() { ... }
+ onDropdownOpen : null, // function(dropdown) { ... }
+ onDropdownClose : null, // function(dropdown) { ... }
+ onType : null, // function(str) { ... }
+ onDelete : null, // function(values) { ... }
+ */
+ render: {
+ /*
+ item: null,
+ optgroup: null,
+ optgroup_header: null,
+ option: null,
+ option_create: null
+ */
+ }
+ };
+
+ /**
+ * Converts a scalar to its best string representation
+ * for hash keys and HTML attribute values.
+ *
+ * Transformations:
+ * 'str' -> 'str'
+ * null -> ''
+ * undefined -> ''
+ * true -> '1'
+ * false -> '0'
+ * 0 -> '0'
+ * 1 -> '1'
+ *
+ */
+ const hash_key = value => {
+ if (typeof value === 'undefined' || value === null) return null;
+ return get_hash(value);
+ };
+ const get_hash = value => {
+ if (typeof value === 'boolean') return value ? '1' : '0';
+ return value + '';
+ };
+ /**
+ * Escapes a string for use within HTML.
+ *
+ */
+
+ const escape_html = str => {
+ return (str + '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
+ };
+ /**
+ * Debounce the user provided load function
+ *
+ */
+
+ const loadDebounce = (fn, delay) => {
+ var timeout;
+ return function (value, callback) {
+ var self = this;
+
+ if (timeout) {
+ self.loading = Math.max(self.loading - 1, 0);
+ clearTimeout(timeout);
+ }
+
+ timeout = setTimeout(function () {
+ timeout = null;
+ self.loadedSearches[value] = true;
+ fn.call(self, value, callback);
+ }, delay);
+ };
+ };
+ /**
+ * Debounce all fired events types listed in `types`
+ * while executing the provided `fn`.
+ *
+ */
+
+ const debounce_events = (self, types, fn) => {
+ var type;
+ var trigger = self.trigger;
+ var event_args = {}; // override trigger method
+
+ self.trigger = function () {
+ var type = arguments[0];
+
+ if (types.indexOf(type) !== -1) {
+ event_args[type] = arguments;
+ } else {
+ return trigger.apply(self, arguments);
+ }
+ }; // invoke provided function
+
+
+ fn.apply(self, []);
+ self.trigger = trigger; // trigger queued events
+
+ for (type of types) {
+ if (type in event_args) {
+ trigger.apply(self, event_args[type]);
+ }
+ }
+ };
+ /**
+ * Determines the current selection within a text input control.
+ * Returns an object containing:
+ * - start
+ * - length
+ *
+ */
+
+ const getSelection = input => {
+ return {
+ start: input.selectionStart || 0,
+ length: (input.selectionEnd || 0) - (input.selectionStart || 0)
+ };
+ };
+ /**
+ * Prevent default
+ *
+ */
+
+ const preventDefault = (evt, stop = false) => {
+ if (evt) {
+ evt.preventDefault();
+
+ if (stop) {
+ evt.stopPropagation();
+ }
+ }
+ };
+ /**
+ * Prevent default
+ *
+ */
+
+ const addEvent = (target, type, callback, options) => {
+ target.addEventListener(type, callback, options);
+ };
+ /**
+ * Return true if the requested key is down
+ * Will return false if more than one control character is pressed ( when [ctrl+shift+a] != [ctrl+a] )
+ * The current evt may not always set ( eg calling advanceSelection() )
+ *
+ */
+
+ const isKeyDown = (key_name, evt) => {
+ if (!evt) {
+ return false;
+ }
+
+ if (!evt[key_name]) {
+ return false;
+ }
+
+ var count = (evt.altKey ? 1 : 0) + (evt.ctrlKey ? 1 : 0) + (evt.shiftKey ? 1 : 0) + (evt.metaKey ? 1 : 0);
+
+ if (count === 1) {
+ return true;
+ }
+
+ return false;
+ };
+ /**
+ * Get the id of an element
+ * If the id attribute is not set, set the attribute with the given id
+ *
+ */
+
+ const getId = (el, id) => {
+ const existing_id = el.getAttribute('id');
+
+ if (existing_id) {
+ return existing_id;
+ }
+
+ el.setAttribute('id', id);
+ return id;
+ };
+ /**
+ * Returns a string with backslashes added before characters that need to be escaped.
+ */
+
+ const addSlashes = str => {
+ return str.replace(/[\\"']/g, '\\$&');
+ };
+ /**
+ *
+ */
+
+ const append = (parent, node) => {
+ if (node) parent.append(node);
+ };
+
+ function getSettings(input, settings_user) {
+ var settings = Object.assign({}, defaults, settings_user);
+ var attr_data = settings.dataAttr;
+ var field_label = settings.labelField;
+ var field_value = settings.valueField;
+ var field_disabled = settings.disabledField;
+ var field_optgroup = settings.optgroupField;
+ var field_optgroup_label = settings.optgroupLabelField;
+ var field_optgroup_value = settings.optgroupValueField;
+ var tag_name = input.tagName.toLowerCase();
+ var placeholder = input.getAttribute('placeholder') || input.getAttribute('data-placeholder');
+
+ if (!placeholder && !settings.allowEmptyOption) {
+ let option = input.querySelector('option[value=""]');
+
+ if (option) {
+ placeholder = option.textContent;
+ }
+ }
+
+ var settings_element = {
+ placeholder: placeholder,
+ options: [],
+ optgroups: [],
+ items: [],
+ maxItems: null
+ };
+ /**
+ * Initialize from a <select> element.
+ *
+ */
+
+ var init_select = () => {
+ var tagName;
+ var options = settings_element.options;
+ var optionsMap = {};
+ var group_count = 1;
+
+ var readData = el => {
+ var data = Object.assign({}, el.dataset); // get plain object from DOMStringMap
+
+ var json = attr_data && data[attr_data];
+
+ if (typeof json === 'string' && json.length) {
+ data = Object.assign(data, JSON.parse(json));
+ }
+
+ return data;
+ };
+
+ var addOption = (option, group) => {
+ var value = hash_key(option.value);
+ if (value == null) return;
+ if (!value && !settings.allowEmptyOption) return; // if the option already exists, it's probably been
+ // duplicated in another optgroup. in this case, push
+ // the current group to the "optgroup" property on the
+ // existing option so that it's rendered in both places.
+
+ if (optionsMap.hasOwnProperty(value)) {
+ if (group) {
+ var arr = optionsMap[value][field_optgroup];
+
+ if (!arr) {
+ optionsMap[value][field_optgroup] = group;
+ } else if (!Array.isArray(arr)) {
+ optionsMap[value][field_optgroup] = [arr, group];
+ } else {
+ arr.push(group);
+ }
+ }
+ } else {
+ var option_data = readData(option);
+ option_data[field_label] = option_data[field_label] || option.textContent;
+ option_data[field_value] = option_data[field_value] || value;
+ option_data[field_disabled] = option_data[field_disabled] || option.disabled;
+ option_data[field_optgroup] = option_data[field_optgroup] || group;
+ option_data.$option = option;
+ optionsMap[value] = option_data;
+ options.push(option_data);
+ }
+
+ if (option.selected) {
+ settings_element.items.push(value);
+ }
+ };
+
+ var addGroup = optgroup => {
+ var id, optgroup_data;
+ optgroup_data = readData(optgroup);
+ optgroup_data[field_optgroup_label] = optgroup_data[field_optgroup_label] || optgroup.getAttribute('label') || '';
+ optgroup_data[field_optgroup_value] = optgroup_data[field_optgroup_value] || group_count++;
+ optgroup_data[field_disabled] = optgroup_data[field_disabled] || optgroup.disabled;
+ settings_element.optgroups.push(optgroup_data);
+ id = optgroup_data[field_optgroup_value];
+ iterate(optgroup.children, option => {
+ addOption(option, id);
+ });
+ };
+
+ settings_element.maxItems = input.hasAttribute('multiple') ? null : 1;
+ iterate(input.children, child => {
+ tagName = child.tagName.toLowerCase();
+
+ if (tagName === 'optgroup') {
+ addGroup(child);
+ } else if (tagName === 'option') {
+ addOption(child);
+ }
+ });
+ };
+ /**
+ * Initialize from a <input type="text"> element.
+ *
+ */
+
+
+ var init_textbox = () => {
+ const data_raw = input.getAttribute(attr_data);
+
+ if (!data_raw) {
+ var value = input.value.trim() || '';
+ if (!settings.allowEmptyOption && !value.length) return;
+ const values = value.split(settings.delimiter);
+ iterate(values, value => {
+ const option = {};
+ option[field_label] = value;
+ option[field_value] = value;
+ settings_element.options.push(option);
+ });
+ settings_element.items = values;
+ } else {
+ settings_element.options = JSON.parse(data_raw);
+ iterate(settings_element.options, opt => {
+ settings_element.items.push(opt[field_value]);
+ });
+ }
+ };
+
+ if (tag_name === 'select') {
+ init_select();
+ } else {
+ init_textbox();
+ }
+
+ return Object.assign({}, defaults, settings_element, settings_user);
+ }
+
+ var instance_i = 0;
+ class TomSelect extends MicroPlugin(MicroEvent) {
+ // @deprecated 1.8
+ constructor(input_arg, user_settings) {
+ super();
+ this.order = 0;
+ this.isOpen = false;
+ this.isDisabled = false;
+ this.isInvalid = false;
+ this.isValid = true;
+ this.isLocked = false;
+ this.isFocused = false;
+ this.isInputHidden = false;
+ this.isSetup = false;
+ this.ignoreFocus = false;
+ this.hasOptions = false;
+ this.lastValue = '';
+ this.caretPos = 0;
+ this.loading = 0;
+ this.loadedSearches = {};
+ this.activeOption = null;
+ this.activeItems = [];
+ this.optgroups = {};
+ this.options = {};
+ this.userOptions = {};
+ this.items = [];
+ instance_i++;
+ var dir;
+ var input = getDom(input_arg);
+
+ if (input.tomselect) {
+ throw new Error('Tom Select already initialized on this element');
+ }
+
+ input.tomselect = this; // detect rtl environment
+
+ var computedStyle = window.getComputedStyle && window.getComputedStyle(input, null);
+ dir = computedStyle.getPropertyValue('direction'); // setup default state
+
+ const settings = getSettings(input, user_settings);
+ this.settings = settings;
+ this.input = input;
+ this.tabIndex = input.tabIndex || 0;
+ this.is_select_tag = input.tagName.toLowerCase() === 'select';
+ this.rtl = /rtl/i.test(dir);
+ this.inputId = getId(input, 'tomselect-' + instance_i);
+ this.isRequired = input.required; // search system
+
+ this.sifter = new Sifter(this.options, {
+ diacritics: settings.diacritics
+ }); // option-dependent defaults
+
+ settings.mode = settings.mode || (settings.maxItems === 1 ? 'single' : 'multi');
+
+ if (typeof settings.hideSelected !== 'boolean') {
+ settings.hideSelected = settings.mode === 'multi';
+ }
+
+ if (typeof settings.hidePlaceholder !== 'boolean') {
+ settings.hidePlaceholder = settings.mode !== 'multi';
+ } // set up createFilter callback
+
+
+ var filter = settings.createFilter;
+
+ if (typeof filter !== 'function') {
+ if (typeof filter === 'string') {
+ filter = new RegExp(filter);
+ }
+
+ if (filter instanceof RegExp) {
+ settings.createFilter = input => filter.test(input);
+ } else {
+ settings.createFilter = () => true;
+ }
+ }
+
+ this.initializePlugins(settings.plugins);
+ this.setupCallbacks();
+ this.setupTemplates(); // Create all elements
+
+ const wrapper = getDom('<div>');
+ const control = getDom('<div>');
+
+ const dropdown = this._render('dropdown');
+
+ const dropdown_content = getDom(`<div role="listbox" tabindex="-1">`);
+ const classes = this.input.getAttribute('class') || '';
+ const inputMode = settings.mode;
+ var control_input;
+ addClasses(wrapper, settings.wrapperClass, classes, inputMode);
+ addClasses(control, settings.controlClass);
+ append(wrapper, control);
+ addClasses(dropdown, settings.dropdownClass, inputMode);
+
+ if (settings.copyClassesToDropdown) {
+ addClasses(dropdown, classes);
+ }
+
+ addClasses(dropdown_content, settings.dropdownContentClass);
+ append(dropdown, dropdown_content);
+ getDom(settings.dropdownParent || wrapper).appendChild(dropdown); // default controlInput
+
+ if (isHtmlString(settings.controlInput)) {
+ control_input = getDom(settings.controlInput); // set attributes
+
+ var attrs = ['autocorrect', 'autocapitalize', 'autocomplete'];
+ iterate(attrs, attr => {
+ if (input.getAttribute(attr)) {
+ setAttr(control_input, {
+ [attr]: input.getAttribute(attr)
+ });
+ }
+ });
+ control_input.tabIndex = -1;
+ control.appendChild(control_input);
+ this.focus_node = control_input; // dom element
+ } else if (settings.controlInput) {
+ control_input = getDom(settings.controlInput);
+ this.focus_node = control_input;
+ } else {
+ control_input = getDom('<input/>');
+ this.focus_node = control;
+ }
+
+ this.wrapper = wrapper;
+ this.dropdown = dropdown;
+ this.dropdown_content = dropdown_content;
+ this.control = control;
+ this.control_input = control_input;
+ this.setup();
+ }
+ /**
+ * set up event bindings.
+ *
+ */
+
+
+ setup() {
+ const self = this;
+ const settings = self.settings;
+ const control_input = self.control_input;
+ const dropdown = self.dropdown;
+ const dropdown_content = self.dropdown_content;
+ const wrapper = self.wrapper;
+ const control = self.control;
+ const input = self.input;
+ const focus_node = self.focus_node;
+ const passive_event = {
+ passive: true
+ };
+ const listboxId = self.inputId + '-ts-dropdown';
+ setAttr(dropdown_content, {
+ id: listboxId
+ });
+ setAttr(focus_node, {
+ role: 'combobox',
+ 'aria-haspopup': 'listbox',
+ 'aria-expanded': 'false',
+ 'aria-controls': listboxId
+ });
+ const control_id = getId(focus_node, self.inputId + '-ts-control');
+ const query = "label[for='" + escapeQuery(self.inputId) + "']";
+ const label = document.querySelector(query);
+ const label_click = self.focus.bind(self);
+
+ if (label) {
+ addEvent(label, 'click', label_click);
+ setAttr(label, {
+ for: control_id
+ });
+ const label_id = getId(label, self.inputId + '-ts-label');
+ setAttr(focus_node, {
+ 'aria-labelledby': label_id
+ });
+ setAttr(dropdown_content, {
+ 'aria-labelledby': label_id
+ });
+ }
+
+ wrapper.style.width = input.style.width;
+
+ if (self.plugins.names.length) {
+ const classes_plugins = 'plugin-' + self.plugins.names.join(' plugin-');
+ addClasses([wrapper, dropdown], classes_plugins);
+ }
+
+ if ((settings.maxItems === null || settings.maxItems > 1) && self.is_select_tag) {
+ setAttr(input, {
+ multiple: 'multiple'
+ });
+ }
+
+ if (self.settings.placeholder) {
+ setAttr(control_input, {
+ placeholder: settings.placeholder
+ });
+ } // if splitOn was not passed in, construct it from the delimiter to allow pasting universally
+
+
+ if (!self.settings.splitOn && self.settings.delimiter) {
+ self.settings.splitOn = new RegExp('\\s*' + escape_regex(self.settings.delimiter) + '+\\s*');
+ } // debounce user defined load() if loadThrottle > 0
+ // after initializePlugins() so plugins can create/modify user defined loaders
+
+
+ if (settings.load && settings.loadThrottle) {
+ settings.load = loadDebounce(settings.load, settings.loadThrottle);
+ }
+
+ self.control_input.type = input.type; // clicking on an option should select it
+
+ addEvent(dropdown, 'click', evt => {
+ const option = parentMatch(evt.target, '[data-selectable]');
+
+ if (option) {
+ self.onOptionSelect(evt, option);
+ preventDefault(evt, true);
+ }
+ });
+ addEvent(control, 'click', evt => {
+ var target_match = parentMatch(evt.target, '[data-ts-item]', control);
+
+ if (target_match && self.onItemSelect(evt, target_match)) {
+ preventDefault(evt, true);
+ return;
+ } // retain focus (see control_input mousedown)
+
+
+ if (control_input.value != '') {
+ return;
+ }
+
+ self.onClick();
+ preventDefault(evt, true);
+ }); // keydown on focus_node for arrow_down/arrow_up
+
+ addEvent(focus_node, 'keydown', e => self.onKeyDown(e)); // keypress and input/keyup
+
+ addEvent(control_input, 'keypress', e => self.onKeyPress(e));
+ addEvent(control_input, 'input', e => self.onInput(e));
+ addEvent(focus_node, 'resize', () => self.positionDropdown(), passive_event);
+ addEvent(focus_node, 'blur', e => self.onBlur(e));
+ addEvent(focus_node, 'focus', e => self.onFocus(e));
+ addEvent(focus_node, 'paste', e => self.onPaste(e));
+
+ const doc_mousedown = evt => {
+ // blur if target is outside of this instance
+ // dropdown is not always inside wrapper
+ const target = evt.composedPath()[0];
+
+ if (!wrapper.contains(target) && !dropdown.contains(target)) {
+ if (self.isFocused) {
+ self.blur();
+ }
+
+ self.inputState();
+ return;
+ } // retain focus by preventing native handling. if the
+ // event target is the input it should not be modified.
+ // otherwise, text selection within the input won't work.
+ // Fixes bug #212 which is no covered by tests
+
+
+ if (target == control_input && self.isOpen) {
+ evt.stopPropagation(); // clicking anywhere in the control should not blur the control_input (which would close the dropdown)
+ } else {
+ preventDefault(evt, true);
+ }
+ };
+
+ var win_scroll = () => {
+ if (self.isOpen) {
+ self.positionDropdown();
+ }
+ };
+
+ addEvent(document, 'mousedown', doc_mousedown);
+ addEvent(window, 'scroll', win_scroll, passive_event);
+ addEvent(window, 'resize', win_scroll, passive_event);
+
+ this._destroy = () => {
+ document.removeEventListener('mousedown', doc_mousedown);
+ window.removeEventListener('sroll', win_scroll);
+ window.removeEventListener('resize', win_scroll);
+ if (label) label.removeEventListener('click', label_click);
+ }; // store original html and tab index so that they can be
+ // restored when the destroy() method is called.
+
+
+ this.revertSettings = {
+ innerHTML: input.innerHTML,
+ tabIndex: input.tabIndex
+ };
+ input.tabIndex = -1;
+ input.insertAdjacentElement('afterend', self.wrapper);
+ self.sync(false);
+ settings.items = [];
+ delete settings.optgroups;
+ delete settings.options;
+ addEvent(input, 'invalid', e => {
+ if (self.isValid) {
+ self.isValid = false;
+ self.isInvalid = true;
+ self.refreshState();
+ }
+ });
+ self.updateOriginalInput();
+ self.refreshItems();
+ self.close(false);
+ self.inputState();
+ self.isSetup = true;
+
+ if (input.disabled) {
+ self.disable();
+ } else {
+ self.enable(); //sets tabIndex
+ }
+
+ self.on('change', this.onChange);
+ addClasses(input, 'tomselected', 'ts-hidden-accessible');
+ self.trigger('initialize'); // preload options
+
+ if (settings.preload === true) {
+ self.preload();
+ }
+ }
+ /**
+ * Register options and optgroups
+ *
+ */
+
+
+ setupOptions(options = [], optgroups = []) {
+ // build options table
+ this.addOptions(options); // build optgroup table
+
+ iterate(optgroups, optgroup => {
+ this.registerOptionGroup(optgroup);
+ });
+ }
+ /**
+ * Sets up default rendering functions.
+ */
+
+
+ setupTemplates() {
+ var self = this;
+ var field_label = self.settings.labelField;
+ var field_optgroup = self.settings.optgroupLabelField;
+ var templates = {
+ 'optgroup': data => {
+ let optgroup = document.createElement('div');
+ optgroup.className = 'optgroup';
+ optgroup.appendChild(data.options);
+ return optgroup;
+ },
+ 'optgroup_header': (data, escape) => {
+ return '<div class="optgroup-header">' + escape(data[field_optgroup]) + '</div>';
+ },
+ 'option': (data, escape) => {
+ return '<div>' + escape(data[field_label]) + '</div>';
+ },
+ 'item': (data, escape) => {
+ return '<div>' + escape(data[field_label]) + '</div>';
+ },
+ 'option_create': (data, escape) => {
+ return '<div class="create">Add <strong>' + escape(data.input) + '</strong>…</div>';
+ },
+ 'no_results': () => {
+ return '<div class="no-results">No results found</div>';
+ },
+ 'loading': () => {
+ return '<div class="spinner"></div>';
+ },
+ 'not_loading': () => {},
+ 'dropdown': () => {
+ return '<div></div>';
+ }
+ };
+ self.settings.render = Object.assign({}, templates, self.settings.render);
+ }
+ /**
+ * Maps fired events to callbacks provided
+ * in the settings used when creating the control.
+ */
+
+
+ setupCallbacks() {
+ var key, fn;
+ var callbacks = {
+ 'initialize': 'onInitialize',
+ 'change': 'onChange',
+ 'item_add': 'onItemAdd',
+ 'item_remove': 'onItemRemove',
+ 'item_select': 'onItemSelect',
+ 'clear': 'onClear',
+ 'option_add': 'onOptionAdd',
+ 'option_remove': 'onOptionRemove',
+ 'option_clear': 'onOptionClear',
+ 'optgroup_add': 'onOptionGroupAdd',
+ 'optgroup_remove': 'onOptionGroupRemove',
+ 'optgroup_clear': 'onOptionGroupClear',
+ 'dropdown_open': 'onDropdownOpen',
+ 'dropdown_close': 'onDropdownClose',
+ 'type': 'onType',
+ 'load': 'onLoad',
+ 'focus': 'onFocus',
+ 'blur': 'onBlur'
+ };
+
+ for (key in callbacks) {
+ fn = this.settings[callbacks[key]];
+ if (fn) this.on(key, fn);
+ }
+ }
+ /**
+ * Sync the Tom Select instance with the original input or select
+ *
+ */
+
+
+ sync(get_settings = true) {
+ const self = this;
+ const settings = get_settings ? getSettings(self.input, {
+ delimiter: self.settings.delimiter
+ }) : self.settings;
+ self.setupOptions(settings.options, settings.optgroups);
+ self.setValue(settings.items, true); // silent prevents recursion
+
+ self.lastQuery = null; // so updated options will be displayed in dropdown
+ }
+ /**
+ * Triggered when the main control element
+ * has a click event.
+ *
+ */
+
+
+ onClick() {
+ var self = this;
+
+ if (self.activeItems.length > 0) {
+ self.clearActiveItems();
+ self.focus();
+ return;
+ }
+
+ if (self.isFocused && self.isOpen) {
+ self.blur();
+ } else {
+ self.focus();
+ }
+ }
+ /**
+ * @deprecated v1.7
+ *
+ */
+
+
+ onMouseDown() {}
+ /**
+ * Triggered when the value of the control has been changed.
+ * This should propagate the event to the original DOM
+ * input / select element.
+ */
+
+
+ onChange() {
+ triggerEvent(this.input, 'input');
+ triggerEvent(this.input, 'change');
+ }
+ /**
+ * Triggered on <input> paste.
+ *
+ */
+
+
+ onPaste(e) {
+ var self = this;
+
+ if (self.isInputHidden || self.isLocked) {
+ preventDefault(e);
+ return;
+ } // If a regex or string is included, this will split the pasted
+ // input and create Items for each separate value
+
+
+ if (self.settings.splitOn) {
+ // Wait for pasted text to be recognized in value
+ setTimeout(() => {
+ var pastedText = self.inputValue();
+
+ if (!pastedText.match(self.settings.splitOn)) {
+ return;
+ }
+
+ var splitInput = pastedText.trim().split(self.settings.splitOn);
+ iterate(splitInput, piece => {
+ self.createItem(piece);
+ });
+ }, 0);
+ }
+ }
+ /**
+ * Triggered on <input> keypress.
+ *
+ */
+
+
+ onKeyPress(e) {
+ var self = this;
+
+ if (self.isLocked) {
+ preventDefault(e);
+ return;
+ }
+
+ var character = String.fromCharCode(e.keyCode || e.which);
+
+ if (self.settings.create && self.settings.mode === 'multi' && character === self.settings.delimiter) {
+ self.createItem();
+ preventDefault(e);
+ return;
+ }
+ }
+ /**
+ * Triggered on <input> keydown.
+ *
+ */
+
+
+ onKeyDown(e) {
+ var self = this;
+
+ if (self.isLocked) {
+ if (e.keyCode !== KEY_TAB) {
+ preventDefault(e);
+ }
+
+ return;
+ }
+
+ switch (e.keyCode) {
+ // ctrl+A: select all
+ case KEY_A:
+ if (isKeyDown(KEY_SHORTCUT, e)) {
+ if (self.control_input.value == '') {
+ preventDefault(e);
+ self.selectAll();
+ return;
+ }
+ }
+
+ break;
+ // esc: close dropdown
+
+ case KEY_ESC:
+ if (self.isOpen) {
+ preventDefault(e, true);
+ self.close();
+ }
+
+ self.clearActiveItems();
+ return;
+ // down: open dropdown or move selection down
+
+ case KEY_DOWN:
+ if (!self.isOpen && self.hasOptions) {
+ self.open();
+ } else if (self.activeOption) {
+ let next = self.getAdjacent(self.activeOption, 1);
+ if (next) self.setActiveOption(next);
+ }
+
+ preventDefault(e);
+ return;
+ // up: move selection up
+
+ case KEY_UP:
+ if (self.activeOption) {
+ let prev = self.getAdjacent(self.activeOption, -1);
+ if (prev) self.setActiveOption(prev);
+ }
+
+ preventDefault(e);
+ return;
+ // return: select active option
+
+ case KEY_RETURN:
+ if (self.canSelect(self.activeOption)) {
+ self.onOptionSelect(e, self.activeOption);
+ preventDefault(e); // if the option_create=null, the dropdown might be closed
+ } else if (self.settings.create && self.createItem()) {
+ preventDefault(e);
+ }
+
+ return;
+ // left: modifiy item selection to the left
+
+ case KEY_LEFT:
+ self.advanceSelection(-1, e);
+ return;
+ // right: modifiy item selection to the right
+
+ case KEY_RIGHT:
+ self.advanceSelection(1, e);
+ return;
+ // tab: select active option and/or create item
+
+ case KEY_TAB:
+ if (self.settings.selectOnTab) {
+ if (self.canSelect(self.activeOption)) {
+ self.onOptionSelect(e, self.activeOption); // prevent default [tab] behaviour of jump to the next field
+ // if select isFull, then the dropdown won't be open and [tab] will work normally
+
+ preventDefault(e);
+ }
+
+ if (self.settings.create && self.createItem()) {
+ preventDefault(e);
+ }
+ }
+
+ return;
+ // delete|backspace: delete items
+
+ case KEY_BACKSPACE:
+ case KEY_DELETE:
+ self.deleteSelection(e);
+ return;
+ } // don't enter text in the control_input when active items are selected
+
+
+ if (self.isInputHidden && !isKeyDown(KEY_SHORTCUT, e)) {
+ preventDefault(e);
+ }
+ }
+ /**
+ * Triggered on <input> keyup.
+ *
+ */
+
+
+ onInput(e) {
+ var self = this;
+
+ if (self.isLocked) {
+ return;
+ }
+
+ var value = self.inputValue();
+
+ if (self.lastValue !== value) {
+ self.lastValue = value;
+
+ if (self.settings.shouldLoad.call(self, value)) {
+ self.load(value);
+ }
+
+ self.refreshOptions();
+ self.trigger('type', value);
+ }
+ }
+ /**
+ * Triggered on <input> focus.
+ *
+ */
+
+
+ onFocus(e) {
+ var self = this;
+ var wasFocused = self.isFocused;
+
+ if (self.isDisabled) {
+ self.blur();
+ preventDefault(e);
+ return;
+ }
+
+ if (self.ignoreFocus) return;
+ self.isFocused = true;
+ if (self.settings.preload === 'focus') self.preload();
+ if (!wasFocused) self.trigger('focus');
+
+ if (!self.activeItems.length) {
+ self.showInput();
+ self.refreshOptions(!!self.settings.openOnFocus);
+ }
+
+ self.refreshState();
+ }
+ /**
+ * Triggered on <input> blur.
+ *
+ */
+
+
+ onBlur(e) {
+ if (document.hasFocus() === false) return;
+ var self = this;
+ if (!self.isFocused) return;
+ self.isFocused = false;
+ self.ignoreFocus = false;
+
+ var deactivate = () => {
+ self.close();
+ self.setActiveItem();
+ self.setCaret(self.items.length);
+ self.trigger('blur');
+ };
+
+ if (self.settings.create && self.settings.createOnBlur) {
+ self.createItem(null, false, deactivate);
+ } else {
+ deactivate();
+ }
+ }
+ /**
+ * Triggered when the user clicks on an option
+ * in the autocomplete dropdown menu.
+ *
+ */
+
+
+ onOptionSelect(evt, option) {
+ var value,
+ self = this; // should not be possible to trigger a option under a disabled optgroup
+
+ if (option.parentElement && option.parentElement.matches('[data-disabled]')) {
+ return;
+ }
+
+ if (option.classList.contains('create')) {
+ self.createItem(null, true, () => {
+ if (self.settings.closeAfterSelect) {
+ self.close();
+ }
+ });
+ } else {
+ value = option.dataset.value;
+
+ if (typeof value !== 'undefined') {
+ self.lastQuery = null;
+ self.addItem(value);
+
+ if (self.settings.closeAfterSelect) {
+ self.close();
+ }
+
+ if (!self.settings.hideSelected && evt.type && /click/.test(evt.type)) {
+ self.setActiveOption(option);
+ }
+ }
+ }
+ }
+ /**
+ * Return true if the given option can be selected
+ *
+ */
+
+
+ canSelect(option) {
+ if (this.isOpen && option && this.dropdown_content.contains(option)) {
+ return true;
+ }
+
+ return false;
+ }
+ /**
+ * Triggered when the user clicks on an item
+ * that has been selected.
+ *
+ */
+
+
+ onItemSelect(evt, item) {
+ var self = this;
+
+ if (!self.isLocked && self.settings.mode === 'multi') {
+ preventDefault(evt);
+ self.setActiveItem(item, evt);
+ return true;
+ }
+
+ return false;
+ }
+ /**
+ * Determines whether or not to invoke
+ * the user-provided option provider / loader
+ *
+ * Note, there is a subtle difference between
+ * this.canLoad() and this.settings.shouldLoad();
+ *
+ * - settings.shouldLoad() is a user-input validator.
+ * When false is returned, the not_loading template
+ * will be added to the dropdown
+ *
+ * - canLoad() is lower level validator that checks
+ * the Tom Select instance. There is no inherent user
+ * feedback when canLoad returns false
+ *
+ */
+
+
+ canLoad(value) {
+ if (!this.settings.load) return false;
+ if (this.loadedSearches.hasOwnProperty(value)) return false;
+ return true;
+ }
+ /**
+ * Invokes the user-provided option provider / loader.
+ *
+ */
+
+
+ load(value) {
+ const self = this;
+ if (!self.canLoad(value)) return;
+ addClasses(self.wrapper, self.settings.loadingClass);
+ self.loading++;
+ const callback = self.loadCallback.bind(self);
+ self.settings.load.call(self, value, callback);
+ }
+ /**
+ * Invoked by the user-provided option provider
+ *
+ */
+
+
+ loadCallback(options, optgroups) {
+ const self = this;
+ self.loading = Math.max(self.loading - 1, 0);
+ self.lastQuery = null;
+ self.clearActiveOption(); // when new results load, focus should be on first option
+
+ self.setupOptions(options, optgroups);
+ self.refreshOptions(self.isFocused && !self.isInputHidden);
+
+ if (!self.loading) {
+ removeClasses(self.wrapper, self.settings.loadingClass);
+ }
+
+ self.trigger('load', options, optgroups);
+ }
+
+ preload() {
+ var classList = this.wrapper.classList;
+ if (classList.contains('preloaded')) return;
+ classList.add('preloaded');
+ this.load('');
+ }
+ /**
+ * Sets the input field of the control to the specified value.
+ *
+ */
+
+
+ setTextboxValue(value = '') {
+ var input = this.control_input;
+ var changed = input.value !== value;
+
+ if (changed) {
+ input.value = value;
+ triggerEvent(input, 'update');
+ this.lastValue = value;
+ }
+ }
+ /**
+ * Returns the value of the control. If multiple items
+ * can be selected (e.g. <select multiple>), this returns
+ * an array. If only one item can be selected, this
+ * returns a string.
+ *
+ */
+
+
+ getValue() {
+ if (this.is_select_tag && this.input.hasAttribute('multiple')) {
+ return this.items;
+ }
+
+ return this.items.join(this.settings.delimiter);
+ }
+ /**
+ * Resets the selected items to the given value.
+ *
+ */
+
+
+ setValue(value, silent) {
+ var events = silent ? [] : ['change'];
+ debounce_events(this, events, () => {
+ this.clear(silent);
+ this.addItems(value, silent);
+ });
+ }
+ /**
+ * Resets the number of max items to the given value
+ *
+ */
+
+
+ setMaxItems(value) {
+ if (value === 0) value = null; //reset to unlimited items.
+
+ this.settings.maxItems = value;
+ this.refreshState();
+ }
+ /**
+ * Sets the selected item.
+ *
+ */
+
+
+ setActiveItem(item, e) {
+ var self = this;
+ var eventName;
+ var i, begin, end, swap;
+ var last;
+ if (self.settings.mode === 'single') return; // clear the active selection
+
+ if (!item) {
+ self.clearActiveItems();
+
+ if (self.isFocused) {
+ self.showInput();
+ }
+
+ return;
+ } // modify selection
+
+
+ eventName = e && e.type.toLowerCase();
+
+ if (eventName === 'click' && isKeyDown('shiftKey', e) && self.activeItems.length) {
+ last = self.getLastActive();
+ begin = Array.prototype.indexOf.call(self.control.children, last);
+ end = Array.prototype.indexOf.call(self.control.children, item);
+
+ if (begin > end) {
+ swap = begin;
+ begin = end;
+ end = swap;
+ }
+
+ for (i = begin; i <= end; i++) {
+ item = self.control.children[i];
+
+ if (self.activeItems.indexOf(item) === -1) {
+ self.setActiveItemClass(item);
+ }
+ }
+
+ preventDefault(e);
+ } else if (eventName === 'click' && isKeyDown(KEY_SHORTCUT, e) || eventName === 'keydown' && isKeyDown('shiftKey', e)) {
+ if (item.classList.contains('active')) {
+ self.removeActiveItem(item);
+ } else {
+ self.setActiveItemClass(item);
+ }
+ } else {
+ self.clearActiveItems();
+ self.setActiveItemClass(item);
+ } // ensure control has focus
+
+
+ self.hideInput();
+
+ if (!self.isFocused) {
+ self.focus();
+ }
+ }
+ /**
+ * Set the active and last-active classes
+ *
+ */
+
+
+ setActiveItemClass(item) {
+ const self = this;
+ const last_active = self.control.querySelector('.last-active');
+ if (last_active) removeClasses(last_active, 'last-active');
+ addClasses(item, 'active last-active');
+ self.trigger('item_select', item);
+
+ if (self.activeItems.indexOf(item) == -1) {
+ self.activeItems.push(item);
+ }
+ }
+ /**
+ * Remove active item
+ *
+ */
+
+
+ removeActiveItem(item) {
+ var idx = this.activeItems.indexOf(item);
+ this.activeItems.splice(idx, 1);
+ removeClasses(item, 'active');
+ }
+ /**
+ * Clears all the active items
+ *
+ */
+
+
+ clearActiveItems() {
+ removeClasses(this.activeItems, 'active');
+ this.activeItems = [];
+ }
+ /**
+ * Sets the selected item in the dropdown menu
+ * of available options.
+ *
+ */
+
+
+ setActiveOption(option) {
+ if (option === this.activeOption) {
+ return;
+ }
+
+ this.clearActiveOption();
+ if (!option) return;
+ this.activeOption = option;
+ setAttr(this.focus_node, {
+ 'aria-activedescendant': option.getAttribute('id')
+ });
+ setAttr(option, {
+ 'aria-selected': 'true'
+ });
+ addClasses(option, 'active');
+ this.scrollToOption(option);
+ }
+ /**
+ * Sets the dropdown_content scrollTop to display the option
+ *
+ */
+
+
+ scrollToOption(option, behavior) {
+ if (!option) return;
+ const content = this.dropdown_content;
+ const height_menu = content.clientHeight;
+ const scrollTop = content.scrollTop || 0;
+ const height_item = option.offsetHeight;
+ const y = option.getBoundingClientRect().top - content.getBoundingClientRect().top + scrollTop;
+
+ if (y + height_item > height_menu + scrollTop) {
+ this.scroll(y - height_menu + height_item, behavior);
+ } else if (y < scrollTop) {
+ this.scroll(y, behavior);
+ }
+ }
+ /**
+ * Scroll the dropdown to the given position
+ *
+ */
+
+
+ scroll(scrollTop, behavior) {
+ const content = this.dropdown_content;
+
+ if (behavior) {
+ content.style.scrollBehavior = behavior;
+ }
+
+ content.scrollTop = scrollTop;
+ content.style.scrollBehavior = '';
+ }
+ /**
+ * Clears the active option
+ *
+ */
+
+
+ clearActiveOption() {
+ if (this.activeOption) {
+ removeClasses(this.activeOption, 'active');
+ setAttr(this.activeOption, {
+ 'aria-selected': null
+ });
+ }
+
+ this.activeOption = null;
+ setAttr(this.focus_node, {
+ 'aria-activedescendant': null
+ });
+ }
+ /**
+ * Selects all items (CTRL + A).
+ */
+
+
+ selectAll() {
+ if (this.settings.mode === 'single') return;
+ const activeItems = this.controlChildren();
+ if (!activeItems.length) return;
+ this.hideInput();
+ this.close();
+ this.activeItems = activeItems;
+ addClasses(activeItems, 'active');
+ }
+ /**
+ * Determines if the control_input should be in a hidden or visible state
+ *
+ */
+
+
+ inputState() {
+ var self = this;
+ if (!self.control.contains(self.control_input)) return;
+ setAttr(self.control_input, {
+ placeholder: self.settings.placeholder
+ });
+
+ if (self.activeItems.length > 0 || !self.isFocused && self.settings.hidePlaceholder && self.items.length > 0) {
+ self.setTextboxValue();
+ self.isInputHidden = true;
+ } else {
+ if (self.settings.hidePlaceholder && self.items.length > 0) {
+ setAttr(self.control_input, {
+ placeholder: ''
+ });
+ }
+
+ self.isInputHidden = false;
+ }
+
+ self.wrapper.classList.toggle('input-hidden', self.isInputHidden);
+ }
+ /**
+ * Hides the input element out of view, while
+ * retaining its focus.
+ * @deprecated 1.3
+ */
+
+
+ hideInput() {
+ this.inputState();
+ }
+ /**
+ * Restores input visibility.
+ * @deprecated 1.3
+ */
+
+
+ showInput() {
+ this.inputState();
+ }
+ /**
+ * Get the input value
+ */
+
+
+ inputValue() {
+ return this.control_input.value.trim();
+ }
+ /**
+ * Gives the control focus.
+ */
+
+
+ focus() {
+ var self = this;
+ if (self.isDisabled) return;
+ self.ignoreFocus = true;
+
+ if (self.control_input.offsetWidth) {
+ self.control_input.focus();
+ } else {
+ self.focus_node.focus();
+ }
+
+ setTimeout(() => {
+ self.ignoreFocus = false;
+ self.onFocus();
+ }, 0);
+ }
+ /**
+ * Forces the control out of focus.
+ *
+ */
+
+
+ blur() {
+ this.focus_node.blur();
+ this.onBlur();
+ }
+ /**
+ * Returns a function that scores an object
+ * to show how good of a match it is to the
+ * provided query.
+ *
+ * @return {function}
+ */
+
+
+ getScoreFunction(query) {
+ return this.sifter.getScoreFunction(query, this.getSearchOptions());
+ }
+ /**
+ * Returns search options for sifter (the system
+ * for scoring and sorting results).
+ *
+ * @see https://github.com/orchidjs/sifter.js
+ * @return {object}
+ */
+
+
+ getSearchOptions() {
+ var settings = this.settings;
+ var sort = settings.sortField;
+
+ if (typeof settings.sortField === 'string') {
+ sort = [{
+ field: settings.sortField
+ }];
+ }
+
+ return {
+ fields: settings.searchField,
+ conjunction: settings.searchConjunction,
+ sort: sort,
+ nesting: settings.nesting
+ };
+ }
+ /**
+ * Searches through available options and returns
+ * a sorted array of matches.
+ *
+ */
+
+
+ search(query) {
+ var i, result, calculateScore;
+ var self = this;
+ var options = this.getSearchOptions(); // validate user-provided result scoring function
+
+ if (self.settings.score) {
+ calculateScore = self.settings.score.call(self, query);
+
+ if (typeof calculateScore !== 'function') {
+ throw new Error('Tom Select "score" setting must be a function that returns a function');
+ }
+ } // perform search
+
+
+ if (query !== self.lastQuery) {
+ self.lastQuery = query;
+ result = self.sifter.search(query, Object.assign(options, {
+ score: calculateScore
+ }));
+ self.currentResults = result;
+ } else {
+ result = Object.assign({}, self.currentResults);
+ } // filter out selected items
+
+
+ if (self.settings.hideSelected) {
+ for (i = result.items.length - 1; i >= 0; i--) {
+ let hashed = hash_key(result.items[i].id);
+
+ if (hashed && self.items.indexOf(hashed) !== -1) {
+ result.items.splice(i, 1);
+ }
+ }
+ }
+
+ return result;
+ }
+ /**
+ * Refreshes the list of available options shown
+ * in the autocomplete dropdown menu.
+ *
+ */
+
+
+ refreshOptions(triggerDropdown = true) {
+ var i, j, k, n, optgroup, optgroups, html, has_create_option, active_value, active_group;
+ var create;
+ const groups = {};
+ const groups_order = [];
+ var self = this;
+ var query = self.inputValue();
+ var results = self.search(query);
+ var active_option = self.activeOption;
+ var show_dropdown = self.settings.shouldOpen || false;
+ var dropdown_content = self.dropdown_content;
+
+ if (active_option) {
+ active_value = active_option.dataset.value;
+ active_group = active_option.closest('[data-group]');
+ } // build markup
+
+
+ n = results.items.length;
+
+ if (typeof self.settings.maxOptions === 'number') {
+ n = Math.min(n, self.settings.maxOptions);
+ }
+
+ if (n > 0) {
+ show_dropdown = true;
+ } // render and group available options individually
+
+
+ for (i = 0; i < n; i++) {
+ // get option dom element
+ let opt_value = results.items[i].id;
+ let option = self.options[opt_value];
+ let option_el = self.getOption(opt_value, true); // toggle 'selected' class
+
+ if (!self.settings.hideSelected) {
+ option_el.classList.toggle('selected', self.items.includes(opt_value));
+ }
+
+ optgroup = option[self.settings.optgroupField] || '';
+ optgroups = Array.isArray(optgroup) ? optgroup : [optgroup];
+
+ for (j = 0, k = optgroups && optgroups.length; j < k; j++) {
+ optgroup = optgroups[j];
+
+ if (!self.optgroups.hasOwnProperty(optgroup)) {
+ optgroup = '';
+ }
+
+ if (!groups.hasOwnProperty(optgroup)) {
+ groups[optgroup] = document.createDocumentFragment();
+ groups_order.push(optgroup);
+ } // nodes can only have one parent, so if the option is in mutple groups, we need a clone
+
+
+ if (j > 0) {
+ option_el = option_el.cloneNode(true);
+ setAttr(option_el, {
+ id: option.$id + '-clone-' + j,
+ 'aria-selected': null
+ });
+ option_el.classList.add('ts-cloned');
+ removeClasses(option_el, 'active');
+ } // make sure we keep the activeOption in the same group
+
+
+ if (active_value == opt_value && active_group && active_group.dataset.group === optgroup) {
+ active_option = option_el;
+ }
+
+ groups[optgroup].appendChild(option_el);
+ }
+ } // sort optgroups
+
+
+ if (this.settings.lockOptgroupOrder) {
+ groups_order.sort((a, b) => {
+ var a_order = self.optgroups[a] && self.optgroups[a].$order || 0;
+ var b_order = self.optgroups[b] && self.optgroups[b].$order || 0;
+ return a_order - b_order;
+ });
+ } // render optgroup headers & join groups
+
+
+ html = document.createDocumentFragment();
+ iterate(groups_order, optgroup => {
+ if (self.optgroups.hasOwnProperty(optgroup) && groups[optgroup].children.length) {
+ let group_options = document.createDocumentFragment();
+ let header = self.render('optgroup_header', self.optgroups[optgroup]);
+ append(group_options, header);
+ append(group_options, groups[optgroup]);
+ let group_html = self.render('optgroup', {
+ group: self.optgroups[optgroup],
+ options: group_options
+ });
+ append(html, group_html);
+ } else {
+ append(html, groups[optgroup]);
+ }
+ });
+ dropdown_content.innerHTML = '';
+ append(dropdown_content, html); // highlight matching terms inline
+
+ if (self.settings.highlight) {
+ removeHighlight(dropdown_content);
+
+ if (results.query.length && results.tokens.length) {
+ iterate(results.tokens, tok => {
+ highlight(dropdown_content, tok.regex);
+ });
+ }
+ } // helper method for adding templates to dropdown
+
+
+ var add_template = template => {
+ let content = self.render(template, {
+ input: query
+ });
+
+ if (content) {
+ show_dropdown = true;
+ dropdown_content.insertBefore(content, dropdown_content.firstChild);
+ }
+
+ return content;
+ }; // add loading message
+
+
+ if (self.loading) {
+ add_template('loading'); // invalid query
+ } else if (!self.settings.shouldLoad.call(self, query)) {
+ add_template('not_loading'); // add no_results message
+ } else if (results.items.length === 0) {
+ add_template('no_results');
+ } // add create option
+
+
+ has_create_option = self.canCreate(query);
+
+ if (has_create_option) {
+ create = add_template('option_create');
+ } // activate
+
+
+ self.hasOptions = results.items.length > 0 || has_create_option;
+
+ if (show_dropdown) {
+ if (results.items.length > 0) {
+ if (!dropdown_content.contains(active_option) && self.settings.mode === 'single' && self.items.length) {
+ active_option = self.getOption(self.items[0]);
+ }
+
+ if (!dropdown_content.contains(active_option)) {
+ let active_index = 0;
+
+ if (create && !self.settings.addPrecedence) {
+ active_index = 1;
+ }
+
+ active_option = self.selectable()[active_index];
+ }
+ } else if (create) {
+ active_option = create;
+ }
+
+ if (triggerDropdown && !self.isOpen) {
+ self.open();
+ self.scrollToOption(active_option, 'auto');
+ }
+
+ self.setActiveOption(active_option);
+ } else {
+ self.clearActiveOption();
+
+ if (triggerDropdown && self.isOpen) {
+ self.close(false); // if create_option=null, we want the dropdown to close but not reset the textbox value
+ }
+ }
+ }
+ /**
+ * Return list of selectable options
+ *
+ */
+
+
+ selectable() {
+ return this.dropdown_content.querySelectorAll('[data-selectable]');
+ }
+ /**
+ * Adds an available option. If it already exists,
+ * nothing will happen. Note: this does not refresh
+ * the options list dropdown (use `refreshOptions`
+ * for that).
+ *
+ * Usage:
+ *
+ * this.addOption(data)
+ *
+ */
+
+
+ addOption(data, user_created = false) {
+ const self = this; // @deprecated 1.7.7
+ // use addOptions( array, user_created ) for adding multiple options
+
+ if (Array.isArray(data)) {
+ self.addOptions(data, user_created);
+ return false;
+ }
+
+ const key = hash_key(data[self.settings.valueField]);
+
+ if (key === null || self.options.hasOwnProperty(key)) {
+ return false;
+ }
+
+ data.$order = data.$order || ++self.order;
+ data.$id = self.inputId + '-opt-' + data.$order;
+ self.options[key] = data;
+ self.lastQuery = null;
+
+ if (user_created) {
+ self.userOptions[key] = user_created;
+ self.trigger('option_add', key, data);
+ }
+
+ return key;
+ }
+ /**
+ * Add multiple options
+ *
+ */
+
+
+ addOptions(data, user_created = false) {
+ iterate(data, dat => {
+ this.addOption(dat, user_created);
+ });
+ }
+ /**
+ * @deprecated 1.7.7
+ */
+
+
+ registerOption(data) {
+ return this.addOption(data);
+ }
+ /**
+ * Registers an option group to the pool of option groups.
+ *
+ * @return {boolean|string}
+ */
+
+
+ registerOptionGroup(data) {
+ var key = hash_key(data[this.settings.optgroupValueField]);
+ if (key === null) return false;
+ data.$order = data.$order || ++this.order;
+ this.optgroups[key] = data;
+ return key;
+ }
+ /**
+ * Registers a new optgroup for options
+ * to be bucketed into.
+ *
+ */
+
+
+ addOptionGroup(id, data) {
+ var hashed_id;
+ data[this.settings.optgroupValueField] = id;
+
+ if (hashed_id = this.registerOptionGroup(data)) {
+ this.trigger('optgroup_add', hashed_id, data);
+ }
+ }
+ /**
+ * Removes an existing option group.
+ *
+ */
+
+
+ removeOptionGroup(id) {
+ if (this.optgroups.hasOwnProperty(id)) {
+ delete this.optgroups[id];
+ this.clearCache();
+ this.trigger('optgroup_remove', id);
+ }
+ }
+ /**
+ * Clears all existing option groups.
+ */
+
+
+ clearOptionGroups() {
+ this.optgroups = {};
+ this.clearCache();
+ this.trigger('optgroup_clear');
+ }
+ /**
+ * Updates an option available for selection. If
+ * it is visible in the selected items or options
+ * dropdown, it will be re-rendered automatically.
+ *
+ */
+
+
+ updateOption(value, data) {
+ const self = this;
+ var item_new;
+ var index_item;
+ const value_old = hash_key(value);
+ const value_new = hash_key(data[self.settings.valueField]); // sanity checks
+
+ if (value_old === null) return;
+ if (!self.options.hasOwnProperty(value_old)) return;
+ if (typeof value_new !== 'string') throw new Error('Value must be set in option data');
+ const option = self.getOption(value_old);
+ const item = self.getItem(value_old);
+ data.$order = data.$order || self.options[value_old].$order;
+ delete self.options[value_old]; // invalidate render cache
+ // don't remove existing node yet, we'll remove it after replacing it
+
+ self.uncacheValue(value_new);
+ self.options[value_new] = data; // update the option if it's in the dropdown
+
+ if (option) {
+ if (self.dropdown_content.contains(option)) {
+ const option_new = self._render('option', data);
+
+ replaceNode(option, option_new);
+
+ if (self.activeOption === option) {
+ self.setActiveOption(option_new);
+ }
+ }
+
+ option.remove();
+ } // update the item if we have one
+
+
+ if (item) {
+ index_item = self.items.indexOf(value_old);
+
+ if (index_item !== -1) {
+ self.items.splice(index_item, 1, value_new);
+ }
+
+ item_new = self._render('item', data);
+ if (item.classList.contains('active')) addClasses(item_new, 'active');
+ replaceNode(item, item_new);
+ } // invalidate last query because we might have updated the sortField
+
+
+ self.lastQuery = null;
+ }
+ /**
+ * Removes a single option.
+ *
+ */
+
+
+ removeOption(value, silent) {
+ const self = this;
+ value = get_hash(value);
+ self.uncacheValue(value);
+ delete self.userOptions[value];
+ delete self.options[value];
+ self.lastQuery = null;
+ self.trigger('option_remove', value);
+ self.removeItem(value, silent);
+ }
+ /**
+ * Clears all options.
+ */
+
+
+ clearOptions() {
+ this.loadedSearches = {};
+ this.userOptions = {};
+ this.clearCache();
+ var selected = {};
+ iterate(this.options, (option, key) => {
+ if (this.items.indexOf(key) >= 0) {
+ selected[key] = this.options[key];
+ }
+ });
+ this.options = this.sifter.items = selected;
+ this.lastQuery = null;
+ this.trigger('option_clear');
+ }
+ /**
+ * Returns the dom element of the option
+ * matching the given value.
+ *
+ */
+
+
+ getOption(value, create = false) {
+ const hashed = hash_key(value);
+
+ if (hashed !== null && this.options.hasOwnProperty(hashed)) {
+ const option = this.options[hashed];
+
+ if (option.$div) {
+ return option.$div;
+ }
+
+ if (create) {
+ return this._render('option', option);
+ }
+ }
+
+ return null;
+ }
+ /**
+ * Returns the dom element of the next or previous dom element of the same type
+ * Note: adjacent options may not be adjacent DOM elements (optgroups)
+ *
+ */
+
+
+ getAdjacent(option, direction, type = 'option') {
+ var self = this,
+ all;
+
+ if (!option) {
+ return null;
+ }
+
+ if (type == 'item') {
+ all = self.controlChildren();
+ } else {
+ all = self.dropdown_content.querySelectorAll('[data-selectable]');
+ }
+
+ for (let i = 0; i < all.length; i++) {
+ if (all[i] != option) {
+ continue;
+ }
+
+ if (direction > 0) {
+ return all[i + 1];
+ }
+
+ return all[i - 1];
+ }
+
+ return null;
+ }
+ /**
+ * Returns the dom element of the item
+ * matching the given value.
+ *
+ */
+
+
+ getItem(item) {
+ if (typeof item == 'object') {
+ return item;
+ }
+
+ var value = hash_key(item);
+ return value !== null ? this.control.querySelector(`[data-value="${addSlashes(value)}"]`) : null;
+ }
+ /**
+ * "Selects" multiple items at once. Adds them to the list
+ * at the current caret position.
+ *
+ */
+
+
+ addItems(values, silent) {
+ var self = this;
+ var items = Array.isArray(values) ? values : [values];
+ items = items.filter(x => self.items.indexOf(x) === -1);
+
+ for (let i = 0, n = items.length; i < n; i++) {
+ self.isPending = i < n - 1;
+ self.addItem(items[i], silent);
+ }
+ }
+ /**
+ * "Selects" an item. Adds it to the list
+ * at the current caret position.
+ *
+ */
+
+
+ addItem(value, silent) {
+ var events = silent ? [] : ['change', 'dropdown_close'];
+ debounce_events(this, events, () => {
+ var item, wasFull;
+ const self = this;
+ const inputMode = self.settings.mode;
+ const hashed = hash_key(value);
+
+ if (hashed && self.items.indexOf(hashed) !== -1) {
+ if (inputMode === 'single') {
+ self.close();
+ }
+
+ if (inputMode === 'single' || !self.settings.duplicates) {
+ return;
+ }
+ }
+
+ if (hashed === null || !self.options.hasOwnProperty(hashed)) return;
+ if (inputMode === 'single') self.clear(silent);
+ if (inputMode === 'multi' && self.isFull()) return;
+ item = self._render('item', self.options[hashed]);
+
+ if (self.control.contains(item)) {
+ // duplicates
+ item = item.cloneNode(true);
+ }
+
+ wasFull = self.isFull();
+ self.items.splice(self.caretPos, 0, hashed);
+ self.insertAtCaret(item);
+
+ if (self.isSetup) {
+ // update menu / remove the option (if this is not one item being added as part of series)
+ if (!self.isPending && self.settings.hideSelected) {
+ let option = self.getOption(hashed);
+ let next = self.getAdjacent(option, 1);
+
+ if (next) {
+ self.setActiveOption(next);
+ }
+ } // refreshOptions after setActiveOption(),
+ // otherwise setActiveOption() will be called by refreshOptions() with the wrong value
+
+
+ if (!self.isPending && !self.settings.closeAfterSelect) {
+ self.refreshOptions(self.isFocused && inputMode !== 'single');
+ } // hide the menu if the maximum number of items have been selected or no options are left
+
+
+ if (self.settings.closeAfterSelect != false && self.isFull()) {
+ self.close();
+ } else if (!self.isPending) {
+ self.positionDropdown();
+ }
+
+ self.trigger('item_add', hashed, item);
+
+ if (!self.isPending) {
+ self.updateOriginalInput({
+ silent: silent
+ });
+ }
+ }
+
+ if (!self.isPending || !wasFull && self.isFull()) {
+ self.inputState();
+ self.refreshState();
+ }
+ });
+ }
+ /**
+ * Removes the selected item matching
+ * the provided value.
+ *
+ */
+
+
+ removeItem(item = null, silent) {
+ const self = this;
+ item = self.getItem(item);
+ if (!item) return;
+ var i, idx;
+ const value = item.dataset.value;
+ i = nodeIndex(item);
+ item.remove();
+
+ if (item.classList.contains('active')) {
+ idx = self.activeItems.indexOf(item);
+ self.activeItems.splice(idx, 1);
+ removeClasses(item, 'active');
+ }
+
+ self.items.splice(i, 1);
+ self.lastQuery = null;
+
+ if (!self.settings.persist && self.userOptions.hasOwnProperty(value)) {
+ self.removeOption(value, silent);
+ }
+
+ if (i < self.caretPos) {
+ self.setCaret(self.caretPos - 1);
+ }
+
+ self.updateOriginalInput({
+ silent: silent
+ });
+ self.refreshState();
+ self.positionDropdown();
+ self.trigger('item_remove', value, item);
+ }
+ /**
+ * Invokes the `create` method provided in the
+ * TomSelect options that should provide the data
+ * for the new item, given the user input.
+ *
+ * Once this completes, it will be added
+ * to the item list.
+ *
+ */
+
+
+ createItem(input = null, triggerDropdown = true, callback = () => {}) {
+ var self = this;
+ var caret = self.caretPos;
+ var output;
+ input = input || self.inputValue();
+
+ if (!self.canCreate(input)) {
+ callback();
+ return false;
+ }
+
+ self.lock();
+ var created = false;
+
+ var create = data => {
+ self.unlock();
+ if (!data || typeof data !== 'object') return callback();
+ var value = hash_key(data[self.settings.valueField]);
+
+ if (typeof value !== 'string') {
+ return callback();
+ }
+
+ self.setTextboxValue();
+ self.addOption(data, true);
+ self.setCaret(caret);
+ self.addItem(value);
+ callback(data);
+ created = true;
+ };
+
+ if (typeof self.settings.create === 'function') {
+ output = self.settings.create.call(this, input, create);
+ } else {
+ output = {
+ [self.settings.labelField]: input,
+ [self.settings.valueField]: input
+ };
+ }
+
+ if (!created) {
+ create(output);
+ }
+
+ return true;
+ }
+ /**
+ * Re-renders the selected item lists.
+ */
+
+
+ refreshItems() {
+ var self = this;
+ self.lastQuery = null;
+
+ if (self.isSetup) {
+ self.addItems(self.items);
+ }
+
+ self.updateOriginalInput();
+ self.refreshState();
+ }
+ /**
+ * Updates all state-dependent attributes
+ * and CSS classes.
+ */
+
+
+ refreshState() {
+ const self = this;
+ self.refreshValidityState();
+ const isFull = self.isFull();
+ const isLocked = self.isLocked;
+ self.wrapper.classList.toggle('rtl', self.rtl);
+ const wrap_classList = self.wrapper.classList;
+ wrap_classList.toggle('focus', self.isFocused);
+ wrap_classList.toggle('disabled', self.isDisabled);
+ wrap_classList.toggle('required', self.isRequired);
+ wrap_classList.toggle('invalid', !self.isValid);
+ wrap_classList.toggle('locked', isLocked);
+ wrap_classList.toggle('full', isFull);
+ wrap_classList.toggle('input-active', self.isFocused && !self.isInputHidden);
+ wrap_classList.toggle('dropdown-active', self.isOpen);
+ wrap_classList.toggle('has-options', isEmptyObject(self.options));
+ wrap_classList.toggle('has-items', self.items.length > 0);
+ }
+ /**
+ * Update the `required` attribute of both input and control input.
+ *
+ * The `required` property needs to be activated on the control input
+ * for the error to be displayed at the right place. `required` also
+ * needs to be temporarily deactivated on the input since the input is
+ * hidden and can't show errors.
+ */
+
+
+ refreshValidityState() {
+ var self = this;
+
+ if (!self.input.checkValidity) {
+ return;
+ }
+
+ self.isValid = self.input.checkValidity();
+ self.isInvalid = !self.isValid;
+ }
+ /**
+ * Determines whether or not more items can be added
+ * to the control without exceeding the user-defined maximum.
+ *
+ * @returns {boolean}
+ */
+
+
+ isFull() {
+ return this.settings.maxItems !== null && this.items.length >= this.settings.maxItems;
+ }
+ /**
+ * Refreshes the original <select> or <input>
+ * element to reflect the current state.
+ *
+ */
+
+
+ updateOriginalInput(opts = {}) {
+ const self = this;
+ var option, label;
+ const empty_option = self.input.querySelector('option[value=""]');
+
+ if (self.is_select_tag) {
+ const selected = [];
+
+ function AddSelected(option_el, value, label) {
+ if (!option_el) {
+ option_el = getDom('<option value="' + escape_html(value) + '">' + escape_html(label) + '</option>');
+ } // don't move empty option from top of list
+ // fixes bug in firefox https://bugzilla.mozilla.org/show_bug.cgi?id=1725293
+
+
+ if (option_el != empty_option) {
+ self.input.append(option_el);
+ }
+
+ selected.push(option_el);
+ option_el.selected = true;
+ return option_el;
+ } // unselect all selected options
+
+
+ self.input.querySelectorAll('option:checked').forEach(option_el => {
+ option_el.selected = false;
+ }); // nothing selected?
+
+ if (self.items.length == 0 && self.settings.mode == 'single') {
+ AddSelected(empty_option, "", ""); // order selected <option> tags for values in self.items
+ } else {
+ self.items.forEach(value => {
+ option = self.options[value];
+ label = option[self.settings.labelField] || '';
+
+ if (selected.includes(option.$option)) {
+ const reuse_opt = self.input.querySelector(`option[value="${addSlashes(value)}"]:not(:checked)`);
+ AddSelected(reuse_opt, value, label);
+ } else {
+ option.$option = AddSelected(option.$option, value, label);
+ }
+ });
+ }
+ } else {
+ self.input.value = self.getValue();
+ }
+
+ if (self.isSetup) {
+ if (!opts.silent) {
+ self.trigger('change', self.getValue());
+ }
+ }
+ }
+ /**
+ * Shows the autocomplete dropdown containing
+ * the available options.
+ */
+
+
+ open() {
+ var self = this;
+ if (self.isLocked || self.isOpen || self.settings.mode === 'multi' && self.isFull()) return;
+ self.isOpen = true;
+ setAttr(self.focus_node, {
+ 'aria-expanded': 'true'
+ });
+ self.refreshState();
+ applyCSS(self.dropdown, {
+ visibility: 'hidden',
+ display: 'block'
+ });
+ self.positionDropdown();
+ applyCSS(self.dropdown, {
+ visibility: 'visible',
+ display: 'block'
+ });
+ self.focus();
+ self.trigger('dropdown_open', self.dropdown);
+ }
+ /**
+ * Closes the autocomplete dropdown menu.
+ */
+
+
+ close(setTextboxValue = true) {
+ var self = this;
+ var trigger = self.isOpen;
+
+ if (setTextboxValue) {
+ // before blur() to prevent form onchange event
+ self.setTextboxValue();
+
+ if (self.settings.mode === 'single' && self.items.length) {
+ self.hideInput();
+ }
+ }
+
+ self.isOpen = false;
+ setAttr(self.focus_node, {
+ 'aria-expanded': 'false'
+ });
+ applyCSS(self.dropdown, {
+ display: 'none'
+ });
+
+ if (self.settings.hideSelected) {
+ self.clearActiveOption();
+ }
+
+ self.refreshState();
+ if (trigger) self.trigger('dropdown_close', self.dropdown);
+ }
+ /**
+ * Calculates and applies the appropriate
+ * position of the dropdown if dropdownParent = 'body'.
+ * Otherwise, position is determined by css
+ */
+
+
+ positionDropdown() {
+ if (this.settings.dropdownParent !== 'body') {
+ return;
+ }
+
+ var context = this.control;
+ var rect = context.getBoundingClientRect();
+ var top = context.offsetHeight + rect.top + window.scrollY;
+ var left = rect.left + window.scrollX;
+ applyCSS(this.dropdown, {
+ width: rect.width + 'px',
+ top: top + 'px',
+ left: left + 'px'
+ });
+ }
+ /**
+ * Resets / clears all selected items
+ * from the control.
+ *
+ */
+
+
+ clear(silent) {
+ var self = this;
+ if (!self.items.length) return;
+ var items = self.controlChildren();
+ iterate(items, item => {
+ self.removeItem(item, true);
+ });
+ self.showInput();
+ if (!silent) self.updateOriginalInput();
+ self.trigger('clear');
+ }
+ /**
+ * A helper method for inserting an element
+ * at the current caret position.
+ *
+ */
+
+
+ insertAtCaret(el) {
+ const self = this;
+ const caret = self.caretPos;
+ const target = self.control;
+ target.insertBefore(el, target.children[caret]);
+ self.setCaret(caret + 1);
+ }
+ /**
+ * Removes the current selected item(s).
+ *
+ */
+
+
+ deleteSelection(e) {
+ var direction, selection, caret, tail;
+ var self = this;
+ direction = e && e.keyCode === KEY_BACKSPACE ? -1 : 1;
+ selection = getSelection(self.control_input); // determine items that will be removed
+
+ const rm_items = [];
+
+ if (self.activeItems.length) {
+ tail = getTail(self.activeItems, direction);
+ caret = nodeIndex(tail);
+
+ if (direction > 0) {
+ caret++;
+ }
+
+ iterate(self.activeItems, item => rm_items.push(item));
+ } else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) {
+ const items = self.controlChildren();
+
+ if (direction < 0 && selection.start === 0 && selection.length === 0) {
+ rm_items.push(items[self.caretPos - 1]);
+ } else if (direction > 0 && selection.start === self.inputValue().length) {
+ rm_items.push(items[self.caretPos]);
+ }
+ }
+
+ const values = rm_items.map(item => item.dataset.value); // allow the callback to abort
+
+ if (!values.length || typeof self.settings.onDelete === 'function' && self.settings.onDelete.call(self, values, e) === false) {
+ return false;
+ }
+
+ preventDefault(e, true); // perform removal
+
+ if (typeof caret !== 'undefined') {
+ self.setCaret(caret);
+ }
+
+ while (rm_items.length) {
+ self.removeItem(rm_items.pop());
+ }
+
+ self.showInput();
+ self.positionDropdown();
+ self.refreshOptions(false);
+ return true;
+ }
+ /**
+ * Selects the previous / next item (depending on the `direction` argument).
+ *
+ * > 0 - right
+ * < 0 - left
+ *
+ */
+
+
+ advanceSelection(direction, e) {
+ var last_active,
+ adjacent,
+ self = this;
+ if (self.rtl) direction *= -1;
+ if (self.inputValue().length) return; // add or remove to active items
+
+ if (isKeyDown(KEY_SHORTCUT, e) || isKeyDown('shiftKey', e)) {
+ last_active = self.getLastActive(direction);
+
+ if (last_active) {
+ if (!last_active.classList.contains('active')) {
+ adjacent = last_active;
+ } else {
+ adjacent = self.getAdjacent(last_active, direction, 'item');
+ } // if no active item, get items adjacent to the control input
+
+ } else if (direction > 0) {
+ adjacent = self.control_input.nextElementSibling;
+ } else {
+ adjacent = self.control_input.previousElementSibling;
+ }
+
+ if (adjacent) {
+ if (adjacent.classList.contains('active')) {
+ self.removeActiveItem(last_active);
+ }
+
+ self.setActiveItemClass(adjacent); // mark as last_active !! after removeActiveItem() on last_active
+ } // move caret to the left or right
+
+ } else {
+ self.moveCaret(direction);
+ }
+ }
+
+ moveCaret(direction) {}
+ /**
+ * Get the last active item
+ *
+ */
+
+
+ getLastActive(direction) {
+ let last_active = this.control.querySelector('.last-active');
+
+ if (last_active) {
+ return last_active;
+ }
+
+ var result = this.control.querySelectorAll('.active');
+
+ if (result) {
+ return getTail(result, direction);
+ }
+ }
+ /**
+ * Moves the caret to the specified index.
+ *
+ * The input must be moved by leaving it in place and moving the
+ * siblings, due to the fact that focus cannot be restored once lost
+ * on mobile webkit devices
+ *
+ */
+
+
+ setCaret(new_pos) {
+ this.caretPos = this.items.length;
+ }
+ /**
+ * Return list of item dom elements
+ *
+ */
+
+
+ controlChildren() {
+ return Array.from(this.control.querySelectorAll('[data-ts-item]'));
+ }
+ /**
+ * Disables user input on the control. Used while
+ * items are being asynchronously created.
+ */
+
+
+ lock() {
+ this.isLocked = true;
+ this.refreshState();
+ }
+ /**
+ * Re-enables user input on the control.
+ */
+
+
+ unlock() {
+ this.isLocked = false;
+ this.refreshState();
+ }
+ /**
+ * Disables user input on the control completely.
+ * While disabled, it cannot receive focus.
+ */
+
+
+ disable() {
+ var self = this;
+ self.input.disabled = true;
+ self.control_input.disabled = true;
+ self.focus_node.tabIndex = -1;
+ self.isDisabled = true;
+ this.close();
+ self.lock();
+ }
+ /**
+ * Enables the control so that it can respond
+ * to focus and user input.
+ */
+
+
+ enable() {
+ var self = this;
+ self.input.disabled = false;
+ self.control_input.disabled = false;
+ self.focus_node.tabIndex = self.tabIndex;
+ self.isDisabled = false;
+ self.unlock();
+ }
+ /**
+ * Completely destroys the control and
+ * unbinds all event listeners so that it can
+ * be garbage collected.
+ */
+
+
+ destroy() {
+ var self = this;
+ var revertSettings = self.revertSettings;
+ self.trigger('destroy');
+ self.off();
+ self.wrapper.remove();
+ self.dropdown.remove();
+ self.input.innerHTML = revertSettings.innerHTML;
+ self.input.tabIndex = revertSettings.tabIndex;
+ removeClasses(self.input, 'tomselected', 'ts-hidden-accessible');
+
+ self._destroy();
+
+ delete self.input.tomselect;
+ }
+ /**
+ * A helper method for rendering "item" and
+ * "option" templates, given the data.
+ *
+ */
+
+
+ render(templateName, data) {
+ if (typeof this.settings.render[templateName] !== 'function') {
+ return null;
+ }
+
+ return this._render(templateName, data);
+ }
+ /**
+ * _render() can be called directly when we know we don't want to hit the cache
+ * return type could be null for some templates, we need https://github.com/microsoft/TypeScript/issues/33014
+ */
+
+
+ _render(templateName, data) {
+ var value = '',
+ id,
+ html;
+ const self = this;
+
+ if (templateName === 'option' || templateName == 'item') {
+ value = get_hash(data[self.settings.valueField]);
+ } // render markup
+
+
+ html = self.settings.render[templateName].call(this, data, escape_html);
+
+ if (html == null) {
+ return html;
+ }
+
+ html = getDom(html); // add mandatory attributes
+
+ if (templateName === 'option' || templateName === 'option_create') {
+ if (data[self.settings.disabledField]) {
+ setAttr(html, {
+ 'aria-disabled': 'true'
+ });
+ } else {
+ setAttr(html, {
+ 'data-selectable': ''
+ });
+ }
+ } else if (templateName === 'optgroup') {
+ id = data.group[self.settings.optgroupValueField];
+ setAttr(html, {
+ 'data-group': id
+ });
+
+ if (data.group[self.settings.disabledField]) {
+ setAttr(html, {
+ 'data-disabled': ''
+ });
+ }
+ }
+
+ if (templateName === 'option' || templateName === 'item') {
+ setAttr(html, {
+ 'data-value': value
+ }); // make sure we have some classes if a template is overwritten
+
+ if (templateName === 'item') {
+ addClasses(html, self.settings.itemClass);
+ setAttr(html, {
+ 'data-ts-item': ''
+ });
+ } else {
+ addClasses(html, self.settings.optionClass);
+ setAttr(html, {
+ role: 'option',
+ id: data.$id
+ }); // update cache
+
+ self.options[value].$div = html;
+ }
+ }
+
+ return html;
+ }
+ /**
+ * Clears the render cache for a template. If
+ * no template is given, clears all render
+ * caches.
+ *
+ */
+
+
+ clearCache() {
+ iterate(this.options, (option, value) => {
+ if (option.$div) {
+ option.$div.remove();
+ delete option.$div;
+ }
+ });
+ }
+ /**
+ * Removes a value from item and option caches
+ *
+ */
+
+
+ uncacheValue(value) {
+ const option_el = this.getOption(value);
+ if (option_el) option_el.remove();
+ }
+ /**
+ * Determines whether or not to display the
+ * create item prompt, given a user input.
+ *
+ */
+
+
+ canCreate(input) {
+ return this.settings.create && input.length > 0 && this.settings.createFilter.call(this, input);
+ }
+ /**
+ * Wraps this.`method` so that `new_fn` can be invoked 'before', 'after', or 'instead' of the original method
+ *
+ * this.hook('instead','onKeyDown',function( arg1, arg2 ...){
+ *
+ * });
+ */
+
+
+ hook(when, method, new_fn) {
+ var self = this;
+ var orig_method = self[method];
+
+ self[method] = function () {
+ var result, result_new;
+
+ if (when === 'after') {
+ result = orig_method.apply(self, arguments);
+ }
+
+ result_new = new_fn.apply(self, arguments);
+
+ if (when === 'instead') {
+ return result_new;
+ }
+
+ if (when === 'before') {
+ result = orig_method.apply(self, arguments);
+ }
+
+ return result;
+ };
+ }
+
+ }
+
+ /**
+ * Plugin: "change_listener" (Tom Select)
+ * Copyright (c) contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function change_listener () {
+ addEvent(this.input, 'change', () => {
+ this.sync();
+ });
+ }
+
+ /**
+ * Plugin: "restore_on_backspace" (Tom Select)
+ * Copyright (c) contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function checkbox_options () {
+ var self = this;
+ var orig_onOptionSelect = self.onOptionSelect;
+ self.settings.hideSelected = false; // update the checkbox for an option
+
+ var UpdateCheckbox = function UpdateCheckbox(option) {
+ setTimeout(() => {
+ var checkbox = option.querySelector('input');
+
+ if (option.classList.contains('selected')) {
+ checkbox.checked = true;
+ } else {
+ checkbox.checked = false;
+ }
+ }, 1);
+ }; // add checkbox to option template
+
+
+ self.hook('after', 'setupTemplates', () => {
+ var orig_render_option = self.settings.render.option;
+
+ self.settings.render.option = (data, escape_html) => {
+ var rendered = getDom(orig_render_option.call(self, data, escape_html));
+ var checkbox = document.createElement('input');
+ checkbox.addEventListener('click', function (evt) {
+ preventDefault(evt);
+ });
+ checkbox.type = 'checkbox';
+ const hashed = hash_key(data[self.settings.valueField]);
+
+ if (hashed && self.items.indexOf(hashed) > -1) {
+ checkbox.checked = true;
+ }
+
+ rendered.prepend(checkbox);
+ return rendered;
+ };
+ }); // uncheck when item removed
+
+ self.on('item_remove', value => {
+ var option = self.getOption(value);
+
+ if (option) {
+ // if dropdown hasn't been opened yet, the option won't exist
+ option.classList.remove('selected'); // selected class won't be removed yet
+
+ UpdateCheckbox(option);
+ }
+ }); // remove items when selected option is clicked
+
+ self.hook('instead', 'onOptionSelect', (evt, option) => {
+ if (option.classList.contains('selected')) {
+ option.classList.remove('selected');
+ self.removeItem(option.dataset.value);
+ self.refreshOptions();
+ preventDefault(evt, true);
+ return;
+ }
+
+ orig_onOptionSelect.call(self, evt, option);
+ UpdateCheckbox(option);
+ });
+ }
+
+ /**
+ * Plugin: "dropdown_header" (Tom Select)
+ * Copyright (c) contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function clear_button (userOptions) {
+ const self = this;
+ const options = Object.assign({
+ className: 'clear-button',
+ title: 'Clear All',
+ html: data => {
+ return `<div class="${data.className}" title="${data.title}">×</div>`;
+ }
+ }, userOptions);
+ self.on('initialize', () => {
+ var button = getDom(options.html(options));
+ button.addEventListener('click', evt => {
+ self.clear();
+
+ if (self.settings.mode === 'single' && self.settings.allowEmptyOption) {
+ self.addItem('');
+ }
+
+ evt.preventDefault();
+ evt.stopPropagation();
+ });
+ self.control.appendChild(button);
+ });
+ }
+
+ /**
+ * Plugin: "drag_drop" (Tom Select)
+ * Copyright (c) contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function drag_drop () {
+ var self = this;
+ if (!$.fn.sortable) throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".');
+ if (self.settings.mode !== 'multi') return;
+ var orig_lock = self.lock;
+ var orig_unlock = self.unlock;
+ self.hook('instead', 'lock', () => {
+ var sortable = $(self.control).data('sortable');
+ if (sortable) sortable.disable();
+ return orig_lock.call(self);
+ });
+ self.hook('instead', 'unlock', () => {
+ var sortable = $(self.control).data('sortable');
+ if (sortable) sortable.enable();
+ return orig_unlock.call(self);
+ });
+ self.on('initialize', () => {
+ var $control = $(self.control).sortable({
+ items: '[data-value]',
+ forcePlaceholderSize: true,
+ disabled: self.isLocked,
+ start: (e, ui) => {
+ ui.placeholder.css('width', ui.helper.css('width'));
+ $control.css({
+ overflow: 'visible'
+ });
+ },
+ stop: () => {
+ $control.css({
+ overflow: 'hidden'
+ });
+ var values = [];
+ $control.children('[data-value]').each(function () {
+ if (this.dataset.value) values.push(this.dataset.value);
+ });
+ self.setValue(values);
+ }
+ });
+ });
+ }
+
+ /**
+ * Plugin: "dropdown_header" (Tom Select)
+ * Copyright (c) contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function dropdown_header (userOptions) {
+ const self = this;
+ const options = Object.assign({
+ title: 'Untitled',
+ headerClass: 'dropdown-header',
+ titleRowClass: 'dropdown-header-title',
+ labelClass: 'dropdown-header-label',
+ closeClass: 'dropdown-header-close',
+ html: data => {
+ return '<div class="' + data.headerClass + '">' + '<div class="' + data.titleRowClass + '">' + '<span class="' + data.labelClass + '">' + data.title + '</span>' + '<a class="' + data.closeClass + '">×</a>' + '</div>' + '</div>';
+ }
+ }, userOptions);
+ self.on('initialize', () => {
+ var header = getDom(options.html(options));
+ var close_link = header.querySelector('.' + options.closeClass);
+
+ if (close_link) {
+ close_link.addEventListener('click', evt => {
+ preventDefault(evt, true);
+ self.close();
+ });
+ }
+
+ self.dropdown.insertBefore(header, self.dropdown.firstChild);
+ });
+ }
+
+ /**
+ * Plugin: "dropdown_input" (Tom Select)
+ * Copyright (c) contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function caret_position () {
+ var self = this;
+ /**
+ * Moves the caret to the specified index.
+ *
+ * The input must be moved by leaving it in place and moving the
+ * siblings, due to the fact that focus cannot be restored once lost
+ * on mobile webkit devices
+ *
+ */
+
+ self.hook('instead', 'setCaret', new_pos => {
+ if (self.settings.mode === 'single' || !self.control.contains(self.control_input)) {
+ new_pos = self.items.length;
+ } else {
+ new_pos = Math.max(0, Math.min(self.items.length, new_pos));
+
+ if (new_pos != self.caretPos && !self.isPending) {
+ self.controlChildren().forEach((child, j) => {
+ if (j < new_pos) {
+ self.control_input.insertAdjacentElement('beforebegin', child);
+ } else {
+ self.control.appendChild(child);
+ }
+ });
+ }
+ }
+
+ self.caretPos = new_pos;
+ });
+ self.hook('instead', 'moveCaret', direction => {
+ if (!self.isFocused) return; // move caret before or after selected items
+
+ const last_active = self.getLastActive(direction);
+
+ if (last_active) {
+ const idx = nodeIndex(last_active);
+ self.setCaret(direction > 0 ? idx + 1 : idx);
+ self.setActiveItem(); // move caret left or right of current position
+ } else {
+ self.setCaret(self.caretPos + direction);
+ }
+ });
+ }
+
+ /**
+ * Plugin: "dropdown_input" (Tom Select)
+ * Copyright (c) contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function dropdown_input () {
+ var self = this;
+ self.settings.shouldOpen = true; // make sure the input is shown even if there are no options to display in the dropdown
+
+ self.hook('before', 'setup', () => {
+ self.focus_node = self.control;
+ addClasses(self.control_input, 'dropdown-input');
+ const div = getDom('<div class="dropdown-input-wrap">');
+ div.append(self.control_input);
+ self.dropdown.insertBefore(div, self.dropdown.firstChild);
+ });
+ self.on('initialize', () => {
+ // set tabIndex on control to -1, otherwise [shift+tab] will put focus right back on control_input
+ self.control_input.addEventListener('keydown', evt => {
+ //addEvent(self.control_input,'keydown' as const,(evt:KeyboardEvent) =>{
+ switch (evt.keyCode) {
+ case KEY_ESC:
+ if (self.isOpen) {
+ preventDefault(evt, true);
+ self.close();
+ }
+
+ self.clearActiveItems();
+ return;
+
+ case KEY_TAB:
+ self.focus_node.tabIndex = -1;
+ break;
+ }
+
+ return self.onKeyDown.call(self, evt);
+ });
+ self.on('blur', () => {
+ self.focus_node.tabIndex = self.isDisabled ? -1 : self.tabIndex;
+ }); // give the control_input focus when the dropdown is open
+
+ self.on('dropdown_open', () => {
+ self.control_input.focus();
+ }); // prevent onBlur from closing when focus is on the control_input
+
+ const orig_onBlur = self.onBlur;
+ self.hook('instead', 'onBlur', evt => {
+ if (evt && evt.relatedTarget == self.control_input) return;
+ return orig_onBlur.call(self);
+ });
+ addEvent(self.control_input, 'blur', () => self.onBlur()); // return focus to control to allow further keyboard input
+
+ self.hook('before', 'close', () => {
+ if (!self.isOpen) return;
+ self.focus_node.focus();
+ });
+ });
+ }
+
+ /**
+ * Plugin: "input_autogrow" (Tom Select)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function input_autogrow () {
+ var self = this;
+ self.on('initialize', () => {
+ var test_input = document.createElement('span');
+ var control = self.control_input;
+ test_input.style.cssText = 'position:absolute; top:-99999px; left:-99999px; width:auto; padding:0; white-space:pre; ';
+ self.wrapper.appendChild(test_input);
+ var transfer_styles = ['letterSpacing', 'fontSize', 'fontFamily', 'fontWeight', 'textTransform'];
+
+ for (const style_name of transfer_styles) {
+ // @ts-ignore TS7015 https://stackoverflow.com/a/50506154/697576
+ test_input.style[style_name] = control.style[style_name];
+ }
+ /**
+ * Set the control width
+ *
+ */
+
+
+ var resize = () => {
+ if (self.items.length > 0) {
+ test_input.textContent = control.value;
+ control.style.width = test_input.clientWidth + 'px';
+ } else {
+ control.style.width = '';
+ }
+ };
+
+ resize();
+ self.on('update item_add item_remove', resize);
+ addEvent(control, 'input', resize);
+ addEvent(control, 'keyup', resize);
+ addEvent(control, 'blur', resize);
+ addEvent(control, 'update', resize);
+ });
+ }
+
+ /**
+ * Plugin: "input_autogrow" (Tom Select)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function no_backspace_delete () {
+ var self = this;
+ var orig_deleteSelection = self.deleteSelection;
+ this.hook('instead', 'deleteSelection', evt => {
+ if (self.activeItems.length) {
+ return orig_deleteSelection.call(self, evt);
+ }
+
+ return false;
+ });
+ }
+
+ /**
+ * Plugin: "input_autogrow" (Tom Select)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function no_active_items () {
+ this.hook('instead', 'setActiveItem', () => {});
+ this.hook('instead', 'selectAll', () => {});
+ }
+
+ /**
+ * Plugin: "optgroup_columns" (Tom Select.js)
+ * Copyright (c) contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function optgroup_columns () {
+ var self = this;
+ var orig_keydown = self.onKeyDown;
+ self.hook('instead', 'onKeyDown', evt => {
+ var index, option, options, optgroup;
+
+ if (!self.isOpen || !(evt.keyCode === KEY_LEFT || evt.keyCode === KEY_RIGHT)) {
+ return orig_keydown.call(self, evt);
+ }
+
+ optgroup = parentMatch(self.activeOption, '[data-group]');
+ index = nodeIndex(self.activeOption, '[data-selectable]');
+
+ if (!optgroup) {
+ return;
+ }
+
+ if (evt.keyCode === KEY_LEFT) {
+ optgroup = optgroup.previousSibling;
+ } else {
+ optgroup = optgroup.nextSibling;
+ }
+
+ if (!optgroup) {
+ return;
+ }
+
+ options = optgroup.querySelectorAll('[data-selectable]');
+ option = options[Math.min(options.length - 1, index)];
+
+ if (option) {
+ self.setActiveOption(option);
+ }
+ });
+ }
+
+ /**
+ * Plugin: "remove_button" (Tom Select)
+ * Copyright (c) contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function remove_button (userOptions) {
+ const options = Object.assign({
+ label: '×',
+ title: 'Remove',
+ className: 'remove',
+ append: true
+ }, userOptions); //options.className = 'remove-single';
+
+ var self = this; // override the render method to add remove button to each item
+
+ if (!options.append) {
+ return;
+ }
+
+ var html = '<a href="javascript:void(0)" class="' + options.className + '" tabindex="-1" title="' + escape_html(options.title) + '">' + options.label + '</a>';
+ self.hook('after', 'setupTemplates', () => {
+ var orig_render_item = self.settings.render.item;
+
+ self.settings.render.item = (data, escape) => {
+ var rendered = getDom(orig_render_item.call(self, data, escape));
+ var close_button = getDom(html);
+ rendered.appendChild(close_button);
+ addEvent(close_button, 'mousedown', evt => {
+ preventDefault(evt, true);
+ });
+ addEvent(close_button, 'click', evt => {
+ // propagating will trigger the dropdown to show for single mode
+ preventDefault(evt, true);
+ if (self.isLocked) return;
+ var value = rendered.dataset.value;
+ self.removeItem(value);
+ self.refreshOptions(false);
+ });
+ return rendered;
+ };
+ });
+ }
+
+ /**
+ * Plugin: "restore_on_backspace" (Tom Select)
+ * Copyright (c) contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function restore_on_backspace (userOptions) {
+ const self = this;
+ const options = Object.assign({
+ text: option => {
+ return option[self.settings.labelField];
+ }
+ }, userOptions);
+ self.on('item_remove', function (value) {
+ if (self.control_input.value.trim() === '') {
+ var option = self.options[value];
+
+ if (option) {
+ self.setTextboxValue(options.text.call(self, option));
+ }
+ }
+ });
+ }
+
+ /**
+ * Plugin: "restore_on_backspace" (Tom Select)
+ * Copyright (c) contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
+ * file except in compliance with the License. You may obtain a copy of the License at:
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+ * ANY KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ *
+ */
+ function virtual_scroll () {
+ const self = this;
+ const orig_canLoad = self.canLoad;
+ const orig_clearActiveOption = self.clearActiveOption;
+ const orig_loadCallback = self.loadCallback;
+ var pagination = {};
+ var dropdown_content;
+ var loading_more = false;
+
+ if (!self.settings.firstUrl) {
+ throw 'virtual_scroll plugin requires a firstUrl() method';
+ } // in order for virtual scrolling to work,
+ // options need to be ordered the same way they're returned from the remote data source
+
+
+ self.settings.sortField = [{
+ field: '$order'
+ }, {
+ field: '$score'
+ }]; // can we load more results for given query?
+
+ function canLoadMore(query) {
+ if (typeof self.settings.maxOptions === 'number' && dropdown_content.children.length >= self.settings.maxOptions) {
+ return false;
+ }
+
+ if (query in pagination && pagination[query]) {
+ return true;
+ }
+
+ return false;
+ } // set the next url that will be
+
+
+ self.setNextUrl = function (value, next_url) {
+ pagination[value] = next_url;
+ }; // getUrl() to be used in settings.load()
+
+
+ self.getUrl = function (query) {
+ if (query in pagination) {
+ const next_url = pagination[query];
+ pagination[query] = false;
+ return next_url;
+ } // if the user goes back to a previous query
+ // we need to load the first page again
+
+
+ pagination = {};
+ return self.settings.firstUrl(query);
+ }; // don't clear the active option (and cause unwanted dropdown scroll)
+ // while loading more results
+
+
+ self.hook('instead', 'clearActiveOption', () => {
+ if (loading_more) {
+ return;
+ }
+
+ return orig_clearActiveOption.call(self);
+ }); // override the canLoad method
+
+ self.hook('instead', 'canLoad', query => {
+ // first time the query has been seen
+ if (!(query in pagination)) {
+ return orig_canLoad.call(self, query);
+ }
+
+ return canLoadMore(query);
+ }); // wrap the load
+
+ self.hook('instead', 'loadCallback', (options, optgroups) => {
+ if (!loading_more) {
+ self.clearOptions();
+ }
+
+ orig_loadCallback.call(self, options, optgroups);
+ loading_more = false;
+ }); // add templates to dropdown
+ // loading_more if we have another url in the queue
+ // no_more_results if we don't have another url in the queue
+
+ self.hook('after', 'refreshOptions', () => {
+ const query = self.lastValue;
+ var option;
+
+ if (canLoadMore(query)) {
+ option = self.render('loading_more', {
+ query: query
+ });
+ if (option) option.setAttribute('data-selectable', ''); // so that navigating dropdown with [down] keypresses can navigate to this node
+ } else if (query in pagination && !dropdown_content.querySelector('.no-results')) {
+ option = self.render('no_more_results', {
+ query: query
+ });
+ }
+
+ if (option) {
+ addClasses(option, self.settings.optionClass);
+ dropdown_content.append(option);
+ }
+ }); // add scroll listener and default templates
+
+ self.on('initialize', () => {
+ dropdown_content = self.dropdown_content; // default templates
+
+ self.settings.render = Object.assign({}, {
+ loading_more: function () {
+ return `<div class="loading-more-results">Loading more results ... </div>`;
+ },
+ no_more_results: function () {
+ return `<div class="no-more-results">No more results</div>`;
+ }
+ }, self.settings.render); // watch dropdown content scroll position
+
+ dropdown_content.addEventListener('scroll', function () {
+ const scroll_percent = dropdown_content.clientHeight / (dropdown_content.scrollHeight - dropdown_content.scrollTop);
+
+ if (scroll_percent < 0.95) {
+ return;
+ } // !important: this will get checked again in load() but we still need to check here otherwise loading_more will be set to true
+
+
+ if (!canLoadMore(self.lastValue)) {
+ return;
+ } // don't call load() too much
+
+
+ if (loading_more) return;
+ loading_more = true;
+ self.load.call(self, self.lastValue);
+ });
+ });
+ }
+
+ TomSelect.define('change_listener', change_listener);
+ TomSelect.define('checkbox_options', checkbox_options);
+ TomSelect.define('clear_button', clear_button);
+ TomSelect.define('drag_drop', drag_drop);
+ TomSelect.define('dropdown_header', dropdown_header);
+ TomSelect.define('caret_position', caret_position);
+ TomSelect.define('dropdown_input', dropdown_input);
+ TomSelect.define('input_autogrow', input_autogrow);
+ TomSelect.define('no_backspace_delete', no_backspace_delete);
+ TomSelect.define('no_active_items', no_active_items);
+ TomSelect.define('optgroup_columns', optgroup_columns);
+ TomSelect.define('remove_button', remove_button);
+ TomSelect.define('restore_on_backspace', restore_on_backspace);
+ TomSelect.define('virtual_scroll', virtual_scroll);
+
+ return TomSelect;
+
+})));
+var tomSelect=function(el,opts){return new TomSelect(el,opts);}
+//# sourceMappingURL=tom-select.complete.js.map
@@ -2,6 +2,7 @@
require "braintree"
require "bigdecimal/util"
+require "countries"
require "date"
require "delegate"
require "dhall"
@@ -10,6 +11,7 @@ require "pg"
require "redis"
require "roda"
require "uri"
+require "json"
if ENV["RACK_ENV"] == "development"
require "pry-rescue"
@@ -54,9 +56,8 @@ class CreditCardGateway
end
end
- def initialize(jid, customer_id, antifraud)
- @jid = jid
- @customer_id = customer_id
+ def initialize(currency, antifraud)
+ @currency = currency
@antifraud = antifraud
@gateway = Braintree::Gateway.new(
@@ -67,6 +68,71 @@ class CreditCardGateway
)
end
+ def merchant_account
+ BRAINTREE_CONFIG[:merchant_accounts][@currency]
+ end
+
+ def client_token(**kwargs)
+ kwargs[:merchant_account_id] = merchant_account.to_s if merchant_account
+ @gateway.client_token.generate(**kwargs)
+ end
+
+ def antifraud
+ REDIS.mget(@antifraud.map { |k| "jmp_antifraud-#{k}" }).find do |anti|
+ anti.to_i > 2
+ end &&
+ Braintree::ErrorResult.new(
+ @gateway, errors: {}, message: "Please contact support"
+ )
+ end
+
+ def with_antifraud
+ result = antifraud || yield
+ return result if result.success?
+
+ @antifraud.each do |k|
+ REDIS.incr("jmp_antifraud-#{k}")
+ REDIS.expire("jmp_antifraud-#{k}", 60 * 60 * 24)
+ end
+
+ raise ErrorResult.for(result)
+ end
+
+ def sale(nonce, amount, **kwargs)
+ with_antifraud do
+ @gateway.transaction.sale(
+ payment_method_nonce: nonce,
+ amount: amount, merchant_account_id: merchant_account.to_s,
+ options: {
+ store_in_vault_on_success: true, submit_for_settlement: true
+ }, **kwargs
+ )
+ end
+ end
+
+ def customer
+ @gateway.customer
+ end
+
+ def payment_method
+ @gateway.payment_method
+ end
+end
+
+class CreditCardCustomerGateway
+ def initialize(jid, customer_id, antifraud)
+ @jid = jid
+ @customer_id = customer_id
+ @gateway = CreditCardGateway.new(
+ customer_plan&.dig(:currency),
+ antifraud
+ )
+ end
+
+ def merchant_account
+ @gateway.merchant_account
+ end
+
def check_customer_id(cid)
return cid unless ENV["RACK_ENV"] == "production"
@@ -94,17 +160,8 @@ class CreditCardGateway
PLANS.find { |plan| plan[:name].to_s == name }
end
- def merchant_account
- plan = customer_plan
- return unless plan
-
- BRAINTREE_CONFIG[:merchant_accounts][plan[:currency]]
- end
-
def client_token
- kwargs = {}
- kwargs[:merchant_account_id] = merchant_account.to_s if merchant_account
- @gateway.client_token.generate(customer_id: customer_id, **kwargs)
+ @gateway.client_token(customer_id: customer_id)
end
def payment_methods?
@@ -114,36 +171,15 @@ class CreditCardGateway
def antifraud
return if REDIS.exists?("jmp_antifraud_bypass-#{customer_id}")
- REDIS.mget(@antifraud.map { |k| "jmp_antifraud-#{k}" }).find do |anti|
- anti.to_i > 2
- end &&
- Braintree::ErrorResult.new(
- @gateway, errors: {}, message: "Please contact support"
- )
+ @gateway.antifraud
end
- def with_antifraud
- result = antifraud || yield
- return result if result.success?
-
- @antifraud.each do |k|
- REDIS.incr("jmp_antifraud-#{k}")
- REDIS.expire("jmp_antifraud-#{k}", 60 * 60 * 24)
- end
-
- raise ErrorResult.for(result)
+ def with_antifraud(&blk)
+ @gateway.with_antifraud(&blk)
end
def sale(nonce, amount)
- with_antifraud do
- @gateway.transaction.sale(
- customer_id: customer_id, payment_method_nonce: nonce,
- amount: amount, merchant_account_id: merchant_account.to_s,
- options: {
- store_in_vault_on_success: true, submit_for_settlement: true
- }
- )
- end
+ @gateway.sale(nonce, amount, customer_id: customer_id)
end
def default_method(nonce)
@@ -272,6 +308,17 @@ class JmpPay < Roda
plugin :render, engine: "slim"
plugin :cookies, path: "/"
plugin :common_logger, $stdout
+ plugin :content_for
+ plugin(
+ :assets,
+ css: { tom_select: "tom_select.scss", loader: "loader.scss" },
+ js: {
+ section_list: "section_list.js",
+ tom_select: "tom_select.js",
+ htmx: "htmx.js"
+ },
+ add_suffix: true
+ )
extend Forwardable
def_delegators :request, :params
@@ -300,6 +347,67 @@ class JmpPay < Roda
])
end
+ def nil_empty(s)
+ s.to_s == "" ? nil : s
+ end
+
+ def stallion_shipment
+ {
+ to_address: {
+ country_code: params["country-name"],
+ postal_code: params["postal-code"],
+ address1: nil_empty(params["street-address"]),
+ email: nil_empty(params["email"])
+ }.compact,
+ weight_unit: "g",
+ weight:
+ (params["esim_adapter_quantity"].to_i * 10) +
+ (params["pcsc_quantity"].to_i * 30),
+ size_unit: "in",
+ length: 18,
+ width: 8.5,
+ height: params["pcsc_quantity"].to_i.positive? ? 1 : 0.1,
+ package_type: "Large Envelope Or Flat",
+ items: [
+ {
+ title: "Memory Card",
+ description: "Memory Card",
+ quantity: params["esim_adapter_quantity"].to_i,
+ value: params["currency"] == "CAD" ? 54.99 : 39.99,
+ currency: params["currency"],
+ country_of_origin: "CN"
+ },
+ {
+ title: "Card Reader",
+ description: "Card Reader",
+ quantity: params["pcsc_quantity"].to_i,
+ value: params["currency"] == "CAD" ? 13.50 : 10,
+ currency: params["currency"],
+ country_of_origin: "CN"
+ }
+ ].select { |item| item[:quantity].positive? },
+ insured: true
+ }
+ end
+
+ def get_rates
+ uri = URI("https://ship.stallionexpress.ca/api/v4/rates")
+ Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
+ req = Net::HTTP::Post.new(uri)
+ req["Content-Type"] = "application/json"
+ req["Authorization"] = "Bearer #{ENV.fetch('STALLION_TOKEN')}"
+ body = stallion_shipment
+ req.body = body.to_json
+ JSON.parse(http.request(req).read_body)
+ end
+ end
+
+ def retail_rate(rates)
+ total = BigDecimal(rates.first["total"], 2)
+ total *= 0.75 if params["currency"] == "USD"
+ params["country-name"] == "US" ? total.round : total.ceil
+ end
+
route do |r|
r.on "electrum_notify" do
verify_address_customer_id(r)
@@ -316,19 +424,97 @@ class JmpPay < Roda
"OK"
end
+ r.assets
+
+ atfd = r.cookies["atfd"] || SecureRandom.uuid
+ one_year = 60 * 60 * 24 * 365
+ response.set_cookie(
+ "atfd",
+ value: atfd, expires: Time.now + one_year
+ )
+ params.delete("atfd") if params["atfd"].to_s == ""
+ antifrauds = [atfd, r.ip, params["atfd"]].compact.uniq
+
+ r.on "esim-adapter" do
+ r.get "braintree" do
+ gateway = CreditCardGateway.new(params["currency"], antifrauds)
+ if gateway.antifraud
+ next view(
+ :message,
+ locals: { message: "Please contact support" }
+ )
+ end
+ render :braintree, locals: { token: gateway.client_token }
+ end
+
+ r.get "total" do
+ next "" unless params["postal-code"].to_s != ""
+
+ resp = get_rates
+ next resp["errors"].to_a.join("<br />") unless resp["success"]
+
+ render :total, locals: resp.merge("body" => stallion_shipment)
+ end
+
+ r.post do
+ gateway = CreditCardGateway.new(params["currency"], antifrauds)
+ if gateway.antifraud
+ next view(
+ :message,
+ locals: { message: "Please contact support" }
+ )
+ end
+
+ cost = stallion_shipment[:items].map { |item| item[:quantity] * item[:value] }.sum
+ rate = retail_rate(get_rates["rates"])
+
+ unless BigDecimal(params["amount"], 2) >= (cost + rate)
+ raise "Invalid amount"
+ end
+
+ sale_result = gateway.sale(params["braintree_nonce"], params["amount"])
+
+ postal_lookup = JSON.parse(Net::HTTP.get(URI(
+ "https://app.zipcodebase.com/api/v1/search?" \
+ "apikey=#{ENV.fetch('ZIPCODEBASE_TOKEN')}&" \
+ "codes=#{params['postal-code']}&" \
+ "country=#{params['country-name']}"
+ )))
+
+ uri = URI("https://ship.stallionexpress.ca/api/v4/orders")
+ Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
+ req = Net::HTTP::Post.new(uri)
+ req["Content-Type"] = "application/json"
+ req["Authorization"] = "Bearer #{ENV.fetch('STALLION_TOKEN')}"
+ body = stallion_shipment
+ body.merge!(body.delete(:to_address))
+ body[:store_id] = ENV.fetch("STALLION_STORE_ID")
+ body[:value] = BigDecimal(params["amount"], 2)
+ body[:currency] = params["currency"]
+ body[:order_at] = Time.now.strftime("%Y-%m-%d %H:%m:%S")
+ body[:order_id] = sale_result.transaction.id
+ body[:name] = "Customer"
+ body[:city] = postal_lookup["results"].values.first.first["city"]
+ body[:province_code] = postal_lookup["results"].values.first.first["state_code"]
+ req.body = body.to_json
+ resp = JSON.parse(http.request(req).read_body)
+ view :receipt, locals: resp.merge("rate" => rate)
+ end
+ rescue CreditCardGateway::ErrorResult
+ response.status = 400
+ $!.message
+ end
+
+ r.get do
+ view :esim_adapter, locals: { antifraud: atfd }
+ end
+ end
+
r.on :jid do |jid|
Sentry.set_user(id: params["customer_id"], jid: jid)
- atfd = r.cookies["atfd"] || SecureRandom.uuid
- one_year = 60 * 60 * 24 * 365
- response.set_cookie(
- "atfd",
- value: atfd, expires: Time.now + one_year
- )
- params.delete("atfd") if params["atfd"].to_s == ""
- antifrauds = [atfd, r.ip, params["atfd"]].compact.uniq
customer_id = params["customer_id"]
- gateway = CreditCardGateway.new(jid, customer_id, antifrauds)
+ gateway = CreditCardCustomerGateway.new(jid, customer_id, antifrauds)
topup = AutoTopUpRepo.new
r.on "credit_cards" do
@@ -0,0 +1,15 @@
+javascript:
+ document.querySelector("#braintree").innerHTML = "";
+ braintree.dropin.create({
+ authorization: #{{token.to_json}},
+ container: "#braintree",
+ card: { vault: { vaultCard: false } },
+ vaultManager: false,
+ threeDSecure: true,
+ }, function (createErr, instance) {
+ if(createErr) {
+ console.log(createErr);
+ Sentry.captureException(createErr);
+ }
+ window.braintreeInstance = instance;
+ });
@@ -0,0 +1,160 @@
+- content_for :head do
+ == assets [:css, :loader]
+ == assets [:css, :tom_select]
+ == assets [:js, :tom_select]
+ == assets [:js, :htmx]
+ script src="https://js.braintreegateway.com/web/dropin/1.42.0/js/dropin.js"
+ javascript:
+ window.addEventListener("load", function() {
+ const country = new TomSelect("select[name=country-name]", {
+ plugins: [
+ "change_listener",
+ "no_backspace_delete",
+ "dropdown_input"
+ ],
+ highlight: false,
+ maxOptions: 500,
+ onChange: (value) => {
+ document.querySelector("input[name=postal-code]").previousSibling.textContent = value === "US" ? "Zip Code" : "Postal Code";
+ document.querySelector("select[name=currency]").value = value === "CA" ? "CAD" : "USD";
+ document.querySelector("select[name=currency]").dispatchEvent(new Event("change"));
+ }
+ });
+
+ document.querySelector("select[name=currency]").addEventListener("change", (e) => {
+ if (e.target.value === "CAD") {
+ document.querySelector("input[name=esim_adapter_quantity]").previousSibling.textContent = "eSIM Adapters ($54.99 each)"
+ document.querySelector("input[name=pcsc_quantity]").previousSibling.textContent = "USB PCSC Readers ($13.50 each)"
+ } else {
+ document.querySelector("input[name=esim_adapter_quantity]").previousSibling.textContent = "eSIM Adapters ($39.99 each)"
+ document.querySelector("input[name=pcsc_quantity]").previousSibling.textContent = "USB PCSC Readers ($10.00 each)"
+ }
+ });
+
+ country.trigger("change", document.querySelector("select[name=country-name]").value);
+ });
+
+scss:
+ body {
+ font-family: sans-serif;
+ }
+ h1 {
+ text-align: center;
+ }
+ form {
+ display: block;
+ max-width: 40em;
+ margin: auto;
+ * { box-sizing: border-box; }
+ label {
+ display: block;
+ margin-top: 1em;
+ }
+ .half {
+ margin-top: 1em;
+ display: flex;
+ & > * {
+ flex: 1;
+ }
+ & > span {
+ padding: 8px 0;
+ }
+ }
+ button {
+ display: block;
+ margin: 1em auto;
+ padding: 0.5em;
+ font-size: 1.2em;
+ }
+ }
+ .htmx-indicator {
+ margin-top: 1em;
+ text-align: center;
+ float: right;
+ }
+
+section data-hx-get="/esim-adapter/total" data-hx-trigger="input delay:1s,change" data-hx-include="form" data-hx-target="#total"
+ h1 Order an eSIM Adapter
+
+ form method="post" action=""
+ label
+ div Country for Shipping Address
+ select name="country-name" required=true
+ - ISO3166::Country.all.each do |country|
+ option selected=(country.alpha2 == "US") value=country.alpha2 = "#{country.emoji_flag} #{country.translation('en')}"
+
+ label
+ div Currency
+ select.ts-control name="currency" data-hx-get="/esim-adapter/braintree" data-hx-trigger="change" data-hx-target="#braintree-js"
+ option value="USD" US Dollars
+ option value="CAD" Canadian Dollars
+
+ label.half
+ span eSIM Adapters ($39.99 each)
+ input.ts-control name="esim_adapter_quantity" type="number" step="1" min="0" required=true value=1
+
+ label.half
+ span USB PCSC Readers ($10 each)
+ input.ts-control name="pcsc_quantity" type="number" step="1" min="0" required=true value=0
+
+ label
+ div Zip Code
+ input.ts-control type="text" name="postal-code" required=true
+
+ label
+ div Street Address
+ input.ts-control type="text" name="street-address" required=true
+
+ label
+ div Email Address
+ input.ts-control type="email" name="email" required=true
+
+ .htmx-indicator
+ .lds-ring <div></div><div></div><div></div><div></div></div>
+ #total
+
+ #braintree
+ input type="hidden" name="atfd" value=antifraud
+ input type="hidden" name="braintree_nonce"
+
+ button Place Order
+
+javascript:
+ if(window.localStorage) {
+ var atfd = localStorage.getItem("atfd");
+ if(!atfd) {
+ atfd = "#{antifraud}";
+ localStorage.setItem("atfd", atfd);
+ }
+ document.querySelector("input[name=atfd]").value = atfd;
+ }
+
+ window.braintreeInstance = null;
+ document.querySelector("form").addEventListener("submit", function(e) {
+ e.preventDefault();
+ if (!braintreeInstance || !document.querySelector("input[name=amount]")) {
+ return;
+ }
+ document.querySelector("form button").disabled = true;
+ document.querySelector("form button").style.display = "none";
+
+ braintreeInstance.requestPaymentMethod({
+ threeDSecure: {
+ amount: document.querySelector("input[name=amount]").value,
+ requireChallenge: true,
+ collectDeviceData: true,
+ email: document.querySelector("input[name=email]").value
+ }
+ }, function(err, payload) {
+ if(err) {
+ console.log(err);
+ document.querySelector("form button").disabled = false;
+ document.querySelector("form button").style.display = "block";
+ } else {
+ e.target.braintree_nonce.value = payload.nonce;
+ e.target.submit();
+ }
+ });
+ });
+
+#braintree-js
@@ -5,5 +5,6 @@ html
meta content="width=device-width, initial-scale=1" name="viewport"
title JMP Pay
script src="https://js.sentry-cdn.com/#{SENTRY_DSN&.user}.min.js" crossorigin="anonymous"
+ == content_for :head
body
== yield
@@ -0,0 +1,36 @@
+scss:
+ body {
+ font-family: sans-serif;
+ }
+ h1, p { text-align: center; }
+ table {
+ width: 20em;
+ margin: auto;
+ }
+ tr {
+ td:first-of-type {
+ font-weight: bold;
+ }
+ }
+
+h1 JMP Order Receipt
+
+p This is your receipt, please print or screenshot it for your records.
+
+table
+ tr
+ td Order ID
+ td= order["order_id"]
+ tr
+ td Ordered At
+ td= order["order_at"]
+ - order["items"].each do |item|
+ tr
+ td= "#{item['title']} × #{item['quantity']}"
+ td= "$%.2f" % item["value"]
+ tr
+ td Shipping
+ td= "$%.2f" % rate
+ tr
+ td Total
+ td= "$%.2f" % order["value"]
@@ -0,0 +1,17 @@
+- total = retail_rate(rates)
+- cost = body[:items].map { |item| item[:quantity] * item[:value] }.sum
+.half.shipping
+ span Shipping
+ span
+ = rates.first["postage_type"]
+ '
+ strong= "$#{'%.2f' % total}"
+ '
+ = rates.first["delivery_days"]
+ ' days
+
+.half
+ span Total
+ strong= "$#{'%.2f' % (cost + total)}"
+
+input type="hidden" name="amount" value=(cost + total)