diff --git a/basxbread/forms/forms.py b/basxbread/forms/forms.py
index ae45abf0..ba9bd630 100644
--- a/basxbread/forms/forms.py
+++ b/basxbread/forms/forms.py
@@ -240,6 +240,8 @@ def _generate_formset_class(
def _formfield_callback_with_request(field, request, model, instance, cache_querysets):
kwargs = getattr(field, "formfield_kwargs", {})
+ if hasattr(field, "widget"):
+ kwargs["widget"] = field.widget
choices = None
if hasattr(field, "lazy_choices"):
choices = field.lazy_choices(field, request, instance)
@@ -250,6 +252,8 @@ def _formfield_callback_with_request(field, request, model, instance, cache_quer
kwargs["initial"] = field.lazy_initial(field, request, instance)
ret = field.formfield(**kwargs)
+ if hasattr(field, "breadwidget"):
+ ret.breadwidget = field.breadwidget
if isinstance(choices, models.QuerySet):
ret.queryset = choices
diff --git a/basxbread/layout/components/forms/__init__.py b/basxbread/layout/components/forms/__init__.py
index c7461066..81b88c2e 100644
--- a/basxbread/layout/components/forms/__init__.py
+++ b/basxbread/layout/components/forms/__init__.py
@@ -9,6 +9,7 @@
from ..notification import InlineNotification
from .fields import DEFAULT_FORM_CONTEXTNAME, FormField, FormFieldMarker
from .helpers import HelpText, Submit # noqa
+from .widgets import *
class Form(hg.FORM):
diff --git a/basxbread/layout/components/forms/fields.py b/basxbread/layout/components/forms/fields.py
index ce60a2cf..e66ae9d1 100644
--- a/basxbread/layout/components/forms/fields.py
+++ b/basxbread/layout/components/forms/fields.py
@@ -172,6 +172,9 @@ def wrapper(context):
if suggested_widgetclass is not None:
return suggested_widgetclass
+ if hasattr(realform[fieldname].field, "breadwidget"):
+ return realform[fieldname].field.breadwidget
+
# Auto-detection declared by the bread widget has third priority
return (
django2bread_widgetclass(widgetclass, type(realform[fieldname].field))
diff --git a/basxbread/layout/components/forms/widgets.py b/basxbread/layout/components/forms/widgets.py
index dafc0cfc..5f9e8a26 100644
--- a/basxbread/layout/components/forms/widgets.py
+++ b/basxbread/layout/components/forms/widgets.py
@@ -8,6 +8,7 @@
from _strptime import TimeRE
from django.conf import settings
from django.forms import widgets
+from django.urls import reverse
from django.utils import formats
from django.utils.translation import gettext_lazy as _
from phonenumber_field.formfields import PhoneNumberField
@@ -857,9 +858,7 @@ def __init__(
def format_date_value(context):
bfield = hg.resolve_lazy(boundfield, context)
- return bfield.field.widget.format_value(
- hg.resolve_lazy(inputelement_attrs, context).get("value")
- )
+ return bfield.field.widget.format_value(bfield.value())
super().__init__(
hg.DIV(
@@ -1105,6 +1104,112 @@ class LazySelect(Select):
django_widget = django_countries.widgets.LazySelect
+class AjaxSearchWidget(BaseWidget):
+ carbon_input_error_class = "bx--text-input--invalid"
+
+ def __init__(
+ self,
+ label=None,
+ help_text=None,
+ errors=None,
+ inputelement_attrs=None,
+ boundfield=None,
+ **attributes,
+ ):
+ inputelement_attrs = inputelement_attrs or {}
+ searchresult_id = hg.format("{}-searchresult", inputelement_attrs.get("id"))
+ super().__init__(
+ label,
+ hg.DIV(
+ hg.If(
+ getattr(errors, "condition", None),
+ Icon(
+ "warning--filled",
+ size=16,
+ _class="bx--text-input__invalid-icon",
+ ),
+ ),
+ hg.DIV(
+ _("Loading..."),
+ id=hg.format("{}-loader", inputelement_attrs.get("id")),
+ _class="htmx-indicator",
+ style="position: absolute;z-index: 1;right: 8px; pointer-events: none",
+ ),
+ hg.INPUT(type="hidden", lazy_attributes=inputelement_attrs),
+ hg.INPUT(
+ _class=hg.BaseElement(
+ "bx--text-input",
+ hg.If(
+ getattr(errors, "condition", False),
+ " bx--text-input--invalid",
+ ),
+ ),
+ data_invalid=hg.If(getattr(errors, "condition", False), True),
+ name="query",
+ type="text",
+ hx_get=reverse(self.url),
+ hx_trigger="input changed delay:100ms",
+ hx_target=hg.format("#{}", searchresult_id),
+ hx_indicator=hg.format("#{}-loader", inputelement_attrs.get("id")),
+ onfocusin="this.parentElement.nextElementSibling.nextElementSibling.style.display = 'block'",
+ style="padding-right: 2.5rem",
+ ),
+ hg.SCRIPT(
+ hg.mark_safe(
+ """
+ let elem = document.currentScript;
+ document.addEventListener('click', (ev) => {
+ if(!elem.parentElement.parentElement.contains(ev.target))
+ elem.parentElement.nextElementSibling.nextElementSibling.style.display = 'none'
+ });
+
+ document.addEventListener('htmx:load', (ev) => {
+ $$('.result-item', ev.target)._.bind({'click': (e) => {
+ elem.previousElementSibling.previousElementSibling.value = e.target.value;
+ elem.previousElementSibling.value = '';
+ elem.parentElement.nextElementSibling.firstElementChild.innerText = e.target.innerText;
+ elem.parentElement.nextElementSibling.style.display = 'flex';
+ elem.parentElement.nextElementSibling.nextElementSibling.style.display = 'none';
+ }})
+ })"""
+ )
+ ),
+ _class="bx--text-input__field-wrapper",
+ data_invalid=hg.If(getattr(errors, "condition", None), True),
+ ),
+ Tag(
+ hg.F(
+ lambda c: hg.resolve_lazy(boundfield, c).field.to_python(
+ hg.resolve_lazy(boundfield, c).value()
+ )
+ ),
+ can_delete=hg.F(
+ lambda c: not hg.resolve_lazy(boundfield, c).field.required
+ ),
+ style=hg.If(
+ hg.F(lambda c: not hg.resolve_lazy(boundfield, c).value()),
+ "display: none",
+ ),
+ ondelete=hg.format(
+ """document.getElementById('{}').value = ''; this.parentElement.style.display = 'none'""",
+ inputelement_attrs.get("id"),
+ ),
+ ),
+ hg.DIV(
+ hg.SPAN("...", style="padding: 8px"),
+ id=searchresult_id,
+ style="border-left: solid 1px gray; border-right: solid 1px gray; border-bottom: solid 1px gray; background: white; z-index: 99; display: none",
+ ),
+ errors,
+ help_text,
+ **hg.merge_html_attrs(attributes, {"_class": "bx--text-input-wrapper"}),
+ )
+
+
+def AjaxSearch(url):
+ return type("SubclassedAjaxSearchWidget", (AjaxSearchWidget,), {"url": url})
+
+
class MultiWidget(BaseWidget):
django_widget = widgets.MultiWidget
diff --git a/basxbread/layout/components/tag.py b/basxbread/layout/components/tag.py
index 622e90f9..7d07ae57 100644
--- a/basxbread/layout/components/tag.py
+++ b/basxbread/layout/components/tag.py
@@ -27,17 +27,18 @@ def __init__(self, *label, can_delete=False, tag_color=None, **kwargs):
kwargs.setdefault(
"type", "button"
) # prevents this from trying to submit a form when inside a FORM element
- kwargs["_class"] = (
- kwargs.get("_class", "")
- + " bx--tag"
- + (" bx--tag--filter" if can_delete else "")
- + (f" bx--tag--{tag_color}" if tag_color else "")
+ kwargs["_class"] = hg.BaseElement(
+ kwargs.get("_class", ""),
+ " bx--tag",
+ hg.If(can_delete, " bx--tag--filter"),
+ (f" bx--tag--{tag_color}" if tag_color else ""),
)
- if can_delete:
- kwargs.setdefault("title", _("Remove"))
+ on_del = kwargs.pop("ondelete", None)
super().__init__(
hg.SPAN(*label, _class="bx--tag__label"),
- *([Icon("close", size=16)] if can_delete else []),
+ hg.If(
+ can_delete, Icon("close", size=16, onclick=on_del, title=_("Remove"))
+ ),
**kwargs,
)
diff --git a/basxbread/static/js/basxbread.min.js b/basxbread/static/js/basxbread.min.js
index ad95d043..9ac8f377 100644
--- a/basxbread/static/js/basxbread.min.js
+++ b/basxbread/static/js/basxbread.min.js
@@ -1 +1 @@
-(function(root,factory){if(typeof define==="function"&&define.amd){define([],factory)}else{root.htmx=factory()}})(typeof self!=="undefined"?self:this,function(){return function(){"use strict";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,inlineScriptNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",disableSelector:"[hx-disable], [data-hx-disable]",useTemplateFragments:false,scrollBehavior:"smooth",defaultFocusScroll:false},parseInterval:parseInterval,_:internalEval,createEventSource:function(url){return new EventSource(url,{withCredentials:true})},createWebSocket:function(url){return new WebSocket(url,[])},version:"1.7.0"};var internalAPI={bodyContains:bodyContains,filterValues:filterValues,hasAttribute:hasAttribute,getAttributeValue:getAttributeValue,getClosestMatch:getClosestMatch,getExpressionVars:getExpressionVars,getHeaders:getHeaders,getInputValues:getInputValues,getInternalData:getInternalData,getSwapSpecification:getSwapSpecification,getTriggerSpecs:getTriggerSpecs,getTarget:getTarget,makeFragment:makeFragment,mergeObjects:mergeObjects,makeSettleInfo:makeSettleInfo,oobSwap:oobSwap,selectAndSwap:selectAndSwap,settleImmediately:settleImmediately,shouldCancel:shouldCancel,triggerEvent:triggerEvent,triggerErrorEvent:triggerErrorEvent,withExtensions:withExtensions};var VERBS=["get","post","put","delete","patch"];var VERB_SELECTOR=VERBS.map(function(verb){return"[hx-"+verb+"], [data-hx-"+verb+"]"}).join(", ");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))*1e3||undefined}return parseFloat(str)||undefined}function getRawAttribute(elt,name){return elt.getAttribute&&elt.getAttribute(name)}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 getAttributeValueWithDisinheritance(initialElement,ancestor,attributeName){var attributeValue=getAttributeValue(ancestor,attributeName);var disinherit=getAttributeValue(ancestor,"hx-disinherit");if(initialElement!==ancestor&&disinherit&&(disinherit==="*"||disinherit.split(" ").indexOf(attributeName)>=0)){return"unset"}else{return attributeValue}}function getClosestAttributeValue(elt,attributeName){var closestAttr=null;getClosestMatch(elt,function(e){return closestAttr=getAttributeValueWithDisinheritance(elt,e,attributeName)});if(closestAttr!=="unset"){return closestAttr}}function matches(elt,selector){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--;responseNode=responseNode.firstChild}if(responseNode==null){responseNode=getDocument().createDocumentFragment()}return responseNode}function makeFragment(resp){if(htmx.config.useTemplateFragments){var documentFragment=parseHTML("
"+resp+"",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("",1);case"col":return parseHTML("",2);case"tr":return parseHTML("",2);case"td":case"th":return parseHTML("",3);case"script":return parseHTML(""+resp+"
",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=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}}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(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}var DUMMY_ELT=getDocument().createElement("output");function findAttributeTargets(elt,attrName){var attrTarget=getClosestAttributeValue(elt,attrName);if(attrTarget){if(attrTarget==="this"){return[findThisElement(elt,attrName)]}else{var result=querySelectorAllExt(elt,attrTarget);if(result.length===0){logError('The selector "'+attrTarget+'" on '+attrName+" returned no matches!");return[DUMMY_ELT]}else{return result}}}}function findThisElement(elt,attribute){return getClosestMatch(elt,function(elt){return getAttributeValue(elt,attribute)!=null})}function getTarget(elt){var targetStr=getClosestAttributeValue(elt,"hx-target");if(targetStr){if(targetStr==="this"){return findThisElement(elt,"hx-target")}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;i0){swapStyle=oobValue.substr(0,oobValue.indexOf(":"));selector=oobValue.substr(oobValue.indexOf(":")+1,oobValue.length)}else{swapStyle=oobValue}var targets=getDocument().querySelectorAll(selector);if(targets){forEach(targets,function(target){var fragment;var oobElementClone=oobElement.cloneNode(true);fragment=getDocument().createDocumentFragment();fragment.appendChild(oobElementClone);if(!isInlineSwap(swapStyle,target)){fragment=oobElementClone}var beforeSwapDetails={shouldSwap:true,target:target,fragment:fragment};if(!triggerEvent(target,"htmx:oobBeforeSwap",beforeSwapDetails))return;target=beforeSwapDetails.target;if(beforeSwapDetails["shouldSwap"]){swap(swapStyle,target,target,fragment,settleInfo)}forEach(settleInfo.elts,function(elt){triggerEvent(elt,"htmx:oobAfterSwap",beforeSwapDetails)})});oobElement.parentNode.removeChild(oobElement)}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()}triggerEvent(element,"htmx:beforeCleanupElement");if(internalData.listenerInfos){forEach(internalData.listenerInfos,function(info){if(element!==info.on){info.on.removeEventListener(info.trigger,info.listener)}})}if(element.children){forEach(element.children,function(child){cleanUpElement(child)})}}function swapOuterHTML(target,fragment,settleInfo){if(target.tagName==="BODY"){return swapInnerHTML(target,fragment,settleInfo)}else{var newElt;var eltBeforeNewContent=target.previousSibling;insertNodesBefore(parentElt(target),target,fragment,settleInfo);if(eltBeforeNewContent==null){newElt=parentElt(target).firstChild}else{newElt=eltBeforeNewContent.nextSibling}getInternalData(target).replacedWith=newElt;settleInfo.elts=[];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 swapDelete(target,fragment,settleInfo){cleanUpElement(target);return parentElt(target).removeChild(target)}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;case"delete":swapDelete(target,fragment,settleInfo);return;default:var extensions=getExtensions(elt);for(var i=0;i-1){var contentWithSvgsRemoved=content.replace(/",noCalendar:false,now:new Date,onChange:[],onClose:[],onDayCreate:[],onDestroy:[],onKeyDown:[],onMonthChange:[],onOpen:[],onParseConfig:[],onReady:[],onValueUpdate:[],onYearChange:[],onPreCalendarPosition:[],plugins:[],position:"auto",positionElement:undefined,prevArrow:"",shorthandCurrentMonth:false,showMonths:1,static:false,time_24hr:false,weekNumbers:false,wrap:false};var english={weekdays:{shorthand:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],longhand:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},months:{shorthand:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],longhand:["January","February","March","April","May","June","July","August","September","October","November","December"]},daysInMonth:[31,28,31,30,31,30,31,31,30,31,30,31],firstDayOfWeek:0,ordinal:function(nth){var s=nth%100;if(s>3&&s<21)return"th";switch(s%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}},rangeSeparator:" to ",weekAbbreviation:"Wk",scrollTitle:"Scroll to increment",toggleTitle:"Click to toggle",amPM:["AM","PM"],yearAriaLabel:"Year",time_24hr:false};var pad=function(number){return("0"+number).slice(-2)};var int=function(bool){return bool===true?1:0};function debounce(func,wait,immediate){if(immediate===void 0){immediate=false}var timeout;return function(){var context=this,args=arguments;timeout!==null&&clearTimeout(timeout);timeout=window.setTimeout(function(){timeout=null;if(!immediate)func.apply(context,args)},wait);if(immediate&&!timeout)func.apply(context,args)}}var arrayify=function(obj){return obj instanceof Array?obj:[obj]};function toggleClass(elem,className,bool){if(bool===true)return elem.classList.add(className);elem.classList.remove(className)}function createElement(tag,className,content){var e=window.document.createElement(tag);className=className||"";content=content||"";e.className=className;if(content!==undefined)e.textContent=content;return e}function clearNode(node){while(node.firstChild)node.removeChild(node.firstChild)}function findParent(node,condition){if(condition(node))return node;else if(node.parentNode)return findParent(node.parentNode,condition);return undefined}function createNumberInput(inputClassName,opts){var wrapper=createElement("div","numInputWrapper"),numInput=createElement("input","numInput "+inputClassName),arrowUp=createElement("span","arrowUp"),arrowDown=createElement("span","arrowDown");if(navigator.userAgent.indexOf("MSIE 9.0")===-1){numInput.type="number"}else{numInput.type="text";numInput.pattern="\\d*"}if(opts!==undefined)for(var key in opts)numInput.setAttribute(key,opts[key]);wrapper.appendChild(numInput);wrapper.appendChild(arrowUp);wrapper.appendChild(arrowDown);return wrapper}function getEventTarget(event){if(typeof event.composedPath==="function"){var path=event.composedPath();return path[0]}return event.target}var doNothing=function(){return undefined};var monthToStr=function(monthNumber,shorthand,locale){return locale.months[shorthand?"shorthand":"longhand"][monthNumber]};var revFormat={D:doNothing,F:function(dateObj,monthName,locale){dateObj.setMonth(locale.months.longhand.indexOf(monthName))},G:function(dateObj,hour){dateObj.setHours(parseFloat(hour))},H:function(dateObj,hour){dateObj.setHours(parseFloat(hour))},J:function(dateObj,day){dateObj.setDate(parseFloat(day))},K:function(dateObj,amPM,locale){dateObj.setHours(dateObj.getHours()%12+12*int(new RegExp(locale.amPM[1],"i").test(amPM)))},M:function(dateObj,shortMonth,locale){dateObj.setMonth(locale.months.shorthand.indexOf(shortMonth))},S:function(dateObj,seconds){dateObj.setSeconds(parseFloat(seconds))},U:function(_,unixSeconds){return new Date(parseFloat(unixSeconds)*1e3)},W:function(dateObj,weekNum,locale){var weekNumber=parseInt(weekNum);var date=new Date(dateObj.getFullYear(),0,2+(weekNumber-1)*7,0,0,0,0);date.setDate(date.getDate()-date.getDay()+locale.firstDayOfWeek);return date},Y:function(dateObj,year){dateObj.setFullYear(parseFloat(year))},Z:function(_,ISODate){return new Date(ISODate)},d:function(dateObj,day){dateObj.setDate(parseFloat(day))},h:function(dateObj,hour){dateObj.setHours(parseFloat(hour))},i:function(dateObj,minutes){dateObj.setMinutes(parseFloat(minutes))},j:function(dateObj,day){dateObj.setDate(parseFloat(day))},l:doNothing,m:function(dateObj,month){dateObj.setMonth(parseFloat(month)-1)},n:function(dateObj,month){dateObj.setMonth(parseFloat(month)-1)},s:function(dateObj,seconds){dateObj.setSeconds(parseFloat(seconds))},u:function(_,unixMillSeconds){return new Date(parseFloat(unixMillSeconds))},w:doNothing,y:function(dateObj,year){dateObj.setFullYear(2e3+parseFloat(year))}};var tokenRegex={D:"(\\w+)",F:"(\\w+)",G:"(\\d\\d|\\d)",H:"(\\d\\d|\\d)",J:"(\\d\\d|\\d)\\w+",K:"",M:"(\\w+)",S:"(\\d\\d|\\d)",U:"(.+)",W:"(\\d\\d|\\d)",Y:"(\\d{4})",Z:"(.+)",d:"(\\d\\d|\\d)",h:"(\\d\\d|\\d)",i:"(\\d\\d|\\d)",j:"(\\d\\d|\\d)",l:"(\\w+)",m:"(\\d\\d|\\d)",n:"(\\d\\d|\\d)",s:"(\\d\\d|\\d)",u:"(.+)",w:"(\\d\\d|\\d)",y:"(\\d{2})"};var formats={Z:function(date){return date.toISOString()},D:function(date,locale,options){return locale.weekdays.shorthand[formats.w(date,locale,options)]},F:function(date,locale,options){return monthToStr(formats.n(date,locale,options)-1,false,locale)},G:function(date,locale,options){return pad(formats.h(date,locale,options))},H:function(date){return pad(date.getHours())},J:function(date,locale){return locale.ordinal!==undefined?date.getDate()+locale.ordinal(date.getDate()):date.getDate()},K:function(date,locale){return locale.amPM[int(date.getHours()>11)]},M:function(date,locale){return monthToStr(date.getMonth(),true,locale)},S:function(date){return pad(date.getSeconds())},U:function(date){return date.getTime()/1e3},W:function(date,_,options){return options.getWeek(date)},Y:function(date){return date.getFullYear()},d:function(date){return pad(date.getDate())},h:function(date){return date.getHours()%12?date.getHours()%12:12},i:function(date){return pad(date.getMinutes())},j:function(date){return date.getDate()},l:function(date,locale){return locale.weekdays.longhand[date.getDay()]},m:function(date){return pad(date.getMonth()+1)},n:function(date){return date.getMonth()+1},s:function(date){return date.getSeconds()},u:function(date){return date.getTime()},w:function(date){return date.getDay()},y:function(date){return String(date.getFullYear()).substring(2)}};var createDateFormatter=function(_a){var _b=_a.config,config=_b===void 0?defaults:_b,_c=_a.l10n,l10n=_c===void 0?english:_c;return function(dateObj,frmt,overrideLocale){var locale=overrideLocale||l10n;if(config.formatDate!==undefined){return config.formatDate(dateObj,frmt,locale)}return frmt.split("").map(function(c,i,arr){return formats[c]&&arr[i-1]!=="\\"?formats[c](dateObj,locale,config):c!=="\\"?c:""}).join("")}};var createDateParser=function(_a){var _b=_a.config,config=_b===void 0?defaults:_b,_c=_a.l10n,l10n=_c===void 0?english:_c;return function(date,givenFormat,timeless,customLocale){if(date!==0&&!date)return undefined;var locale=customLocale||l10n;var parsedDate;var dateOrig=date;if(date instanceof Date)parsedDate=new Date(date.getTime());else if(typeof date!=="string"&&date.toFixed!==undefined)parsedDate=new Date(date);else if(typeof date==="string"){var format=givenFormat||(config||defaults).dateFormat;var datestr=String(date).trim();if(datestr==="today"){parsedDate=new Date;timeless=true}else if(/Z$/.test(datestr)||/GMT$/.test(datestr))parsedDate=new Date(date);else if(config&&config.parseDate)parsedDate=config.parseDate(date,format);else{parsedDate=!config||!config.noCalendar?new Date((new Date).getFullYear(),0,1,0,0,0,0):new Date((new Date).setHours(0,0,0,0));var matched=void 0,ops=[];for(var i=0,matchIndex=0,regexStr="";iMath.min(ts1,ts2)&&ts0||self.config.noCalendar;var isSafari=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);if(!self.isMobile&&isSafari){positionCalendar()}triggerEvent("onReady")}function bindToInstance(fn){return fn.bind(self)}function setCalendarWidth(){var config=self.config;if(config.weekNumbers===false&&config.showMonths===1)return;else if(config.noCalendar!==true){window.requestAnimationFrame(function(){if(self.calendarContainer!==undefined){self.calendarContainer.style.visibility="hidden";self.calendarContainer.style.display="block"}if(self.daysContainer!==undefined){var daysWidth=(self.days.offsetWidth+1)*config.showMonths;self.daysContainer.style.width=daysWidth+"px";self.calendarContainer.style.width=daysWidth+(self.weekWrapper!==undefined?self.weekWrapper.offsetWidth:0)+"px";self.calendarContainer.style.removeProperty("visibility");self.calendarContainer.style.removeProperty("display")}})}}function updateTime(e){if(self.selectedDates.length===0){setDefaultTime()}if(e!==undefined&&e.type!=="blur"){timeWrapper(e)}var prevValue=self._input.value;setHoursFromInputs();updateValue();if(self._input.value!==prevValue){self._debouncedChange()}}function ampm2military(hour,amPM){return hour%12+12*int(amPM===self.l10n.amPM[1])}function military2ampm(hour){switch(hour%24){case 0:case 12:return 12;default:return hour%12}}function setHoursFromInputs(){if(self.hourElement===undefined||self.minuteElement===undefined)return;var hours=(parseInt(self.hourElement.value.slice(-2),10)||0)%24,minutes=(parseInt(self.minuteElement.value,10)||0)%60,seconds=self.secondElement!==undefined?(parseInt(self.secondElement.value,10)||0)%60:0;if(self.amPM!==undefined){hours=ampm2military(hours,self.amPM.textContent)}var limitMinHours=self.config.minTime!==undefined||self.config.minDate&&self.minDateHasTime&&self.latestSelectedDateObj&&compareDates(self.latestSelectedDateObj,self.config.minDate,true)===0;var limitMaxHours=self.config.maxTime!==undefined||self.config.maxDate&&self.maxDateHasTime&&self.latestSelectedDateObj&&compareDates(self.latestSelectedDateObj,self.config.maxDate,true)===0;if(limitMaxHours){var maxTime=self.config.maxTime!==undefined?self.config.maxTime:self.config.maxDate;hours=Math.min(hours,maxTime.getHours());if(hours===maxTime.getHours())minutes=Math.min(minutes,maxTime.getMinutes());if(minutes===maxTime.getMinutes())seconds=Math.min(seconds,maxTime.getSeconds())}if(limitMinHours){var minTime=self.config.minTime!==undefined?self.config.minTime:self.config.minDate;hours=Math.max(hours,minTime.getHours());if(hours===minTime.getHours())minutes=Math.max(minutes,minTime.getMinutes());if(minutes===minTime.getMinutes())seconds=Math.max(seconds,minTime.getSeconds())}setHours(hours,minutes,seconds)}function setHoursFromDate(dateObj){var date=dateObj||self.latestSelectedDateObj;if(date)setHours(date.getHours(),date.getMinutes(),date.getSeconds())}function setDefaultHours(){var hours=self.config.defaultHour;var minutes=self.config.defaultMinute;var seconds=self.config.defaultSeconds;if(self.config.minDate!==undefined){var minHr=self.config.minDate.getHours();var minMinutes=self.config.minDate.getMinutes();hours=Math.max(hours,minHr);if(hours===minHr)minutes=Math.max(minMinutes,minutes);if(hours===minHr&&minutes===minMinutes)seconds=self.config.minDate.getSeconds()}if(self.config.maxDate!==undefined){var maxHr=self.config.maxDate.getHours();var maxMinutes=self.config.maxDate.getMinutes();hours=Math.min(hours,maxHr);if(hours===maxHr)minutes=Math.min(maxMinutes,minutes);if(hours===maxHr&&minutes===maxMinutes)seconds=self.config.maxDate.getSeconds()}setHours(hours,minutes,seconds)}function setHours(hours,minutes,seconds){if(self.latestSelectedDateObj!==undefined){self.latestSelectedDateObj.setHours(hours%24,minutes,seconds||0,0)}if(!self.hourElement||!self.minuteElement||self.isMobile)return;self.hourElement.value=pad(!self.config.time_24hr?(12+hours)%12+12*int(hours%12===0):hours);self.minuteElement.value=pad(minutes);if(self.amPM!==undefined)self.amPM.textContent=self.l10n.amPM[int(hours>=12)];if(self.secondElement!==undefined)self.secondElement.value=pad(seconds)}function onYearInput(event){var year=parseInt(event.target.value)+(event.delta||0);if(year/1e3>1||event.key==="Enter"&&!/[^\d]/.test(year.toString())){changeYear(year)}}function bind(element,event,handler,options){if(event instanceof Array)return event.forEach(function(ev){return bind(element,ev,handler,options)});if(element instanceof Array)return element.forEach(function(el){return bind(el,event,handler,options)});element.addEventListener(event,handler,options);self._handlers.push({element:element,event:event,handler:handler,options:options})}function onClick(handler){return function(evt){evt.which===1&&handler(evt)}}function triggerChange(){triggerEvent("onChange")}function bindEvents(){if(self.config.wrap){["open","close","toggle","clear"].forEach(function(evt){Array.prototype.forEach.call(self.element.querySelectorAll("[data-"+evt+"]"),function(el){return bind(el,"click",self[evt])})})}if(self.isMobile){setupMobile();return}var debouncedResize=debounce(onResize,50);self._debouncedChange=debounce(triggerChange,DEBOUNCED_CHANGE_MS);if(self.daysContainer&&!/iPhone|iPad|iPod/i.test(navigator.userAgent))bind(self.daysContainer,"mouseover",function(e){if(self.config.mode==="range")onMouseOver(e.target)});bind(window.document.body,"keydown",onKeyDown);if(!self.config.inline&&!self.config.static)bind(window,"resize",debouncedResize);if(window.ontouchstart!==undefined)bind(window.document,"touchstart",documentClick);else bind(window.document,"mousedown",onClick(documentClick));bind(window.document,"focus",documentClick,{capture:true});if(self.config.clickOpens===true){bind(self._input,"focus",self.open);bind(self._input,"mousedown",onClick(self.open))}if(self.daysContainer!==undefined){bind(self.monthNav,"mousedown",onClick(onMonthNavClick));bind(self.monthNav,["keyup","increment"],onYearInput);bind(self.daysContainer,"mousedown",onClick(selectDate))}if(self.timeContainer!==undefined&&self.minuteElement!==undefined&&self.hourElement!==undefined){var selText=function(e){return e.target.select()};bind(self.timeContainer,["increment"],updateTime);bind(self.timeContainer,"blur",updateTime,{capture:true});bind(self.timeContainer,"mousedown",onClick(timeIncrement));bind([self.hourElement,self.minuteElement],["focus","click"],selText);if(self.secondElement!==undefined)bind(self.secondElement,"focus",function(){return self.secondElement&&self.secondElement.select()});if(self.amPM!==undefined){bind(self.amPM,"mousedown",onClick(function(e){updateTime(e);triggerChange()}))}}}function jumpToDate(jumpDate,triggerChange){var jumpTo=jumpDate!==undefined?self.parseDate(jumpDate):self.latestSelectedDateObj||(self.config.minDate&&self.config.minDate>self.now?self.config.minDate:self.config.maxDate&&self.config.maxDate1);self.calendarContainer.appendChild(fragment);var customAppend=self.config.appendTo!==undefined&&self.config.appendTo.nodeType!==undefined;if(self.config.inline||self.config.static){self.calendarContainer.classList.add(self.config.inline?"inline":"static");if(self.config.inline){if(!customAppend&&self.element.parentNode)self.element.parentNode.insertBefore(self.calendarContainer,self._input.nextSibling);else if(self.config.appendTo!==undefined)self.config.appendTo.appendChild(self.calendarContainer)}if(self.config.static){var wrapper=createElement("div","flatpickr-wrapper");if(self.element.parentNode)self.element.parentNode.insertBefore(wrapper,self.element);wrapper.appendChild(self.element);if(self.altInput)wrapper.appendChild(self.altInput);wrapper.appendChild(self.calendarContainer)}}if(!self.config.static&&!self.config.inline)(self.config.appendTo!==undefined?self.config.appendTo:window.document.body).appendChild(self.calendarContainer)}function createDay(className,date,dayNumber,i){var dateIsEnabled=isEnabled(date,true),dayElement=createElement("span","flatpickr-day "+className,date.getDate().toString());dayElement.dateObj=date;dayElement.$i=i;dayElement.setAttribute("aria-label",self.formatDate(date,self.config.ariaDateFormat));if(className.indexOf("hidden")===-1&&compareDates(date,self.now)===0){self.todayDateElem=dayElement;dayElement.classList.add("today");dayElement.setAttribute("aria-current","date")}if(dateIsEnabled){dayElement.tabIndex=-1;if(isDateSelected(date)){dayElement.classList.add("selected");self.selectedDateElem=dayElement;if(self.config.mode==="range"){toggleClass(dayElement,"startRange",self.selectedDates[0]&&compareDates(date,self.selectedDates[0],true)===0);toggleClass(dayElement,"endRange",self.selectedDates[1]&&compareDates(date,self.selectedDates[1],true)===0);if(className==="nextMonthDay")dayElement.classList.add("inRange")}}}else{dayElement.classList.add("flatpickr-disabled")}if(self.config.mode==="range"){if(isDateInRange(date)&&!isDateSelected(date))dayElement.classList.add("inRange")}if(self.weekNumbers&&self.config.showMonths===1&&className!=="prevMonthDay"&&dayNumber%7===1){self.weekNumbers.insertAdjacentHTML("beforeend",""+self.config.getWeek(date)+"")}triggerEvent("onDayCreate",dayElement);return dayElement}function focusOnDayElem(targetNode){targetNode.focus();if(self.config.mode==="range")onMouseOver(targetNode)}function getFirstAvailableDay(delta){var startMonth=delta>0?0:self.config.showMonths-1;var endMonth=delta>0?self.config.showMonths:-1;for(var m=startMonth;m!=endMonth;m+=delta){var month=self.daysContainer.children[m];var startIndex=delta>0?0:month.children.length-1;var endIndex=delta>0?month.children.length:-1;for(var i=startIndex;i!=endIndex;i+=delta){var c=month.children[i];if(c.className.indexOf("hidden")===-1&&isEnabled(c.dateObj))return c}}return undefined}function getNextAvailableDay(current,delta){var givenMonth=current.className.indexOf("Month")===-1?current.dateObj.getMonth():self.currentMonth;var endMonth=delta>0?self.config.showMonths:-1;var loopDelta=delta>0?1:-1;for(var m=givenMonth-self.currentMonth;m!=endMonth;m+=loopDelta){var month=self.daysContainer.children[m];var startIndex=givenMonth-self.currentMonth===m?current.$i+delta:delta<0?month.children.length-1:0;var numMonthDays=month.children.length;for(var i=startIndex;i>=0&&i0?numMonthDays:-1);i+=loopDelta){var c=month.children[i];if(c.className.indexOf("hidden")===-1&&isEnabled(c.dateObj)&&Math.abs(current.$i-i)>=Math.abs(delta))return focusOnDayElem(c)}}self.changeMonth(loopDelta);focusOnDay(getFirstAvailableDay(loopDelta),0);return undefined}function focusOnDay(current,offset){var dayFocused=isInView(document.activeElement||document.body);var startElem=current!==undefined?current:dayFocused?document.activeElement:self.selectedDateElem!==undefined&&isInView(self.selectedDateElem)?self.selectedDateElem:self.todayDateElem!==undefined&&isInView(self.todayDateElem)?self.todayDateElem:getFirstAvailableDay(offset>0?1:-1);if(startElem===undefined)return self._input.focus();if(!dayFocused)return focusOnDayElem(startElem);getNextAvailableDay(startElem,offset)}function buildMonthDays(year,month){var firstOfMonth=(new Date(year,month,1).getDay()-self.l10n.firstDayOfWeek+7)%7;var prevMonthDays=self.utils.getDaysInMonth((month-1+12)%12);var daysInMonth=self.utils.getDaysInMonth(month),days=window.document.createDocumentFragment(),isMultiMonth=self.config.showMonths>1,prevMonthDayClass=isMultiMonth?"prevMonthDay hidden":"prevMonthDay",nextMonthDayClass=isMultiMonth?"nextMonthDay hidden":"nextMonthDay";var dayNumber=prevMonthDays+1-firstOfMonth,dayIndex=0;for(;dayNumber<=prevMonthDays;dayNumber++,dayIndex++){days.appendChild(createDay(prevMonthDayClass,new Date(year,month-1,dayNumber),dayNumber,dayIndex))}for(dayNumber=1;dayNumber<=daysInMonth;dayNumber++,dayIndex++){days.appendChild(createDay("",new Date(year,month,dayNumber),dayNumber,dayIndex))}for(var dayNum=daysInMonth+1;dayNum<=42-firstOfMonth&&(self.config.showMonths===1||dayIndex%7!==0);dayNum++,dayIndex++){days.appendChild(createDay(nextMonthDayClass,new Date(year,month+1,dayNum%daysInMonth),dayNum,dayIndex))}var dayContainer=createElement("div","dayContainer");dayContainer.appendChild(days);return dayContainer}function buildDays(){if(self.daysContainer===undefined){return}clearNode(self.daysContainer);if(self.weekNumbers)clearNode(self.weekNumbers);var frag=document.createDocumentFragment();for(var i=0;i1)return;var shouldBuildMonth=function(month){if(self.config.minDate!==undefined&&self.currentYear===self.config.minDate.getFullYear()&&monthself.config.maxDate.getMonth())};self.monthsDropdownContainer.tabIndex=-1;self.monthsDropdownContainer.innerHTML="";for(var i=0;i<12;i++){if(!shouldBuildMonth(i))continue;var month=createElement("option","flatpickr-monthDropdown-month");month.value=new Date(self.currentYear,i).getMonth().toString();month.textContent=monthToStr(i,false,self.l10n);month.tabIndex=-1;if(self.currentMonth===i){month.selected=true}self.monthsDropdownContainer.appendChild(month)}}function buildMonth(){var container=createElement("div","flatpickr-month");var monthNavFragment=window.document.createDocumentFragment();var monthElement;if(self.config.showMonths>1){monthElement=createElement("span","cur-month")}else{self.monthsDropdownContainer=createElement("select","flatpickr-monthDropdown-months");bind(self.monthsDropdownContainer,"change",function(e){var target=e.target;var selectedMonth=parseInt(target.value,10);self.changeMonth(selectedMonth-self.currentMonth);triggerEvent("onMonthChange")});buildMonthSwitch();monthElement=self.monthsDropdownContainer}var yearInput=createNumberInput("cur-year",{tabindex:"-1"});var yearElement=yearInput.getElementsByTagName("input")[0];yearElement.setAttribute("aria-label",self.l10n.yearAriaLabel);if(self.config.minDate){yearElement.setAttribute("min",self.config.minDate.getFullYear().toString())}if(self.config.maxDate){yearElement.setAttribute("max",self.config.maxDate.getFullYear().toString());yearElement.disabled=!!self.config.minDate&&self.config.minDate.getFullYear()===self.config.maxDate.getFullYear()}var currentMonth=createElement("div","flatpickr-current-month");currentMonth.appendChild(monthElement);currentMonth.appendChild(yearInput);monthNavFragment.appendChild(currentMonth);container.appendChild(monthNavFragment);return{container:container,yearElement:yearElement,monthElement:monthElement}}function buildMonths(){clearNode(self.monthNav);self.monthNav.appendChild(self.prevMonthNav);if(self.config.showMonths){self.yearElements=[];self.monthElements=[]}for(var m=self.config.showMonths;m--;){var month=buildMonth();self.yearElements.push(month.yearElement);self.monthElements.push(month.monthElement);self.monthNav.appendChild(month.container)}self.monthNav.appendChild(self.nextMonthNav)}function buildMonthNav(){self.monthNav=createElement("div","flatpickr-months");self.yearElements=[];self.monthElements=[];self.prevMonthNav=createElement("span","flatpickr-prev-month");self.prevMonthNav.innerHTML=self.config.prevArrow;self.nextMonthNav=createElement("span","flatpickr-next-month");self.nextMonthNav.innerHTML=self.config.nextArrow;buildMonths();Object.defineProperty(self,"_hidePrevMonthArrow",{get:function(){return self.__hidePrevMonthArrow},set:function(bool){if(self.__hidePrevMonthArrow!==bool){toggleClass(self.prevMonthNav,"flatpickr-disabled",bool);self.__hidePrevMonthArrow=bool}}});Object.defineProperty(self,"_hideNextMonthArrow",{get:function(){return self.__hideNextMonthArrow},set:function(bool){if(self.__hideNextMonthArrow!==bool){toggleClass(self.nextMonthNav,"flatpickr-disabled",bool);self.__hideNextMonthArrow=bool}}});self.currentYearElement=self.yearElements[0];updateNavigationCurrentMonth();return self.monthNav}function buildTime(){self.calendarContainer.classList.add("hasTime");if(self.config.noCalendar)self.calendarContainer.classList.add("noCalendar");self.timeContainer=createElement("div","flatpickr-time");self.timeContainer.tabIndex=-1;var separator=createElement("span","flatpickr-time-separator",":");var hourInput=createNumberInput("flatpickr-hour");self.hourElement=hourInput.getElementsByTagName("input")[0];var minuteInput=createNumberInput("flatpickr-minute");self.minuteElement=minuteInput.getElementsByTagName("input")[0];self.hourElement.tabIndex=self.minuteElement.tabIndex=-1;self.hourElement.value=pad(self.latestSelectedDateObj?self.latestSelectedDateObj.getHours():self.config.time_24hr?self.config.defaultHour:military2ampm(self.config.defaultHour));self.minuteElement.value=pad(self.latestSelectedDateObj?self.latestSelectedDateObj.getMinutes():self.config.defaultMinute);self.hourElement.setAttribute("step",self.config.hourIncrement.toString());self.minuteElement.setAttribute("step",self.config.minuteIncrement.toString());self.hourElement.setAttribute("min",self.config.time_24hr?"0":"1");self.hourElement.setAttribute("max",self.config.time_24hr?"23":"12");self.minuteElement.setAttribute("min","0");self.minuteElement.setAttribute("max","59");self.timeContainer.appendChild(hourInput);self.timeContainer.appendChild(separator);self.timeContainer.appendChild(minuteInput);if(self.config.time_24hr)self.timeContainer.classList.add("time24hr");if(self.config.enableSeconds){self.timeContainer.classList.add("hasSeconds");var secondInput=createNumberInput("flatpickr-second");self.secondElement=secondInput.getElementsByTagName("input")[0];self.secondElement.value=pad(self.latestSelectedDateObj?self.latestSelectedDateObj.getSeconds():self.config.defaultSeconds);self.secondElement.setAttribute("step",self.minuteElement.getAttribute("step"));self.secondElement.setAttribute("min","0");self.secondElement.setAttribute("max","59");self.timeContainer.appendChild(createElement("span","flatpickr-time-separator",":"));self.timeContainer.appendChild(secondInput)}if(!self.config.time_24hr){self.amPM=createElement("span","flatpickr-am-pm",self.l10n.amPM[int((self.latestSelectedDateObj?self.hourElement.value:self.config.defaultHour)>11)]);self.amPM.title=self.l10n.toggleTitle;self.amPM.tabIndex=-1;self.timeContainer.appendChild(self.amPM)}return self.timeContainer}function buildWeekdays(){if(!self.weekdayContainer)self.weekdayContainer=createElement("div","flatpickr-weekdays");else clearNode(self.weekdayContainer);for(var i=self.config.showMonths;i--;){var container=createElement("div","flatpickr-weekdaycontainer");self.weekdayContainer.appendChild(container)}updateWeekdays();return self.weekdayContainer}function updateWeekdays(){var firstDayOfWeek=self.l10n.firstDayOfWeek;var weekdays=self.l10n.weekdays.shorthand.slice();if(firstDayOfWeek>0&&firstDayOfWeek\n "+weekdays.join("")+"\n \n "}}function buildWeeks(){self.calendarContainer.classList.add("hasWeeks");var weekWrapper=createElement("div","flatpickr-weekwrapper");weekWrapper.appendChild(createElement("span","flatpickr-weekday",self.l10n.weekAbbreviation));var weekNumbers=createElement("div","flatpickr-weeks");weekWrapper.appendChild(weekNumbers);return{weekWrapper:weekWrapper,weekNumbers:weekNumbers}}function changeMonth(value,isOffset){if(isOffset===void 0){isOffset=true}var delta=isOffset?value:value-self.currentMonth;if(delta<0&&self._hidePrevMonthArrow===true||delta>0&&self._hideNextMonthArrow===true)return;self.currentMonth+=delta;if(self.currentMonth<0||self.currentMonth>11){self.currentYear+=self.currentMonth>11?1:-1;self.currentMonth=(self.currentMonth+12)%12;triggerEvent("onYearChange");buildMonthSwitch()}buildDays();triggerEvent("onMonthChange");updateNavigationCurrentMonth()}function clear(triggerChangeEvent,toInitial){if(triggerChangeEvent===void 0){triggerChangeEvent=true}if(toInitial===void 0){toInitial=true}self.input.value="";if(self.altInput!==undefined)self.altInput.value="";if(self.mobileInput!==undefined)self.mobileInput.value="";self.selectedDates=[];self.latestSelectedDateObj=undefined;if(toInitial===true){self.currentYear=self._initialDate.getFullYear();self.currentMonth=self._initialDate.getMonth()}self.showTimeInput=false;if(self.config.enableTime===true){setDefaultHours()}self.redraw();if(triggerChangeEvent)triggerEvent("onChange")}function close(){self.isOpen=false;if(!self.isMobile){if(self.calendarContainer!==undefined){self.calendarContainer.classList.remove("open")}if(self._input!==undefined){self._input.classList.remove("active")}}triggerEvent("onClose")}function destroy(){if(self.config!==undefined)triggerEvent("onDestroy");for(var i=self._handlers.length;i--;){var h=self._handlers[i];h.element.removeEventListener(h.event,h.handler,h.options)}self._handlers=[];if(self.mobileInput){if(self.mobileInput.parentNode)self.mobileInput.parentNode.removeChild(self.mobileInput);self.mobileInput=undefined}else if(self.calendarContainer&&self.calendarContainer.parentNode){if(self.config.static&&self.calendarContainer.parentNode){var wrapper=self.calendarContainer.parentNode;wrapper.lastChild&&wrapper.removeChild(wrapper.lastChild);if(wrapper.parentNode){while(wrapper.firstChild)wrapper.parentNode.insertBefore(wrapper.firstChild,wrapper);wrapper.parentNode.removeChild(wrapper)}}else self.calendarContainer.parentNode.removeChild(self.calendarContainer)}if(self.altInput){self.input.type="text";if(self.altInput.parentNode)self.altInput.parentNode.removeChild(self.altInput);delete self.altInput}if(self.input){self.input.type=self.input._type;self.input.classList.remove("flatpickr-input");self.input.removeAttribute("readonly");self.input.value=""}["_showTimeInput","latestSelectedDateObj","_hideNextMonthArrow","_hidePrevMonthArrow","__hideNextMonthArrow","__hidePrevMonthArrow","isMobile","isOpen","selectedDateElem","minDateHasTime","maxDateHasTime","days","daysContainer","_input","_positionElement","innerContainer","rContainer","monthNav","todayDateElem","calendarContainer","weekdayContainer","prevMonthNav","nextMonthNav","monthsDropdownContainer","currentMonthElement","currentYearElement","navigationCurrentMonth","selectedDateElem","config"].forEach(function(k){try{delete self[k]}catch(_){}})}function isCalendarElem(elem){if(self.config.appendTo&&self.config.appendTo.contains(elem))return true;return self.calendarContainer.contains(elem)}function documentClick(e){if(self.isOpen&&!self.config.inline){var eventTarget_1=getEventTarget(e);var isCalendarElement=isCalendarElem(eventTarget_1);var isInput=eventTarget_1===self.input||eventTarget_1===self.altInput||self.element.contains(eventTarget_1)||e.path&&e.path.indexOf&&(~e.path.indexOf(self.input)||~e.path.indexOf(self.altInput));var lostFocus=e.type==="blur"?isInput&&e.relatedTarget&&!isCalendarElem(e.relatedTarget):!isInput&&!isCalendarElement&&!isCalendarElem(e.relatedTarget);var isIgnored=!self.config.ignoredFocusElements.some(function(elem){return elem.contains(eventTarget_1)});if(lostFocus&&isIgnored){self.close();if(self.config.mode==="range"&&self.selectedDates.length===1){self.clear(false);self.redraw()}}}}function changeYear(newYear){if(!newYear||self.config.minDate&&newYearself.config.maxDate.getFullYear())return;var newYearNum=newYear,isNewYear=self.currentYear!==newYearNum;self.currentYear=newYearNum||self.currentYear;if(self.config.maxDate&&self.currentYear===self.config.maxDate.getFullYear()){self.currentMonth=Math.min(self.config.maxDate.getMonth(),self.currentMonth)}else if(self.config.minDate&&self.currentYear===self.config.minDate.getFullYear()){self.currentMonth=Math.max(self.config.minDate.getMonth(),self.currentMonth)}if(isNewYear){self.redraw();triggerEvent("onYearChange");buildMonthSwitch()}}function isEnabled(date,timeless){if(timeless===void 0){timeless=true}var dateToCheck=self.parseDate(date,undefined,timeless);if(self.config.minDate&&dateToCheck&&compareDates(dateToCheck,self.config.minDate,timeless!==undefined?timeless:!self.minDateHasTime)<0||self.config.maxDate&&dateToCheck&&compareDates(dateToCheck,self.config.maxDate,timeless!==undefined?timeless:!self.maxDateHasTime)>0)return false;if(self.config.enable.length===0&&self.config.disable.length===0)return true;if(dateToCheck===undefined)return false;var bool=self.config.enable.length>0,array=bool?self.config.enable:self.config.disable;for(var i=0,d=void 0;i=d.from.getTime()&&dateToCheck.getTime()<=d.to.getTime())return bool}return!bool}function isInView(elem){if(self.daysContainer!==undefined)return elem.className.indexOf("hidden")===-1&&self.daysContainer.contains(elem);return false}function onKeyDown(e){var isInput=e.target===self._input;var allowInput=self.config.allowInput;var allowKeydown=self.isOpen&&(!allowInput||!isInput);var allowInlineKeydown=self.config.inline&&isInput&&!allowInput;if(e.keyCode===13&&isInput){if(allowInput){self.setDate(self._input.value,true,e.target===self.altInput?self.config.altFormat:self.config.dateFormat);return e.target.blur()}else{self.open()}}else if(isCalendarElem(e.target)||allowKeydown||allowInlineKeydown){var isTimeObj=!!self.timeContainer&&self.timeContainer.contains(e.target);switch(e.keyCode){case 13:if(isTimeObj){e.preventDefault();updateTime();focusAndClose()}else selectDate(e);break;case 27:e.preventDefault();focusAndClose();break;case 8:case 46:if(isInput&&!self.config.allowInput){e.preventDefault();self.clear()}break;case 37:case 39:if(!isTimeObj&&!isInput){e.preventDefault();if(self.daysContainer!==undefined&&(allowInput===false||document.activeElement&&isInView(document.activeElement))){var delta_1=e.keyCode===39?1:-1;if(!e.ctrlKey)focusOnDay(undefined,delta_1);else{e.stopPropagation();changeMonth(delta_1);focusOnDay(getFirstAvailableDay(1),0)}}}else if(self.hourElement)self.hourElement.focus();break;case 38:case 40:e.preventDefault();var delta=e.keyCode===40?1:-1;if(self.daysContainer&&e.target.$i!==undefined||e.target===self.input){if(e.ctrlKey){e.stopPropagation();changeYear(self.currentYear-delta);focusOnDay(getFirstAvailableDay(1),0)}else if(!isTimeObj)focusOnDay(undefined,delta*7)}else if(e.target===self.currentYearElement){changeYear(self.currentYear-delta)}else if(self.config.enableTime){if(!isTimeObj&&self.hourElement)self.hourElement.focus();updateTime(e);self._debouncedChange()}break;case 9:if(isTimeObj){var elems=[self.hourElement,self.minuteElement,self.secondElement,self.amPM].concat(self.pluginElements).filter(function(x){return x});var i=elems.indexOf(e.target);if(i!==-1){var target=elems[i+(e.shiftKey?-1:1)];e.preventDefault();(target||self._input).focus()}}else if(!self.config.noCalendar&&self.daysContainer&&self.daysContainer.contains(e.target)&&e.shiftKey){e.preventDefault();self._input.focus()}break}}if(self.amPM!==undefined&&e.target===self.amPM){switch(e.key){case self.l10n.amPM[0].charAt(0):case self.l10n.amPM[0].charAt(0).toLowerCase():self.amPM.textContent=self.l10n.amPM[0];setHoursFromInputs();updateValue();break;case self.l10n.amPM[1].charAt(0):case self.l10n.amPM[1].charAt(0).toLowerCase():self.amPM.textContent=self.l10n.amPM[1];setHoursFromInputs();updateValue();break}}if(isInput||isCalendarElem(e.target)){triggerEvent("onKeyDown",e)}}function onMouseOver(elem){if(self.selectedDates.length!==1||elem&&(!elem.classList.contains("flatpickr-day")||elem.classList.contains("flatpickr-disabled")))return;var hoverDate=elem?elem.dateObj.getTime():self.days.firstElementChild.dateObj.getTime(),initialDate=self.parseDate(self.selectedDates[0],undefined,true).getTime(),rangeStartDate=Math.min(hoverDate,self.selectedDates[0].getTime()),rangeEndDate=Math.max(hoverDate,self.selectedDates[0].getTime());var containsDisabled=false;var minRange=0,maxRange=0;for(var t=rangeStartDate;trangeStartDate&&tminRange))minRange=t;else if(t>initialDate&&(!maxRange||t0&×tamp0&×tamp>maxRange;if(outOfRange){dayElem.classList.add("notAllowed");["inRange","startRange","endRange"].forEach(function(c){dayElem.classList.remove(c)});return"continue"}else if(containsDisabled&&!outOfRange)return"continue";["startRange","inRange","endRange","notAllowed"].forEach(function(c){dayElem.classList.remove(c)});if(elem!==undefined){elem.classList.add(hoverDate<=self.selectedDates[0].getTime()?"startRange":"endRange");if(initialDatehoverDate&×tamp===initialDate)dayElem.classList.add("endRange");if(timestamp>=minRange&&(maxRange===0||timestamp<=maxRange)&&isBetween(timestamp,initialDate,hoverDate))dayElem.classList.add("inRange")}};for(var i=0,l=month.children.length;i0||dateObj.getMinutes()>0||dateObj.getSeconds()>0}if(self.selectedDates){self.selectedDates=self.selectedDates.filter(function(d){return isEnabled(d)});if(!self.selectedDates.length&&type==="min")setHoursFromDate(dateObj);updateValue()}if(self.daysContainer){redraw();if(dateObj!==undefined)self.currentYearElement[type]=dateObj.getFullYear().toString();else self.currentYearElement.removeAttribute(type);self.currentYearElement.disabled=!!inverseDateObj&&dateObj!==undefined&&inverseDateObj.getFullYear()===dateObj.getFullYear()}}}function parseConfig(){var boolOpts=["wrap","weekNumbers","allowInput","clickOpens","time_24hr","enableTime","noCalendar","altInput","shorthandCurrentMonth","inline","static","enableSeconds","disableMobile"];var userConfig=__assign({},instanceConfig,JSON.parse(JSON.stringify(element.dataset||{})));var formats={};self.config.parseDate=userConfig.parseDate;self.config.formatDate=userConfig.formatDate;Object.defineProperty(self.config,"enable",{get:function(){return self.config._enable},set:function(dates){self.config._enable=parseDateRules(dates)}});Object.defineProperty(self.config,"disable",{get:function(){return self.config._disable},set:function(dates){self.config._disable=parseDateRules(dates)}});var timeMode=userConfig.mode==="time";if(!userConfig.dateFormat&&(userConfig.enableTime||timeMode)){var defaultDateFormat=flatpickr.defaultConfig.dateFormat||defaults.dateFormat;formats.dateFormat=userConfig.noCalendar||timeMode?"H:i"+(userConfig.enableSeconds?":S":""):defaultDateFormat+" H:i"+(userConfig.enableSeconds?":S":"")}if(userConfig.altInput&&(userConfig.enableTime||timeMode)&&!userConfig.altFormat){var defaultAltFormat=flatpickr.defaultConfig.altFormat||defaults.altFormat;formats.altFormat=userConfig.noCalendar||timeMode?"h:i"+(userConfig.enableSeconds?":S K":" K"):defaultAltFormat+(" h:i"+(userConfig.enableSeconds?":S":"")+" K")}if(!userConfig.altInputClass){self.config.altInputClass=self.input.className+" "+self.config.altInputClass}Object.defineProperty(self.config,"minDate",{get:function(){return self.config._minDate},set:minMaxDateSetter("min")});Object.defineProperty(self.config,"maxDate",{get:function(){return self.config._maxDate},set:minMaxDateSetter("max")});var minMaxTimeSetter=function(type){return function(val){self.config[type==="min"?"_minTime":"_maxTime"]=self.parseDate(val,"H:i")}};Object.defineProperty(self.config,"minTime",{get:function(){return self.config._minTime},set:minMaxTimeSetter("min")});Object.defineProperty(self.config,"maxTime",{get:function(){return self.config._maxTime},set:minMaxTimeSetter("max")});if(userConfig.mode==="time"){self.config.noCalendar=true;self.config.enableTime=true}Object.assign(self.config,formats,userConfig);for(var i=0;i-1){self.config[key]=arrayify(pluginConf[key]).map(bindToInstance).concat(self.config[key])}else if(typeof userConfig[key]==="undefined")self.config[key]=pluginConf[key]}}triggerEvent("onParseConfig")}function setupLocale(){if(typeof self.config.locale!=="object"&&typeof flatpickr.l10ns[self.config.locale]==="undefined")self.config.errorHandler(new Error("flatpickr: invalid locale "+self.config.locale));self.l10n=__assign({},flatpickr.l10ns["default"],typeof self.config.locale==="object"?self.config.locale:self.config.locale!=="default"?flatpickr.l10ns[self.config.locale]:undefined);tokenRegex.K="("+self.l10n.amPM[0]+"|"+self.l10n.amPM[1]+"|"+self.l10n.amPM[0].toLowerCase()+"|"+self.l10n.amPM[1].toLowerCase()+")";var userConfig=__assign({},instanceConfig,JSON.parse(JSON.stringify(element.dataset||{})));if(userConfig.time_24hr===undefined&&flatpickr.defaultConfig.time_24hr===undefined){self.config.time_24hr=self.l10n.time_24hr}self.formatDate=createDateFormatter(self);self.parseDate=createDateParser({config:self.config,l10n:self.l10n})}function positionCalendar(customPositionElement){if(self.calendarContainer===undefined)return;triggerEvent("onPreCalendarPosition");var positionElement=customPositionElement||self._positionElement;var calendarHeight=Array.prototype.reduce.call(self.calendarContainer.children,function(acc,child){return acc+child.offsetHeight},0),calendarWidth=self.calendarContainer.offsetWidth,configPos=self.config.position.split(" "),configPosVertical=configPos[0],configPosHorizontal=configPos.length>1?configPos[1]:null,inputBounds=positionElement.getBoundingClientRect(),distanceFromBottom=window.innerHeight-inputBounds.bottom,showOnTop=configPosVertical==="above"||configPosVertical!=="below"&&distanceFromBottomcalendarHeight;var top=window.pageYOffset+inputBounds.top+(!showOnTop?positionElement.offsetHeight+2:-calendarHeight-2);toggleClass(self.calendarContainer,"arrowTop",!showOnTop);toggleClass(self.calendarContainer,"arrowBottom",showOnTop);if(self.config.inline)return;var left=window.pageXOffset+inputBounds.left-(configPosHorizontal!=null&&configPosHorizontal==="center"?(calendarWidth-inputBounds.width)/2:0);var right=window.document.body.offsetWidth-(window.pageXOffset+inputBounds.right);var rightMost=left+calendarWidth>window.document.body.offsetWidth;var centerMost=right+calendarWidth>window.document.body.offsetWidth;toggleClass(self.calendarContainer,"rightMost",rightMost);if(self.config.static)return;self.calendarContainer.style.top=top+"px";if(!rightMost){self.calendarContainer.style.left=left+"px";self.calendarContainer.style.right="auto"}else if(!centerMost){self.calendarContainer.style.left="auto";self.calendarContainer.style.right=right+"px"}else{var doc=document.styleSheets[0];if(doc===undefined)return;var bodyWidth=window.document.body.offsetWidth;var centerLeft=Math.max(0,bodyWidth/2-calendarWidth/2);var centerBefore=".flatpickr-calendar.centerMost:before";var centerAfter=".flatpickr-calendar.centerMost:after";var centerIndex=doc.cssRules.length;var centerStyle="{left:"+inputBounds.left+"px;right:auto;}";toggleClass(self.calendarContainer,"rightMost",false);toggleClass(self.calendarContainer,"centerMost",true);doc.insertRule(centerBefore+","+centerAfter+centerStyle,centerIndex);self.calendarContainer.style.left=centerLeft+"px";self.calendarContainer.style.right="auto"}}function redraw(){if(self.config.noCalendar||self.isMobile)return;updateNavigationCurrentMonth();buildDays()}function focusAndClose(){self._input.focus();if(window.navigator.userAgent.indexOf("MSIE")!==-1||navigator.msMaxTouchPoints!==undefined){setTimeout(self.close,0)}else{self.close()}}function selectDate(e){e.preventDefault();e.stopPropagation();var isSelectable=function(day){return day.classList&&day.classList.contains("flatpickr-day")&&!day.classList.contains("flatpickr-disabled")&&!day.classList.contains("notAllowed")};var t=findParent(e.target,isSelectable);if(t===undefined)return;var target=t;var selectedDate=self.latestSelectedDateObj=new Date(target.dateObj.getTime());var shouldChangeMonth=(selectedDate.getMonth()self.currentMonth+self.config.showMonths-1)&&self.config.mode!=="range";self.selectedDateElem=target;if(self.config.mode==="single")self.selectedDates=[selectedDate];else if(self.config.mode==="multiple"){var selectedIndex=isDateSelected(selectedDate);if(selectedIndex)self.selectedDates.splice(parseInt(selectedIndex),1);else self.selectedDates.push(selectedDate)}else if(self.config.mode==="range"){if(self.selectedDates.length===2){self.clear(false,false)}self.latestSelectedDateObj=selectedDate;self.selectedDates.push(selectedDate);if(compareDates(selectedDate,self.selectedDates[0],true)!==0)self.selectedDates.sort(function(a,b){return a.getTime()-b.getTime()})}setHoursFromInputs();if(shouldChangeMonth){var isNewYear=self.currentYear!==selectedDate.getFullYear();self.currentYear=selectedDate.getFullYear();self.currentMonth=selectedDate.getMonth();if(isNewYear){triggerEvent("onYearChange");buildMonthSwitch()}triggerEvent("onMonthChange")}updateNavigationCurrentMonth();buildDays();updateValue();if(self.config.enableTime)setTimeout(function(){return self.showTimeInput=true},50);if(!shouldChangeMonth&&self.config.mode!=="range"&&self.config.showMonths===1)focusOnDayElem(target);else if(self.selectedDateElem!==undefined&&self.hourElement===undefined){self.selectedDateElem&&self.selectedDateElem.focus()}if(self.hourElement!==undefined)self.hourElement!==undefined&&self.hourElement.focus();if(self.config.closeOnSelect){var single=self.config.mode==="single"&&!self.config.enableTime;var range=self.config.mode==="range"&&self.selectedDates.length===2&&!self.config.enableTime;if(single||range){focusAndClose()}}triggerChange()}var CALLBACKS={locale:[setupLocale,updateWeekdays],showMonths:[buildMonths,setCalendarWidth,buildWeekdays],minDate:[jumpToDate],maxDate:[jumpToDate]};function set(option,value){if(option!==null&&typeof option==="object"){Object.assign(self.config,option);for(var key in option){if(CALLBACKS[key]!==undefined)CALLBACKS[key].forEach(function(x){return x()})}}else{self.config[option]=value;if(CALLBACKS[option]!==undefined)CALLBACKS[option].forEach(function(x){return x()});else if(HOOKS.indexOf(option)>-1)self.config[option]=arrayify(value)}self.redraw();updateValue(false)}function setSelectedDate(inputDate,format){var dates=[];if(inputDate instanceof Array)dates=inputDate.map(function(d){return self.parseDate(d,format)});else if(inputDate instanceof Date||typeof inputDate==="number")dates=[self.parseDate(inputDate,format)];else if(typeof inputDate==="string"){switch(self.config.mode){case"single":case"time":dates=[self.parseDate(inputDate,format)];break;case"multiple":dates=inputDate.split(self.config.conjunction).map(function(date){return self.parseDate(date,format)});break;case"range":dates=inputDate.split(self.l10n.rangeSeparator).map(function(date){return self.parseDate(date,format)});break}}else self.config.errorHandler(new Error("Invalid date supplied: "+JSON.stringify(inputDate)));self.selectedDates=dates.filter(function(d){return d instanceof Date&&isEnabled(d,false)});if(self.config.mode==="range")self.selectedDates.sort(function(a,b){return a.getTime()-b.getTime()})}function setDate(date,triggerChange,format){if(triggerChange===void 0){triggerChange=false}if(format===void 0){format=self.config.dateFormat}if(date!==0&&!date||date instanceof Array&&date.length===0)return self.clear(triggerChange);setSelectedDate(date,format);self.showTimeInput=self.selectedDates.length>0;self.latestSelectedDateObj=self.selectedDates[self.selectedDates.length-1];self.redraw();jumpToDate();setHoursFromDate();if(self.selectedDates.length===0){self.clear(false)}updateValue(triggerChange);if(triggerChange)triggerEvent("onChange")}function parseDateRules(arr){return arr.slice().map(function(rule){if(typeof rule==="string"||typeof rule==="number"||rule instanceof Date){return self.parseDate(rule,undefined,true)}else if(rule&&typeof rule==="object"&&rule.from&&rule.to)return{from:self.parseDate(rule.from,undefined),to:self.parseDate(rule.to,undefined)};return rule}).filter(function(x){return x})}function setupDates(){self.selectedDates=[];self.now=self.parseDate(self.config.now)||new Date;var preloadedDate=self.config.defaultDate||((self.input.nodeName==="INPUT"||self.input.nodeName==="TEXTAREA")&&self.input.placeholder&&self.input.value===self.input.placeholder?null:self.input.value);if(preloadedDate)setSelectedDate(preloadedDate,self.config.dateFormat);self._initialDate=self.selectedDates.length>0?self.selectedDates[0]:self.config.minDate&&self.config.minDate.getTime()>self.now.getTime()?self.config.minDate:self.config.maxDate&&self.config.maxDate.getTime()0)self.latestSelectedDateObj=self.selectedDates[0];if(self.config.minTime!==undefined)self.config.minTime=self.parseDate(self.config.minTime,"H:i");if(self.config.maxTime!==undefined)self.config.maxTime=self.parseDate(self.config.maxTime,"H:i");self.minDateHasTime=!!self.config.minDate&&(self.config.minDate.getHours()>0||self.config.minDate.getMinutes()>0||self.config.minDate.getSeconds()>0);self.maxDateHasTime=!!self.config.maxDate&&(self.config.maxDate.getHours()>0||self.config.maxDate.getMinutes()>0||self.config.maxDate.getSeconds()>0);Object.defineProperty(self,"showTimeInput",{get:function(){return self._showTimeInput},set:function(bool){self._showTimeInput=bool;if(self.calendarContainer)toggleClass(self.calendarContainer,"showTimeInput",bool);self.isOpen&&positionCalendar()}})}function setupInputs(){self.input=self.config.wrap?element.querySelector("[data-input]"):element;if(!self.input){self.config.errorHandler(new Error("Invalid input element specified"));return}self.input._type=self.input.type;self.input.type="text";self.input.classList.add("flatpickr-input");self._input=self.input;if(self.config.altInput){self.altInput=createElement(self.input.nodeName,self.config.altInputClass);self._input=self.altInput;self.altInput.placeholder=self.input.placeholder;self.altInput.disabled=self.input.disabled;self.altInput.required=self.input.required;self.altInput.tabIndex=self.input.tabIndex;self.altInput.type="text";self.input.setAttribute("type","hidden");if(!self.config.static&&self.input.parentNode)self.input.parentNode.insertBefore(self.altInput,self.input.nextSibling)}if(!self.config.allowInput)self._input.setAttribute("readonly","readonly");self._positionElement=self.config.positionElement||self._input}function setupMobile(){var inputType=self.config.enableTime?self.config.noCalendar?"time":"datetime-local":"date";self.mobileInput=createElement("input",self.input.className+" flatpickr-mobile");self.mobileInput.step=self.input.getAttribute("step")||"any";self.mobileInput.tabIndex=1;self.mobileInput.type=inputType;self.mobileInput.disabled=self.input.disabled;self.mobileInput.required=self.input.required;self.mobileInput.placeholder=self.input.placeholder;self.mobileFormatStr=inputType==="datetime-local"?"Y-m-d\\TH:i:S":inputType==="date"?"Y-m-d":"H:i:S";if(self.selectedDates.length>0){self.mobileInput.defaultValue=self.mobileInput.value=self.formatDate(self.selectedDates[0],self.mobileFormatStr)}if(self.config.minDate)self.mobileInput.min=self.formatDate(self.config.minDate,"Y-m-d");if(self.config.maxDate)self.mobileInput.max=self.formatDate(self.config.maxDate,"Y-m-d");self.input.type="hidden";if(self.altInput!==undefined)self.altInput.type="hidden";try{if(self.input.parentNode)self.input.parentNode.insertBefore(self.mobileInput,self.input.nextSibling)}catch(_a){}bind(self.mobileInput,"change",function(e){self.setDate(e.target.value,false,self.mobileFormatStr);triggerEvent("onChange");triggerEvent("onClose")})}function toggle(e){if(self.isOpen===true)return self.close();self.open(e)}function triggerEvent(event,data){if(self.config===undefined)return;var hooks=self.config[event];if(hooks!==undefined&&hooks.length>0){for(var i=0;hooks[i]&&i=0&&compareDates(date,self.selectedDates[1])<=0}function updateNavigationCurrentMonth(){if(self.config.noCalendar||self.isMobile||!self.monthNav)return;self.yearElements.forEach(function(yearElement,i){var d=new Date(self.currentYear,self.currentMonth,1);d.setMonth(self.currentMonth+i);if(self.config.showMonths>1){self.monthElements[i].textContent=monthToStr(d.getMonth(),self.config.shorthandCurrentMonth,self.l10n)+" "}else{self.monthsDropdownContainer.value=d.getMonth().toString()}yearElement.value=d.getFullYear().toString()});self._hidePrevMonthArrow=self.config.minDate!==undefined&&(self.currentYear===self.config.minDate.getFullYear()?self.currentMonth<=self.config.minDate.getMonth():self.currentYearself.config.maxDate.getMonth():self.currentYear>self.config.maxDate.getFullYear())}function getDateStr(format){return self.selectedDates.map(function(dObj){return self.formatDate(dObj,format)}).filter(function(d,i,arr){return self.config.mode!=="range"||self.config.enableTime||arr.indexOf(d)===i}).join(self.config.mode!=="range"?self.config.conjunction:self.l10n.rangeSeparator)}function updateValue(triggerChange){if(triggerChange===void 0){triggerChange=true}if(self.mobileInput!==undefined&&self.mobileFormatStr){self.mobileInput.value=self.latestSelectedDateObj!==undefined?self.formatDate(self.latestSelectedDateObj,self.mobileFormatStr):""}self.input.value=getDateStr(self.config.dateFormat);if(self.altInput!==undefined){self.altInput.value=getDateStr(self.config.altFormat)}if(triggerChange!==false)triggerEvent("onValueUpdate")}function onMonthNavClick(e){var isPrevMonth=self.prevMonthNav.contains(e.target);var isNextMonth=self.nextMonthNav.contains(e.target);if(isPrevMonth||isNextMonth){changeMonth(isPrevMonth?-1:1)}else if(self.yearElements.indexOf(e.target)>=0){e.target.select()}else if(e.target.classList.contains("arrowUp")){self.changeYear(self.currentYear+1)}else if(e.target.classList.contains("arrowDown")){self.changeYear(self.currentYear-1)}}function timeWrapper(e){e.preventDefault();var isKeyDown=e.type==="keydown",input=e.target;if(self.amPM!==undefined&&e.target===self.amPM){self.amPM.textContent=self.l10n.amPM[int(self.amPM.textContent===self.l10n.amPM[0])]}var min=parseFloat(input.getAttribute("min")),max=parseFloat(input.getAttribute("max")),step=parseFloat(input.getAttribute("step")),curValue=parseInt(input.value,10),delta=e.delta||(isKeyDown?e.which===38?1:-1:0);var newValue=curValue+step*delta;if(typeof input.value!=="undefined"&&input.value.length===2){var isHourElem=input===self.hourElement,isMinuteElem=input===self.minuteElement;if(newValuemax){newValue=input===self.hourElement?newValue-max-int(!self.amPM):min;if(isMinuteElem)incrementNumInput(undefined,1,self.hourElement)}if(self.amPM&&isHourElem&&(step===1?newValue+curValue===23:Math.abs(newValue-curValue)>step)){self.amPM.textContent=self.l10n.amPM[int(self.amPM.textContent===self.l10n.amPM[0])]}input.value=pad(newValue)}}init();return self}function _flatpickr(nodeList,config){var nodes=Array.prototype.slice.call(nodeList).filter(function(x){return x instanceof HTMLElement});var instances=[];for(var i=0;i1?_len-1:0),_key=1;_key<_len;_key++){remainder[_key-1]=arguments[_key]}if(!_onClose||_onClose.call.apply(_onClose,[this,selectedDates].concat(remainder))!==false){self._updateClassNames(calendar);self._updateInputFields(selectedDates,type)}},onChange:function onChange(){for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}if(!_onChange||_onChange.call.apply(_onChange,[this].concat(args))!==false){self._updateClassNames(calendar);if(type==="range"){if(calendar.selectedDates.length===1&&calendar.isOpen){self.element.querySelector(self.options.selectorDatePickerInputTo).classList.add(self.options.classFocused)}else{self.element.querySelector(self.options.selectorDatePickerInputTo).classList.remove(self.options.classFocused)}}}},onMonthChange:function onMonthChange(){for(var _len3=arguments.length,args=new Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3]}if(!_onMonthChange||_onMonthChange.call.apply(_onMonthChange,[this].concat(args))!==false){self._updateClassNames(calendar)}},onYearChange:function onYearChange(){for(var _len4=arguments.length,args=new Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4]}if(!_onYearChange||_onYearChange.call.apply(_onYearChange,[this].concat(args))!==false){self._updateClassNames(calendar)}},onOpen:function onOpen(){self.shouldForceOpen=true;setTimeout(function(){self.shouldForceOpen=false},0);for(var _len5=arguments.length,args=new Array(_len5),_key5=0;_key5<_len5;_key5++){args[_key5]=arguments[_key5]}if(!_onOpen||_onOpen.call.apply(_onOpen,[this].concat(args))!==false){self._updateClassNames(calendar)}},onValueUpdate:function onValueUpdate(){for(var _len6=arguments.length,args=new Array(_len6),_key6=0;_key6<_len6;_key6++){args[_key6]=arguments[_key6]}if((!_onValueUpdate||_onValueUpdate.call.apply(_onValueUpdate,[this].concat(args))!==false)&&type==="range"){self._updateInputFields(self.calendar.selectedDates,type)}},nextArrow:_this._rightArrowHTML(),prevArrow:_this._leftArrowHTML(),plugins:[].concat(_toConsumableArray(_this.options.plugins||[]),[carbonFlatpickrMonthSelectPlugin(_this.options)])}));if(type==="range"){_this._addInputLogic(_this.element.querySelector(_this.options.selectorDatePickerInputFrom),0);_this._addInputLogic(_this.element.querySelector(_this.options.selectorDatePickerInputTo),1)}_this.manage(on(_this.element.querySelector(_this.options.selectorDatePickerIcon),"click",function(){calendar.open()}));_this._updateClassNames(calendar);if(type!=="range"){_this._addInputLogic(date)}return calendar});_defineProperty(_assertThisInitialized(_this),"_addInputLogic",function(input,index){if(!isNaN(index)&&(index<0||index>1)){throw new RangeError("The index of (".concat(index,") is out of range."))}var inputField=input;_this.manage(on(inputField,"change",function(evt){if(evt.isTrusted||evt.detail&&evt.detail.isNotFromFlatpickr){var inputDate=_this.calendar.parseDate(inputField.value);if(inputDate&&!isNaN(inputDate.valueOf())){if(isNaN(index)){_this.calendar.setDate(inputDate)}else{var selectedDates=_this.calendar.selectedDates;selectedDates[index]=inputDate;_this.calendar.setDate(selectedDates)}}}_this._updateClassNames(_this.calendar)}));_this.manage(on(inputField,"keydown",function(evt){var origInput=_this.calendar._input;_this.calendar._input=evt.target;setTimeout(function(){_this.calendar._input=origInput})}))});_defineProperty(_assertThisInitialized(_this),"_updateClassNames",function(_ref){var calendarContainer=_ref.calendarContainer,selectedDates=_ref.selectedDates;if(calendarContainer){calendarContainer.classList.add(_this.options.classCalendarContainer);calendarContainer.querySelector(".flatpickr-month").classList.add(_this.options.classMonth);calendarContainer.querySelector(".flatpickr-weekdays").classList.add(_this.options.classWeekdays);calendarContainer.querySelector(".flatpickr-days").classList.add(_this.options.classDays);toArray$5(calendarContainer.querySelectorAll(".flatpickr-weekday")).forEach(function(item){var currentItem=item;currentItem.innerHTML=currentItem.innerHTML.replace(/\s+/g,"");currentItem.classList.add(_this.options.classWeekday)});toArray$5(calendarContainer.querySelectorAll(".flatpickr-day")).forEach(function(item){item.classList.add(_this.options.classDay);if(item.classList.contains("today")&&selectedDates.length>0){item.classList.add("no-border")}else if(item.classList.contains("today")&&selectedDates.length===0){item.classList.remove("no-border")}})}});_defineProperty(_assertThisInitialized(_this),"_updateInputFields",function(selectedDates,type){if(type==="range"){if(selectedDates.length===2){_this.element.querySelector(_this.options.selectorDatePickerInputFrom).value=_this._formatDate(selectedDates[0]);_this.element.querySelector(_this.options.selectorDatePickerInputTo).value=_this._formatDate(selectedDates[1])}else if(selectedDates.length===1){_this.element.querySelector(_this.options.selectorDatePickerInputFrom).value=_this._formatDate(selectedDates[0])}}else if(selectedDates.length===1){_this.element.querySelector(_this.options.selectorDatePickerInput).value=_this._formatDate(selectedDates[0])}_this._updateClassNames(_this.calendar)});_defineProperty(_assertThisInitialized(_this),"_formatDate",function(date){return _this.calendar.formatDate(date,_this.calendar.config.dateFormat)});var _type=_this.element.getAttribute(_this.options.attribType);_this.calendar=_this._initDatePicker(_type);if(_this.calendar.calendarContainer){_this.manage(on(_this.element,"keydown",function(e){if(e.which===40){e.preventDefault();(_this.calendar.selectedDateElem||_this.calendar.todayDateElem||_this.calendar.calendarContainer).focus()}}));_this.manage(on(_this.calendar.calendarContainer,"keydown",function(e){if(e.which===9&&_type==="range"){_this._updateClassNames(_this.calendar);_this.element.querySelector(_this.options.selectorDatePickerInputFrom).focus()}}))}return _this}_createClass(DatePicker,[{key:"_rightArrowHTML",value:function _rightArrowHTML(){return'\n \n \n '}},{key:"_leftArrowHTML",value:function _leftArrowHTML(){return'\n \n \n '}},{key:"release",value:function release(){if(this._rangeInput&&this._rangeInput.parentNode){this._rangeInput.parentNode.removeChild(this._rangeInput)}if(this.calendar){try{this.calendar.destroy()}catch(err){}this.calendar=null}return _get(_getPrototypeOf(DatePicker.prototype),"release",this).call(this)}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-date-picker]",selectorDatePickerInput:"[data-date-picker-input]",selectorDatePickerInputFrom:"[data-date-picker-input-from]",selectorDatePickerInputTo:"[data-date-picker-input-to]",selectorDatePickerIcon:"[data-date-picker-icon]",selectorFlatpickrMonthYearContainer:".flatpickr-current-month",selectorFlatpickrYearContainer:".numInputWrapper",selectorFlatpickrCurrentMonth:".cur-month",classCalendarContainer:"".concat(prefix,"--date-picker__calendar"),classMonth:"".concat(prefix,"--date-picker__month"),classWeekdays:"".concat(prefix,"--date-picker__weekdays"),classDays:"".concat(prefix,"--date-picker__days"),classWeekday:"".concat(prefix,"--date-picker__weekday"),classDay:"".concat(prefix,"--date-picker__day"),classFocused:"".concat(prefix,"--focused"),classVisuallyHidden:"".concat(prefix,"--visually-hidden"),classFlatpickrCurrentMonth:"cur-month",attribType:"data-date-picker-type",dateFormat:"m/d/Y"}}}]);return DatePicker}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(DatePicker,"components",new WeakMap);var Pagination=function(_mixin){_inherits(Pagination,_mixin);var _super=_createSuper(Pagination);function Pagination(element,options){var _this;_classCallCheck(this,Pagination);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_emitEvent",function(evtName,detail){var event=new CustomEvent("".concat(evtName),{bubbles:true,cancelable:true,detail:detail});_this.element.dispatchEvent(event)});_this.manage(on(_this.element,"click",function(evt){if(eventMatches(evt,_this.options.selectorPageBackward)){var detail={initialEvt:evt,element:evt.target,direction:"backward"};_this._emitEvent(_this.options.eventPageChange,detail)}else if(eventMatches(evt,_this.options.selectorPageForward)){var _detail={initialEvt:evt,element:evt.target,direction:"forward"};_this._emitEvent(_this.options.eventPageChange,_detail)}}));_this.manage(on(_this.element,"input",function(evt){if(eventMatches(evt,_this.options.selectorItemsPerPageInput)){var detail={initialEvt:evt,element:evt.target,value:evt.target.value};_this._emitEvent(_this.options.eventItemsPerPage,detail)}else if(eventMatches(evt,_this.options.selectorPageNumberInput)){var _detail2={initialEvt:evt,element:evt.target,value:evt.target.value};_this._emitEvent(_this.options.eventPageNumber,_detail2)}}));return _this}return Pagination}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(Pagination,"components",new WeakMap);_defineProperty(Pagination,"options",{selectorInit:"[data-pagination]",selectorItemsPerPageInput:"[data-items-per-page]",selectorPageNumberInput:"[data-page-number-input]",selectorPageBackward:"[data-page-backward]",selectorPageForward:"[data-page-forward]",eventItemsPerPage:"itemsPerPage",eventPageNumber:"pageNumber",eventPageChange:"pageChange"});function svgToggleClass(svg,name,forceAdd){var list=svg.getAttribute("class").trim().split(/\s+/);var uniqueList=Object.keys(list.reduce(function(o,item){return Object.assign(o,_defineProperty({},item,1))},{}));var index=uniqueList.indexOf(name);var found=index>=0;var add=forceAdd===undefined?!found:forceAdd;if(found===!add){if(add){uniqueList.push(name)}else{uniqueList.splice(index,1)}svg.setAttribute("class",uniqueList.join(" "))}}var toArray$6=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var Search=function(_mixin){_inherits(Search,_mixin);var _super=_createSuper(Search);function Search(element,options){var _this;_classCallCheck(this,Search);_this=_super.call(this,element,options);var closeIcon=_this.element.querySelector(_this.options.selectorClearIcon);var input=_this.element.querySelector(_this.options.selectorSearchInput);if(!input){throw new Error("Cannot find the search input.")}if(closeIcon){_this.manage(on(closeIcon,"click",function(){svgToggleClass(closeIcon,_this.options.classClearHidden,true);input.value="";input.focus()}))}_this.manage(on(_this.element,"click",function(evt){var toggleItem=eventMatches(evt,_this.options.selectorIconContainer);if(toggleItem)_this.toggleLayout(toggleItem)}));_this.manage(on(input,"input",function(evt){if(closeIcon)_this.showClear(evt.target.value,closeIcon)}));return _this}_createClass(Search,[{key:"toggleLayout",value:function toggleLayout(element){var _this2=this;toArray$6(element.querySelectorAll(this.options.selectorSearchView)).forEach(function(item){item.classList.toggle(_this2.options.classLayoutHidden)})}},{key:"showClear",value:function showClear(value,icon){svgToggleClass(icon,this.options.classClearHidden,value.length===0)}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-search]",selectorSearchView:"[data-search-view]",selectorSearchInput:".".concat(prefix,"--search-input"),selectorClearIcon:".".concat(prefix,"--search-close"),selectorIconContainer:".".concat(prefix,"--search-button[data-search-toggle]"),classClearHidden:"".concat(prefix,"--search-close--hidden"),classLayoutHidden:"".concat(prefix,"--search-view--hidden")}}}]);return Search}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(Search,"components",new WeakMap);var Accordion=function(_mixin){_inherits(Accordion,_mixin);var _super=_createSuper(Accordion);function Accordion(element,options){var _this;_classCallCheck(this,Accordion);_this=_super.call(this,element,options);_this.manage(on(_this.element,"click",function(event){var item=eventMatches(event,_this.options.selectorAccordionItem);if(item&&!eventMatches(event,_this.options.selectorAccordionContent)){_this._toggle(item)}}));if(!_this._checkIfButton()){_this.manage(on(_this.element,"keypress",function(event){var item=eventMatches(event,_this.options.selectorAccordionItem);if(item&&!eventMatches(event,_this.options.selectorAccordionContent)){_this._handleKeypress(event)}}))}return _this}_createClass(Accordion,[{key:"_checkIfButton",value:function _checkIfButton(){return this.element.firstElementChild.firstElementChild.nodeName==="BUTTON"}},{key:"_handleKeypress",value:function _handleKeypress(event){if(event.which===13||event.which===32){this._toggle(event.target)}}},{key:"_toggle",value:function _toggle(element){var heading=element.querySelector(this.options.selectorAccordionItemHeading);var expanded=heading.getAttribute("aria-expanded");if(expanded!==null){heading.setAttribute("aria-expanded",expanded==="true"?"false":"true")}element.classList.toggle(this.options.classActive)}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-accordion]",selectorAccordionItem:".".concat(prefix,"--accordion__item"),selectorAccordionItemHeading:".".concat(prefix,"--accordion__heading"),selectorAccordionContent:".".concat(prefix,"--accordion__content"),classActive:"".concat(prefix,"--accordion__item--active")}}}]);return Accordion}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(Accordion,"components",new WeakMap);var CopyButton=function(_mixin){_inherits(CopyButton,_mixin);var _super=_createSuper(CopyButton);function CopyButton(element,options){var _this;_classCallCheck(this,CopyButton);_this=_super.call(this,element,options);_this.manage(on(_this.element,"click",function(){return _this.handleClick()}));_this.manage(on(_this.element,"animationend",function(event){return _this.handleAnimationEnd(event)}));return _this}_createClass(CopyButton,[{key:"handleAnimationEnd",value:function handleAnimationEnd(event){if(event.animationName==="hide-feedback"){this.element.classList.remove(this.options.classAnimating);this.element.classList.remove(this.options.classFadeOut)}}},{key:"handleClick",value:function handleClick(){var _this2=this;var feedback=this.element.querySelector(this.options.feedbackTooltip);if(feedback){feedback.classList.add(this.options.classShowFeedback);setTimeout(function(){feedback.classList.remove(_this2.options.classShowFeedback)},this.options.timeoutValue)}else{this.element.classList.add(this.options.classAnimating);this.element.classList.add(this.options.classFadeIn);setTimeout(function(){_this2.element.classList.remove(_this2.options.classFadeIn);_this2.element.classList.add(_this2.options.classFadeOut)},this.options.timeoutValue)}}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-copy-btn]",feedbackTooltip:"[data-feedback]",classShowFeedback:"".concat(prefix,"--btn--copy__feedback--displayed"),classAnimating:"".concat(prefix,"--copy-btn--animating"),classFadeIn:"".concat(prefix,"--copy-btn--fade-in"),classFadeOut:"".concat(prefix,"--copy-btn--fade-out"),timeoutValue:2e3}}}]);return CopyButton}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(CopyButton,"components",new WeakMap);var Notification=function(_mixin){_inherits(Notification,_mixin);var _super=_createSuper(Notification);function Notification(element,options){var _this;_classCallCheck(this,Notification);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_changeState",function(state,callback){if(state==="delete-notification"){_this.element.parentNode.removeChild(_this.element);_this.release()}callback()});_this.button=element.querySelector(_this.options.selectorButton);if(_this.button){_this.manage(on(_this.button,"click",function(evt){if(evt.currentTarget===_this.button){_this.remove()}}))}return _this}_createClass(Notification,[{key:"remove",value:function remove(){this.changeState("delete-notification")}}]);return Notification}(mixin(createComponent,initComponentBySearch,eventedState,handles));_defineProperty(Notification,"components",new WeakMap);_defineProperty(Notification,"options",{selectorInit:"[data-notification]",selectorButton:"[data-notification-btn]",eventBeforeDeleteNotification:"notification-before-delete",eventAfterDeleteNotification:"notification-after-delete"});var toArray$7=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var Toolbar=function(_mixin){_inherits(Toolbar,_mixin);var _super=_createSuper(Toolbar);function Toolbar(element,options){var _this;_classCallCheck(this,Toolbar);_this=_super.call(this,element,options);if(!_this.element.dataset.tableTarget){console.warn("There is no table bound to this toolbar!")}else{var boundTable=_this.element.ownerDocument.querySelector(_this.element.dataset.tableTarget);var rowHeightBtns=_this.element.querySelector(_this.options.selectorRowHeight);if(rowHeightBtns){_this.manage(on(rowHeightBtns,"click",function(event){_this._handleRowHeightChange(event,boundTable)}))}}_this.manage(on(_this.element.ownerDocument,"keydown",function(evt){_this._handleKeyDown(evt)}));_this.manage(on(_this.element.ownerDocument,"click",function(evt){_this._handleDocumentClick(evt)}));return _this}_createClass(Toolbar,[{key:"_handleDocumentClick",value:function _handleDocumentClick(event){var _this2=this;var searchInput=eventMatches(event,this.options.selectorSearch);var isOfSelfSearchInput=searchInput&&this.element.contains(searchInput);if(isOfSelfSearchInput){var shouldBeOpen=isOfSelfSearchInput&&!this.element.classList.contains(this.options.classSearchActive);searchInput.classList.toggle(this.options.classSearchActive,shouldBeOpen);if(shouldBeOpen){searchInput.querySelector("input").focus()}}var targetComponentElement=eventMatches(event,this.options.selectorInit);toArray$7(this.element.ownerDocument.querySelectorAll(this.options.selectorSearch)).forEach(function(item){if(!targetComponentElement||!targetComponentElement.contains(item)){item.classList.remove(_this2.options.classSearchActive)}})}},{key:"_handleKeyDown",value:function _handleKeyDown(event){var searchInput=eventMatches(event,this.options.selectorSearch);if(searchInput&&event.which===27){searchInput.classList.remove(this.options.classSearchActive)}}},{key:"_handleRowHeightChange",value:function _handleRowHeightChange(event,boundTable){var _event$currentTarget$=event.currentTarget.querySelector("input:checked"),value=_event$currentTarget$.value;if(value==="tall"){boundTable.classList.add(this.options.classTallRows)}else{boundTable.classList.remove(this.options.classTallRows)}}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-toolbar]",selectorSearch:"[data-toolbar-search]",selectorRowHeight:"[data-row-height]",classTallRows:"".concat(prefix,"--responsive-table--tall"),classSearchActive:"".concat(prefix,"--toolbar-search--active")}}}]);return Toolbar}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(Toolbar,"components",new WeakMap);function initComponentByEvent(ToMix){var InitComponentByEvent=function(_ToMix){_inherits(InitComponentByEvent,_ToMix);var _super=_createSuper(InitComponentByEvent);function InitComponentByEvent(){_classCallCheck(this,InitComponentByEvent);return _super.apply(this,arguments)}_createClass(InitComponentByEvent,null,[{key:"init",value:function init(){var _this=this;var target=arguments.length>0&&arguments[0]!==undefined?arguments[0]:document;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var effectiveOptions=Object.assign(Object.create(this.options),options);if(!target||target.nodeType!==Node.ELEMENT_NODE&&target.nodeType!==Node.DOCUMENT_NODE){throw new TypeError("DOM document or DOM element should be given to search for and initialize this widget.")}if(target.nodeType===Node.ELEMENT_NODE&&target.matches(effectiveOptions.selectorInit)){this.create(target,options)}else{var hasFocusin="onfocusin"in(target.nodeType===Node.ELEMENT_NODE?target.ownerDocument:target).defaultView;var handles=effectiveOptions.initEventNames.map(function(name){var eventName=name==="focus"&&hasFocusin?"focusin":name;return on(target,eventName,function(event){var element=eventMatches(event,effectiveOptions.selectorInit);if(element&&!_this.components.has(element)){var component=_this.create(element,options);if(typeof component.createdByEvent==="function"){component.createdByEvent(event)}}},name==="focus"&&!hasFocusin)});return{release:function release(){for(var handle=handles.pop();handle;handle=handles.pop()){handle.release()}}}}return""}}]);return InitComponentByEvent}(ToMix);_defineProperty(InitComponentByEvent,"forLazyInit",true);return InitComponentByEvent}var getMenuOffset$1=function getMenuOffset(menuBody,menuDirection){var _DIRECTION_LEFT$DIREC,_DIRECTION_LEFT$DIREC2;var arrowStyle=menuBody.ownerDocument.defaultView.getComputedStyle(menuBody,":before");var arrowPositionProp=(_DIRECTION_LEFT$DIREC={},_defineProperty(_DIRECTION_LEFT$DIREC,DIRECTION_LEFT,"right"),_defineProperty(_DIRECTION_LEFT$DIREC,DIRECTION_TOP,"bottom"),_defineProperty(_DIRECTION_LEFT$DIREC,DIRECTION_RIGHT,"left"),_defineProperty(_DIRECTION_LEFT$DIREC,DIRECTION_BOTTOM,"top"),_DIRECTION_LEFT$DIREC)[menuDirection];var menuPositionAdjustmentProp=(_DIRECTION_LEFT$DIREC2={},_defineProperty(_DIRECTION_LEFT$DIREC2,DIRECTION_LEFT,"left"),_defineProperty(_DIRECTION_LEFT$DIREC2,DIRECTION_TOP,"top"),_defineProperty(_DIRECTION_LEFT$DIREC2,DIRECTION_RIGHT,"left"),_defineProperty(_DIRECTION_LEFT$DIREC2,DIRECTION_BOTTOM,"top"),_DIRECTION_LEFT$DIREC2)[menuDirection];var values=[arrowPositionProp,"border-bottom-width"].reduce(function(o,name){return _objectSpread2(_objectSpread2({},o),{},_defineProperty({},name,Number((/^([\d-.]+)px$/.exec(arrowStyle.getPropertyValue(name))||[])[1])))},{});var margin=0;if(menuDirection!==DIRECTION_BOTTOM){var style=menuBody.ownerDocument.defaultView.getComputedStyle(menuBody);margin=Number((/^([\d-.]+)px$/.exec(style.getPropertyValue("margin-top"))||[])[1])}values[arrowPositionProp]=values[arrowPositionProp]||-6;if(Object.keys(values).every(function(name){return!isNaN(values[name])})){var arrowPosition=values[arrowPositionProp],borderBottomWidth=values["border-bottom-width"];return _defineProperty({left:0,top:0},menuPositionAdjustmentProp,Math.sqrt(Math.pow(borderBottomWidth,2)*2)-arrowPosition+margin*(menuDirection===DIRECTION_TOP?2:1))}return undefined};var allowedOpenKeys=[32,13];var Tooltip=function(_mixin){_inherits(Tooltip,_mixin);var _super=_createSuper(Tooltip);function Tooltip(element,options){var _this;_classCallCheck(this,Tooltip);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_hasContextMenu",false);_this._hookOn(element);return _this}_createClass(Tooltip,[{key:"createdByEvent",value:function createdByEvent(event){var relatedTarget=event.relatedTarget,type=event.type,which=event.which;if(type==="click"||allowedOpenKeys.includes(which)){this._handleClick({relatedTarget:relatedTarget,type:type,details:getLaunchingDetails(event)})}}},{key:"changeState",value:function changeState(state,detail,callback){if(!this.tooltip){var tooltip=this.element.ownerDocument.querySelector(this.element.getAttribute(this.options.attribTooltipTarget));if(!tooltip){throw new Error("Cannot find the target tooltip.")}this.tooltip=FloatingMenu.create(tooltip,{refNode:this.element,classShown:this.options.classShown,offset:this.options.objMenuOffset,contentNode:tooltip.querySelector(this.options.selectorContent)});this._hookOn(tooltip);this.children.push(this.tooltip)}this.tooltip.changeState(state,Object.assign(detail,{delegatorNode:this.element}),callback)}},{key:"_hookOn",value:function _hookOn(element){var _this2=this;var handleClickContextMenu=function handleClickContextMenu(evt,allowedKeys){var relatedTarget=evt.relatedTarget,type=evt.type,which=evt.which;if(typeof allowedKeys==="undefined"||allowedKeys.includes(which)){var hadContextMenu=_this2._hasContextMenu;_this2._hasContextMenu=type==="contextmenu";_this2._handleClick({relatedTarget:relatedTarget,type:type,hadContextMenu:hadContextMenu,details:getLaunchingDetails(evt)})}};this.manage(on(element,"click",handleClickContextMenu,false));if(this.element.tagName!=="BUTTON"){this.manage(on(this.element,"keydown",function(event){handleClickContextMenu(event,allowedOpenKeys)},false))}}},{key:"_handleClick",value:function _handleClick(_ref2){var relatedTarget=_ref2.relatedTarget,type=_ref2.type,hadContextMenu=_ref2.hadContextMenu,details=_ref2.details;var state={click:"shown",keydown:"shown",blur:"hidden",touchleave:"hidden",touchcancel:"hidden"}[type];var shouldPreventClose;if(type==="blur"){var wentToSelf=relatedTarget&&this.element.contains&&this.element.contains(relatedTarget)||this.tooltip&&this.tooltip.element.contains(relatedTarget);shouldPreventClose=hadContextMenu||wentToSelf}if(!shouldPreventClose){this.changeState(state,details)}}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-tooltip-trigger]",selectorContent:".".concat(prefix,"--tooltip__content"),classShown:"".concat(prefix,"--tooltip--shown"),attribTooltipTarget:"data-tooltip-target",objMenuOffset:getMenuOffset$1,initEventNames:["click","keydown"]}}}]);return Tooltip}(mixin(createComponent,initComponentByEvent,exports$1,handles));_defineProperty(Tooltip,"components",new WeakMap);var FUNC_ERROR_TEXT="Expected a function";var NAN=0/0;var symbolTag="[object Symbol]";var reTrim=/^\s+|\s+$/g;var reIsBadHex=/^[-+]0x[0-9a-f]+$/i;var reIsBinary=/^0b[01]+$/i;var reIsOctal=/^0o[0-7]+$/i;var freeParseInt=parseInt;var freeGlobal=typeof commonjsGlobal=="object"&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal;var freeSelf=typeof self=="object"&&self&&self.Object===Object&&self;var root=freeGlobal||freeSelf||Function("return this")();var objectProto=Object.prototype;var objectToString=objectProto.toString;var nativeMax=Math.max,nativeMin=Math.min;var now=function(){return root.Date.now()};function debounce(func,wait,options){var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=false,maxing=false,trailing=true;if(typeof func!="function"){throw new TypeError(FUNC_ERROR_TEXT)}wait=toNumber(wait)||0;if(isObject(options)){leading=!!options.leading;maxing="maxWait"in options;maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait;trailing="trailing"in options?!!options.trailing:trailing}function invokeFunc(time){var args=lastArgs,thisArg=lastThis;lastArgs=lastThis=undefined;lastInvokeTime=time;result=func.apply(thisArg,args);return result}function leadingEdge(time){lastInvokeTime=time;timerId=setTimeout(timerExpired,wait);return leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||timeSinceLastCall<0||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();if(shouldInvoke(time)){return trailingEdge(time)}timerId=setTimeout(timerExpired,remainingWait(time))}function trailingEdge(time){timerId=undefined;if(trailing&&lastArgs){return invokeFunc(time)}lastArgs=lastThis=undefined;return result}function cancel(){if(timerId!==undefined){clearTimeout(timerId)}lastInvokeTime=0;lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);lastArgs=arguments;lastThis=this;lastCallTime=time;if(isInvoking){if(timerId===undefined){return leadingEdge(lastCallTime)}if(maxing){timerId=setTimeout(timerExpired,wait);return invokeFunc(lastCallTime)}}if(timerId===undefined){timerId=setTimeout(timerExpired,wait)}return result}debounced.cancel=cancel;debounced.flush=flush;return debounced}function isObject(value){var type=typeof value;return!!value&&(type=="object"||type=="function")}function isObjectLike(value){return!!value&&typeof value=="object"}function isSymbol(value){return typeof value=="symbol"||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toNumber(value){if(typeof value=="number"){return value}if(isSymbol(value)){return NAN}if(isObject(value)){var other=typeof value.valueOf=="function"?value.valueOf():value;value=isObject(other)?other+"":other}if(typeof value!="string"){return value===0?value:+value}value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}var lodash_debounce=debounce;var TooltipSimple=function(_mixin){_inherits(TooltipSimple,_mixin);var _super=_createSuper(TooltipSimple);function TooltipSimple(element,options){var _this;_classCallCheck(this,TooltipSimple);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"tooltipFadeOut",lodash_debounce(function(){var tooltipTriggerButton=_this.getTooltipTriggerButton();if(tooltipTriggerButton){tooltipTriggerButton.classList.remove(_this.options.classTooltipVisible)}},100));_defineProperty(_assertThisInitialized(_this),"getTooltipTriggerButton",function(){return _this.element.matches(_this.options.selectorTriggerButton)?_this.element:_this.element.querySelector(_this.options.selectorTriggerButton)});_defineProperty(_assertThisInitialized(_this),"allowTooltipVisibility",function(_ref){var visible=_ref.visible;var tooltipTriggerButton=_this.getTooltipTriggerButton();if(!tooltipTriggerButton){return}if(visible){tooltipTriggerButton.classList.remove(_this.options.classTooltipHidden)}else{tooltipTriggerButton.classList.add(_this.options.classTooltipHidden)}});_this.manage(on(_this.element.ownerDocument,"keydown",function(event){if(event.which===27){_this.allowTooltipVisibility({visible:false});var tooltipTriggerButton=_this.getTooltipTriggerButton();if(tooltipTriggerButton){tooltipTriggerButton.classList.remove(_this.options.classTooltipVisible)}}}));_this.manage(on(_this.element,"mouseenter",function(){_this.tooltipFadeOut.cancel();_this.allowTooltipVisibility({visible:true});var tooltipTriggerButton=_this.getTooltipTriggerButton();if(tooltipTriggerButton){tooltipTriggerButton.classList.add(_this.options.classTooltipVisible)}}));_this.manage(on(_this.element,"mouseleave",_this.tooltipFadeOut));_this.manage(on(_this.element,"focusin",function(event){if(eventMatches(event,_this.options.selectorTriggerButton)){_this.allowTooltipVisibility({visible:true})}}));return _this}_createClass(TooltipSimple,null,[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-tooltip-definition],[data-tooltip-icon]",selectorTriggerButton:".".concat(prefix,"--tooltip__trigger.").concat(prefix,"--tooltip--a11y"),classTooltipHidden:"".concat(prefix,"--tooltip--hidden"),classTooltipVisible:"".concat(prefix,"--tooltip--visible")}}}]);return TooltipSimple}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(TooltipSimple,"components",new WeakMap);var toArray$8=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var ProgressIndicator=function(_mixin){_inherits(ProgressIndicator,_mixin);var _super=_createSuper(ProgressIndicator);function ProgressIndicator(element,options){var _this;_classCallCheck(this,ProgressIndicator);_this=_super.call(this,element,options);_this.state={currentIndex:_this.getCurrent().index,totalSteps:_this.getSteps().length};_this.addOverflowTooltip();return _this}_createClass(ProgressIndicator,[{key:"getSteps",value:function getSteps(){return toArray$8(this.element.querySelectorAll(this.options.selectorStepElement)).map(function(element,index){return{element:element,index:index}})}},{key:"getCurrent",value:function getCurrent(){var currentEl=this.element.querySelector(this.options.selectorCurrent);return this.getSteps().filter(function(step){return step.element===currentEl})[0]}},{key:"setCurrent",value:function setCurrent(){var _this2=this;var newCurrentStep=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this.state.currentIndex;var changed=false;if(newCurrentStep!==this.state.currentIndex){this.state.currentIndex=newCurrentStep;changed=true}if(changed){this.getSteps().forEach(function(step){if(step.indexnewCurrentStep){_this2._updateStep({element:step.element,className:_this2.options.classIncomplete,html:_this2._getIncompleteSVG()})}})}}},{key:"_updateStep",value:function _updateStep(args){var element=args.element,className=args.className,html=args.html;if(element.firstElementChild){element.removeChild(element.firstElementChild)}if(!element.classList.contains(className)){element.setAttribute("class",this.options.classStep);element.classList.add(className)}element.insertAdjacentHTML("afterbegin",html)}},{key:"_getSVGComplete",value:function _getSVGComplete(){return'\n \n \n '}},{key:"_getCurrentSVG",value:function _getCurrentSVG(){return'\n \n \n '}},{key:"_getIncompleteSVG",value:function _getIncompleteSVG(){return'\n \n '}},{key:"addOverflowTooltip",value:function addOverflowTooltip(){var _this3=this;var stepLabels=toArray$8(this.element.querySelectorAll(this.options.selectorLabel));var tooltips=toArray$8(this.element.querySelectorAll(this.options.selectorTooltip));stepLabels.forEach(function(step){if(step.scrollWidth>_this3.options.maxWidth){step.classList.add(_this3.options.classOverflowLabel)}});tooltips.forEach(function(tooltip){var childText=tooltip.querySelector(_this3.options.selectorTooltipText);if(childText.scrollHeight>_this3.options.tooltipMaxHeight){tooltip.classList.add(_this3.options.classTooltipMulti)}})}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-progress]",selectorStepElement:".".concat(prefix,"--progress-step"),selectorCurrent:".".concat(prefix,"--progress-step--current"),selectorIncomplete:".".concat(prefix,"--progress-step--incomplete"),selectorComplete:".".concat(prefix,"--progress-step--complete"),selectorLabel:".".concat(prefix,"--progress-label"),selectorTooltip:".".concat(prefix,"--tooltip"),selectorTooltipText:".".concat(prefix,"--tooltip__text"),classStep:"".concat(prefix,"--progress-step"),classComplete:"".concat(prefix,"--progress-step--complete"),classCurrent:"".concat(prefix,"--progress-step--current"),classIncomplete:"".concat(prefix,"--progress-step--incomplete"),classOverflowLabel:"".concat(prefix,"--progress-label-overflow"),classTooltipMulti:"".concat(prefix,"--tooltip_multi"),maxWidth:87,tooltipMaxHeight:21}}}]);return ProgressIndicator}(mixin(createComponent,initComponentBySearch));_defineProperty(ProgressIndicator,"components",new WeakMap);var toArray$9=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var StructuredList=function(_mixin){_inherits(StructuredList,_mixin);var _super=_createSuper(StructuredList);function StructuredList(element,options){var _this;_classCallCheck(this,StructuredList);_this=_super.call(this,element,options);_this.manage(on(_this.element,"keydown",function(evt){if(evt.which===37||evt.which===38||evt.which===39||evt.which===40){_this._handleKeydownArrow(evt)}if(evt.which===13||evt.which===32){_this._handleKeydownChecked(evt)}}));_this.manage(on(_this.element,"click",function(evt){_this._handleClick(evt)}));return _this}_createClass(StructuredList,[{key:"_direction",value:function _direction(evt){return{37:-1,38:-1,39:1,40:1}[evt.which]}},{key:"_nextIndex",value:function _nextIndex(array,arrayItem,direction){return array.indexOf(arrayItem)+direction}},{key:"_getInput",value:function _getInput(index){var rows=toArray$9(this.element.querySelectorAll(this.options.selectorRow));return this.element.ownerDocument.querySelector(this.options.selectorListInput(rows[index].getAttribute("for")))}},{key:"_handleInputChecked",value:function _handleInputChecked(index){var rows=this.element.querySelectorAll(this.options.selectorRow);var input=this.getInput(index)||rows[index].querySelector("input");input.checked=true}},{key:"_handleClick",value:function _handleClick(evt){var _this2=this;var selectedRow=eventMatches(evt,this.options.selectorRow);toArray$9(this.element.querySelectorAll(this.options.selectorRow)).forEach(function(row){return row.classList.remove(_this2.options.classActive)});if(selectedRow){selectedRow.classList.add(this.options.classActive)}}},{key:"_handleKeydownChecked",value:function _handleKeydownChecked(evt){var _this3=this;evt.preventDefault();var selectedRow=eventMatches(evt,this.options.selectorRow);toArray$9(this.element.querySelectorAll(this.options.selectorRow)).forEach(function(row){return row.classList.remove(_this3.options.classActive)});if(selectedRow){selectedRow.classList.add(this.options.classActive);var input=selectedRow.querySelector(this.options.selectorListInput(selectedRow.getAttribute("for")))||selectedRow.querySelector("input");input.checked=true}}},{key:"_handleKeydownArrow",value:function _handleKeydownArrow(evt){var _this4=this;evt.preventDefault();var selectedRow=eventMatches(evt,this.options.selectorRow);var direction=this._direction(evt);if(direction&&selectedRow!==undefined){var rows=toArray$9(this.element.querySelectorAll(this.options.selectorRow));rows.forEach(function(row){return row.classList.remove(_this4.options.classActive)});var firstIndex=0;var nextIndex=this._nextIndex(rows,selectedRow,direction);var lastIndex=rows.length-1;var getSelectedIndex=function getSelectedIndex(){switch(nextIndex){case-1:return lastIndex;case rows.length:return firstIndex;default:return nextIndex}};var selectedIndex=getSelectedIndex();rows[selectedIndex].classList.add(this.options.classActive);rows[selectedIndex].focus();this._handleInputChecked(selectedIndex)}}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-structured-list]",selectorRow:"[data-structured-list] .".concat(prefix,"--structured-list-tbody > label.").concat(prefix,"--structured-list-row"),selectorListInput:function selectorListInput(id){return"#".concat(id,".").concat(prefix,"--structured-list-input")},classActive:"".concat(prefix,"--structured-list-row--selected")}}}]);return StructuredList}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(StructuredList,"components",new WeakMap);var Slider=function(_mixin){_inherits(Slider,_mixin);var _super=_createSuper(Slider);function Slider(element,options){var _this;_classCallCheck(this,Slider);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_changeState",function(state,detail,callback){callback()});_this.sliderActive=false;_this.dragging=false;_this.track=_this.element.querySelector(_this.options.selectorTrack);_this.filledTrack=_this.element.querySelector(_this.options.selectorFilledTrack);_this.thumb=_this.element.querySelector(_this.options.selectorThumb);_this.input=_this.element.querySelector(_this.options.selectorInput);if(_this.element.dataset.sliderInputBox){_this.boundInput=_this.element.ownerDocument.querySelector(_this.element.dataset.sliderInputBox);_this._updateInput();_this.manage(on(_this.boundInput,"change",function(evt){_this.setValue(evt.target.value)}));_this.manage(on(_this.boundInput,"focus",function(evt){evt.target.select()}));_this.manage(on(_this.boundInput,"mouseup",function(evt){evt.preventDefault()}))}_this._updatePosition();_this.manage(on(_this.thumb,"mousedown",function(){_this.sliderActive=true}));_this.manage(on(_this.element.ownerDocument,"mouseup",function(){_this.sliderActive=false}));_this.manage(on(_this.element.ownerDocument,"mousemove",function(evt){var disabled=_this.element.classList.contains(_this.options.classDisabled);if(_this.sliderActive===true&&!disabled){_this._updatePosition(evt)}}));_this.manage(on(_this.thumb,"keydown",function(evt){var disabled=_this.element.classList.contains(_this.options.classDisabled);if(!disabled){_this._updatePosition(evt)}}));_this.manage(on(_this.track,"click",function(evt){var disabled=_this.element.classList.contains(_this.options.classDisabled);if(!disabled){_this._updatePosition(evt)}}));return _this}_createClass(Slider,[{key:"_updatePosition",value:function _updatePosition(evt){var _this2=this;var _this$_calcValue=this._calcValue(evt),left=_this$_calcValue.left,newValue=_this$_calcValue.newValue;if(this.dragging){return}this.dragging=true;requestAnimationFrame(function(){_this2.dragging=false;_this2.thumb.style.left="".concat(left,"%");_this2.filledTrack.style.transform="translate(0%, -50%) scaleX(".concat(left/100,")");_this2.input.value=newValue;_this2._updateInput();_this2.changeState("slider-value-change",{value:newValue})})}},{key:"_calcValue",value:function _calcValue(evt){var _this$getInputProps=this.getInputProps(),value=_this$getInputProps.value,min=_this$getInputProps.min,max=_this$getInputProps.max,step=_this$getInputProps.step;var range=max-min;var valuePercentage=(value-min)/range*100;var left;var newValue;left=valuePercentage;newValue=value;if(evt){var type=evt.type;if(type==="keydown"){var direction={40:-1,37:-1,38:1,39:1}[evt.which];if(direction!==undefined){var multiplier=evt.shiftKey===true?range/step/this.options.stepMultiplier:1;var stepMultiplied=step*multiplier;var stepSize=stepMultiplied/range*100;left=valuePercentage+stepSize*direction;newValue=Number(value)+stepMultiplied*direction}}if(type==="mousemove"||type==="click"){if(type==="click"){this.element.querySelector(this.options.selectorThumb).classList.add(this.options.classThumbClicked)}else{this.element.querySelector(this.options.selectorThumb).classList.remove(this.options.classThumbClicked)}var track=this.track.getBoundingClientRect();var unrounded=(evt.clientX-track.left)/track.width;var rounded=Math.round(range*unrounded/step)*step;left=rounded/range*100;newValue=rounded+min}}if(newValue<=Number(min)){left=0;newValue=min}if(newValue>=Number(max)){left=100;newValue=max}return{left:left,newValue:newValue}}},{key:"_updateInput",value:function _updateInput(){if(this.boundInput){this.boundInput.value=this.input.value}}},{key:"getInputProps",value:function getInputProps(){var values={value:Number(this.input.value),min:Number(this.input.min),max:Number(this.input.max),step:this.input.step?Number(this.input.step):1};return values}},{key:"setValue",value:function setValue(value){this.input.value=value;this._updatePosition()}},{key:"stepUp",value:function stepUp(){this.input.stepUp();this._updatePosition()}},{key:"stepDown",value:function stepDown(){this.input.stepDown();this._updatePosition()}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-slider]",selectorTrack:".".concat(prefix,"--slider__track"),selectorFilledTrack:".".concat(prefix,"--slider__filled-track"),selectorThumb:".".concat(prefix,"--slider__thumb"),selectorInput:".".concat(prefix,"--slider__input"),classDisabled:"".concat(prefix,"--slider--disabled"),classThumbClicked:"".concat(prefix,"--slider__thumb--clicked"),eventBeforeSliderValueChange:"slider-before-value-change",eventAfterSliderValueChange:"slider-after-value-change",stepMultiplier:4}}}]);return Slider}(mixin(createComponent,initComponentBySearch,eventedState,handles));_defineProperty(Slider,"components",new WeakMap);var Tile=function(_mixin){_inherits(Tile,_mixin);var _super=_createSuper(Tile);function Tile(element,options){var _this;_classCallCheck(this,Tile);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_getClass",function(type){var typeObj={expandable:_this.options.classExpandedTile,clickable:_this.options.classClickableTile,selectable:_this.options.classSelectableTile};return typeObj[type]});_defineProperty(_assertThisInitialized(_this),"_hookActions",function(tileClass){var isExpandable=_this.tileType==="expandable";if(isExpandable){var aboveTheFold=_this.element.querySelector(_this.options.selectorAboveTheFold);var getStyle=_this.element.ownerDocument.defaultView.getComputedStyle(_this.element,null);var tilePaddingTop=parseInt(getStyle.getPropertyValue("padding-top"),10);var tilePaddingBottom=parseInt(getStyle.getPropertyValue("padding-bottom"),10);var tilePadding=tilePaddingTop+tilePaddingBottom;if(aboveTheFold){_this.tileHeight=_this.element.getBoundingClientRect().height;_this.atfHeight=aboveTheFold.getBoundingClientRect().height+tilePadding;_this.element.style.maxHeight="".concat(_this.atfHeight,"px")}if(_this.element.classList.contains(_this.options.classExpandedTile)){_this._setTileHeight()}}_this.element.addEventListener("click",function(evt){var input=eventMatches(evt,_this.options.selectorTileInput);if(!input){_this.element.classList.toggle(tileClass)}if(isExpandable){_this._setTileHeight()}});_this.element.addEventListener("keydown",function(evt){var input=_this.element.querySelector(_this.options.selectorTileInput);if(input){if(evt.which===13||evt.which===32){if(!isExpandable){_this.element.classList.toggle(tileClass);input.checked=!input.checked}}}})});_defineProperty(_assertThisInitialized(_this),"_setTileHeight",function(){var isExpanded=_this.element.classList.contains(_this.options.classExpandedTile);_this.element.style.maxHeight=isExpanded?"".concat(_this.tileHeight,"px"):"".concat(_this.atfHeight,"px")});_this.tileType=_this.element.dataset.tile;_this.tileHeight=0;_this.atfHeight=0;_this._hookActions(_this._getClass(_this.tileType));return _this}_createClass(Tile,[{key:"release",value:function release(){_get(_getPrototypeOf(Tile.prototype),"release",this).call(this)}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-tile]",selectorAboveTheFold:"[data-tile-atf]",selectorTileInput:"[data-tile-input]",classExpandedTile:"".concat(prefix,"--tile--is-expanded"),classClickableTile:"".concat(prefix,"--tile--is-clicked"),classSelectableTile:"".concat(prefix,"--tile--is-selected")}}}]);return Tile}(mixin(createComponent,initComponentBySearch));_defineProperty(Tile,"components",new WeakMap);var CodeSnippet=function(_mixin){_inherits(CodeSnippet,_mixin);var _super=_createSuper(CodeSnippet);function CodeSnippet(element,options){var _this;_classCallCheck(this,CodeSnippet);_this=_super.call(this,element,options);_this._initCodeSnippet();_this.element.querySelector(_this.options.classExpandBtn).addEventListener("click",function(evt){return _this._handleClick(evt)});return _this}_createClass(CodeSnippet,[{key:"_handleClick",value:function _handleClick(){var expandBtn=this.element.querySelector(this.options.classExpandText);this.element.classList.toggle(this.options.classExpanded);if(this.element.classList.contains(this.options.classExpanded)){expandBtn.textContent=expandBtn.getAttribute(this.options.attribShowLessText)}else{expandBtn.textContent=expandBtn.getAttribute(this.options.attribShowMoreText)}}},{key:"_initCodeSnippet",value:function _initCodeSnippet(){var expandBtn=this.element.querySelector(this.options.classExpandText);if(!expandBtn){throw new TypeError("Cannot find the expand button.")}expandBtn.textContent=expandBtn.getAttribute(this.options.attribShowMoreText);if(this.element.offsetHeight .").concat(prefix,"--assistive-text"),passwordIsVisible:"".concat(prefix,"--text-input--password-visible"),svgIconVisibilityOn:"svg.".concat(prefix,"--icon--visibility-on"),svgIconVisibilityOff:"svg.".concat(prefix,"--icon--visibility-off")}}}]);return TextInput}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(TextInput,"components",new WeakMap);var prefix=settings_1.prefix;var SideNav=function(_mixin){_inherits(SideNav,_mixin);var _super=_createSuper(SideNav);function SideNav(element,options){var _this;_classCallCheck(this,SideNav);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_handleClick",function(evt){var matchesToggle=eventMatches(evt,_this.options.selectorSideNavToggle);var matchesNavSubmenu=eventMatches(evt,_this.options.selectorSideNavSubmenu);var matchesSideNavLink=eventMatches(evt,_this.options.selectorSideNavLink);if(!matchesToggle&&!matchesNavSubmenu&&!matchesSideNavLink){return}if(matchesToggle){_this.changeState(!_this.isNavExpanded()?_this.constructor.state.EXPANDED:_this.constructor.state.COLLAPSED);return}if(matchesNavSubmenu){var isSubmenuExpanded=matchesNavSubmenu.getAttribute("aria-expanded")==="true";matchesNavSubmenu.setAttribute("aria-expanded","".concat(!isSubmenuExpanded));return}if(matchesSideNavLink){_toConsumableArray(_this.element.querySelectorAll(_this.options.selectorSideNavLinkCurrent)).forEach(function(el){el.classList.remove(_this.options.classSideNavItemActive,_this.options.classSideNavLinkCurrent);el.removeAttribute("aria-current")});matchesSideNavLink.classList.add(_this.options.classSideNavLinkCurrent);var closestSideNavItem=matchesSideNavLink.closest(_this.options.selectorSideNavItem);if(closestSideNavItem){closestSideNavItem.classList.add(_this.options.classSideNavItemActive)}}});_this.manage(on(element,"click",_this._handleClick));return _this}_createClass(SideNav,[{key:"isNavExpanded",value:function isNavExpanded(){return this.element.classList.contains(this.options.classSideNavExpanded)}},{key:"changeState",value:function changeState(state){this.element.classList.toggle(this.options.classSideNavExpanded,state===this.constructor.state.EXPANDED)}}]);return SideNav}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(SideNav,"components",new WeakMap);_defineProperty(SideNav,"state",{EXPANDED:"expanded",COLLAPSED:"collapsed"});_defineProperty(SideNav,"options",{selectorInit:"[data-side-nav]",selectorSideNavToggle:".".concat(prefix,"--side-nav__toggle"),selectorSideNavSubmenu:".".concat(prefix,"--side-nav__submenu"),selectorSideNavItem:".".concat(prefix,"--side-nav__item"),selectorSideNavLink:".".concat(prefix,"--side-nav__link"),selectorSideNavLinkCurrent:'[aria-current="page"],.'.concat(prefix,"--side-nav__link--current,.").concat(prefix,"--side-nav__item--active"),classSideNavExpanded:"".concat(prefix,"--side-nav--expanded"),classSideNavItemActive:"".concat(prefix,"--side-nav__item--active"),classSideNavLinkCurrent:"".concat(prefix,"--side-nav__link--current")});var forEach=function(){return Array.prototype.forEach}();var toArray$a=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var HeaderSubmenu=function(_mixin){_inherits(HeaderSubmenu,_mixin);var _super=_createSuper(HeaderSubmenu);function HeaderSubmenu(element,options){var _this;_classCallCheck(this,HeaderSubmenu);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_getAction",function(event){var isFlyoutMenu=eventMatches(event,_this.options.selectorFlyoutMenu);if(isFlyoutMenu){return _this.constructor.actions.DELEGATE_TO_FLYOUT_MENU}switch(event.type){case"keydown":return{32:_this.constructor.actions.TOGGLE_SUBMENU_WITH_FOCUS,13:_this.constructor.actions.TOGGLE_SUBMENU_WITH_FOCUS,27:_this.constructor.actions.CLOSE_SUBMENU}[event.which];case"click":return eventMatches(event,_this.options.selectorItem)?_this.constructor.actions.CLOSE_SUBMENU:null;case"blur":case"focusout":{var isOfSelf=_this.element.contains(event.relatedTarget);return isOfSelf?null:_this.constructor.actions.CLOSE_SUBMENU}case"mouseenter":return _this.constructor.actions.OPEN_SUBMENU;case"mouseleave":return _this.constructor.actions.CLOSE_SUBMENU;default:return null}});_defineProperty(_assertThisInitialized(_this),"_getNewState",function(action){var trigger=_this.element.querySelector(_this.options.selectorTrigger);var isExpanded=trigger.getAttribute(_this.options.attribExpanded)==="true";switch(action){case _this.constructor.actions.CLOSE_SUBMENU:return false;case _this.constructor.actions.OPEN_SUBMENU:return true;case _this.constructor.actions.TOGGLE_SUBMENU_WITH_FOCUS:return!isExpanded;default:return isExpanded}});_defineProperty(_assertThisInitialized(_this),"_setState",function(_ref){var shouldBeExpanded=_ref.shouldBeExpanded,shouldFocusOnOpen=_ref.shouldFocusOnOpen;var trigger=_this.element.querySelector(_this.options.selectorTrigger);trigger.setAttribute(_this.options.attribExpanded,shouldBeExpanded);forEach.call(_this.element.querySelectorAll(_this.options.selectorItem),function(item){item.tabIndex=shouldBeExpanded?0:-1});if(shouldBeExpanded&&shouldFocusOnOpen){_this.element.querySelector(_this.options.selectorItem).focus()}});_defineProperty(_assertThisInitialized(_this),"getCurrentNavigation",function(){var focused=_this.element.ownerDocument.activeElement;return focused.nodeType===Node.ELEMENT_NODE&&focused.matches(_this.options.selectorItem)?focused:null});_defineProperty(_assertThisInitialized(_this),"navigate",function(direction){var items=toArray$a(_this.element.querySelectorAll(_this.options.selectorItem));var start=_this.getCurrentNavigation()||_this.element.querySelector(_this.options.selectorItemSelected);var getNextItem=function getNextItem(old){var handleUnderflow=function handleUnderflow(index,length){return index+(index>=0?0:length)};var handleOverflow=function handleOverflow(index,length){return index-(index=0?0:length)};var handleOverflow=function handleOverflow(index,length){return index-(index .").concat(prefix,"--header__menu-item")}}}]);return HeaderNav}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(HeaderNav,"components",new WeakMap);_defineProperty(HeaderNav,"NAVIGATE",{BACKWARD:-1,FORWARD:1});var NavigationMenuPanel=function(_mixin){_inherits(NavigationMenuPanel,_mixin);var _super=_createSuper(NavigationMenuPanel);function NavigationMenuPanel(){var _this;_classCallCheck(this,NavigationMenuPanel);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}_this=_super.call.apply(_super,[this].concat(args));_defineProperty(_assertThisInitialized(_this),"createdByLauncher",function(event){var isExpanded=!_this.element.hasAttribute("hidden");var newState=isExpanded?"collapsed":"expanded";_this.triggerButton=event.delegateTarget;_this.changeState(newState)});_defineProperty(_assertThisInitialized(_this),"shouldStateBeChanged",function(state){return state==="expanded"===_this.element.hasAttribute("hidden")});_defineProperty(_assertThisInitialized(_this),"_changeState",function(state,callback){toggleAttribute(_this.element,"hidden",state!=="expanded");if(_this.triggerButton){if(state==="expanded"){var focusableMenuItems=_this.element.querySelector(_this.options.selectorFocusableMenuItem);if(focusableMenuItems){focusableMenuItems.focus()}}var label=state==="expanded"?_this.triggerButton.getAttribute(_this.options.attribLabelCollapse):_this.triggerButton.getAttribute(_this.options.attribLabelExpand);_this.triggerButton.classList.toggle(_this.options.classNavigationMenuPanelHeaderActionActive,state==="expanded");_this.triggerButton.setAttribute("aria-label",label);_this.triggerButton.setAttribute("title",label)}callback()});return _this}_createClass(NavigationMenuPanel,null,[{key:"options",get:function get(){var prefix=settings_1.prefix;return{initEventNames:["click"],eventBeforeExpanded:"navigation-menu-being-expanded",eventAfterExpanded:"navigation-menu-expanded",eventBeforeCollapsed:"navigation-menu-being-collapsed",eventAfterCollapsed:"navigation-menu-collapsed",selectorFocusableMenuItem:".".concat(prefix,"--navigation__category-toggle, .").concat(prefix,"--navigation-link"),classNavigationMenuPanelHeaderActionActive:"".concat(prefix,"--header__action--active"),attribLabelExpand:"data-navigation-menu-panel-label-expand",attribLabelCollapse:"data-navigation-menu-panel-label-collapse"}}}]);return NavigationMenuPanel}(mixin(createComponent,initComponentByLauncher,exports$1,handles,eventedState));_defineProperty(NavigationMenuPanel,"components",new WeakMap);var NavigationMenu=function(_NavigationMenuPanel){_inherits(NavigationMenu,_NavigationMenuPanel);var _super=_createSuper(NavigationMenu);function NavigationMenu(element,options){var _this;_classCallCheck(this,NavigationMenu);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"getCurrentNavigation",function(){return _this.element.ownerDocument.activeElement});_defineProperty(_assertThisInitialized(_this),"navigate",function(direction){var items=_toConsumableArray(_this.element.querySelectorAll(_this.options.selectorFocusableNavItems));var start=_this.getCurrentNavigation();var getNextItem=function getNextItem(old){var handleUnderflow=function handleUnderflow(index,length){return index+(index>=0?0:length)};var handleOverflow=function handleOverflow(index,length){return index-(index a.").concat(prefix,"--navigation-link"),selectorShellNavLinkCurrent:".".concat(prefix,"--navigation-item--active,.").concat(prefix,"--navigation__category-item--active"),selectorFocusableNavItems:"\n .".concat(prefix,"--navigation__category-toggle,\n .").concat(prefix,"--navigation-item > .").concat(prefix,"--navigation-link,\n .").concat(prefix,'--navigation-link[tabindex="0"]\n '),selectorShellNavItem:".".concat(prefix,"--navigation-item"),selectorShellNavCategory:".".concat(prefix,"--navigation__category"),selectorShellNavNestedCategory:".".concat(prefix,"--navigation__category-item"),classShellNavItemActive:"".concat(prefix,"--navigation-item--active"),classShellNavLinkCurrent:"".concat(prefix,"--navigation__category-item--active"),classShellNavCategoryExpanded:"".concat(prefix,"--navigation__category--expanded")})}}]);return NavigationMenu}(NavigationMenuPanel);_defineProperty(NavigationMenu,"components",new WeakMap);_defineProperty(NavigationMenu,"NAVIGATE",{BACKWARD:-1,FORWARD:1});function onFocusByKeyboard(node,name,callback){var hasFocusout="onfocusout"in window;var focusinEventName=hasFocusout?"focusin":"focus";var focusoutEventName=hasFocusout?"focusout":"blur";var supportedEvents={focus:focusinEventName,blur:focusoutEventName};var eventName=supportedEvents[name];if(!eventName){throw new Error("Unsupported event!")}var clicked;var handleMousedown=function handleMousedown(){clicked=true;requestAnimationFrame(function(){clicked=false})};var handleFocusin=function handleFocusin(evt){if(!clicked){callback(evt)}};node.ownerDocument.addEventListener("mousedown",handleMousedown);node.addEventListener(eventName,handleFocusin,!hasFocusout);return{release:function release(){if(handleFocusin){node.removeEventListener(eventName,handleFocusin,!hasFocusout);handleFocusin=null}if(handleMousedown){node.ownerDocument.removeEventListener("mousedown",handleMousedown);handleMousedown=null}return null}}}var seq=0;var ProductSwitcher=function(_NavigationMenuPanel){_inherits(ProductSwitcher,_NavigationMenuPanel);var _super=_createSuper(ProductSwitcher);function ProductSwitcher(element,options){var _this;_classCallCheck(this,ProductSwitcher);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"current","");_defineProperty(_assertThisInitialized(_this),"triggerButtonIds",new Set);_defineProperty(_assertThisInitialized(_this),"_handleFocusOut",function(event){if(_this.element.contains(event.relatedTarget)){return}var currentTriggerButton=_this.element.ownerDocument.getElementById(_this.current);if(currentTriggerButton&&event.relatedTarget&&!event.relatedTarget.matches(_this.options.selectorFloatingMenus)){currentTriggerButton.focus()}});_defineProperty(_assertThisInitialized(_this),"_handleKeyDown",function(event){var isExpanded=!_this.element.hasAttribute("hidden");if(event.which===27&&isExpanded){var triggerButton=_this.current;_this.changeState(_this.constructor.SELECT_NONE);_this.element.ownerDocument.getElementById(triggerButton).focus()}});_defineProperty(_assertThisInitialized(_this),"createdByLauncher",function(event){var isExpanded=_this.element.classList.contains(_this.options.classProductSwitcherExpanded);var launcher=event.delegateTarget;if(!launcher.id){launcher.id="__carbon-product-switcher-launcher-".concat(seq++)}var current=launcher.id;_this.changeState(isExpanded&&_this.current===current?_this.constructor.SELECT_NONE:current)});_defineProperty(_assertThisInitialized(_this),"shouldStateBeChanged",function(current){return _this.current!==current});_defineProperty(_assertThisInitialized(_this),"_changeState",function(state,callback){_this.element.classList.toggle(_this.options.classProductSwitcherExpanded,state!==_this.constructor.SELECT_NONE);_this.current=state;if(_this.current!==_this.constructor.SELECT_NONE){_this.triggerButtonIds.add(_this.current)}_this.triggerButtonIds.forEach(function(id){var button=_this.element.ownerDocument.getElementById(id);var label=button.getAttribute(_this.options.attribLabelExpand);button.classList.remove(_this.options.classNavigationMenuPanelHeaderActionActive);button.setAttribute("aria-label",label);button.setAttribute("title",label)});var currentTriggerButton=_this.element.ownerDocument.getElementById(_this.current);if(currentTriggerButton){var label=currentTriggerButton.getAttribute(_this.options.attribLabelCollapse);currentTriggerButton.classList.toggle(_this.options.classNavigationMenuPanelHeaderActionActive);currentTriggerButton.setAttribute("aria-label",label);currentTriggerButton.setAttribute("title",label)}if(state!==_this.constructor.SELECT_NONE){_this.element.setAttribute("tabindex","0");_this.element.focus()}else{_this.element.setAttribute("tabindex","-1")}callback()});_this.manage(on(element,"keydown",_this._handleKeyDown));_this.manage(onFocusByKeyboard(element,"blur",_this._handleFocusOut));return _this}_createClass(ProductSwitcher,[{key:"release",value:function release(){this.triggerButtonIds.clear();return _get(_getPrototypeOf(ProductSwitcher.prototype),"release",this).call(this)}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return Object.assign(Object.create(NavigationMenuPanel.options),{selectorInit:"[data-product-switcher]",selectorFloatingMenus:"\n .".concat(prefix,"--overflow-menu-options,\n .").concat(prefix,"--overflow-menu-options *,\n .").concat(prefix,"--tooltip,\n .").concat(prefix,"--tooltip *,\n .flatpicker-calendar,\n .flatpicker-calendar *\n "),attribInitTarget:"data-product-switcher-target",classProductSwitcherExpanded:"".concat(prefix,"--panel--expanded")})}}]);return ProductSwitcher}(NavigationMenuPanel);_defineProperty(ProductSwitcher,"SELECT_NONE","__carbon-product-switcher-launcher-NONE");_defineProperty(ProductSwitcher,"components",new WeakMap);var PaginationNav=function(_mixin){_inherits(PaginationNav,_mixin);var _super=_createSuper(PaginationNav);function PaginationNav(element,options){var _this;_classCallCheck(this,PaginationNav);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"getActivePageNumber",function(){var pageNum;var activePageElement=_this.element.querySelector(_this.options.selectorPageActive);if(activePageElement){pageNum=Number(activePageElement.getAttribute(_this.options.attribPage))}return pageNum});_defineProperty(_assertThisInitialized(_this),"clearActivePage",function(evt){var pageButtonNodeList=_this.element.querySelectorAll(_this.options.selectorPageButton);var pageSelectElement=_this.element.querySelector(_this.options.selectorPageSelect);Array.prototype.forEach.call(pageButtonNodeList,function(el){el.classList.remove(_this.options.classActive,_this.options.classDisabled);el.removeAttribute(_this.options.attribActive);el.removeAttribute("aria-disabled");el.removeAttribute("aria-current")});if(pageSelectElement){pageSelectElement.removeAttribute("aria-current");var pageSelectElementOptions=pageSelectElement.options;Array.prototype.forEach.call(pageSelectElementOptions,function(el){el.removeAttribute(_this.options.attribActive)});if(!evt.target.matches(_this.options.selectorPageSelect)){pageSelectElement.classList.remove(_this.options.classActive);pageSelectElement.value=""}}});_defineProperty(_assertThisInitialized(_this),"handleClick",function(evt){if(!evt.target.getAttribute("aria-disabled")===true){var nextActivePageNumber=_this.getActivePageNumber();var pageElementNodeList=_this.element.querySelectorAll(_this.options.selectorPageElement);var pageSelectElement=_this.element.querySelector(_this.options.selectorPageSelect);_this.clearActivePage(evt);if(evt.target.matches(_this.options.selectorPageButton)){nextActivePageNumber=Number(evt.target.getAttribute(_this.options.attribPage))}if(evt.target.matches(_this.options.selectorPagePrevious)){nextActivePageNumber-=1}if(evt.target.matches(_this.options.selectorPageNext)){nextActivePageNumber+=1}var pageTargetElement=pageElementNodeList[nextActivePageNumber-1];pageTargetElement.setAttribute(_this.options.attribActive,true);if(pageTargetElement.tagName==="OPTION"){pageSelectElement.value=_this.getActivePageNumber();pageSelectElement.classList.add(_this.options.classActive);pageSelectElement.setAttribute("aria-current","page")}else{pageTargetElement.classList.add(_this.options.classActive,_this.options.classDisabled);pageTargetElement.setAttribute("aria-disabled",true);pageTargetElement.setAttribute("aria-current","page")}_this.setPrevNextStates()}});_defineProperty(_assertThisInitialized(_this),"handleSelectChange",function(evt){_this.clearActivePage(evt);var pageSelectElement=_this.element.querySelector(_this.options.selectorPageSelect);var pageSelectElementOptions=pageSelectElement.options;pageSelectElementOptions[pageSelectElementOptions.selectedIndex].setAttribute(_this.options.attribActive,true);evt.target.setAttribute("aria-current","page");evt.target.classList.add(_this.options.classActive);_this.setPrevNextStates()});_defineProperty(_assertThisInitialized(_this),"setPrevNextStates",function(){var pageElementNodeList=_this.element.querySelectorAll(_this.options.selectorPageElement);var totalPages=pageElementNodeList.length;var pageDirectionElementPrevious=_this.element.querySelector(_this.options.selectorPagePrevious);var pageDirectionElementNext=_this.element.querySelector(_this.options.selectorPageNext);if(pageDirectionElementPrevious){if(_this.getActivePageNumber()<=1){pageDirectionElementPrevious.setAttribute("aria-disabled",true);pageDirectionElementPrevious.classList.add(_this.options.classDisabled)}else{pageDirectionElementPrevious.removeAttribute("aria-disabled");pageDirectionElementPrevious.classList.remove(_this.options.classDisabled)}}if(pageDirectionElementNext){if(_this.getActivePageNumber()>=totalPages){pageDirectionElementNext.setAttribute("aria-disabled",true);pageDirectionElementNext.classList.add(_this.options.classDisabled)}else{pageDirectionElementNext.removeAttribute("aria-disabled");pageDirectionElementNext.classList.remove(_this.options.classDisabled)}}});_this.manage(on(_this.element,"click",function(evt){return _this.handleClick(evt)}));_this.manage(on(_this.element,"change",function(evt){if(evt.target.matches(_this.options.selectorPageSelect)){_this.handleSelectChange(evt)}}));return _this}_createClass(PaginationNav,null,[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-pagination-nav]",selectorPageElement:"[data-page]",selectorPageButton:"[data-page-button]",selectorPagePrevious:"[data-page-previous]",selectorPageNext:"[data-page-next]",selectorPageSelect:"[data-page-select]",selectorPageActive:'[data-page-active="true"]',attribPage:"data-page",attribActive:"data-page-active",classActive:"".concat(prefix,"--pagination-nav__page--active"),classDisabled:"".concat(prefix,"--pagination-nav__page--disabled")}}}]);return PaginationNav}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(PaginationNav,"components",new WeakMap);var components=Object.freeze({__proto__:null,Checkbox:Checkbox,FileUploader:FileUploader,ContentSwitcher:ContentSwitcher,Tab:Tab,OverflowMenu:OverflowMenu,Modal:Modal,Loading:Loading,InlineLoading:InlineLoading,Dropdown:Dropdown,NumberInput:NumberInput,DataTableV2:DataTable,DataTable:DataTable,DatePicker:DatePicker,Pagination:Pagination,Search:Search,Accordion:Accordion,CopyButton:CopyButton,Notification:Notification,Toolbar:Toolbar,Tooltip:Tooltip,TooltipSimple:TooltipSimple,ProgressIndicator:ProgressIndicator,FloatingMenu:FloatingMenu,StructuredList:StructuredList,Slider:Slider,Tile:Tile,CodeSnippet:CodeSnippet,TextInput:TextInput,SideNav:SideNav,HeaderSubmenu:HeaderSubmenu,HeaderNav:HeaderNav,NavigationMenu:NavigationMenu,ProductSwitcher:ProductSwitcher,PaginationNav:PaginationNav});var components$1=components;var init=function init(){var componentClasses=Object.keys(components$1).map(function(key){return components$1[key]}).filter(function(component){return typeof component.init==="function"});if(!settings_1.disableAutoInit){componentClasses.forEach(function(Clz){var h=Clz.init()})}};if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",init)}else{setTimeout(init,0)}var forEach$1=Array.prototype.forEach;var createAndReleaseComponentsUponDOMMutation=function createAndReleaseComponentsUponDOMMutation(records,componentClasses,componentClassesForWatchInit,options){records.forEach(function(record){forEach$1.call(record.addedNodes,function(node){if(node.nodeType===Node.ELEMENT_NODE){componentClassesForWatchInit.forEach(function(Clz){Clz.init(node,options)})}});forEach$1.call(record.removedNodes,function(node){if(node.nodeType===Node.ELEMENT_NODE){componentClasses.forEach(function(Clz){if(node.matches(Clz.options.selectorInit)){var instance=Clz.components.get(node);if(instance){instance.release()}}else{forEach$1.call(node.querySelectorAll(Clz.options.selectorInit),function(element){var instance=Clz.components.get(element);if(instance){instance.release()}})}})}})})};function watch(){var target=arguments.length>0&&arguments[0]!==undefined?arguments[0]:document;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(target.nodeType!==Node.ELEMENT_NODE&&target.nodeType!==Node.DOCUMENT_NODE){throw new TypeError("DOM document or DOM element should be given to watch for DOM node to create/release components.")}var componentClasses=Object.keys(components).map(function(key){return components[key]}).filter(function(component){return typeof component.init==="function"});var handles=componentClasses.map(function(Clz){return Clz.init(target,options)}).filter(Boolean);var componentClassesForWatchInit=componentClasses.filter(function(Clz){return!Clz.forLazyInit});var observer=new MutationObserver(function(records){createAndReleaseComponentsUponDOMMutation(records,componentClasses,componentClassesForWatchInit,options)});observer.observe(target,{childList:true,subtree:true});return{release:function release(){for(var handle=handles.pop();handle;handle=handles.pop()){handle.release()}if(observer){observer.disconnect();observer=null}}}}exports.Accordion=Accordion;exports.Checkbox=Checkbox;exports.CodeSnippet=CodeSnippet;exports.ContentSwitcher=ContentSwitcher;exports.CopyButton=CopyButton;exports.DataTable=DataTable;exports.DataTableV2=DataTable;exports.DatePicker=DatePicker;exports.Dropdown=Dropdown;exports.FileUploader=FileUploader;exports.FloatingMenu=FloatingMenu;exports.HeaderNav=HeaderNav;exports.HeaderSubmenu=HeaderSubmenu;exports.InlineLoading=InlineLoading;exports.Loading=Loading;exports.Modal=Modal;exports.NavigationMenu=NavigationMenu;exports.Notification=Notification;exports.NumberInput=NumberInput;exports.OverflowMenu=OverflowMenu;exports.Pagination=Pagination;exports.PaginationNav=PaginationNav;exports.ProductSwitcher=ProductSwitcher;exports.ProgressIndicator=ProgressIndicator;exports.Search=Search;exports.SideNav=SideNav;exports.Slider=Slider;exports.StructuredList=StructuredList;exports.Tab=Tab;exports.TextInput=TextInput;exports.Tile=Tile;exports.Toolbar=Toolbar;exports.Tooltip=Tooltip;exports.TooltipSimple=TooltipSimple;exports.settings=settings_1;exports.watch=watch;return exports}({});
+(function(e,t){if(typeof define==="function"&&define.amd){define([],t)}else if(typeof module==="object"&&module.exports){module.exports=t()}else{e.htmx=e.htmx||t()}})(typeof self!=="undefined"?self:this,function(){return function(){"use strict";var Q={onLoad:F,process:zt,on:de,off:ge,trigger:ce,ajax:Nr,find:C,findAll:f,closest:v,values:function(e,t){var r=dr(e,t||"post");return r.values},remove:_,addClass:z,removeClass:n,toggleClass:$,takeClass:W,defineExtension:Ur,removeExtension:Br,logAll:V,logNone:j,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,allowScriptTags:true,inlineScriptNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",useTemplateFragments:false,scrollBehavior:"smooth",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get"],selfRequestsOnly:false,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null},parseInterval:d,_:t,createEventSource:function(e){return new EventSource(e,{withCredentials:true})},createWebSocket:function(e){var t=new WebSocket(e,[]);t.binaryType=Q.config.wsBinaryType;return t},version:"1.9.12"};var r={addTriggerHandler:Lt,bodyContains:se,canAccessLocalStorage:U,findThisElement:xe,filterValues:yr,hasAttribute:o,getAttributeValue:te,getClosestAttributeValue:ne,getClosestMatch:c,getExpressionVars:Hr,getHeaders:xr,getInputValues:dr,getInternalData:ae,getSwapSpecification:wr,getTriggerSpecs:it,getTarget:ye,makeFragment:l,mergeObjects:le,makeSettleInfo:T,oobSwap:Ee,querySelectorExt:ue,selectAndSwap:je,settleImmediately:nr,shouldCancel:ut,triggerEvent:ce,triggerErrorEvent:fe,withExtensions:R};var w=["get","post","put","delete","patch"];var i=w.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");var S=e("head"),q=e("title"),H=e("svg",true);function e(e,t){return new RegExp("<"+e+"(\\s[^>]*>|>)([\\s\\S]*?)<\\/"+e+">",!!t?"gim":"im")}function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e.getAttribute&&e.getAttribute(t)}function o(e,t){return e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){return e.parentElement}function re(){return document}function c(e,t){while(e&&!t(e)){e=u(e)}return e?e:null}function L(e,t,r){var n=te(t,r);var i=te(t,"hx-disinherit");if(e!==t&&i&&(i==="*"||i.split(" ").indexOf(r)>=0)){return"unset"}else{return n}}function ne(t,r){var n=null;c(t,function(e){return n=L(t,e,r)});if(n!=="unset"){return n}}function h(e,t){var r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;return r&&r.call(e,t)}function A(e){var t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;var r=t.exec(e);if(r){return r[1].toLowerCase()}else{return""}}function s(e,t){var r=new DOMParser;var n=r.parseFromString(e,"text/html");var i=n.body;while(t>0){t--;i=i.firstChild}if(i==null){i=re().createDocumentFragment()}return i}function N(e){return/"+n+"",0);var a=i.querySelector("template").content;if(Q.config.allowScriptTags){oe(a.querySelectorAll("script"),function(e){if(Q.config.inlineScriptNonce){e.nonce=Q.config.inlineScriptNonce}e.htmxExecuted=navigator.userAgent.indexOf("Firefox")===-1})}else{oe(a.querySelectorAll("script"),function(e){_(e)})}return a}switch(r){case"thead":case"tbody":case"tfoot":case"colgroup":case"caption":return s("",1);case"col":return s("",2);case"tr":return s("",2);case"td":case"th":return s("",3);case"script":case"style":return s(""+n+"
",1);default:return s(n,0)}}function ie(e){if(e){e()}}function I(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return I(e,"Function")}function P(e){return I(e,"Object")}function ae(e){var t="htmx-internal-data";var r=e[t];if(!r){r=e[t]={}}return r}function M(e){var t=[];if(e){for(var r=0;r=0}function se(e){if(e.getRootNode&&e.getRootNode()instanceof window.ShadowRoot){return re().body.contains(e.getRootNode().host)}else{return re().body.contains(e)}}function D(e){return e.trim().split(/\s+/)}function le(e,t){for(var r in t){if(t.hasOwnProperty(r)){e[r]=t[r]}}return e}function E(e){try{return JSON.parse(e)}catch(e){b(e);return null}}function U(){var e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function B(t){try{var e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function t(e){return Tr(re().body,function(){return eval(e)})}function F(t){var e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,r){if(console){console.log(t,e,r)}}}function j(){Q.logger=null}function C(e,t){if(t){return e.querySelector(t)}else{return C(re(),e)}}function f(e,t){if(t){return e.querySelectorAll(t)}else{return f(re(),e)}}function _(e,t){e=p(e);if(t){setTimeout(function(){_(e);e=null},t)}else{e.parentElement.removeChild(e)}}function z(e,t,r){e=p(e);if(r){setTimeout(function(){z(e,t);e=null},r)}else{e.classList&&e.classList.add(t)}}function n(e,t,r){e=p(e);if(r){setTimeout(function(){n(e,t);e=null},r)}else{if(e.classList){e.classList.remove(t);if(e.classList.length===0){e.removeAttribute("class")}}}}function $(e,t){e=p(e);e.classList.toggle(t)}function W(e,t){e=p(e);oe(e.parentElement.children,function(e){n(e,t)});z(e,t)}function v(e,t){e=p(e);if(e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&u(e));return null}}function g(e,t){return e.substring(0,t.length)===t}function G(e,t){return e.substring(e.length-t.length)===t}function J(e){var t=e.trim();if(g(t,"<")&&G(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function Z(e,t){if(t.indexOf("closest ")===0){return[v(e,J(t.substr(8)))]}else if(t.indexOf("find ")===0){return[C(e,J(t.substr(5)))]}else if(t==="next"){return[e.nextElementSibling]}else if(t.indexOf("next ")===0){return[K(e,J(t.substr(5)))]}else if(t==="previous"){return[e.previousElementSibling]}else if(t.indexOf("previous ")===0){return[Y(e,J(t.substr(9)))]}else if(t==="document"){return[document]}else if(t==="window"){return[window]}else if(t==="body"){return[document.body]}else{return re().querySelectorAll(J(t))}}var K=function(e,t){var r=re().querySelectorAll(t);for(var n=0;n=0;n--){var i=r[n];if(i.compareDocumentPosition(e)===Node.DOCUMENT_POSITION_FOLLOWING){return i}}};function ue(e,t){if(t){return Z(e,t)[0]}else{return Z(re().body,e)[0]}}function p(e){if(I(e,"String")){return C(e)}else{return e}}function ve(e,t,r){if(k(t)){return{target:re().body,event:e,listener:t}}else{return{target:p(e),event:t,listener:r}}}function de(t,r,n){jr(function(){var e=ve(t,r,n);e.target.addEventListener(e.event,e.listener)});var e=k(r);return e?r:n}function ge(t,r,n){jr(function(){var e=ve(t,r,n);e.target.removeEventListener(e.event,e.listener)});return k(r)?r:n}var pe=re().createElement("output");function me(e,t){var r=ne(e,t);if(r){if(r==="this"){return[xe(e,t)]}else{var n=Z(e,r);if(n.length===0){b('The selector "'+r+'" on '+t+" returned no matches!");return[pe]}else{return n}}}}function xe(e,t){return c(e,function(e){return te(e,t)!=null})}function ye(e){var t=ne(e,"hx-target");if(t){if(t==="this"){return xe(e,"hx-target")}else{return ue(e,t)}}else{var r=ae(e);if(r.boosted){return re().body}else{return e}}}function be(e){var t=Q.config.attributesToSettle;for(var r=0;r0){o=e.substr(0,e.indexOf(":"));t=e.substr(e.indexOf(":")+1,e.length)}else{o=e}var r=re().querySelectorAll(t);if(r){oe(r,function(e){var t;var r=i.cloneNode(true);t=re().createDocumentFragment();t.appendChild(r);if(!Se(o,e)){t=r}var n={shouldSwap:true,target:e,fragment:t};if(!ce(e,"htmx:oobBeforeSwap",n))return;e=n.target;if(n["shouldSwap"]){Fe(o,e,e,t,a)}oe(a.elts,function(e){ce(e,"htmx:oobAfterSwap",n)})});i.parentNode.removeChild(i)}else{i.parentNode.removeChild(i);fe(re().body,"htmx:oobErrorNoTarget",{content:i})}return e}function Ce(e,t,r){var n=ne(e,"hx-select-oob");if(n){var i=n.split(",");for(var a=0;a0){var r=t.replace("'","\\'");var n=e.tagName.replace(":","\\:");var i=o.querySelector(n+"[id='"+r+"']");if(i&&i!==o){var a=e.cloneNode();we(e,i);s.tasks.push(function(){we(e,a)})}}})}function Oe(e){return function(){n(e,Q.config.addedClass);zt(e);Nt(e);qe(e);ce(e,"htmx:load")}}function qe(e){var t="[autofocus]";var r=h(e,t)?e:e.querySelector(t);if(r!=null){r.focus()}}function a(e,t,r,n){Te(e,r,n);while(r.childNodes.length>0){var i=r.firstChild;z(i,Q.config.addedClass);e.insertBefore(i,t);if(i.nodeType!==Node.TEXT_NODE&&i.nodeType!==Node.COMMENT_NODE){n.tasks.push(Oe(i))}}}function He(e,t){var r=0;while(r-1){var t=e.replace(H,"");var r=t.match(q);if(r){return r[2]}}}function je(e,t,r,n,i,a){i.title=Ve(n);var o=l(n);if(o){Ce(r,o,i);o=Be(r,o,a);Re(o);return Fe(e,r,t,o,i)}}function _e(e,t,r){var n=e.getResponseHeader(t);if(n.indexOf("{")===0){var i=E(n);for(var a in i){if(i.hasOwnProperty(a)){var o=i[a];if(!P(o)){o={value:o}}ce(r,a,o)}}}else{var s=n.split(",");for(var l=0;l0){var o=t[0];if(o==="]"){n--;if(n===0){if(a===null){i=i+"true"}t.shift();i+=")})";try{var s=Tr(e,function(){return Function(i)()},function(){return true});s.source=i;return s}catch(e){fe(re().body,"htmx:syntax:error",{error:e,source:i});return null}}}else if(o==="["){n++}if(Qe(o,a,r)){i+="(("+r+"."+o+") ? ("+r+"."+o+") : (window."+o+"))"}else{i=i+o}a=t.shift()}}}function y(e,t){var r="";while(e.length>0&&!t.test(e[0])){r+=e.shift()}return r}function tt(e){var t;if(e.length>0&&Ze.test(e[0])){e.shift();t=y(e,Ke).trim();e.shift()}else{t=y(e,x)}return t}var rt="input, textarea, select";function nt(e,t,r){var n=[];var i=Ye(t);do{y(i,Je);var a=i.length;var o=y(i,/[,\[\s]/);if(o!==""){if(o==="every"){var s={trigger:"every"};y(i,Je);s.pollInterval=d(y(i,/[,\[\s]/));y(i,Je);var l=et(e,i,"event");if(l){s.eventFilter=l}n.push(s)}else if(o.indexOf("sse:")===0){n.push({trigger:"sse",sseEvent:o.substr(4)})}else{var u={trigger:o};var l=et(e,i,"event");if(l){u.eventFilter=l}while(i.length>0&&i[0]!==","){y(i,Je);var f=i.shift();if(f==="changed"){u.changed=true}else if(f==="once"){u.once=true}else if(f==="consume"){u.consume=true}else if(f==="delay"&&i[0]===":"){i.shift();u.delay=d(y(i,x))}else if(f==="from"&&i[0]===":"){i.shift();if(Ze.test(i[0])){var c=tt(i)}else{var c=y(i,x);if(c==="closest"||c==="find"||c==="next"||c==="previous"){i.shift();var h=tt(i);if(h.length>0){c+=" "+h}}}u.from=c}else if(f==="target"&&i[0]===":"){i.shift();u.target=tt(i)}else if(f==="throttle"&&i[0]===":"){i.shift();u.throttle=d(y(i,x))}else if(f==="queue"&&i[0]===":"){i.shift();u.queue=y(i,x)}else if(f==="root"&&i[0]===":"){i.shift();u[f]=tt(i)}else if(f==="threshold"&&i[0]===":"){i.shift();u[f]=y(i,x)}else{fe(e,"htmx:syntax:error",{token:i.shift()})}}n.push(u)}}if(i.length===a){fe(e,"htmx:syntax:error",{token:i.shift()})}y(i,Je)}while(i[0]===","&&i.shift());if(r){r[t]=n}return n}function it(e){var t=te(e,"hx-trigger");var r=[];if(t){var n=Q.config.triggerSpecsCache;r=n&&n[t]||nt(e,t,n)}if(r.length>0){return r}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,rt)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function at(e){ae(e).cancelled=true}function ot(e,t,r){var n=ae(e);n.timeout=setTimeout(function(){if(se(e)&&n.cancelled!==true){if(!ct(r,e,Wt("hx:poll:trigger",{triggerSpec:r,target:e}))){t(e)}ot(e,t,r)}},r.pollInterval)}function st(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function lt(t,r,e){if(t.tagName==="A"&&st(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"){r.boosted=true;var n,i;if(t.tagName==="A"){n="get";i=ee(t,"href")}else{var a=ee(t,"method");n=a?a.toLowerCase():"get";if(n==="get"){}i=ee(t,"action")}e.forEach(function(e){ht(t,function(e,t){if(v(e,Q.config.disableSelector)){m(e);return}he(n,i,e,t)},r,e,true)})}}function ut(e,t){if(e.type==="submit"||e.type==="click"){if(t.tagName==="FORM"){return true}if(h(t,'input[type="submit"], button')&&v(t,"form")!==null){return true}if(t.tagName==="A"&&t.href&&(t.getAttribute("href")==="#"||t.getAttribute("href").indexOf("#")!==0)){return true}}return false}function ft(e,t){return ae(e).boosted&&e.tagName==="A"&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function ct(e,t,r){var n=e.eventFilter;if(n){try{return n.call(t,r)!==true}catch(e){fe(re().body,"htmx:eventFilter:error",{error:e,source:n.source});return true}}return false}function ht(a,o,e,s,l){var u=ae(a);var t;if(s.from){t=Z(a,s.from)}else{t=[a]}if(s.changed){t.forEach(function(e){var t=ae(e);t.lastValue=e.value})}oe(t,function(n){var i=function(e){if(!se(a)){n.removeEventListener(s.trigger,i);return}if(ft(a,e)){return}if(l||ut(e,a)){e.preventDefault()}if(ct(s,a,e)){return}var t=ae(e);t.triggerSpec=s;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(a)<0){t.handledFor.push(a);if(s.consume){e.stopPropagation()}if(s.target&&e.target){if(!h(e.target,s.target)){return}}if(s.once){if(u.triggeredOnce){return}else{u.triggeredOnce=true}}if(s.changed){var r=ae(n);if(r.lastValue===n.value){return}r.lastValue=n.value}if(u.delayed){clearTimeout(u.delayed)}if(u.throttle){return}if(s.throttle>0){if(!u.throttle){o(a,e);u.throttle=setTimeout(function(){u.throttle=null},s.throttle)}}else if(s.delay>0){u.delayed=setTimeout(function(){o(a,e)},s.delay)}else{ce(a,"htmx:trigger");o(a,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:s.trigger,listener:i,on:n});n.addEventListener(s.trigger,i)})}var vt=false;var dt=null;function gt(){if(!dt){dt=function(){vt=true};window.addEventListener("scroll",dt);setInterval(function(){if(vt){vt=false;oe(re().querySelectorAll("[hx-trigger='revealed'],[data-hx-trigger='revealed']"),function(e){pt(e)})}},200)}}function pt(t){if(!o(t,"data-hx-revealed")&&X(t)){t.setAttribute("data-hx-revealed","true");var e=ae(t);if(e.initHash){ce(t,"revealed")}else{t.addEventListener("htmx:afterProcessNode",function(e){ce(t,"revealed")},{once:true})}}}function mt(e,t,r){var n=D(r);for(var i=0;i=0){var t=wt(n);setTimeout(function(){xt(s,r,n+1)},t)}};t.onopen=function(e){n=0};ae(s).webSocket=t;t.addEventListener("message",function(e){if(yt(s)){return}var t=e.data;R(s,function(e){t=e.transformResponse(t,null,s)});var r=T(s);var n=l(t);var i=M(n.children);for(var a=0;a0){ce(u,"htmx:validation:halted",i);return}t.send(JSON.stringify(l));if(ut(e,u)){e.preventDefault()}})}else{fe(u,"htmx:noWebSocketSourceError")}}function wt(e){var t=Q.config.wsReconnectDelay;if(typeof t==="function"){return t(e)}if(t==="full-jitter"){var r=Math.min(e,6);var n=1e3*Math.pow(2,r);return n*Math.random()}b('htmx.config.wsReconnectDelay must either be a function or the string "full-jitter"')}function St(e,t,r){var n=D(r);for(var i=0;i0){setTimeout(i,n)}else{i()}}function Ht(t,i,e){var a=false;oe(w,function(r){if(o(t,"hx-"+r)){var n=te(t,"hx-"+r);a=true;i.path=n;i.verb=r;e.forEach(function(e){Lt(t,e,i,function(e,t){if(v(e,Q.config.disableSelector)){m(e);return}he(r,n,e,t)})})}});return a}function Lt(n,e,t,r){if(e.sseEvent){Rt(n,r,e.sseEvent)}else if(e.trigger==="revealed"){gt();ht(n,r,t,e);pt(n)}else if(e.trigger==="intersect"){var i={};if(e.root){i.root=ue(n,e.root)}if(e.threshold){i.threshold=parseFloat(e.threshold)}var a=new IntersectionObserver(function(e){for(var t=0;t0){t.polling=true;ot(n,r,e)}else{ht(n,r,t,e)}}function At(e){if(!e.htmxExecuted&&Q.config.allowScriptTags&&(e.type==="text/javascript"||e.type==="module"||e.type==="")){var t=re().createElement("script");oe(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}var r=e.parentElement;try{r.insertBefore(t,e)}catch(e){b(e)}finally{if(e.parentElement){e.parentElement.removeChild(e)}}}}function Nt(e){if(h(e,"script")){At(e)}oe(f(e,"script"),function(e){At(e)})}function It(e){var t=e.attributes;if(!t){return false}for(var r=0;r0){var o=n.shift();var s=o.match(/^\s*([a-zA-Z:\-\.]+:)(.*)/);if(a===0&&s){o.split(":");i=s[1].slice(0,-1);r[i]=s[2]}else{r[i]+=o}a+=Bt(o)}for(var l in r){Ft(e,l,r[l])}}}function jt(e){Ae(e);for(var t=0;tQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(re().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Yt(e){if(!U()){return null}e=B(e);var t=E(localStorage.getItem("htmx-history-cache"))||[];for(var r=0;r=200&&this.status<400){ce(re().body,"htmx:historyCacheMissLoad",o);var e=l(this.response);e=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;var t=Zt();var r=T(t);var n=Ve(this.response);if(n){var i=C("title");if(i){i.innerHTML=n}else{window.document.title=n}}Ue(t,e,r);nr(r.tasks);Jt=a;ce(re().body,"htmx:historyRestore",{path:a,cacheMiss:true,serverResponse:this.response})}else{fe(re().body,"htmx:historyCacheMissLoadError",o)}};e.send()}function ar(e){er();e=e||location.pathname+location.search;var t=Yt(e);if(t){var r=l(t.content);var n=Zt();var i=T(n);Ue(n,r,i);nr(i.tasks);document.title=t.title;setTimeout(function(){window.scrollTo(0,t.scroll)},0);Jt=e;ce(re().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{ir(e)}}}function or(e){var t=me(e,"hx-indicator");if(t==null){t=[e]}oe(t,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)+1;e.classList["add"].call(e.classList,Q.config.requestClass)});return t}function sr(e){var t=me(e,"hx-disabled-elt");if(t==null){t=[]}oe(t,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","")});return t}function lr(e,t){oe(e,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)-1;if(t.requestCount===0){e.classList["remove"].call(e.classList,Q.config.requestClass)}});oe(t,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)-1;if(t.requestCount===0){e.removeAttribute("disabled")}})}function ur(e,t){for(var r=0;r=0}function wr(e,t){var r=t?t:ne(e,"hx-swap");var n={swapStyle:ae(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ae(e).boosted&&!br(e)){n["show"]="top"}if(r){var i=D(r);if(i.length>0){for(var a=0;a0?l.join(":"):null;n["scroll"]=u;n["scrollTarget"]=f}else if(o.indexOf("show:")===0){var c=o.substr(5);var l=c.split(":");var h=l.pop();var f=l.length>0?l.join(":"):null;n["show"]=h;n["showTarget"]=f}else if(o.indexOf("focus-scroll:")===0){var v=o.substr("focus-scroll:".length);n["focusScroll"]=v=="true"}else if(a==0){n["swapStyle"]=o}else{b("Unknown modifier in hx-swap: "+o)}}}}return n}function Sr(e){return ne(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function Er(t,r,n){var i=null;R(r,function(e){if(i==null){i=e.encodeParameters(t,n,r)}});if(i!=null){return i}else{if(Sr(r)){return mr(n)}else{return pr(n)}}}function T(e){return{tasks:[],elts:[e]}}function Cr(e,t){var r=e[0];var n=e[e.length-1];if(t.scroll){var i=null;if(t.scrollTarget){i=ue(r,t.scrollTarget)}if(t.scroll==="top"&&(r||i)){i=i||r;i.scrollTop=0}if(t.scroll==="bottom"&&(n||i)){i=i||n;i.scrollTop=i.scrollHeight}}if(t.show){var i=null;if(t.showTarget){var a=t.showTarget;if(t.showTarget==="window"){a="body"}i=ue(r,a)}if(t.show==="top"&&(r||i)){i=i||r;i.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(n||i)){i=i||n;i.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function Rr(e,t,r,n){if(n==null){n={}}if(e==null){return n}var i=te(e,t);if(i){var a=i.trim();var o=r;if(a==="unset"){return null}if(a.indexOf("javascript:")===0){a=a.substr(11);o=true}else if(a.indexOf("js:")===0){a=a.substr(3);o=true}if(a.indexOf("{")!==0){a="{"+a+"}"}var s;if(o){s=Tr(e,function(){return Function("return ("+a+")")()},{})}else{s=E(a)}for(var l in s){if(s.hasOwnProperty(l)){if(n[l]==null){n[l]=s[l]}}}}return Rr(u(e),t,r,n)}function Tr(e,t,r){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return r}}function Or(e,t){return Rr(e,"hx-vars",true,t)}function qr(e,t){return Rr(e,"hx-vals",false,t)}function Hr(e){return le(Or(e),qr(e))}function Lr(t,r,n){if(n!==null){try{t.setRequestHeader(r,n)}catch(e){t.setRequestHeader(r,encodeURIComponent(n));t.setRequestHeader(r+"-URI-AutoEncoded","true")}}}function Ar(t){if(t.responseURL&&typeof URL!=="undefined"){try{var e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(re().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function O(e,t){return t.test(e.getAllResponseHeaders())}function Nr(e,t,r){e=e.toLowerCase();if(r){if(r instanceof Element||I(r,"String")){return he(e,t,null,null,{targetOverride:p(r),returnPromise:true})}else{return he(e,t,p(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:p(r.target),swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return he(e,t,null,null,{returnPromise:true})}}function Ir(e){var t=[];while(e){t.push(e);e=e.parentElement}return t}function kr(e,t,r){var n;var i;if(typeof URL==="function"){i=new URL(t,document.location.href);var a=document.location.origin;n=a===i.origin}else{i=t;n=g(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!n){return false}}return ce(e,"htmx:validateUrl",le({url:i,sameHost:n},r))}function he(t,r,n,i,a,e){var o=null;var s=null;a=a!=null?a:{};if(a.returnPromise&&typeof Promise!=="undefined"){var l=new Promise(function(e,t){o=e;s=t})}if(n==null){n=re().body}var M=a.handler||Mr;var X=a.select||null;if(!se(n)){ie(o);return l}var u=a.targetOverride||ye(n);if(u==null||u==pe){fe(n,"htmx:targetError",{target:te(n,"hx-target")});ie(s);return l}var f=ae(n);var c=f.lastButtonClicked;if(c){var h=ee(c,"formaction");if(h!=null){r=h}var v=ee(c,"formmethod");if(v!=null){if(v.toLowerCase()!=="dialog"){t=v}}}var d=ne(n,"hx-confirm");if(e===undefined){var D=function(e){return he(t,r,n,i,a,!!e)};var U={target:u,elt:n,path:r,verb:t,triggeringEvent:i,etc:a,issueRequest:D,question:d};if(ce(n,"htmx:confirm",U)===false){ie(o);return l}}var g=n;var p=ne(n,"hx-sync");var m=null;var x=false;if(p){var B=p.split(":");var F=B[0].trim();if(F==="this"){g=xe(n,"hx-sync")}else{g=ue(n,F)}p=(B[1]||"drop").trim();f=ae(g);if(p==="drop"&&f.xhr&&f.abortable!==true){ie(o);return l}else if(p==="abort"){if(f.xhr){ie(o);return l}else{x=true}}else if(p==="replace"){ce(g,"htmx:abort")}else if(p.indexOf("queue")===0){var V=p.split(" ");m=(V[1]||"last").trim()}}if(f.xhr){if(f.abortable){ce(g,"htmx:abort")}else{if(m==null){if(i){var y=ae(i);if(y&&y.triggerSpec&&y.triggerSpec.queue){m=y.triggerSpec.queue}}if(m==null){m="last"}}if(f.queuedRequests==null){f.queuedRequests=[]}if(m==="first"&&f.queuedRequests.length===0){f.queuedRequests.push(function(){he(t,r,n,i,a)})}else if(m==="all"){f.queuedRequests.push(function(){he(t,r,n,i,a)})}else if(m==="last"){f.queuedRequests=[];f.queuedRequests.push(function(){he(t,r,n,i,a)})}ie(o);return l}}var b=new XMLHttpRequest;f.xhr=b;f.abortable=x;var w=function(){f.xhr=null;f.abortable=false;if(f.queuedRequests!=null&&f.queuedRequests.length>0){var e=f.queuedRequests.shift();e()}};var j=ne(n,"hx-prompt");if(j){var S=prompt(j);if(S===null||!ce(n,"htmx:prompt",{prompt:S,target:u})){ie(o);w();return l}}if(d&&!e){if(!confirm(d)){ie(o);w();return l}}var E=xr(n,u,S);if(t!=="get"&&!Sr(n)){E["Content-Type"]="application/x-www-form-urlencoded"}if(a.headers){E=le(E,a.headers)}var _=dr(n,t);var C=_.errors;var R=_.values;if(a.values){R=le(R,a.values)}var z=Hr(n);var $=le(R,z);var T=yr($,n);if(Q.config.getCacheBusterParam&&t==="get"){T["org.htmx.cache-buster"]=ee(u,"id")||"true"}if(r==null||r===""){r=re().location.href}var O=Rr(n,"hx-request");var W=ae(n).boosted;var q=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;var H={boosted:W,useUrlParams:q,parameters:T,unfilteredParameters:$,headers:E,target:u,verb:t,errors:C,withCredentials:a.credentials||O.credentials||Q.config.withCredentials,timeout:a.timeout||O.timeout||Q.config.timeout,path:r,triggeringEvent:i};if(!ce(n,"htmx:configRequest",H)){ie(o);w();return l}r=H.path;t=H.verb;E=H.headers;T=H.parameters;C=H.errors;q=H.useUrlParams;if(C&&C.length>0){ce(n,"htmx:validation:halted",H);ie(o);w();return l}var G=r.split("#");var J=G[0];var L=G[1];var A=r;if(q){A=J;var Z=Object.keys(T).length!==0;if(Z){if(A.indexOf("?")<0){A+="?"}else{A+="&"}A+=pr(T);if(L){A+="#"+L}}}if(!kr(n,A,H)){fe(n,"htmx:invalidPath",H);ie(s);return l}b.open(t.toUpperCase(),A,true);b.overrideMimeType("text/html");b.withCredentials=H.withCredentials;b.timeout=H.timeout;if(O.noHeaders){}else{for(var N in E){if(E.hasOwnProperty(N)){var K=E[N];Lr(b,N,K)}}}var I={xhr:b,target:u,requestConfig:H,etc:a,boosted:W,select:X,pathInfo:{requestPath:r,finalRequestPath:A,anchor:L}};b.onload=function(){try{var e=Ir(n);I.pathInfo.responsePath=Ar(b);M(n,I);lr(k,P);ce(n,"htmx:afterRequest",I);ce(n,"htmx:afterOnLoad",I);if(!se(n)){var t=null;while(e.length>0&&t==null){var r=e.shift();if(se(r)){t=r}}if(t){ce(t,"htmx:afterRequest",I);ce(t,"htmx:afterOnLoad",I)}}ie(o);w()}catch(e){fe(n,"htmx:onLoadError",le({error:e},I));throw e}};b.onerror=function(){lr(k,P);fe(n,"htmx:afterRequest",I);fe(n,"htmx:sendError",I);ie(s);w()};b.onabort=function(){lr(k,P);fe(n,"htmx:afterRequest",I);fe(n,"htmx:sendAbort",I);ie(s);w()};b.ontimeout=function(){lr(k,P);fe(n,"htmx:afterRequest",I);fe(n,"htmx:timeout",I);ie(s);w()};if(!ce(n,"htmx:beforeRequest",I)){ie(o);w();return l}var k=or(n);var P=sr(n);oe(["loadstart","loadend","progress","abort"],function(t){oe([b,b.upload],function(e){e.addEventListener(t,function(e){ce(n,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ce(n,"htmx:beforeSend",I);var Y=q?null:Er(b,n,T);b.send(Y);return l}function Pr(e,t){var r=t.xhr;var n=null;var i=null;if(O(r,/HX-Push:/i)){n=r.getResponseHeader("HX-Push");i="push"}else if(O(r,/HX-Push-Url:/i)){n=r.getResponseHeader("HX-Push-Url");i="push"}else if(O(r,/HX-Replace-Url:/i)){n=r.getResponseHeader("HX-Replace-Url");i="replace"}if(n){if(n==="false"){return{}}else{return{type:i,path:n}}}var a=t.pathInfo.finalRequestPath;var o=t.pathInfo.responsePath;var s=ne(e,"hx-push-url");var l=ne(e,"hx-replace-url");var u=ae(e).boosted;var f=null;var c=null;if(s){f="push";c=s}else if(l){f="replace";c=l}else if(u){f="push";c=o||a}if(c){if(c==="false"){return{}}if(c==="true"){c=o||a}if(t.pathInfo.anchor&&c.indexOf("#")===-1){c=c+"#"+t.pathInfo.anchor}return{type:f,path:c}}else{return{}}}function Mr(l,u){var f=u.xhr;var c=u.target;var e=u.etc;var t=u.requestConfig;var h=u.select;if(!ce(l,"htmx:beforeOnLoad",u))return;if(O(f,/HX-Trigger:/i)){_e(f,"HX-Trigger",l)}if(O(f,/HX-Location:/i)){er();var r=f.getResponseHeader("HX-Location");var v;if(r.indexOf("{")===0){v=E(r);r=v["path"];delete v["path"]}Nr("GET",r,v).then(function(){tr(r)});return}var n=O(f,/HX-Refresh:/i)&&"true"===f.getResponseHeader("HX-Refresh");if(O(f,/HX-Redirect:/i)){location.href=f.getResponseHeader("HX-Redirect");n&&location.reload();return}if(n){location.reload();return}if(O(f,/HX-Retarget:/i)){if(f.getResponseHeader("HX-Retarget")==="this"){u.target=l}else{u.target=ue(l,f.getResponseHeader("HX-Retarget"))}}var d=Pr(l,u);var i=f.status>=200&&f.status<400&&f.status!==204;var g=f.response;var a=f.status>=400;var p=Q.config.ignoreTitle;var o=le({shouldSwap:i,serverResponse:g,isError:a,ignoreTitle:p},u);if(!ce(c,"htmx:beforeSwap",o))return;c=o.target;g=o.serverResponse;a=o.isError;p=o.ignoreTitle;u.target=c;u.failed=a;u.successful=!a;if(o.shouldSwap){if(f.status===286){at(l)}R(l,function(e){g=e.transformResponse(g,f,l)});if(d.type){er()}var s=e.swapOverride;if(O(f,/HX-Reswap:/i)){s=f.getResponseHeader("HX-Reswap")}var v=wr(l,s);if(v.hasOwnProperty("ignoreTitle")){p=v.ignoreTitle}c.classList.add(Q.config.swappingClass);var m=null;var x=null;var y=function(){try{var e=document.activeElement;var t={};try{t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null}}catch(e){}var r;if(h){r=h}if(O(f,/HX-Reselect:/i)){r=f.getResponseHeader("HX-Reselect")}if(d.type){ce(re().body,"htmx:beforeHistoryUpdate",le({history:d},u));if(d.type==="push"){tr(d.path);ce(re().body,"htmx:pushedIntoHistory",{path:d.path})}else{rr(d.path);ce(re().body,"htmx:replacedInHistory",{path:d.path})}}var n=T(c);je(v.swapStyle,c,l,g,n,r);if(t.elt&&!se(t.elt)&&ee(t.elt,"id")){var i=document.getElementById(ee(t.elt,"id"));var a={preventScroll:v.focusScroll!==undefined?!v.focusScroll:!Q.config.defaultFocusScroll};if(i){if(t.start&&i.setSelectionRange){try{i.setSelectionRange(t.start,t.end)}catch(e){}}i.focus(a)}}c.classList.remove(Q.config.swappingClass);oe(n.elts,function(e){if(e.classList){e.classList.add(Q.config.settlingClass)}ce(e,"htmx:afterSwap",u)});if(O(f,/HX-Trigger-After-Swap:/i)){var o=l;if(!se(l)){o=re().body}_e(f,"HX-Trigger-After-Swap",o)}var s=function(){oe(n.tasks,function(e){e.call()});oe(n.elts,function(e){if(e.classList){e.classList.remove(Q.config.settlingClass)}ce(e,"htmx:afterSettle",u)});if(u.pathInfo.anchor){var e=re().getElementById(u.pathInfo.anchor);if(e){e.scrollIntoView({block:"start",behavior:"auto"})}}if(n.title&&!p){var t=C("title");if(t){t.innerHTML=n.title}else{window.document.title=n.title}}Cr(n.elts,v);if(O(f,/HX-Trigger-After-Settle:/i)){var r=l;if(!se(l)){r=re().body}_e(f,"HX-Trigger-After-Settle",r)}ie(m)};if(v.settleDelay>0){setTimeout(s,v.settleDelay)}else{s()}}catch(e){fe(l,"htmx:swapError",u);ie(x);throw e}};var b=Q.config.globalViewTransitions;if(v.hasOwnProperty("transition")){b=v.transition}if(b&&ce(l,"htmx:beforeTransition",u)&&typeof Promise!=="undefined"&&document.startViewTransition){var w=new Promise(function(e,t){m=e;x=t});var S=y;y=function(){document.startViewTransition(function(){S();return w})}}if(v.swapDelay>0){setTimeout(y,v.swapDelay)}else{y()}}if(a){fe(l,"htmx:responseError",le({error:"Response Status Error Code "+f.status+" from "+u.pathInfo.requestPath},u))}}var Xr={};function Dr(){return{init:function(e){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,r){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,r,n){return false},encodeParameters:function(e,t,r){return null}}}function Ur(e,t){if(t.init){t.init(r)}Xr[e]=le(Dr(),t)}function Br(e){delete Xr[e]}function Fr(e,r,n){if(e==undefined){return r}if(r==undefined){r=[]}if(n==undefined){n=[]}var t=te(e,"hx-ext");if(t){oe(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){n.push(e.slice(7));return}if(n.indexOf(e)<0){var t=Xr[e];if(t&&r.indexOf(t)<0){r.push(t)}}})}return Fr(u(e),r,n)}var Vr=false;re().addEventListener("DOMContentLoaded",function(){Vr=true});function jr(e){if(Vr||re().readyState==="complete"){e()}else{re().addEventListener("DOMContentLoaded",e)}}function _r(){if(Q.config.includeIndicatorStyles!==false){re().head.insertAdjacentHTML("beforeend","")}}function zr(){var e=re().querySelector('meta[name="htmx-config"]');if(e){return E(e.content)}else{return null}}function $r(){var e=zr();if(e){Q.config=le(Q.config,e)}}jr(function(){$r();_r();var e=re().body;zt(e);var t=re().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){var t=e.target;var r=ae(t);if(r&&r.xhr){r.xhr.abort()}});const r=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){ar();oe(t,function(e){ce(e,"htmx:restored",{document:re(),triggerEvent:ce})})}else{if(r){r(e)}}};setTimeout(function(){ce(e,"htmx:load",{});e=null},0)});return Q}()});(function(){"use strict";function overload(callback,start,end){start=start===undefined?1:start;end=end||start+1;if(end-start<=1){return function(){if(arguments.length<=start||$.type(arguments[start])==="string"){return callback.apply(this,arguments)}var obj=arguments[start];var ret;for(var key in obj){var args=Array.prototype.slice.call(arguments);args.splice(start,1,key,obj[key]);ret=callback.apply(this,args)}return ret}}return overload(overload(callback,start+1,end),start,end-1)}function extend(to,from,whitelist){var whitelistType=type(whitelist);if(whitelistType==="string"){var descriptor=Object.getOwnPropertyDescriptor(from,whitelist);if(descriptor&&(!descriptor.writable||!descriptor.configurable||!descriptor.enumerable||descriptor.get||descriptor.set)){delete to[whitelist];Object.defineProperty(to,whitelist,descriptor)}else{to[whitelist]=from[whitelist]}}else if(whitelistType==="array"){whitelist.forEach(function(property){if(property in from){extend(to,from,property)}})}else{for(var property in from){if(whitelist){if(whitelistType==="regexp"&&!whitelist.test(property)||whitelistType==="function"&&!whitelist.call(from,property)){continue}}extend(to,from,property)}}return to}function type(obj){if(obj===null){return"null"}if(obj===undefined){return"undefined"}var ret=(Object.prototype.toString.call(obj).match(/^\[object\s+(.*?)\]$/)[1]||"").toLowerCase();if(ret=="number"&&isNaN(obj)){return"nan"}return ret}var $=self.Bliss=extend(function(expr,context){if(arguments.length==2&&!context||!expr){return null}return $.type(expr)==="string"?(context||document).querySelector(expr):expr||null},self.Bliss);extend($,{extend:extend,overload:overload,type:type,property:$.property||"_",listeners:self.WeakMap?new WeakMap:new Map,original:{addEventListener:(self.EventTarget||Node).prototype.addEventListener,removeEventListener:(self.EventTarget||Node).prototype.removeEventListener},sources:{},noop:function(){},$:function(expr,context){if(expr instanceof Node||expr instanceof Window){return[expr]}if(arguments.length==2&&!context){return[]}return Array.prototype.slice.call(typeof expr=="string"?(context||document).querySelectorAll(expr):expr||[])},defined:function(){for(var i=0;i=200&&env.xhr.status<300||env.xhr.status===304){resolve(env.xhr)}else{reject($.extend(Error(env.xhr.statusText),{xhr:env.xhr,get status(){return this.xhr.status}}))}};env.xhr.onerror=function(){document.body.removeAttribute("data-loading");reject($.extend(Error("Network Error"),{xhr:env.xhr}))};env.xhr.ontimeout=function(){document.body.removeAttribute("data-loading");reject($.extend(Error("Network Timeout"),{xhr:env.xhr}))};env.xhr.send(env.method==="GET"?null:env.data)});promise.xhr=env.xhr;return promise},value:function(obj){var hasRoot=typeof obj!=="string";return $.$(arguments).slice(+hasRoot).reduce(function(obj,property){return obj&&obj[property]},hasRoot?obj:self)}});$.Hooks=new $.Class({add:function(name,callback,first){if(typeof arguments[0]!="string"){for(var name in arguments[0]){this.add(name,arguments[0][name],arguments[1])}return}(Array.isArray(name)?name:[name]).forEach(function(name){this[name]=this[name]||[];if(callback){this[name][first?"unshift":"push"](callback)}},this)},run:function(name,env){this[name]=this[name]||[];this[name].forEach(function(callback){callback.call(env&&env.context?env.context:env,env)})}});$.hooks=new $.Hooks;var _=$.property;$.Element=function(subject){this.subject=subject;this.data={};this.bliss={}};$.Element.prototype={set:overload(function(property,value){if(property in $.setProps){$.setProps[property].call(this,value)}else if(property in this){this[property]=value}else{this.setAttribute(property,value)}},0),transition:function(props,duration){return new Promise(function(resolve,reject){if("transition"in this.style&&duration!==0){var previous=$.extend({},this.style,/^transition(Duration|Property)$/);$.style(this,{transitionDuration:(duration||400)+"ms",transitionProperty:Object.keys(props).join(", ")});$.once(this,"transitionend",function(){clearTimeout(i);$.style(this,previous);resolve(this)});var i=setTimeout(resolve,duration+50,this);$.style(this,props)}else{$.style(this,props);resolve(this)}}.bind(this))},fire:function(type,properties){var evt=document.createEvent("HTMLEvents");evt.initEvent(type,true,true);return this.dispatchEvent($.extend(evt,properties))},bind:overload(function(types,options){if(arguments.length>1&&($.type(options)==="function"||options.handleEvent)){var callback=options;options=$.type(arguments[2])==="object"?arguments[2]:{capture:!!arguments[2]};options.callback=callback}var listeners=$.listeners.get(this)||{};types.trim().split(/\s+/).forEach(function(type){if(type.indexOf(".")>-1){type=type.split(".");var className=type[1];type=type[0]}listeners[type]=listeners[type]||[];if(listeners[type].filter(function(l){return l.callback===options.callback&&l.capture==options.capture}).length===0){listeners[type].push($.extend({className:className},options))}$.original.addEventListener.call(this,type,options.callback,options)},this);$.listeners.set(this,listeners)},0),unbind:overload(function(types,options){if(options&&($.type(options)==="function"||options.handleEvent)){var callback=options;options=arguments[2]}if($.type(options)=="boolean"){options={capture:options}}options=options||{};options.callback=options.callback||callback;var listeners=$.listeners.get(this);(types||"").trim().split(/\s+/).forEach(function(type){if(type.indexOf(".")>-1){type=type.split(".");var className=type[1];type=type[0]}if(!listeners){if(type&&options.callback){return $.original.removeEventListener.call(this,type,options.callback,options.capture)}return}for(var ltype in listeners){if(!type||ltype===type){for(var i=0,l;l=listeners[ltype][i];i++){if((!className||className===l.className)&&(!options.callback||options.callback===l.callback)&&(!!options.capture==!!l.capture||!type&&!options.callback&&undefined===options.capture)){listeners[ltype].splice(i,1);$.original.removeEventListener.call(this,ltype,l.callback,l.capture);i--}}}}},this)},0),when:function(type,test){var me=this;return new Promise(function(resolve){me.addEventListener(type,function callee(evt){if(!test||test.call(this,evt)){this.removeEventListener(type,callee);resolve(evt)}})})},toggleAttribute:function(name,value,test){if(arguments.length<3){test=value!==null}if(test){this.setAttribute(name,value)}else{this.removeAttribute(name)}}};$.setProps={style:function(val){for(var property in val){if(property in this.style){this.style[property]=val[property]}else{this.style.setProperty(property,val[property])}}},attributes:function(o){for(var attribute in o){this.setAttribute(attribute,o[attribute])}},properties:function(val){$.extend(this,val)},events:function(val){if(arguments.length==1&&val&&val.addEventListener){var me=this;if($.listeners){var listeners=$.listeners.get(val);for(var type in listeners){listeners[type].forEach(function(l){$.bind(me,type,l.callback,l.capture)})}}for(var onevent in val){if(onevent.indexOf("on")===0){this[onevent]=val[onevent]}}}else{return $.bind.apply(this,[this].concat($.$(arguments)))}},once:overload(function(types,callback){var me=this;var once=function(){$.unbind(me,types,once);return callback.apply(me,arguments)};$.bind(this,types,once,{once:true})},0),delegate:overload(function(type,selector,callback){$.bind(this,type,function(evt){if(evt.target.closest(selector)){callback.call(this,evt)}})},0,2),contents:function(val){if(val||val===0){(Array.isArray(val)?val:[val]).forEach(function(child){var type=$.type(child);if(/^(string|number)$/.test(type)){child=document.createTextNode(child+"")}else if(type==="object"){child=$.create(child)}if(child instanceof Node){this.appendChild(child)}},this)}},inside:function(element){element&&element.appendChild(this)},before:function(element){element&&element.parentNode.insertBefore(this,element)},after:function(element){element&&element.parentNode.insertBefore(this,element.nextSibling)},start:function(element){element&&element.insertBefore(this,element.firstChild)},around:function(element){if(element&&element.parentNode){$.before(this,element)}this.appendChild(element)}};$.Array=function(subject){this.subject=subject};$.Array.prototype={all:function(method){var args=$.$(arguments).slice(1);return this[method].apply(this,args)}};$.add=overload(function(method,callback,on,noOverwrite){on=$.extend({$:true,element:true,array:true},on);if($.type(callback)=="function"){if(on.element&&(!(method in $.Element.prototype)||!noOverwrite)){$.Element.prototype[method]=function(){return this.subject&&$.defined(callback.apply(this.subject,arguments),this.subject)}}if(on.array&&(!(method in $.Array.prototype)||!noOverwrite)){$.Array.prototype[method]=function(){var args=arguments;return this.subject.map(function(element){return element&&$.defined(callback.apply(element,args),element)})}}if(on.$){$.sources[method]=$[method]=callback;if(on.array||on.element){$[method]=function(){var args=[].slice.apply(arguments);var subject=args.shift();var Type=on.array&&Array.isArray(subject)?"Array":"Element";return $[Type].prototype[method].apply({subject:subject},args)}}}}},0);$.add($.Array.prototype,{element:false});$.add($.Element.prototype);$.add($.setProps);$.add($.classProps,{element:false,array:false});var dummy=document.createElement("_");$.add($.extend({},HTMLElement.prototype,function(method){return $.type(dummy[method])==="function"}),null,true)})();(function($){"use strict";if(!Bliss||Bliss.shy){return}var _=Bliss.property;$.add({clone:function(){console.warn("$.clone() is deprecated and will be removed in a future version of Bliss.");var clone=this.cloneNode(true);var descendants=$.$("*",clone).concat(clone);$.$("*",this).concat(this).forEach(function(element,i,arr){$.events(descendants[i],element);descendants[i]._.data=$.extend({},element._.data)});return clone}},{array:false});Object.defineProperty(Node.prototype,_,{get:function getter(){Object.defineProperty(Node.prototype,_,{get:undefined});Object.defineProperty(this,_,{value:new $.Element(this)});Object.defineProperty(Node.prototype,_,{get:getter});return this[_]},configurable:true});Object.defineProperty(Array.prototype,_,{get:function(){Object.defineProperty(this,_,{value:new $.Array(this)});return this[_]},configurable:true});if(self.EventTarget&&"addEventListener"in EventTarget.prototype){EventTarget.prototype.addEventListener=function(type,callback,options){return $.bind(this,type,callback,options)};EventTarget.prototype.removeEventListener=function(type,callback,options){return $.unbind(this,type,callback,options)}}self.$=self.$||$;self.$$=self.$$||$.$})(Bliss);document.addEventListener("DOMContentLoaded",()=>basxbread_load_elements());htmx.onLoad(function(content){basxbread_load_elements()});function basxbread_load_elements(){$$("[onload]:not(body):not(frame):not(iframe):not(img):not(link):not(script):not(style)")._.fire("load");$$("select.autosort").forEach(breadSortSelect);setBasxBreadCookie("timezone",Intl.DateTimeFormat().resolvedOptions().timeZone)}htmx.on("htmx:responseError",function(event){event.detail.target.innerHTML=event.detail.xhr.responseText});function updateMultiselect(e){let elem=$(".bx--list-box__selection",e);if(elem){elem.firstChild.textContent=$$("fieldset input[type=checkbox][checked]",e).length}}function filterOptions(e){var searchterm=$("input.bx--text-input",e).value.toLowerCase();for(i of $$("fieldset .bx--list-box__menu-item",e)){if(i.innerText.toLowerCase().includes(searchterm)){$(i)._.style({display:"initial"})}else{$(i)._.style({display:"none"})}}}function clearMultiselect(e){for(i of $$("fieldset input[type=checkbox][checked]",e)){i.parentElement.setAttribute("data-contained-checkbox-state","false");i.removeAttribute("checked");i.removeAttribute("aria-checked")}updateMultiselect(e)}function init_formset(form_prefix){update_add_button(form_prefix)}function delete_inline_element(checkbox,element){checkbox.checked=true;element.style.display="none"}function update_add_button(form_prefix){var formcount=$("#id_"+form_prefix+"-TOTAL_FORMS");var maxforms=$("#id_"+form_prefix+"-MAX_NUM_FORMS");var addbutton=$("#add_"+form_prefix+"_button");if(addbutton){addbutton.style.display="inline-flex";if(parseInt(formcount.value)>=parseInt(maxforms.value)){addbutton.style.display="none"}}}function formset_add(form_prefix,list_container){let container_elem=$(list_container);let placeholder=document.createElement("DIV");container_elem.appendChild(placeholder);var formcount=$("#id_"+form_prefix+"-TOTAL_FORMS");var newElementStr=$("#empty_"+form_prefix+"_form").innerText.replace(/__prefix__/g,formcount.value);placeholder.outerHTML=newElementStr;formcount.value=parseInt(formcount.value)+1;update_add_button(form_prefix);updateMultiselect(container_elem);basxbread_load_elements();htmx.process(container_elem)}function submitbulkaction(table,actionurl,method="GET"){let form=document.createElement("form");form.method=method;form.action=actionurl;let url=new URL(actionurl,new URL(document.baseURI).origin);for(const[key,value]of url.searchParams){let input=document.createElement("input");input.name=key;input.type="hidden";input.value=value;form.appendChild(input)}for(let checkbox of table.querySelectorAll("input[type=checkbox][data-event=select]")){form.appendChild(checkbox.cloneNode(true))}for(let checkbox of table.querySelectorAll("input[type=checkbox][data-event=select-all]")){form.appendChild(checkbox.cloneNode(true))}document.body.appendChild(form);form.submit()}function setBasxBreadCookie(key,value){document.cookie="basxbread-"+key+"="+encodeURIComponent(value)+"; path=/"}function getBasxBreadCookie(key,_default=null){var ret=document.cookie.split("; ").find(row=>row.startsWith("basxbread-"+key+"="));if(!ret)return _default;ret=ret.split("=")[1];return ret?decodeURIComponent(ret):_default}function getEditDistance(a,b){if(a.length==0)return b.length;if(b.length==0)return a.length;var matrix=[];var i;for(i=0;i<=b.length;i++){matrix[i]=[i]}var j;for(j=0;j<=a.length;j++){matrix[0][j]=j}for(i=1;i<=b.length;i++){for(j=1;j<=a.length;j++){if(b.charAt(i-1)==a.charAt(j-1)){matrix[i][j]=matrix[i-1][j-1]}else{matrix[i][j]=Math.min(matrix[i-1][j-1]+1,Math.min(matrix[i][j-1]+1,matrix[i-1][j]+1))}}}return matrix[b.length][a.length]}function searchMatchRank(searchTerms,value){var score=0;let valueTokens=value.toLowerCase().split(" ");for(let token of valueTokens){var lowestScore=999999;for(let term of searchTerms){if(token==term){lowestScore=0}else if(token.startsWith(term)){lowestScore=1/term.length}else{lowestScore=Math.min(getEditDistance(token,term),lowestScore)}}score+=lowestScore}return score}function breadSortSelect(selectNode){optionNodes=Array.from(selectNode.children);comparator=(new Intl.Collator).compare;optionNodes.sort((a,b)=>comparator(a.textContent,b.textContent));optionNodes.forEach(option=>selectNode.appendChild(option))}var CarbonComponents=function(exports){"use strict";var settings={prefix:"bx",selectorTabbable:"\n a[href], area[href], input:not([disabled]):not([tabindex='-1']),\n button:not([disabled]):not([tabindex='-1']),select:not([disabled]):not([tabindex='-1']),\n textarea:not([disabled]):not([tabindex='-1']),\n iframe, object, embed, *[tabindex]:not([tabindex='-1']), *[contenteditable=true]\n ",selectorFocusable:"\n a[href], area[href], input:not([disabled]),\n button:not([disabled]),select:not([disabled]),\n textarea:not([disabled]),\n iframe, object, embed, *[tabindex], *[contenteditable=true]\n "};var settings_1=settings;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;iarr.length)len=arr.length;for(var i=0,arr2=new Array(len);i1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,CreateComponent);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"children",[]);if(!element||element.nodeType!==Node.ELEMENT_NODE){throw new TypeError("DOM element should be given to initialize this widget.")}_this.element=element;_this.options=Object.assign(Object.create(_this.constructor.options),options);_this.constructor.components.set(_this.element,_assertThisInitialized(_this));return _this}_createClass(CreateComponent,[{key:"release",value:function release(){for(var child=this.children.pop();child;child=this.children.pop()){child.release()}this.constructor.components.delete(this.element);return null}}],[{key:"create",value:function create(element,options){return this.components.get(element)||new this(element,options)}}]);return CreateComponent}(ToMix);return CreateComponent}function initComponentBySearch(ToMix){var InitComponentBySearch=function(_ToMix){_inherits(InitComponentBySearch,_ToMix);var _super=_createSuper(InitComponentBySearch);function InitComponentBySearch(){_classCallCheck(this,InitComponentBySearch);return _super.apply(this,arguments)}_createClass(InitComponentBySearch,null,[{key:"init",value:function init(){var _this=this;var target=arguments.length>0&&arguments[0]!==undefined?arguments[0]:document;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var effectiveOptions=Object.assign(Object.create(this.options),options);if(!target||target.nodeType!==Node.ELEMENT_NODE&&target.nodeType!==Node.DOCUMENT_NODE){throw new TypeError("DOM document or DOM element should be given to search for and initialize this widget.")}if(target.nodeType===Node.ELEMENT_NODE&&target.matches(effectiveOptions.selectorInit)){this.create(target,options)}else{Array.prototype.forEach.call(target.querySelectorAll(effectiveOptions.selectorInit),function(element){return _this.create(element,options)})}}}]);return InitComponentBySearch}(ToMix);return InitComponentBySearch}function handles(ToMix){var Handles=function(_ToMix){_inherits(Handles,_ToMix);var _super=_createSuper(Handles);function Handles(){var _this;_classCallCheck(this,Handles);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}_this=_super.call.apply(_super,[this].concat(args));_defineProperty(_assertThisInitialized(_this),"handles",new Set);return _this}_createClass(Handles,[{key:"manage",value:function manage(handle){this.handles.add(handle);return handle}},{key:"unmanage",value:function unmanage(handle){this.handles.delete(handle);return handle}},{key:"release",value:function release(){var _this2=this;this.handles.forEach(function(handle){handle.release();_this2.handles.delete(handle)});return _get(_getPrototypeOf(Handles.prototype),"release",this).call(this)}}]);return Handles}(ToMix);return Handles}function on(element){for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key]}element.addEventListener.apply(element,args);return{release:function release(){element.removeEventListener.apply(element,args);return null}}}var stateChangeTypes={true:"true",false:"false",mixed:"mixed"};var Checkbox=function(_mixin){_inherits(Checkbox,_mixin);var _super=_createSuper(Checkbox);function Checkbox(element,options){var _this;_classCallCheck(this,Checkbox);_this=_super.call(this,element,options);_this.manage(on(_this.element,"click",function(event){_this._handleClick(event)}));_this.manage(on(_this.element,"focus",function(event){_this._handleFocus(event)}));_this.manage(on(_this.element,"blur",function(event){_this._handleBlur(event)}));_this._indeterminateCheckbox();_this._initCheckbox();return _this}_createClass(Checkbox,[{key:"_handleClick",value:function _handleClick(){if(this.element.checked===true){this.element.setAttribute("checked","");this.element.setAttribute("aria-checked","true");this.element.checked=true;if(this.element.parentElement.classList.contains(this.options.classLabel)){this.element.parentElement.setAttribute(this.options.attribContainedCheckboxState,"true")}}else if(this.element.checked===false){this.element.removeAttribute("checked");this.element.setAttribute("aria-checked","false");this.element.checked=false;if(this.element.parentElement.classList.contains(this.options.classLabel)){this.element.parentElement.setAttribute(this.options.attribContainedCheckboxState,"false")}}}},{key:"_handleFocus",value:function _handleFocus(){if(this.element.parentElement.classList.contains(this.options.classLabel)){this.element.parentElement.classList.add(this.options.classLabelFocused)}}},{key:"_handleBlur",value:function _handleBlur(){if(this.element.parentElement.classList.contains(this.options.classLabel)){this.element.parentElement.classList.remove(this.options.classLabelFocused)}}},{key:"setState",value:function setState(state){if(state===undefined||stateChangeTypes[state]===undefined){throw new TypeError("setState expects a value of true, false or mixed.")}this.element.setAttribute("aria-checked",state);this.element.indeterminate=state===stateChangeTypes.mixed;this.element.checked=state===stateChangeTypes.true;var container=this.element.closest(this.options.selectorContainedCheckboxState);if(container){container.setAttribute(this.options.attribContainedCheckboxState,state)}}},{key:"setDisabled",value:function setDisabled(value){if(value===undefined){throw new TypeError("setDisabled expects a boolean value of true or false")}if(value===true){this.element.setAttribute("disabled",true)}else if(value===false){this.element.removeAttribute("disabled")}var container=this.element.closest(this.options.selectorContainedCheckboxDisabled);if(container){container.setAttribute(this.options.attribContainedCheckboxDisabled,value)}}},{key:"_indeterminateCheckbox",value:function _indeterminateCheckbox(){if(this.element.getAttribute("aria-checked")==="mixed"){this.element.indeterminate=true}if(this.element.indeterminate===true){this.element.setAttribute("aria-checked","mixed")}if(this.element.parentElement.classList.contains(this.options.classLabel)&&this.element.indeterminate===true){this.element.parentElement.setAttribute(this.options.attribContainedCheckboxState,"mixed")}}},{key:"_initCheckbox",value:function _initCheckbox(){if(this.element.checked===true){this.element.setAttribute("aria-checked","true")}if(this.element.parentElement.classList.contains(this.options.classLabel)&&this.element.checked){this.element.parentElement.setAttribute(this.options.attribContainedCheckboxState,"true")}if(this.element.parentElement.classList.contains(this.options.classLabel)){this.element.parentElement.setAttribute(this.options.attribContainedCheckboxDisabled,"false")}if(this.element.parentElement.classList.contains(this.options.classLabel)&&this.element.disabled){this.element.parentElement.setAttribute(this.options.attribContainedCheckboxDisabled,"true")}}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:".".concat(prefix,"--checkbox"),selectorContainedCheckboxState:"[data-contained-checkbox-state]",selectorContainedCheckboxDisabled:"[data-contained-checkbox-disabled]",classLabel:"".concat(prefix,"--checkbox-label"),classLabelFocused:"".concat(prefix,"--checkbox-label__focus"),attribContainedCheckboxState:"data-contained-checkbox-state",attribContainedCheckboxDisabled:"data-contained-checkbox-disabled"}}}]);return Checkbox}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(Checkbox,"components",new WeakMap);_defineProperty(Checkbox,"stateChangeTypes",stateChangeTypes);function eventedState(ToMix){var EventedState=function(_ToMix){_inherits(EventedState,_ToMix);var _super=_createSuper(EventedState);function EventedState(){_classCallCheck(this,EventedState);return _super.apply(this,arguments)}_createClass(EventedState,[{key:"_changeState",value:function _changeState(){throw new Error("_changeState() should be overriden to perform actual change in state.")}},{key:"changeState",value:function changeState(){var _this=this;for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}var state=typeof args[0]==="string"?args.shift():undefined;var detail=Object(args[0])===args[0]&&typeof args[0]!=="function"?args.shift():undefined;var callback=typeof args[0]==="function"?args.shift():undefined;if(typeof this.shouldStateBeChanged==="function"&&!this.shouldStateBeChanged(state,detail)){if(callback){callback(null,true)}return}var data={group:detail&&detail.group,state:state};var eventNameSuffix=[data.group,state].filter(Boolean).join("-").split("-").map(function(item){return item[0].toUpperCase()+item.substr(1)}).join("");var eventStart=new CustomEvent(this.options["eventBefore".concat(eventNameSuffix)],{bubbles:true,cancelable:true,detail:detail});var fireOnNode=detail&&detail.delegatorNode||this.element;var canceled=!fireOnNode.dispatchEvent(eventStart);if(canceled){if(callback){var error=new Error("Changing state (".concat(JSON.stringify(data),") has been canceled."));error.canceled=true;callback(error)}}else{var changeStateArgs=[state,detail].filter(Boolean);this._changeState.apply(this,_toConsumableArray(changeStateArgs).concat([function(){fireOnNode.dispatchEvent(new CustomEvent(_this.options["eventAfter".concat(eventNameSuffix)],{bubbles:true,cancelable:true,detail:detail}));if(callback){callback()}}]))}}}]);return EventedState}(ToMix);return EventedState}function eventMatches(event,selector){var target=event.target,currentTarget=event.currentTarget;if(typeof target.matches==="function"){if(target.matches(selector)){return target}if(target.matches("".concat(selector," *"))){var closest=target.closest(selector);if((currentTarget.nodeType===Node.DOCUMENT_NODE?currentTarget.documentElement:currentTarget).contains(closest)){return closest}}}return undefined}var toArray=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var FileUploader=function(_mixin){_inherits(FileUploader,_mixin);var _super=_createSuper(FileUploader);function FileUploader(element){var _this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,FileUploader);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_changeState",function(state,detail,callback){if(state==="delete-filename-fileuploader"){_this.container.removeChild(detail.filenameElement)}if(typeof callback==="function"){callback()}});_defineProperty(_assertThisInitialized(_this),"_handleDeleteButton",function(evt){var target=eventMatches(evt,_this.options.selectorCloseButton);if(target){_this.changeState("delete-filename-fileuploader",{initialEvt:evt,filenameElement:target.closest(_this.options.selectorSelectedFile)})}});_defineProperty(_assertThisInitialized(_this),"_handleDragDrop",function(evt){var isOfSelf=_this.element.contains(evt.target);if(Array.prototype.indexOf.call(evt.dataTransfer.types,"Files")>=0&&!eventMatches(evt,_this.options.selectorOtherDropContainers)){var inArea=isOfSelf&&eventMatches(evt,_this.options.selectorDropContainer);if(evt.type==="dragover"){evt.preventDefault();var dropEffect=inArea?"copy":"none";if(Array.isArray(evt.dataTransfer.types)){evt.dataTransfer.effectAllowed=dropEffect}evt.dataTransfer.dropEffect=dropEffect;_this.dropContainer.classList.toggle(_this.options.classDragOver,Boolean(inArea))}if(evt.type==="dragleave"){_this.dropContainer.classList.toggle(_this.options.classDragOver,false)}if(inArea&&evt.type==="drop"){evt.preventDefault();_this._displayFilenames(evt.dataTransfer.files);_this.dropContainer.classList.remove(_this.options.classDragOver)}}});_this.input=_this.element.querySelector(_this.options.selectorInput);_this.container=_this.element.querySelector(_this.options.selectorContainer);_this.dropContainer=_this.element.querySelector(_this.options.selectorDropContainer);if(!_this.input){throw new TypeError("Cannot find the file input box.")}if(!_this.container){throw new TypeError("Cannot find the file names container.")}_this.inputId=_this.input.getAttribute("id");_this.manage(on(_this.input,"change",function(){return _this._displayFilenames()}));_this.manage(on(_this.container,"click",_this._handleDeleteButton));_this.manage(on(_this.element.ownerDocument,"dragleave",_this._handleDragDrop));_this.manage(on(_this.dropContainer,"dragover",_this._handleDragDrop));_this.manage(on(_this.dropContainer,"drop",_this._handleDragDrop));return _this}_createClass(FileUploader,[{key:"_filenamesHTML",value:function _filenamesHTML(name,id){return'\n ').concat(name,'
\n \n ')}},{key:"_uploadHTML",value:function _uploadHTML(){return'\n ')}},{key:"_closeButtonHTML",value:function _closeButtonHTML(){return'\n ')}},{key:"_checkmarkHTML",value:function _checkmarkHTML(){return'\n \n \n \n \n ')}},{key:"_getStateContainers",value:function _getStateContainers(){var stateContainers=toArray(this.element.querySelectorAll("[data-for=".concat(this.inputId,"]")));if(stateContainers.length===0){throw new TypeError("State container elements not found; invoke _displayFilenames() first")}if(stateContainers[0].dataset.for!==this.inputId){throw new TypeError("File input id must equal [data-for] attribute")}return stateContainers}},{key:"_displayFilenames",value:function _displayFilenames(){var _this2=this;var files=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this.input.files;var container=this.element.querySelector(this.options.selectorContainer);var HTMLString=toArray(files).map(function(file){return _this2._filenamesHTML(file.name,_this2.inputId)}).join("");container.insertAdjacentHTML("afterbegin",HTMLString)}},{key:"_removeState",value:function _removeState(element){if(!element||element.nodeType!==Node.ELEMENT_NODE){throw new TypeError("DOM element should be given to initialize this widget.")}while(element.firstChild){element.removeChild(element.firstChild)}}},{key:"_handleStateChange",value:function _handleStateChange(elements,selectIndex,html){var _this3=this;if(selectIndex===undefined){elements.forEach(function(el){_this3._removeState(el);el.insertAdjacentHTML("beforeend",html)})}else{elements.forEach(function(el,index){if(index===selectIndex){_this3._removeState(el);el.insertAdjacentHTML("beforeend",html)}})}}},{key:"setState",value:function setState(state,selectIndex){var stateContainers=this._getStateContainers();if(state==="edit"){this._handleStateChange(stateContainers,selectIndex,this._closeButtonHTML())}if(state==="upload"){this._handleStateChange(stateContainers,selectIndex,this._uploadHTML())}if(state==="complete"){this._handleStateChange(stateContainers,selectIndex,this._checkmarkHTML())}}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-file]",selectorInput:'input[type="file"].'.concat(prefix,"--file-input"),selectorContainer:"[data-file-container]",selectorCloseButton:".".concat(prefix,"--file-close"),selectorSelectedFile:".".concat(prefix,"--file__selected-file"),selectorDropContainer:"[data-file-drop-container]",selectorOtherDropContainers:"[data-drop-container]",classLoading:"".concat(prefix,"--loading ").concat(prefix,"--loading--small"),classLoadingAnimation:"".concat(prefix,"--inline-loading__animation"),classLoadingSvg:"".concat(prefix,"--loading__svg"),classLoadingBackground:"".concat(prefix,"--loading__background"),classLoadingStroke:"".concat(prefix,"--loading__stroke"),classFileName:"".concat(prefix,"--file-filename"),classFileClose:"".concat(prefix,"--file-close"),classFileComplete:"".concat(prefix,"--file-complete"),classSelectedFile:"".concat(prefix,"--file__selected-file"),classStateContainer:"".concat(prefix,"--file__state-container"),classDragOver:"".concat(prefix,"--file__drop-container--drag-over"),eventBeforeDeleteFilenameFileuploader:"fileuploader-before-delete-filename",eventAfterDeleteFilenameFileuploader:"fileuploader-after-delete-filename"}}}]);return FileUploader}(mixin(createComponent,initComponentBySearch,eventedState,handles));_defineProperty(FileUploader,"components",new WeakMap);var toArray$1=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var ContentSwitcher=function(_mixin){_inherits(ContentSwitcher,_mixin);var _super=_createSuper(ContentSwitcher);function ContentSwitcher(element,options){var _this;_classCallCheck(this,ContentSwitcher);_this=_super.call(this,element,options);_this.manage(on(_this.element,"click",function(event){_this._handleClick(event)}));return _this}_createClass(ContentSwitcher,[{key:"_handleClick",value:function _handleClick(event){var button=eventMatches(event,this.options.selectorButton);if(button){this.changeState({group:"selected",item:button,launchingEvent:event})}}},{key:"_changeState",value:function _changeState(_ref,callback){var _this2=this;var item=_ref.item;var itemLink=item.querySelector(this.options.selectorLink);if(itemLink){toArray$1(this.element.querySelectorAll(this.options.selectorLink)).forEach(function(link){if(link!==itemLink){link.setAttribute("aria-selected","false")}});itemLink.setAttribute("aria-selected","true")}var selectorButtons=toArray$1(this.element.querySelectorAll(this.options.selectorButton));selectorButtons.forEach(function(button){if(button!==item){button.setAttribute("aria-selected",false);button.classList.toggle(_this2.options.classActive,false);toArray$1(button.ownerDocument.querySelectorAll(button.dataset.target)).forEach(function(element){element.setAttribute("hidden","");element.setAttribute("aria-hidden","true")})}});item.classList.toggle(this.options.classActive,true);item.setAttribute("aria-selected",true);toArray$1(item.ownerDocument.querySelectorAll(item.dataset.target)).forEach(function(element){element.removeAttribute("hidden");element.setAttribute("aria-hidden","false")});if(callback){callback()}}},{key:"setActive",value:function setActive(item,callback){this.changeState({group:"selected",item:item},function(error){if(error){if(callback){callback(Object.assign(error,{item:item}))}}else if(callback){callback(null,item)}})}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-content-switcher]",selectorButton:'input[type="radio"], .'.concat(prefix,"--content-switcher-btn"),classActive:"".concat(prefix,"--content-switcher--selected"),eventBeforeSelected:"content-switcher-beingselected",eventAfterSelected:"content-switcher-selected"}}}]);return ContentSwitcher}(mixin(createComponent,initComponentBySearch,eventedState,handles));_defineProperty(ContentSwitcher,"components",new WeakMap);var toArray$2=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var Tab=function(_ContentSwitcher){_inherits(Tab,_ContentSwitcher);var _super=_createSuper(Tab);function Tab(element,options){var _this;_classCallCheck(this,Tab);_this=_super.call(this,element,options);_this.manage(on(_this.element,"keydown",function(event){_this._handleKeyDown(event)}));_this.manage(on(_this.element.ownerDocument,"click",function(event){_this._handleDocumentClick(event)}));var selected=_this.element.querySelector(_this.options.selectorButtonSelected);if(selected){_this._updateTriggerText(selected)}return _this}_createClass(Tab,[{key:"_changeState",value:function _changeState(detail,callback){var _this2=this;_get(_getPrototypeOf(Tab.prototype),"_changeState",this).call(this,detail,function(error){if(!error){_this2._updateTriggerText(detail.item)}for(var _len=arguments.length,data=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){data[_key-1]=arguments[_key]}callback.apply(void 0,[error].concat(data))})}},{key:"_handleClick",value:function _handleClick(event){var button=eventMatches(event,this.options.selectorButton);var trigger=eventMatches(event,this.options.selectorTrigger);if(button&&!button.classList.contains(this.options.classButtonDisabled)){_get(_getPrototypeOf(Tab.prototype),"_handleClick",this).call(this,event);this._updateMenuState(false)}if(trigger){this._updateMenuState()}}},{key:"_handleDocumentClick",value:function _handleDocumentClick(event){var element=this.element;var isOfSelf=element.contains(event.target);if(isOfSelf){return}this._updateMenuState(false)}},{key:"_handleKeyDown",value:function _handleKeyDown(event){var _this3=this;var triggerNode=eventMatches(event,this.options.selectorTrigger);if(triggerNode){if(event.which===13){this._updateMenuState()}return}var direction={37:this.constructor.NAVIGATE.BACKWARD,39:this.constructor.NAVIGATE.FORWARD}[event.which];if(direction){var buttons=toArray$2(this.element.querySelectorAll(this.options.selectorButtonEnabled));var button=this.element.querySelector(this.options.selectorButtonSelected);var nextIndex=Math.max(buttons.indexOf(button)+direction,-1);var nextIndexLooped=nextIndex>=0&&nextIndex=0){callbacks.splice(index,1)}}}}}}();var DIRECTION_LEFT="left";var DIRECTION_TOP="top";var DIRECTION_RIGHT="right";var DIRECTION_BOTTOM="bottom";var getFloatingPosition=function getFloatingPosition(_ref){var _DIRECTION_LEFT$DIREC;var menuSize=_ref.menuSize,refPosition=_ref.refPosition,_ref$offset=_ref.offset,offset=_ref$offset===void 0?{}:_ref$offset,_ref$direction=_ref.direction,direction=_ref$direction===void 0?DIRECTION_BOTTOM:_ref$direction,_ref$scrollX=_ref.scrollX,scrollX=_ref$scrollX===void 0?0:_ref$scrollX,_ref$scrollY=_ref.scrollY,scrollY=_ref$scrollY===void 0?0:_ref$scrollY;var _refPosition$left=refPosition.left,refLeft=_refPosition$left===void 0?0:_refPosition$left,_refPosition$top=refPosition.top,refTop=_refPosition$top===void 0?0:_refPosition$top,_refPosition$right=refPosition.right,refRight=_refPosition$right===void 0?0:_refPosition$right,_refPosition$bottom=refPosition.bottom,refBottom=_refPosition$bottom===void 0?0:_refPosition$bottom;var width=menuSize.width,height=menuSize.height;var _offset$top=offset.top,top=_offset$top===void 0?0:_offset$top,_offset$left=offset.left,left=_offset$left===void 0?0:_offset$left;var refCenterHorizontal=(refLeft+refRight)/2;var refCenterVertical=(refTop+refBottom)/2;return(_DIRECTION_LEFT$DIREC={},_defineProperty(_DIRECTION_LEFT$DIREC,DIRECTION_LEFT,{left:refLeft-width+scrollX-left,top:refCenterVertical-height/2+scrollY+top}),_defineProperty(_DIRECTION_LEFT$DIREC,DIRECTION_TOP,{left:refCenterHorizontal-width/2+scrollX+left,top:refTop-height+scrollY-top}),_defineProperty(_DIRECTION_LEFT$DIREC,DIRECTION_RIGHT,{left:refRight+scrollX+left,top:refCenterVertical-height/2+scrollY+top}),_defineProperty(_DIRECTION_LEFT$DIREC,DIRECTION_BOTTOM,{left:refCenterHorizontal-width/2+scrollX+left,top:refBottom+scrollY+top}),_DIRECTION_LEFT$DIREC)[direction]};var FloatingMenu=function(_mixin){_inherits(FloatingMenu,_mixin);var _super=_createSuper(FloatingMenu);function FloatingMenu(element,options){var _this;_classCallCheck(this,FloatingMenu);_this=_super.call(this,element,options);var attribDirectionValue=_this.element.getAttribute(_this.options.attribDirection);if(!_this.options.direction){_this.options.direction=attribDirectionValue||"bottom"}if(!attribDirectionValue){_this.element.setAttribute(_this.options.attribDirection,_this.options.direction)}_this.manage(on(_this.element.ownerDocument,"keydown",function(event){_this._handleKeydown(event)}));return _this}_createClass(FloatingMenu,[{key:"_handleKeydown",value:function _handleKeydown(event){var key=event.which;var _this$options=this.options,triggerNode=_this$options.triggerNode,refNode=_this$options.refNode;var isOfMenu=this.element.contains(event.target);switch(key){case 27:this.changeState("hidden",getLaunchingDetails(event),function(){if(isOfMenu){(triggerNode||refNode).focus()}});break}}},{key:"handleBlur",value:function handleBlur(event){if(this.element.classList.contains(this.options.classShown)){this.changeState("hidden",getLaunchingDetails(event));var _this$options2=this.options,refNode=_this$options2.refNode,triggerNode=_this$options2.triggerNode;if((event.relatedTarget===null||this.element.contains(event.relatedTarget))&&refNode&&event.target!==refNode){HTMLElement.prototype.focus.call(triggerNode||refNode)}}}},{key:"_getContainer",value:function _getContainer(){return this.element.closest(this.options.selectorContainer)||this.element.ownerDocument.body}},{key:"_getPos",value:function _getPos(){var element=this.element;var _this$options3=this.options,refNode=_this$options3.refNode,offset=_this$options3.offset,direction=_this$options3.direction;if(!refNode){throw new Error("Cannot find the reference node for positioning floating menu.")}return getFloatingPosition({menuSize:element.getBoundingClientRect(),refPosition:refNode.getBoundingClientRect(),offset:typeof offset!=="function"?offset:offset(element,direction,refNode),direction:direction,scrollX:refNode.ownerDocument.defaultView.pageXOffset,scrollY:refNode.ownerDocument.defaultView.pageYOffset})}},{key:"_testStyles",value:function _testStyles(){if(!this.options.debugStyle){return}var element=this.element;var computedStyle=element.ownerDocument.defaultView.getComputedStyle(element);var styles={position:"absolute",right:"auto",margin:0};Object.keys(styles).forEach(function(key){var expected=typeof styles[key]==="number"?parseFloat(styles[key]):styles[key];var actual=computedStyle.getPropertyValue(key);if(expected!==actual){console.warn("Floating menu component expects ".concat(key,": ").concat(styles[key]," style."))}})}},{key:"_place",value:function _place(){var element=this.element;var _this$_getPos=this._getPos(),left=_this$_getPos.left,top=_this$_getPos.top;element.style.left="".concat(left,"px");element.style.top="".concat(top,"px");this._testStyles()}},{key:"shouldStateBeChanged",value:function shouldStateBeChanged(state){return(state==="shown"||state==="hidden")&&state!==(this.element.classList.contains(this.options.classShown)?"shown":"hidden")}},{key:"_changeState",value:function _changeState(state,detail,callback){var _this2=this;var shown=state==="shown";var _this$options4=this.options,refNode=_this$options4.refNode,classShown=_this$options4.classShown,classRefShown=_this$options4.classRefShown,triggerNode=_this$options4.triggerNode;if(!refNode){throw new TypeError("Cannot find the reference node for changing the style.")}if(state==="shown"){if(!this.hResize){this.hResize=optimizedResize.add(function(){_this2._place()})}this._getContainer().appendChild(this.element)}this.element.setAttribute("aria-hidden",(!shown).toString());(triggerNode||refNode).setAttribute("aria-expanded",shown.toString());this.element.classList.toggle(classShown,shown);if(classRefShown){refNode.classList.toggle(classRefShown,shown)}if(state==="shown"){this._place();if(!this.element.hasAttribute(this.options.attribAvoidFocusOnOpen)){var primaryFocusNode=this.element.querySelector(this.options.selectorPrimaryFocus);var contentNode=this.options.contentNode||this.element;var tabbableNode=contentNode.querySelector(settings_1.selectorTabbable);var focusableNode=contentNode.matches(settings_1.selectorFocusable)?contentNode:contentNode.querySelector(settings_1.selectorFocusable);if(primaryFocusNode){primaryFocusNode.focus()}else if(tabbableNode){tabbableNode.focus()}else if(focusableNode){focusableNode.focus()}else{this.element.focus()}}}if(state==="hidden"&&this.hResize){this.hResize.release();this.hResize=null}callback()}},{key:"release",value:function release(){if(this.hResize){this.hResize.release();this.hResize=null}_get(_getPrototypeOf(FloatingMenu.prototype),"release",this).call(this)}}]);return FloatingMenu}(mixin(createComponent,exports$1,exports$2,handles));_defineProperty(FloatingMenu,"options",{selectorContainer:"[data-floating-menu-container]",selectorPrimaryFocus:"[data-floating-menu-primary-focus]",attribDirection:"data-floating-menu-direction",attribAvoidFocusOnOpen:"data-avoid-focus-on-open",classShown:"",classRefShown:"",eventBeforeShown:"floating-menu-beingshown",eventAfterShown:"floating-menu-shown",eventBeforeHidden:"floating-menu-beinghidden",eventAfterHidden:"floating-menu-hidden",refNode:null,offset:{left:0,top:0}});_defineProperty(FloatingMenu,"components",new WeakMap);var triggerButtonPositionProps=function(){var _ref;return _ref={},_defineProperty(_ref,DIRECTION_TOP,"bottom"),_defineProperty(_ref,DIRECTION_BOTTOM,"top"),_defineProperty(_ref,DIRECTION_LEFT,"left"),_defineProperty(_ref,DIRECTION_RIGHT,"right"),_ref}();var triggerButtonPositionFactors=function(){var _ref2;return _ref2={},_defineProperty(_ref2,DIRECTION_TOP,-2),_defineProperty(_ref2,DIRECTION_BOTTOM,-1),_defineProperty(_ref2,DIRECTION_LEFT,-2),_defineProperty(_ref2,DIRECTION_RIGHT,-1),_ref2}();var getMenuOffset=function getMenuOffset(menuBody,direction,trigger){var triggerButtonPositionProp=triggerButtonPositionProps[direction];var triggerButtonPositionFactor=triggerButtonPositionFactors[direction];if(!triggerButtonPositionProp||!triggerButtonPositionFactor){console.warn("Wrong floating menu direction:",direction)}var menuWidth=menuBody.offsetWidth;var menuHeight=menuBody.offsetHeight;var menu=OverflowMenu.components.get(trigger);if(!menu){throw new TypeError("Overflow menu instance cannot be found.")}var flip=menuBody.classList.contains(menu.options.classMenuFlip);if(triggerButtonPositionProp==="top"||triggerButtonPositionProp==="bottom"){var triggerWidth=trigger.offsetWidth;return{left:(!flip?1:-1)*(menuWidth/2-triggerWidth/2),top:0}}if(triggerButtonPositionProp==="left"||triggerButtonPositionProp==="right"){var triggerHeight=trigger.offsetHeight;return{left:0,top:(!flip?1:-1)*(menuHeight/2-triggerHeight/2)}}return undefined};var OverflowMenu=function(_mixin){_inherits(OverflowMenu,_mixin);var _super=_createSuper(OverflowMenu);function OverflowMenu(element,options){var _this;_classCallCheck(this,OverflowMenu);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"getCurrentNavigation",function(){var focused=_this.element.ownerDocument.activeElement;return focused.nodeType===Node.ELEMENT_NODE&&focused.matches(_this.options.selectorItem)?focused:null});_defineProperty(_assertThisInitialized(_this),"navigate",function(direction){var items=_toConsumableArray(_this.element.ownerDocument.querySelectorAll(_this.options.selectorItem));var start=_this.getCurrentNavigation()||_this.element.querySelector(_this.options.selectorItemSelected);var getNextItem=function getNextItem(old){var handleUnderflow=function handleUnderflow(index,length){return index+(index>=0?0:length)};var handleOverflow=function handleOverflow(index,length){return index-(index\n .").concat(prefix,"--overflow-menu-options__btn\n "),classShown:"".concat(prefix,"--overflow-menu--open"),classMenuShown:"".concat(prefix,"--overflow-menu-options--open"),classMenuFlip:"".concat(prefix,"--overflow-menu--flip"),objMenuOffset:getMenuOffset,objMenuOffsetFlip:getMenuOffset}}}]);return OverflowMenu}(mixin(createComponent,initComponentBySearch,exports$1,handles));_defineProperty(OverflowMenu,"components",new WeakMap);function initComponentByLauncher(ToMix){var InitComponentByLauncher=function(_ToMix){_inherits(InitComponentByLauncher,_ToMix);var _super=_createSuper(InitComponentByLauncher);function InitComponentByLauncher(){_classCallCheck(this,InitComponentByLauncher);return _super.apply(this,arguments)}_createClass(InitComponentByLauncher,null,[{key:"init",value:function init(){var _this=this;var target=arguments.length>0&&arguments[0]!==undefined?arguments[0]:document;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var effectiveOptions=Object.assign(Object.create(this.options),options);if(!target||target.nodeType!==Node.ELEMENT_NODE&&target.nodeType!==Node.DOCUMENT_NODE){throw new TypeError("DOM document or DOM element should be given to search for and initialize this widget.")}if(target.nodeType===Node.ELEMENT_NODE&&target.matches(effectiveOptions.selectorInit)){this.create(target,options)}else{var handles=effectiveOptions.initEventNames.map(function(name){return on(target,name,function(event){var launcher=eventMatches(event,"[".concat(effectiveOptions.attribInitTarget,"]"));if(launcher){event.delegateTarget=launcher;var elements=launcher.ownerDocument.querySelectorAll(launcher.getAttribute(effectiveOptions.attribInitTarget));if(elements.length>1){throw new Error("Target widget must be unique.")}if(elements.length===1){if(launcher.tagName==="A"){event.preventDefault()}var component=_this.create(elements[0],options);if(typeof component.createdByLauncher==="function"){component.createdByLauncher(event)}}}})});return{release:function release(){for(var handle=handles.pop();handle;handle=handles.pop()){handle.release()}}}}return""}}]);return InitComponentByLauncher}(ToMix);_defineProperty(InitComponentByLauncher,"forLazyInit",true);return InitComponentByLauncher}var Modal=function(_mixin){_inherits(Modal,_mixin);var _super=_createSuper(Modal);function Modal(element,options){var _this;_classCallCheck(this,Modal);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_handleFocusinListener",void 0);_defineProperty(_assertThisInitialized(_this),"_handleKeydownListener",void 0);_defineProperty(_assertThisInitialized(_this),"_handleFocusin",function(evt){var focusWrapNode=_this.element.querySelector(_this.options.selectorModalContainer)||_this.element;if(_this.element.classList.contains(_this.options.classVisible)&&!focusWrapNode.contains(evt.target)&&_this.options.selectorsFloatingMenus.every(function(selector){return!eventMatches(evt,selector)})){_this.element.querySelector(settings_1.selectorTabbable).focus()}});_this._hookCloseActions();return _this}_createClass(Modal,[{key:"createdByLauncher",value:function createdByLauncher(evt){this.show(evt)}},{key:"shouldStateBeChanged",value:function shouldStateBeChanged(state){if(state==="shown"){return!this.element.classList.contains(this.options.classVisible)}return this.element.classList.contains(this.options.classVisible)}},{key:"_changeState",value:function _changeState(state,detail,callback){var _this2=this;var handleTransitionEnd;var transitionEnd=function transitionEnd(){if(handleTransitionEnd){handleTransitionEnd=_this2.unmanage(handleTransitionEnd).release()}if(state==="shown"&&_this2.element.offsetWidth>0&&_this2.element.offsetHeight>0){_this2.previouslyFocusedNode=_this2.element.ownerDocument.activeElement;var focusableItem=_this2.element.querySelector(_this2.options.selectorPrimaryFocus)||_this2.element.querySelector(settings_1.selectorTabbable);focusableItem.focus()}callback()};if(this._handleFocusinListener){this._handleFocusinListener=this.unmanage(this._handleFocusinListener).release()}if(state==="shown"){var hasFocusin="onfocusin"in this.element.ownerDocument.defaultView;var focusinEventName=hasFocusin?"focusin":"focus";this._handleFocusinListener=this.manage(on(this.element.ownerDocument,focusinEventName,this._handleFocusin,!hasFocusin))}if(state==="hidden"){this.element.classList.toggle(this.options.classVisible,false);this.element.ownerDocument.body.classList.toggle(this.options.classBody,false);if(this.options.selectorFocusOnClose||this.previouslyFocusedNode){(this.element.ownerDocument.querySelector(this.options.selectorFocusOnClose)||this.previouslyFocusedNode).focus()}}else if(state==="shown"){this.element.classList.toggle(this.options.classVisible,true);this.element.ownerDocument.body.classList.toggle(this.options.classBody,true)}handleTransitionEnd=this.manage(on(this.element,"transitionend",transitionEnd))}},{key:"_hookCloseActions",value:function _hookCloseActions(){var _this3=this;this.manage(on(this.element,"click",function(evt){var closeButton=eventMatches(evt,_this3.options.selectorModalClose);if(closeButton){evt.delegateTarget=closeButton}if(closeButton||evt.target===_this3.element){_this3.hide(evt)}}));if(this._handleKeydownListener){this._handleKeydownListener=this.unmanage(this._handleKeydownListener).release()}this._handleKeydownListener=this.manage(on(this.element.ownerDocument.body,"keydown",function(evt){if(evt.which===27&&_this3.shouldStateBeChanged("hidden")){evt.stopPropagation();_this3.hide(evt)}}))}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-modal]",selectorModalClose:"[data-modal-close]",selectorPrimaryFocus:"[data-modal-primary-focus]",selectorsFloatingMenus:[".".concat(prefix,"--overflow-menu-options"),".".concat(prefix,"--tooltip"),".flatpickr-calendar"],selectorModalContainer:".".concat(prefix,"--modal-container"),classVisible:"is-visible",classBody:"".concat(prefix,"--body--with-modal-open"),attribInitTarget:"data-modal-target",initEventNames:["click"],eventBeforeShown:"modal-beingshown",eventAfterShown:"modal-shown",eventBeforeHidden:"modal-beinghidden",eventAfterHidden:"modal-hidden"}}}]);return Modal}(mixin(createComponent,initComponentByLauncher,exports$1,handles));_defineProperty(Modal,"components",new WeakMap);var Loading=function(_mixin){_inherits(Loading,_mixin);var _super=_createSuper(Loading);function Loading(element,options){var _this;_classCallCheck(this,Loading);_this=_super.call(this,element,options);_this.active=_this.options.active;_this.set(_this.active);return _this}_createClass(Loading,[{key:"set",value:function set(active){if(typeof active!=="boolean"){throw new TypeError("set expects a boolean.")}this.active=active;this.element.classList.toggle(this.options.classLoadingStop,!this.active);var parentNode=this.element.parentNode;if(parentNode&&parentNode.classList.contains(this.options.classLoadingOverlay)){parentNode.classList.toggle(this.options.classLoadingOverlayStop,!this.active)}return this}},{key:"toggle",value:function toggle(){return this.set(!this.active)}},{key:"isActive",value:function isActive(){return this.active}},{key:"end",value:function end(){var _this2=this;this.set(false);var handleAnimationEnd=this.manage(on(this.element,"animationend",function(evt){if(handleAnimationEnd){handleAnimationEnd=_this2.unmanage(handleAnimationEnd).release()}if(evt.animationName==="rotate-end-p2"){_this2._deleteElement()}}))}},{key:"_deleteElement",value:function _deleteElement(){var parentNode=this.element.parentNode;parentNode.removeChild(this.element);if(parentNode.classList.contains(this.options.selectorLoadingOverlay)){parentNode.remove()}}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-loading]",selectorLoadingOverlay:".".concat(prefix,"--loading-overlay"),classLoadingOverlay:"".concat(prefix,"--loading-overlay"),classLoadingStop:"".concat(prefix,"--loading--stop"),classLoadingOverlayStop:"".concat(prefix,"--loading-overlay--stop"),active:true}}}]);return Loading}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(Loading,"components",new WeakMap);function toggleAttribute(elem,name,add){if(add){elem.setAttribute(name,"")}else{elem.removeAttribute(name)}}var InlineLoading=function(_mixin){_inherits(InlineLoading,_mixin);var _super=_createSuper(InlineLoading);function InlineLoading(element,options){var _this;_classCallCheck(this,InlineLoading);_this=_super.call(this,element,options);var initialState=_this.options.initialState;if(initialState){_this.setState(initialState)}return _this}_createClass(InlineLoading,[{key:"setState",value:function setState(state){var states=this.constructor.states;var values=Object.keys(states).map(function(key){return states[key]});if(values.indexOf(state)<0){throw new Error("One of the following value should be given as the state: ".concat(values.join(", ")))}var elem=this.element;var _this$options=this.options,selectorSpinner=_this$options.selectorSpinner,selectorFinished=_this$options.selectorFinished,selectorError=_this$options.selectorError,selectorTextActive=_this$options.selectorTextActive,selectorTextFinished=_this$options.selectorTextFinished,selectorTextError=_this$options.selectorTextError;var spinner=elem.querySelector(selectorSpinner);var finished=elem.querySelector(selectorFinished);var error=elem.querySelector(selectorError);var textActive=elem.querySelector(selectorTextActive);var textFinished=elem.querySelector(selectorTextFinished);var textError=elem.querySelector(selectorTextError);if(spinner){spinner.classList.toggle(this.options.classLoadingStop,state!==states.ACTIVE);toggleAttribute(spinner,"hidden",state!==states.INACTIVE&&state!==states.ACTIVE)}if(finished){toggleAttribute(finished,"hidden",state!==states.FINISHED)}if(error){toggleAttribute(error,"hidden",state!==states.ERROR)}if(textActive){toggleAttribute(textActive,"hidden",state!==states.ACTIVE)}if(textFinished){toggleAttribute(textFinished,"hidden",state!==states.FINISHED)}if(textError){toggleAttribute(textError,"hidden",state!==states.ERROR)}return this}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-inline-loading]",selectorSpinner:"[data-inline-loading-spinner]",selectorFinished:"[data-inline-loading-finished]",selectorError:"[data-inline-loading-error]",selectorTextActive:"[data-inline-loading-text-active]",selectorTextFinished:"[data-inline-loading-text-finished]",selectorTextError:"[data-inline-loading-text-error]",classLoadingStop:"".concat(prefix,"--loading--stop")}}}]);return InlineLoading}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(InlineLoading,"states",{INACTIVE:"inactive",ACTIVE:"active",FINISHED:"finished",ERROR:"error"});_defineProperty(InlineLoading,"components",new WeakMap);var toArray$3=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var Dropdown=function(_mixin){_inherits(Dropdown,_mixin);var _super=_createSuper(Dropdown);function Dropdown(element,options){var _this;_classCallCheck(this,Dropdown);_this=_super.call(this,element,options);_this.manage(on(_this.element.ownerDocument,"click",function(event){_this._toggle(event)}));_this.manage(on(_this.element,"keydown",function(event){_this._handleKeyDown(event)}));_this.manage(on(_this.element,"click",function(event){var item=eventMatches(event,_this.options.selectorItem);if(item){_this.select(item)}}));if(_this.element.querySelector(_this.options.selectorTrigger)&&_this.element.querySelector(_this.options.selectorMenu)){_this.manage(on(_this.element,"mouseover",function(event){var item=eventMatches(event,_this.options.selectorItem);if(item){_this._updateFocus(item)}}))}return _this}_createClass(Dropdown,[{key:"_handleKeyDown",value:function _handleKeyDown(event){var isOpen=this.element.classList.contains(this.options.classOpen);var direction={38:this.constructor.NAVIGATE.BACKWARD,40:this.constructor.NAVIGATE.FORWARD}[event.which];if(isOpen&&direction!==undefined){this.navigate(direction);event.preventDefault()}else{var item=this.getCurrentNavigation();if(item&&isOpen&&(event.which===13||event.which===32)&&!this.element.ownerDocument.activeElement.matches(this.options.selectorItem)){event.preventDefault();this.select(item)}this._toggle(event)}}},{key:"_focusCleanup",value:function _focusCleanup(){var triggerNode=this.element.querySelector(this.options.selectorTrigger);var listNode=triggerNode?this.element.querySelector(this.options.selectorMenu):null;if(listNode){listNode.removeAttribute("aria-activedescendant");var focusedItem=this.element.querySelector(this.options.selectorItemFocused);if(focusedItem){focusedItem.classList.remove(this.options.classFocused)}}}},{key:"_updateFocus",value:function _updateFocus(itemToFocus){var triggerNode=this.element.querySelector(this.options.selectorTrigger);var listNode=triggerNode?this.element.querySelector(this.options.selectorMenu):null;var previouslyFocused=listNode.querySelector(this.options.selectorItemFocused);itemToFocus.classList.add(this.options.classFocused);listNode.setAttribute("aria-activedescendant",itemToFocus.id);if(previouslyFocused){previouslyFocused.classList.remove(this.options.classFocused)}}},{key:"_toggle",value:function _toggle(event){var _this2=this;var isDisabled=this.element.classList.contains(this.options.classDisabled);if(isDisabled){return}var triggerNode=this.element.querySelector(this.options.selectorTrigger);if(event.which===40&&!event.target.matches(this.options.selectorItem)||(!triggerNode||!triggerNode.contains(event.target))&&[13,32].indexOf(event.which)>=0&&!event.target.matches(this.options.selectorItem)||event.which===27||event.type==="click"){var isOpen=this.element.classList.contains(this.options.classOpen);var isOfSelf=this.element.contains(event.target);var actions={add:isOfSelf&&event.which===40&&!isOpen,remove:(!isOfSelf||event.which===27)&&isOpen,toggle:isOfSelf&&event.which!==27&&event.which!==40};var changedState=false;Object.keys(actions).forEach(function(action){if(actions[action]){changedState=true;_this2.element.classList[action](_this2.options.classOpen)}});var listItems=toArray$3(this.element.querySelectorAll(this.options.selectorItem));var listNode=triggerNode?this.element.querySelector(this.options.selectorMenu):null;if(changedState&&this.element.classList.contains(this.options.classOpen)){if(triggerNode){triggerNode.setAttribute("aria-expanded","true")}(listNode||this.element).focus();if(listNode){var selectedNode=listNode.querySelector(this.options.selectorLinkSelected);listNode.setAttribute("aria-activedescendant",(selectedNode||listItems[0]).id);(selectedNode||listItems[0]).classList.add(this.options.classFocused)}}else if(changedState&&(isOfSelf||actions.remove)){setTimeout(function(){return(triggerNode||_this2.element).focus()},0);if(triggerNode){triggerNode.setAttribute("aria-expanded","false")}this._focusCleanup()}if(!triggerNode){listItems.forEach(function(item){if(_this2.element.classList.contains(_this2.options.classOpen)){item.tabIndex=0}else{item.tabIndex=-1}})}var menuListNode=this.element.querySelector(this.options.selectorMenu);if(menuListNode){menuListNode.tabIndex=this.element.classList.contains(this.options.classOpen)?"0":"-1"}}}},{key:"getCurrentNavigation",value:function getCurrentNavigation(){var focusedNode;if(this.element.querySelector(this.options.selectorTrigger)){var listNode=this.element.querySelector(this.options.selectorMenu);var focusedId=listNode.getAttribute("aria-activedescendant");focusedNode=focusedId?listNode.querySelector("#".concat(focusedId)):null}else{var focused=this.element.ownerDocument.activeElement;focusedNode=focused.nodeType===Node.ELEMENT_NODE&&focused.matches(this.options.selectorItem)?focused:null}return focusedNode}},{key:"navigate",value:function navigate(direction){var items=toArray$3(this.element.querySelectorAll(this.options.selectorItem));var start=this.getCurrentNavigation()||this.element.querySelector(this.options.selectorLinkSelected);var getNextItem=function getNextItem(old){var handleUnderflow=function handleUnderflow(i,l){return i+(i>=0?0:l)};var handleOverflow=function handleOverflow(i,l){return i-(i=0){var nextValue=Number(numberInput.value)+step;if(numberInput.max===""){numberInput.value=nextValue}else if(numberInput.valuemax){numberInput.value=max}else if(nextValue=0){var _nextValue=Number(numberInput.value)-step;if(numberInput.min===""){numberInput.value=_nextValue}else if(numberInput.value>min){if(_nextValuemax){numberInput.value=max}else{numberInput.value=_nextValue}}}numberInput.dispatchEvent(new CustomEvent("change",{bubbles:true,cancelable:false}))}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-numberinput]",selectorInput:".".concat(prefix,"--number input")}}}]);return NumberInput}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(NumberInput,"components",new WeakMap);var toArray$4=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var DataTable=function(_mixin){_inherits(DataTable,_mixin);var _super=_createSuper(DataTable);function DataTable(_element,options){var _this;_classCallCheck(this,DataTable);_this=_super.call(this,_element,options);_defineProperty(_assertThisInitialized(_this),"_sortToggle",function(detail){var element=detail.element,previousValue=detail.previousValue;toArray$4(_this.tableHeaders).forEach(function(header){var sortEl=header.querySelector(_this.options.selectorTableSort);if(sortEl!==null&&sortEl!==element){sortEl.classList.remove(_this.options.classTableSortActive);sortEl.classList.remove(_this.options.classTableSortAscending)}});if(!previousValue){element.dataset.previousValue="ascending";element.classList.add(_this.options.classTableSortActive);element.classList.add(_this.options.classTableSortAscending)}else if(previousValue==="ascending"){element.dataset.previousValue="descending";element.classList.add(_this.options.classTableSortActive);element.classList.remove(_this.options.classTableSortAscending)}else if(previousValue==="descending"){element.removeAttribute("data-previous-value");element.classList.remove(_this.options.classTableSortActive);element.classList.remove(_this.options.classTableSortAscending)}});_defineProperty(_assertThisInitialized(_this),"_selectToggle",function(detail){var element=detail.element;var checked=element.checked;_this.state.checkboxCount+=checked?1:-1;_this.countEl.textContent=_this.state.checkboxCount;var row=element.parentNode.parentNode;row.classList.toggle(_this.options.classTableSelected);_this._actionBarToggle(_this.state.checkboxCount>0)});_defineProperty(_assertThisInitialized(_this),"_selectAllToggle",function(_ref){var element=_ref.element;var checked=element.checked;var inputs=toArray$4(_this.element.querySelectorAll(_this.options.selectorCheckbox));_this.state.checkboxCount=checked?inputs.length-1:0;inputs.forEach(function(item){item.checked=checked;var row=item.parentNode.parentNode;if(checked&&row){row.classList.add(_this.options.classTableSelected)}else{row.classList.remove(_this.options.classTableSelected)}});_this._actionBarToggle(_this.state.checkboxCount>0);if(_this.batchActionEl){var count=element.closest("[data-table]").querySelector("[data-total-items]").innerText;if(count&&checked){_this.state.checkboxCount=parseInt(count)}_this.countEl.textContent=_this.state.checkboxCount}});_defineProperty(_assertThisInitialized(_this),"_actionBarCancel",function(){var inputs=toArray$4(_this.element.querySelectorAll(_this.options.selectorCheckbox));var row=toArray$4(_this.element.querySelectorAll(_this.options.selectorTableSelected));row.forEach(function(item){item.classList.remove(_this.options.classTableSelected)});inputs.forEach(function(item){item.checked=false});_this.state.checkboxCount=0;_this._actionBarToggle(false);if(_this.batchActionEl){_this.countEl.textContent=_this.state.checkboxCount}});_defineProperty(_assertThisInitialized(_this),"_actionBarToggle",function(toggleOn){var handleTransitionEnd;var transition=function transition(evt){if(handleTransitionEnd){handleTransitionEnd=_this.unmanage(handleTransitionEnd).release()}if(evt.target.matches(_this.options.selectorActions)){if(_this.batchActionEl.dataset.active==="false"){_this.batchActionEl.setAttribute("tabIndex",-1)}else{_this.batchActionEl.setAttribute("tabIndex",0)}}};if(toggleOn){_this.batchActionEl.dataset.active=true;_this.batchActionEl.classList.add(_this.options.classActionBarActive)}else if(_this.batchActionEl){_this.batchActionEl.dataset.active=false;_this.batchActionEl.classList.remove(_this.options.classActionBarActive)}if(_this.batchActionEl){handleTransitionEnd=_this.manage(on(_this.batchActionEl,"transitionend",transition))}});_defineProperty(_assertThisInitialized(_this),"_rowExpandToggle",function(_ref2){var element=_ref2.element,forceExpand=_ref2.forceExpand;var parent=element.closest(_this.options.eventParentContainer);var shouldExpand=forceExpand!=null?forceExpand:element.dataset.previousValue===undefined||element.dataset.previousValue==="expanded";if(shouldExpand){element.dataset.previousValue="collapsed";parent.classList.add(_this.options.classExpandableRow)}else{parent.classList.remove(_this.options.classExpandableRow);element.dataset.previousValue="expanded";var expandHeader=_this.element.querySelector(_this.options.selectorExpandHeader);if(expandHeader){expandHeader.dataset.previousValue="expanded"}}});_defineProperty(_assertThisInitialized(_this),"_rowExpandToggleAll",function(_ref3){var element=_ref3.element;var shouldExpand=element.dataset.previousValue===undefined||element.dataset.previousValue==="expanded";element.dataset.previousValue=shouldExpand?"collapsed":"expanded";var expandCells=_this.element.querySelectorAll(_this.options.selectorExpandCells);Array.prototype.forEach.call(expandCells,function(cell){_this._rowExpandToggle({element:cell,forceExpand:shouldExpand})})});_defineProperty(_assertThisInitialized(_this),"_expandableHoverToggle",function(evt){var element=eventMatches(evt,_this.options.selectorChildRow);if(element){element.previousElementSibling.classList.toggle(_this.options.classExpandableRowHover,evt.type==="mouseover")}});_defineProperty(_assertThisInitialized(_this),"_toggleState",function(element,evt){var data=element.dataset;var label=data.label?data.label:"";var previousValue=data.previousValue?data.previousValue:"";var initialEvt=evt;_this.changeState({group:data.event,element:element,label:label,previousValue:previousValue,initialEvt:initialEvt})});_defineProperty(_assertThisInitialized(_this),"_keydownHandler",function(evt){var searchContainer=_this.element.querySelector(_this.options.selectorToolbarSearchContainer);var searchEvent=eventMatches(evt,_this.options.selectorSearchMagnifier);var activeSearch=searchContainer.classList.contains(_this.options.classToolbarSearchActive);if(evt.which===27){_this._actionBarCancel()}if(searchContainer&&searchEvent&&evt.which===13){_this.activateSearch(searchContainer)}if(activeSearch&&evt.which===27){_this.deactivateSearch(searchContainer,evt)}});_defineProperty(_assertThisInitialized(_this),"refreshRows",function(){var newExpandCells=toArray$4(_this.element.querySelectorAll(_this.options.selectorExpandCells));var newExpandableRows=toArray$4(_this.element.querySelectorAll(_this.options.selectorExpandableRows));var newParentRows=toArray$4(_this.element.querySelectorAll(_this.options.selectorParentRows));if(_this.parentRows.length>0){var diffParentRows=newParentRows.filter(function(newRow){return!_this.parentRows.some(function(oldRow){return oldRow===newRow})});if(newExpandableRows.length>0){var diffExpandableRows=diffParentRows.map(function(newRow){return newRow.nextElementSibling});var mergedExpandableRows=[].concat(_toConsumableArray(toArray$4(_this.expandableRows)),_toConsumableArray(toArray$4(diffExpandableRows)));_this.expandableRows=mergedExpandableRows}}else if(newExpandableRows.length>0){_this.expandableRows=newExpandableRows}_this.expandCells=newExpandCells;_this.parentRows=newParentRows});_this.container=_element.parentNode;_this.toolbarEl=_this.element.querySelector(_this.options.selectorToolbar);_this.batchActionEl=_this.element.querySelector(_this.options.selectorActions);_this.countEl=_this.element.querySelector(_this.options.selectorCount);_this.cancelEl=_this.element.querySelector(_this.options.selectorActionCancel);_this.tableHeaders=_this.element.querySelectorAll("th");_this.tableBody=_this.element.querySelector(_this.options.selectorTableBody);_this.expandCells=[];_this.expandableRows=[];_this.parentRows=[];_this.refreshRows();_this.manage(on(_this.element,"mouseover",_this._expandableHoverToggle));_this.manage(on(_this.element,"mouseout",_this._expandableHoverToggle));_this.manage(on(_this.element,"click",function(evt){var eventElement=eventMatches(evt,_this.options.eventTrigger);var searchContainer=_this.element.querySelector(_this.options.selectorToolbarSearchContainer);if(eventElement){_this._toggleState(eventElement,evt)}if(searchContainer){_this._handleDocumentClick(evt)}}));_this.manage(on(_this.element,"keydown",_this._keydownHandler));_this.state={checkboxCount:0};return _this}_createClass(DataTable,[{key:"_handleDocumentClick",value:function _handleDocumentClick(evt){var searchContainer=this.element.querySelector(this.options.selectorToolbarSearchContainer);var searchEvent=eventMatches(evt,this.options.selectorSearchMagnifier);var activeSearch=searchContainer.classList.contains(this.options.classToolbarSearchActive);if(searchContainer&&searchEvent){this.activateSearch(searchContainer)}if(activeSearch){this.deactivateSearch(searchContainer,evt)}}},{key:"activateSearch",value:function activateSearch(container){var input=container.querySelector(this.options.selectorSearchInput);container.classList.add(this.options.classToolbarSearchActive);input.focus()}},{key:"deactivateSearch",value:function deactivateSearch(container,evt){var trigger=container.querySelector(this.options.selectorSearchMagnifier);var input=container.querySelector(this.options.selectorSearchInput);var svg=trigger.querySelector("svg");if(input.value.length===0&&evt.target!==input&&evt.target!==trigger&&evt.target!==svg){container.classList.remove(this.options.classToolbarSearchActive);trigger.focus()}if(evt.which===27&&evt.target===input){container.classList.remove(this.options.classToolbarSearchActive);trigger.focus()}}},{key:"_changeState",value:function _changeState(detail,callback){this[this.constructor.eventHandlers[detail.group]](detail);callback()}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-table]",selectorToolbar:".".concat(prefix,"--table--toolbar"),selectorActions:".".concat(prefix,"--batch-actions"),selectorCount:"[data-items-selected]",selectorActionCancel:".".concat(prefix,"--batch-summary__cancel"),selectorCheckbox:".bx--table-column-checkbox "+".".concat(prefix,"--checkbox"),selectorExpandHeader:"th.".concat(prefix,"--table-expand"),selectorExpandCells:"td.".concat(prefix,"--table-expand"),selectorExpandableRows:".".concat(prefix,"--expandable-row"),selectorParentRows:".".concat(prefix,"--parent-row"),selectorChildRow:"[data-child-row]",selectorTableBody:"tbody",selectorTableSort:".".concat(prefix,"--table-sort"),selectorTableSelected:".".concat(prefix,"--data-table--selected"),selectorToolbarSearchContainer:".".concat(prefix,"--toolbar-search-container-expandable"),selectorSearchMagnifier:".".concat(prefix,"--search-magnifier"),selectorSearchInput:".".concat(prefix,"--search-input"),classExpandableRow:"".concat(prefix,"--expandable-row"),classExpandableRowHidden:"".concat(prefix,"--expandable-row--hidden"),classExpandableRowHover:"".concat(prefix,"--expandable-row--hover"),classTableSortAscending:"".concat(prefix,"--table-sort--ascending"),classTableSortActive:"".concat(prefix,"--table-sort--active"),classToolbarSearchActive:"".concat(prefix,"--toolbar-search-container-active"),classActionBarActive:"".concat(prefix,"--batch-actions--active"),classTableSelected:"".concat(prefix,"--data-table--selected"),eventBeforeExpand:"data-table-beforetoggleexpand",eventAfterExpand:"data-table-aftertoggleexpand",eventBeforeExpandAll:"data-table-beforetoggleexpandall",eventAfterExpandAll:"data-table-aftertoggleexpandall",eventBeforeSort:"data-table-beforetogglesort",eventAfterSort:"data-table-aftertogglesort",eventTrigger:"[data-event]",eventParentContainer:"[data-parent-row]"}}}]);return DataTable}(mixin(createComponent,initComponentBySearch,eventedState,handles));_defineProperty(DataTable,"components",new WeakMap);_defineProperty(DataTable,"eventHandlers",{expand:"_rowExpandToggle",expandAll:"_rowExpandToggleAll",sort:"_sortToggle",select:"_selectToggle","select-all":"_selectAllToggle","action-bar-cancel":"_actionBarCancel"});var commonjsGlobal=typeof globalThis!=="undefined"?globalThis:typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function createCommonjsModule(fn,module){return module={exports:{}},fn(module,module.exports),module.exports}var flatpickr=createCommonjsModule(function(module,exports){(function(global,factory){module.exports=factory()})(commonjsGlobal,function(){var __assign=function(){__assign=Object.assign||function __assign(t){for(var s,i=1,n=arguments.length;i",noCalendar:false,now:new Date,onChange:[],onClose:[],onDayCreate:[],onDestroy:[],onKeyDown:[],onMonthChange:[],onOpen:[],onParseConfig:[],onReady:[],onValueUpdate:[],onYearChange:[],onPreCalendarPosition:[],plugins:[],position:"auto",positionElement:undefined,prevArrow:"",shorthandCurrentMonth:false,showMonths:1,static:false,time_24hr:false,weekNumbers:false,wrap:false};var english={weekdays:{shorthand:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],longhand:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},months:{shorthand:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],longhand:["January","February","March","April","May","June","July","August","September","October","November","December"]},daysInMonth:[31,28,31,30,31,30,31,31,30,31,30,31],firstDayOfWeek:0,ordinal:function(nth){var s=nth%100;if(s>3&&s<21)return"th";switch(s%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}},rangeSeparator:" to ",weekAbbreviation:"Wk",scrollTitle:"Scroll to increment",toggleTitle:"Click to toggle",amPM:["AM","PM"],yearAriaLabel:"Year",time_24hr:false};var pad=function(number){return("0"+number).slice(-2)};var int=function(bool){return bool===true?1:0};function debounce(func,wait,immediate){if(immediate===void 0){immediate=false}var timeout;return function(){var context=this,args=arguments;timeout!==null&&clearTimeout(timeout);timeout=window.setTimeout(function(){timeout=null;if(!immediate)func.apply(context,args)},wait);if(immediate&&!timeout)func.apply(context,args)}}var arrayify=function(obj){return obj instanceof Array?obj:[obj]};function toggleClass(elem,className,bool){if(bool===true)return elem.classList.add(className);elem.classList.remove(className)}function createElement(tag,className,content){var e=window.document.createElement(tag);className=className||"";content=content||"";e.className=className;if(content!==undefined)e.textContent=content;return e}function clearNode(node){while(node.firstChild)node.removeChild(node.firstChild)}function findParent(node,condition){if(condition(node))return node;else if(node.parentNode)return findParent(node.parentNode,condition);return undefined}function createNumberInput(inputClassName,opts){var wrapper=createElement("div","numInputWrapper"),numInput=createElement("input","numInput "+inputClassName),arrowUp=createElement("span","arrowUp"),arrowDown=createElement("span","arrowDown");if(navigator.userAgent.indexOf("MSIE 9.0")===-1){numInput.type="number"}else{numInput.type="text";numInput.pattern="\\d*"}if(opts!==undefined)for(var key in opts)numInput.setAttribute(key,opts[key]);wrapper.appendChild(numInput);wrapper.appendChild(arrowUp);wrapper.appendChild(arrowDown);return wrapper}function getEventTarget(event){if(typeof event.composedPath==="function"){var path=event.composedPath();return path[0]}return event.target}var doNothing=function(){return undefined};var monthToStr=function(monthNumber,shorthand,locale){return locale.months[shorthand?"shorthand":"longhand"][monthNumber]};var revFormat={D:doNothing,F:function(dateObj,monthName,locale){dateObj.setMonth(locale.months.longhand.indexOf(monthName))},G:function(dateObj,hour){dateObj.setHours(parseFloat(hour))},H:function(dateObj,hour){dateObj.setHours(parseFloat(hour))},J:function(dateObj,day){dateObj.setDate(parseFloat(day))},K:function(dateObj,amPM,locale){dateObj.setHours(dateObj.getHours()%12+12*int(new RegExp(locale.amPM[1],"i").test(amPM)))},M:function(dateObj,shortMonth,locale){dateObj.setMonth(locale.months.shorthand.indexOf(shortMonth))},S:function(dateObj,seconds){dateObj.setSeconds(parseFloat(seconds))},U:function(_,unixSeconds){return new Date(parseFloat(unixSeconds)*1e3)},W:function(dateObj,weekNum,locale){var weekNumber=parseInt(weekNum);var date=new Date(dateObj.getFullYear(),0,2+(weekNumber-1)*7,0,0,0,0);date.setDate(date.getDate()-date.getDay()+locale.firstDayOfWeek);return date},Y:function(dateObj,year){dateObj.setFullYear(parseFloat(year))},Z:function(_,ISODate){return new Date(ISODate)},d:function(dateObj,day){dateObj.setDate(parseFloat(day))},h:function(dateObj,hour){dateObj.setHours(parseFloat(hour))},i:function(dateObj,minutes){dateObj.setMinutes(parseFloat(minutes))},j:function(dateObj,day){dateObj.setDate(parseFloat(day))},l:doNothing,m:function(dateObj,month){dateObj.setMonth(parseFloat(month)-1)},n:function(dateObj,month){dateObj.setMonth(parseFloat(month)-1)},s:function(dateObj,seconds){dateObj.setSeconds(parseFloat(seconds))},u:function(_,unixMillSeconds){return new Date(parseFloat(unixMillSeconds))},w:doNothing,y:function(dateObj,year){dateObj.setFullYear(2e3+parseFloat(year))}};var tokenRegex={D:"(\\w+)",F:"(\\w+)",G:"(\\d\\d|\\d)",H:"(\\d\\d|\\d)",J:"(\\d\\d|\\d)\\w+",K:"",M:"(\\w+)",S:"(\\d\\d|\\d)",U:"(.+)",W:"(\\d\\d|\\d)",Y:"(\\d{4})",Z:"(.+)",d:"(\\d\\d|\\d)",h:"(\\d\\d|\\d)",i:"(\\d\\d|\\d)",j:"(\\d\\d|\\d)",l:"(\\w+)",m:"(\\d\\d|\\d)",n:"(\\d\\d|\\d)",s:"(\\d\\d|\\d)",u:"(.+)",w:"(\\d\\d|\\d)",y:"(\\d{2})"};var formats={Z:function(date){return date.toISOString()},D:function(date,locale,options){return locale.weekdays.shorthand[formats.w(date,locale,options)]},F:function(date,locale,options){return monthToStr(formats.n(date,locale,options)-1,false,locale)},G:function(date,locale,options){return pad(formats.h(date,locale,options))},H:function(date){return pad(date.getHours())},J:function(date,locale){return locale.ordinal!==undefined?date.getDate()+locale.ordinal(date.getDate()):date.getDate()},K:function(date,locale){return locale.amPM[int(date.getHours()>11)]},M:function(date,locale){return monthToStr(date.getMonth(),true,locale)},S:function(date){return pad(date.getSeconds())},U:function(date){return date.getTime()/1e3},W:function(date,_,options){return options.getWeek(date)},Y:function(date){return date.getFullYear()},d:function(date){return pad(date.getDate())},h:function(date){return date.getHours()%12?date.getHours()%12:12},i:function(date){return pad(date.getMinutes())},j:function(date){return date.getDate()},l:function(date,locale){return locale.weekdays.longhand[date.getDay()]},m:function(date){return pad(date.getMonth()+1)},n:function(date){return date.getMonth()+1},s:function(date){return date.getSeconds()},u:function(date){return date.getTime()},w:function(date){return date.getDay()},y:function(date){return String(date.getFullYear()).substring(2)}};var createDateFormatter=function(_a){var _b=_a.config,config=_b===void 0?defaults:_b,_c=_a.l10n,l10n=_c===void 0?english:_c;return function(dateObj,frmt,overrideLocale){var locale=overrideLocale||l10n;if(config.formatDate!==undefined){return config.formatDate(dateObj,frmt,locale)}return frmt.split("").map(function(c,i,arr){return formats[c]&&arr[i-1]!=="\\"?formats[c](dateObj,locale,config):c!=="\\"?c:""}).join("")}};var createDateParser=function(_a){var _b=_a.config,config=_b===void 0?defaults:_b,_c=_a.l10n,l10n=_c===void 0?english:_c;return function(date,givenFormat,timeless,customLocale){if(date!==0&&!date)return undefined;var locale=customLocale||l10n;var parsedDate;var dateOrig=date;if(date instanceof Date)parsedDate=new Date(date.getTime());else if(typeof date!=="string"&&date.toFixed!==undefined)parsedDate=new Date(date);else if(typeof date==="string"){var format=givenFormat||(config||defaults).dateFormat;var datestr=String(date).trim();if(datestr==="today"){parsedDate=new Date;timeless=true}else if(/Z$/.test(datestr)||/GMT$/.test(datestr))parsedDate=new Date(date);else if(config&&config.parseDate)parsedDate=config.parseDate(date,format);else{parsedDate=!config||!config.noCalendar?new Date((new Date).getFullYear(),0,1,0,0,0,0):new Date((new Date).setHours(0,0,0,0));var matched=void 0,ops=[];for(var i=0,matchIndex=0,regexStr="";iMath.min(ts1,ts2)&&ts0||self.config.noCalendar;var isSafari=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);if(!self.isMobile&&isSafari){positionCalendar()}triggerEvent("onReady")}function bindToInstance(fn){return fn.bind(self)}function setCalendarWidth(){var config=self.config;if(config.weekNumbers===false&&config.showMonths===1)return;else if(config.noCalendar!==true){window.requestAnimationFrame(function(){if(self.calendarContainer!==undefined){self.calendarContainer.style.visibility="hidden";self.calendarContainer.style.display="block"}if(self.daysContainer!==undefined){var daysWidth=(self.days.offsetWidth+1)*config.showMonths;self.daysContainer.style.width=daysWidth+"px";self.calendarContainer.style.width=daysWidth+(self.weekWrapper!==undefined?self.weekWrapper.offsetWidth:0)+"px";self.calendarContainer.style.removeProperty("visibility");self.calendarContainer.style.removeProperty("display")}})}}function updateTime(e){if(self.selectedDates.length===0){setDefaultTime()}if(e!==undefined&&e.type!=="blur"){timeWrapper(e)}var prevValue=self._input.value;setHoursFromInputs();updateValue();if(self._input.value!==prevValue){self._debouncedChange()}}function ampm2military(hour,amPM){return hour%12+12*int(amPM===self.l10n.amPM[1])}function military2ampm(hour){switch(hour%24){case 0:case 12:return 12;default:return hour%12}}function setHoursFromInputs(){if(self.hourElement===undefined||self.minuteElement===undefined)return;var hours=(parseInt(self.hourElement.value.slice(-2),10)||0)%24,minutes=(parseInt(self.minuteElement.value,10)||0)%60,seconds=self.secondElement!==undefined?(parseInt(self.secondElement.value,10)||0)%60:0;if(self.amPM!==undefined){hours=ampm2military(hours,self.amPM.textContent)}var limitMinHours=self.config.minTime!==undefined||self.config.minDate&&self.minDateHasTime&&self.latestSelectedDateObj&&compareDates(self.latestSelectedDateObj,self.config.minDate,true)===0;var limitMaxHours=self.config.maxTime!==undefined||self.config.maxDate&&self.maxDateHasTime&&self.latestSelectedDateObj&&compareDates(self.latestSelectedDateObj,self.config.maxDate,true)===0;if(limitMaxHours){var maxTime=self.config.maxTime!==undefined?self.config.maxTime:self.config.maxDate;hours=Math.min(hours,maxTime.getHours());if(hours===maxTime.getHours())minutes=Math.min(minutes,maxTime.getMinutes());if(minutes===maxTime.getMinutes())seconds=Math.min(seconds,maxTime.getSeconds())}if(limitMinHours){var minTime=self.config.minTime!==undefined?self.config.minTime:self.config.minDate;hours=Math.max(hours,minTime.getHours());if(hours===minTime.getHours())minutes=Math.max(minutes,minTime.getMinutes());if(minutes===minTime.getMinutes())seconds=Math.max(seconds,minTime.getSeconds())}setHours(hours,minutes,seconds)}function setHoursFromDate(dateObj){var date=dateObj||self.latestSelectedDateObj;if(date)setHours(date.getHours(),date.getMinutes(),date.getSeconds())}function setDefaultHours(){var hours=self.config.defaultHour;var minutes=self.config.defaultMinute;var seconds=self.config.defaultSeconds;if(self.config.minDate!==undefined){var minHr=self.config.minDate.getHours();var minMinutes=self.config.minDate.getMinutes();hours=Math.max(hours,minHr);if(hours===minHr)minutes=Math.max(minMinutes,minutes);if(hours===minHr&&minutes===minMinutes)seconds=self.config.minDate.getSeconds()}if(self.config.maxDate!==undefined){var maxHr=self.config.maxDate.getHours();var maxMinutes=self.config.maxDate.getMinutes();hours=Math.min(hours,maxHr);if(hours===maxHr)minutes=Math.min(maxMinutes,minutes);if(hours===maxHr&&minutes===maxMinutes)seconds=self.config.maxDate.getSeconds()}setHours(hours,minutes,seconds)}function setHours(hours,minutes,seconds){if(self.latestSelectedDateObj!==undefined){self.latestSelectedDateObj.setHours(hours%24,minutes,seconds||0,0)}if(!self.hourElement||!self.minuteElement||self.isMobile)return;self.hourElement.value=pad(!self.config.time_24hr?(12+hours)%12+12*int(hours%12===0):hours);self.minuteElement.value=pad(minutes);if(self.amPM!==undefined)self.amPM.textContent=self.l10n.amPM[int(hours>=12)];if(self.secondElement!==undefined)self.secondElement.value=pad(seconds)}function onYearInput(event){var year=parseInt(event.target.value)+(event.delta||0);if(year/1e3>1||event.key==="Enter"&&!/[^\d]/.test(year.toString())){changeYear(year)}}function bind(element,event,handler,options){if(event instanceof Array)return event.forEach(function(ev){return bind(element,ev,handler,options)});if(element instanceof Array)return element.forEach(function(el){return bind(el,event,handler,options)});element.addEventListener(event,handler,options);self._handlers.push({element:element,event:event,handler:handler,options:options})}function onClick(handler){return function(evt){evt.which===1&&handler(evt)}}function triggerChange(){triggerEvent("onChange")}function bindEvents(){if(self.config.wrap){["open","close","toggle","clear"].forEach(function(evt){Array.prototype.forEach.call(self.element.querySelectorAll("[data-"+evt+"]"),function(el){return bind(el,"click",self[evt])})})}if(self.isMobile){setupMobile();return}var debouncedResize=debounce(onResize,50);self._debouncedChange=debounce(triggerChange,DEBOUNCED_CHANGE_MS);if(self.daysContainer&&!/iPhone|iPad|iPod/i.test(navigator.userAgent))bind(self.daysContainer,"mouseover",function(e){if(self.config.mode==="range")onMouseOver(e.target)});bind(window.document.body,"keydown",onKeyDown);if(!self.config.inline&&!self.config.static)bind(window,"resize",debouncedResize);if(window.ontouchstart!==undefined)bind(window.document,"touchstart",documentClick);else bind(window.document,"mousedown",onClick(documentClick));bind(window.document,"focus",documentClick,{capture:true});if(self.config.clickOpens===true){bind(self._input,"focus",self.open);bind(self._input,"mousedown",onClick(self.open))}if(self.daysContainer!==undefined){bind(self.monthNav,"mousedown",onClick(onMonthNavClick));bind(self.monthNav,["keyup","increment"],onYearInput);bind(self.daysContainer,"mousedown",onClick(selectDate))}if(self.timeContainer!==undefined&&self.minuteElement!==undefined&&self.hourElement!==undefined){var selText=function(e){return e.target.select()};bind(self.timeContainer,["increment"],updateTime);bind(self.timeContainer,"blur",updateTime,{capture:true});bind(self.timeContainer,"mousedown",onClick(timeIncrement));bind([self.hourElement,self.minuteElement],["focus","click"],selText);if(self.secondElement!==undefined)bind(self.secondElement,"focus",function(){return self.secondElement&&self.secondElement.select()});if(self.amPM!==undefined){bind(self.amPM,"mousedown",onClick(function(e){updateTime(e);triggerChange()}))}}}function jumpToDate(jumpDate,triggerChange){var jumpTo=jumpDate!==undefined?self.parseDate(jumpDate):self.latestSelectedDateObj||(self.config.minDate&&self.config.minDate>self.now?self.config.minDate:self.config.maxDate&&self.config.maxDate1);self.calendarContainer.appendChild(fragment);var customAppend=self.config.appendTo!==undefined&&self.config.appendTo.nodeType!==undefined;if(self.config.inline||self.config.static){self.calendarContainer.classList.add(self.config.inline?"inline":"static");if(self.config.inline){if(!customAppend&&self.element.parentNode)self.element.parentNode.insertBefore(self.calendarContainer,self._input.nextSibling);else if(self.config.appendTo!==undefined)self.config.appendTo.appendChild(self.calendarContainer)}if(self.config.static){var wrapper=createElement("div","flatpickr-wrapper");if(self.element.parentNode)self.element.parentNode.insertBefore(wrapper,self.element);wrapper.appendChild(self.element);if(self.altInput)wrapper.appendChild(self.altInput);wrapper.appendChild(self.calendarContainer)}}if(!self.config.static&&!self.config.inline)(self.config.appendTo!==undefined?self.config.appendTo:window.document.body).appendChild(self.calendarContainer)}function createDay(className,date,dayNumber,i){var dateIsEnabled=isEnabled(date,true),dayElement=createElement("span","flatpickr-day "+className,date.getDate().toString());dayElement.dateObj=date;dayElement.$i=i;dayElement.setAttribute("aria-label",self.formatDate(date,self.config.ariaDateFormat));if(className.indexOf("hidden")===-1&&compareDates(date,self.now)===0){self.todayDateElem=dayElement;dayElement.classList.add("today");dayElement.setAttribute("aria-current","date")}if(dateIsEnabled){dayElement.tabIndex=-1;if(isDateSelected(date)){dayElement.classList.add("selected");self.selectedDateElem=dayElement;if(self.config.mode==="range"){toggleClass(dayElement,"startRange",self.selectedDates[0]&&compareDates(date,self.selectedDates[0],true)===0);toggleClass(dayElement,"endRange",self.selectedDates[1]&&compareDates(date,self.selectedDates[1],true)===0);if(className==="nextMonthDay")dayElement.classList.add("inRange")}}}else{dayElement.classList.add("flatpickr-disabled")}if(self.config.mode==="range"){if(isDateInRange(date)&&!isDateSelected(date))dayElement.classList.add("inRange")}if(self.weekNumbers&&self.config.showMonths===1&&className!=="prevMonthDay"&&dayNumber%7===1){self.weekNumbers.insertAdjacentHTML("beforeend",""+self.config.getWeek(date)+"")}triggerEvent("onDayCreate",dayElement);return dayElement}function focusOnDayElem(targetNode){targetNode.focus();if(self.config.mode==="range")onMouseOver(targetNode)}function getFirstAvailableDay(delta){var startMonth=delta>0?0:self.config.showMonths-1;var endMonth=delta>0?self.config.showMonths:-1;for(var m=startMonth;m!=endMonth;m+=delta){var month=self.daysContainer.children[m];var startIndex=delta>0?0:month.children.length-1;var endIndex=delta>0?month.children.length:-1;for(var i=startIndex;i!=endIndex;i+=delta){var c=month.children[i];if(c.className.indexOf("hidden")===-1&&isEnabled(c.dateObj))return c}}return undefined}function getNextAvailableDay(current,delta){var givenMonth=current.className.indexOf("Month")===-1?current.dateObj.getMonth():self.currentMonth;var endMonth=delta>0?self.config.showMonths:-1;var loopDelta=delta>0?1:-1;for(var m=givenMonth-self.currentMonth;m!=endMonth;m+=loopDelta){var month=self.daysContainer.children[m];var startIndex=givenMonth-self.currentMonth===m?current.$i+delta:delta<0?month.children.length-1:0;var numMonthDays=month.children.length;for(var i=startIndex;i>=0&&i0?numMonthDays:-1);i+=loopDelta){var c=month.children[i];if(c.className.indexOf("hidden")===-1&&isEnabled(c.dateObj)&&Math.abs(current.$i-i)>=Math.abs(delta))return focusOnDayElem(c)}}self.changeMonth(loopDelta);focusOnDay(getFirstAvailableDay(loopDelta),0);return undefined}function focusOnDay(current,offset){var dayFocused=isInView(document.activeElement||document.body);var startElem=current!==undefined?current:dayFocused?document.activeElement:self.selectedDateElem!==undefined&&isInView(self.selectedDateElem)?self.selectedDateElem:self.todayDateElem!==undefined&&isInView(self.todayDateElem)?self.todayDateElem:getFirstAvailableDay(offset>0?1:-1);if(startElem===undefined)return self._input.focus();if(!dayFocused)return focusOnDayElem(startElem);getNextAvailableDay(startElem,offset)}function buildMonthDays(year,month){var firstOfMonth=(new Date(year,month,1).getDay()-self.l10n.firstDayOfWeek+7)%7;var prevMonthDays=self.utils.getDaysInMonth((month-1+12)%12);var daysInMonth=self.utils.getDaysInMonth(month),days=window.document.createDocumentFragment(),isMultiMonth=self.config.showMonths>1,prevMonthDayClass=isMultiMonth?"prevMonthDay hidden":"prevMonthDay",nextMonthDayClass=isMultiMonth?"nextMonthDay hidden":"nextMonthDay";var dayNumber=prevMonthDays+1-firstOfMonth,dayIndex=0;for(;dayNumber<=prevMonthDays;dayNumber++,dayIndex++){days.appendChild(createDay(prevMonthDayClass,new Date(year,month-1,dayNumber),dayNumber,dayIndex))}for(dayNumber=1;dayNumber<=daysInMonth;dayNumber++,dayIndex++){days.appendChild(createDay("",new Date(year,month,dayNumber),dayNumber,dayIndex))}for(var dayNum=daysInMonth+1;dayNum<=42-firstOfMonth&&(self.config.showMonths===1||dayIndex%7!==0);dayNum++,dayIndex++){days.appendChild(createDay(nextMonthDayClass,new Date(year,month+1,dayNum%daysInMonth),dayNum,dayIndex))}var dayContainer=createElement("div","dayContainer");dayContainer.appendChild(days);return dayContainer}function buildDays(){if(self.daysContainer===undefined){return}clearNode(self.daysContainer);if(self.weekNumbers)clearNode(self.weekNumbers);var frag=document.createDocumentFragment();for(var i=0;i1)return;var shouldBuildMonth=function(month){if(self.config.minDate!==undefined&&self.currentYear===self.config.minDate.getFullYear()&&monthself.config.maxDate.getMonth())};self.monthsDropdownContainer.tabIndex=-1;self.monthsDropdownContainer.innerHTML="";for(var i=0;i<12;i++){if(!shouldBuildMonth(i))continue;var month=createElement("option","flatpickr-monthDropdown-month");month.value=new Date(self.currentYear,i).getMonth().toString();month.textContent=monthToStr(i,false,self.l10n);month.tabIndex=-1;if(self.currentMonth===i){month.selected=true}self.monthsDropdownContainer.appendChild(month)}}function buildMonth(){var container=createElement("div","flatpickr-month");var monthNavFragment=window.document.createDocumentFragment();var monthElement;if(self.config.showMonths>1){monthElement=createElement("span","cur-month")}else{self.monthsDropdownContainer=createElement("select","flatpickr-monthDropdown-months");bind(self.monthsDropdownContainer,"change",function(e){var target=e.target;var selectedMonth=parseInt(target.value,10);self.changeMonth(selectedMonth-self.currentMonth);triggerEvent("onMonthChange")});buildMonthSwitch();monthElement=self.monthsDropdownContainer}var yearInput=createNumberInput("cur-year",{tabindex:"-1"});var yearElement=yearInput.getElementsByTagName("input")[0];yearElement.setAttribute("aria-label",self.l10n.yearAriaLabel);if(self.config.minDate){yearElement.setAttribute("min",self.config.minDate.getFullYear().toString())}if(self.config.maxDate){yearElement.setAttribute("max",self.config.maxDate.getFullYear().toString());yearElement.disabled=!!self.config.minDate&&self.config.minDate.getFullYear()===self.config.maxDate.getFullYear()}var currentMonth=createElement("div","flatpickr-current-month");currentMonth.appendChild(monthElement);currentMonth.appendChild(yearInput);monthNavFragment.appendChild(currentMonth);container.appendChild(monthNavFragment);return{container:container,yearElement:yearElement,monthElement:monthElement}}function buildMonths(){clearNode(self.monthNav);self.monthNav.appendChild(self.prevMonthNav);if(self.config.showMonths){self.yearElements=[];self.monthElements=[]}for(var m=self.config.showMonths;m--;){var month=buildMonth();self.yearElements.push(month.yearElement);self.monthElements.push(month.monthElement);self.monthNav.appendChild(month.container)}self.monthNav.appendChild(self.nextMonthNav)}function buildMonthNav(){self.monthNav=createElement("div","flatpickr-months");self.yearElements=[];self.monthElements=[];self.prevMonthNav=createElement("span","flatpickr-prev-month");self.prevMonthNav.innerHTML=self.config.prevArrow;self.nextMonthNav=createElement("span","flatpickr-next-month");self.nextMonthNav.innerHTML=self.config.nextArrow;buildMonths();Object.defineProperty(self,"_hidePrevMonthArrow",{get:function(){return self.__hidePrevMonthArrow},set:function(bool){if(self.__hidePrevMonthArrow!==bool){toggleClass(self.prevMonthNav,"flatpickr-disabled",bool);self.__hidePrevMonthArrow=bool}}});Object.defineProperty(self,"_hideNextMonthArrow",{get:function(){return self.__hideNextMonthArrow},set:function(bool){if(self.__hideNextMonthArrow!==bool){toggleClass(self.nextMonthNav,"flatpickr-disabled",bool);self.__hideNextMonthArrow=bool}}});self.currentYearElement=self.yearElements[0];updateNavigationCurrentMonth();return self.monthNav}function buildTime(){self.calendarContainer.classList.add("hasTime");if(self.config.noCalendar)self.calendarContainer.classList.add("noCalendar");self.timeContainer=createElement("div","flatpickr-time");self.timeContainer.tabIndex=-1;var separator=createElement("span","flatpickr-time-separator",":");var hourInput=createNumberInput("flatpickr-hour");self.hourElement=hourInput.getElementsByTagName("input")[0];var minuteInput=createNumberInput("flatpickr-minute");self.minuteElement=minuteInput.getElementsByTagName("input")[0];self.hourElement.tabIndex=self.minuteElement.tabIndex=-1;self.hourElement.value=pad(self.latestSelectedDateObj?self.latestSelectedDateObj.getHours():self.config.time_24hr?self.config.defaultHour:military2ampm(self.config.defaultHour));self.minuteElement.value=pad(self.latestSelectedDateObj?self.latestSelectedDateObj.getMinutes():self.config.defaultMinute);self.hourElement.setAttribute("step",self.config.hourIncrement.toString());self.minuteElement.setAttribute("step",self.config.minuteIncrement.toString());self.hourElement.setAttribute("min",self.config.time_24hr?"0":"1");self.hourElement.setAttribute("max",self.config.time_24hr?"23":"12");self.minuteElement.setAttribute("min","0");self.minuteElement.setAttribute("max","59");self.timeContainer.appendChild(hourInput);self.timeContainer.appendChild(separator);self.timeContainer.appendChild(minuteInput);if(self.config.time_24hr)self.timeContainer.classList.add("time24hr");if(self.config.enableSeconds){self.timeContainer.classList.add("hasSeconds");var secondInput=createNumberInput("flatpickr-second");self.secondElement=secondInput.getElementsByTagName("input")[0];self.secondElement.value=pad(self.latestSelectedDateObj?self.latestSelectedDateObj.getSeconds():self.config.defaultSeconds);self.secondElement.setAttribute("step",self.minuteElement.getAttribute("step"));self.secondElement.setAttribute("min","0");self.secondElement.setAttribute("max","59");self.timeContainer.appendChild(createElement("span","flatpickr-time-separator",":"));self.timeContainer.appendChild(secondInput)}if(!self.config.time_24hr){self.amPM=createElement("span","flatpickr-am-pm",self.l10n.amPM[int((self.latestSelectedDateObj?self.hourElement.value:self.config.defaultHour)>11)]);self.amPM.title=self.l10n.toggleTitle;self.amPM.tabIndex=-1;self.timeContainer.appendChild(self.amPM)}return self.timeContainer}function buildWeekdays(){if(!self.weekdayContainer)self.weekdayContainer=createElement("div","flatpickr-weekdays");else clearNode(self.weekdayContainer);for(var i=self.config.showMonths;i--;){var container=createElement("div","flatpickr-weekdaycontainer");self.weekdayContainer.appendChild(container)}updateWeekdays();return self.weekdayContainer}function updateWeekdays(){var firstDayOfWeek=self.l10n.firstDayOfWeek;var weekdays=self.l10n.weekdays.shorthand.slice();if(firstDayOfWeek>0&&firstDayOfWeek\n "+weekdays.join("")+"\n \n "}}function buildWeeks(){self.calendarContainer.classList.add("hasWeeks");var weekWrapper=createElement("div","flatpickr-weekwrapper");weekWrapper.appendChild(createElement("span","flatpickr-weekday",self.l10n.weekAbbreviation));var weekNumbers=createElement("div","flatpickr-weeks");weekWrapper.appendChild(weekNumbers);return{weekWrapper:weekWrapper,weekNumbers:weekNumbers}}function changeMonth(value,isOffset){if(isOffset===void 0){isOffset=true}var delta=isOffset?value:value-self.currentMonth;if(delta<0&&self._hidePrevMonthArrow===true||delta>0&&self._hideNextMonthArrow===true)return;self.currentMonth+=delta;if(self.currentMonth<0||self.currentMonth>11){self.currentYear+=self.currentMonth>11?1:-1;self.currentMonth=(self.currentMonth+12)%12;triggerEvent("onYearChange");buildMonthSwitch()}buildDays();triggerEvent("onMonthChange");updateNavigationCurrentMonth()}function clear(triggerChangeEvent,toInitial){if(triggerChangeEvent===void 0){triggerChangeEvent=true}if(toInitial===void 0){toInitial=true}self.input.value="";if(self.altInput!==undefined)self.altInput.value="";if(self.mobileInput!==undefined)self.mobileInput.value="";self.selectedDates=[];self.latestSelectedDateObj=undefined;if(toInitial===true){self.currentYear=self._initialDate.getFullYear();self.currentMonth=self._initialDate.getMonth()}self.showTimeInput=false;if(self.config.enableTime===true){setDefaultHours()}self.redraw();if(triggerChangeEvent)triggerEvent("onChange")}function close(){self.isOpen=false;if(!self.isMobile){if(self.calendarContainer!==undefined){self.calendarContainer.classList.remove("open")}if(self._input!==undefined){self._input.classList.remove("active")}}triggerEvent("onClose")}function destroy(){if(self.config!==undefined)triggerEvent("onDestroy");for(var i=self._handlers.length;i--;){var h=self._handlers[i];h.element.removeEventListener(h.event,h.handler,h.options)}self._handlers=[];if(self.mobileInput){if(self.mobileInput.parentNode)self.mobileInput.parentNode.removeChild(self.mobileInput);self.mobileInput=undefined}else if(self.calendarContainer&&self.calendarContainer.parentNode){if(self.config.static&&self.calendarContainer.parentNode){var wrapper=self.calendarContainer.parentNode;wrapper.lastChild&&wrapper.removeChild(wrapper.lastChild);if(wrapper.parentNode){while(wrapper.firstChild)wrapper.parentNode.insertBefore(wrapper.firstChild,wrapper);wrapper.parentNode.removeChild(wrapper)}}else self.calendarContainer.parentNode.removeChild(self.calendarContainer)}if(self.altInput){self.input.type="text";if(self.altInput.parentNode)self.altInput.parentNode.removeChild(self.altInput);delete self.altInput}if(self.input){self.input.type=self.input._type;self.input.classList.remove("flatpickr-input");self.input.removeAttribute("readonly");self.input.value=""}["_showTimeInput","latestSelectedDateObj","_hideNextMonthArrow","_hidePrevMonthArrow","__hideNextMonthArrow","__hidePrevMonthArrow","isMobile","isOpen","selectedDateElem","minDateHasTime","maxDateHasTime","days","daysContainer","_input","_positionElement","innerContainer","rContainer","monthNav","todayDateElem","calendarContainer","weekdayContainer","prevMonthNav","nextMonthNav","monthsDropdownContainer","currentMonthElement","currentYearElement","navigationCurrentMonth","selectedDateElem","config"].forEach(function(k){try{delete self[k]}catch(_){}})}function isCalendarElem(elem){if(self.config.appendTo&&self.config.appendTo.contains(elem))return true;return self.calendarContainer.contains(elem)}function documentClick(e){if(self.isOpen&&!self.config.inline){var eventTarget_1=getEventTarget(e);var isCalendarElement=isCalendarElem(eventTarget_1);var isInput=eventTarget_1===self.input||eventTarget_1===self.altInput||self.element.contains(eventTarget_1)||e.path&&e.path.indexOf&&(~e.path.indexOf(self.input)||~e.path.indexOf(self.altInput));var lostFocus=e.type==="blur"?isInput&&e.relatedTarget&&!isCalendarElem(e.relatedTarget):!isInput&&!isCalendarElement&&!isCalendarElem(e.relatedTarget);var isIgnored=!self.config.ignoredFocusElements.some(function(elem){return elem.contains(eventTarget_1)});if(lostFocus&&isIgnored){self.close();if(self.config.mode==="range"&&self.selectedDates.length===1){self.clear(false);self.redraw()}}}}function changeYear(newYear){if(!newYear||self.config.minDate&&newYearself.config.maxDate.getFullYear())return;var newYearNum=newYear,isNewYear=self.currentYear!==newYearNum;self.currentYear=newYearNum||self.currentYear;if(self.config.maxDate&&self.currentYear===self.config.maxDate.getFullYear()){self.currentMonth=Math.min(self.config.maxDate.getMonth(),self.currentMonth)}else if(self.config.minDate&&self.currentYear===self.config.minDate.getFullYear()){self.currentMonth=Math.max(self.config.minDate.getMonth(),self.currentMonth)}if(isNewYear){self.redraw();triggerEvent("onYearChange");buildMonthSwitch()}}function isEnabled(date,timeless){if(timeless===void 0){timeless=true}var dateToCheck=self.parseDate(date,undefined,timeless);if(self.config.minDate&&dateToCheck&&compareDates(dateToCheck,self.config.minDate,timeless!==undefined?timeless:!self.minDateHasTime)<0||self.config.maxDate&&dateToCheck&&compareDates(dateToCheck,self.config.maxDate,timeless!==undefined?timeless:!self.maxDateHasTime)>0)return false;if(self.config.enable.length===0&&self.config.disable.length===0)return true;if(dateToCheck===undefined)return false;var bool=self.config.enable.length>0,array=bool?self.config.enable:self.config.disable;for(var i=0,d=void 0;i=d.from.getTime()&&dateToCheck.getTime()<=d.to.getTime())return bool}return!bool}function isInView(elem){if(self.daysContainer!==undefined)return elem.className.indexOf("hidden")===-1&&self.daysContainer.contains(elem);return false}function onKeyDown(e){var isInput=e.target===self._input;var allowInput=self.config.allowInput;var allowKeydown=self.isOpen&&(!allowInput||!isInput);var allowInlineKeydown=self.config.inline&&isInput&&!allowInput;if(e.keyCode===13&&isInput){if(allowInput){self.setDate(self._input.value,true,e.target===self.altInput?self.config.altFormat:self.config.dateFormat);return e.target.blur()}else{self.open()}}else if(isCalendarElem(e.target)||allowKeydown||allowInlineKeydown){var isTimeObj=!!self.timeContainer&&self.timeContainer.contains(e.target);switch(e.keyCode){case 13:if(isTimeObj){e.preventDefault();updateTime();focusAndClose()}else selectDate(e);break;case 27:e.preventDefault();focusAndClose();break;case 8:case 46:if(isInput&&!self.config.allowInput){e.preventDefault();self.clear()}break;case 37:case 39:if(!isTimeObj&&!isInput){e.preventDefault();if(self.daysContainer!==undefined&&(allowInput===false||document.activeElement&&isInView(document.activeElement))){var delta_1=e.keyCode===39?1:-1;if(!e.ctrlKey)focusOnDay(undefined,delta_1);else{e.stopPropagation();changeMonth(delta_1);focusOnDay(getFirstAvailableDay(1),0)}}}else if(self.hourElement)self.hourElement.focus();break;case 38:case 40:e.preventDefault();var delta=e.keyCode===40?1:-1;if(self.daysContainer&&e.target.$i!==undefined||e.target===self.input){if(e.ctrlKey){e.stopPropagation();changeYear(self.currentYear-delta);focusOnDay(getFirstAvailableDay(1),0)}else if(!isTimeObj)focusOnDay(undefined,delta*7)}else if(e.target===self.currentYearElement){changeYear(self.currentYear-delta)}else if(self.config.enableTime){if(!isTimeObj&&self.hourElement)self.hourElement.focus();updateTime(e);self._debouncedChange()}break;case 9:if(isTimeObj){var elems=[self.hourElement,self.minuteElement,self.secondElement,self.amPM].concat(self.pluginElements).filter(function(x){return x});var i=elems.indexOf(e.target);if(i!==-1){var target=elems[i+(e.shiftKey?-1:1)];e.preventDefault();(target||self._input).focus()}}else if(!self.config.noCalendar&&self.daysContainer&&self.daysContainer.contains(e.target)&&e.shiftKey){e.preventDefault();self._input.focus()}break}}if(self.amPM!==undefined&&e.target===self.amPM){switch(e.key){case self.l10n.amPM[0].charAt(0):case self.l10n.amPM[0].charAt(0).toLowerCase():self.amPM.textContent=self.l10n.amPM[0];setHoursFromInputs();updateValue();break;case self.l10n.amPM[1].charAt(0):case self.l10n.amPM[1].charAt(0).toLowerCase():self.amPM.textContent=self.l10n.amPM[1];setHoursFromInputs();updateValue();break}}if(isInput||isCalendarElem(e.target)){triggerEvent("onKeyDown",e)}}function onMouseOver(elem){if(self.selectedDates.length!==1||elem&&(!elem.classList.contains("flatpickr-day")||elem.classList.contains("flatpickr-disabled")))return;var hoverDate=elem?elem.dateObj.getTime():self.days.firstElementChild.dateObj.getTime(),initialDate=self.parseDate(self.selectedDates[0],undefined,true).getTime(),rangeStartDate=Math.min(hoverDate,self.selectedDates[0].getTime()),rangeEndDate=Math.max(hoverDate,self.selectedDates[0].getTime());var containsDisabled=false;var minRange=0,maxRange=0;for(var t=rangeStartDate;trangeStartDate&&tminRange))minRange=t;else if(t>initialDate&&(!maxRange||t0&×tamp0&×tamp>maxRange;if(outOfRange){dayElem.classList.add("notAllowed");["inRange","startRange","endRange"].forEach(function(c){dayElem.classList.remove(c)});return"continue"}else if(containsDisabled&&!outOfRange)return"continue";["startRange","inRange","endRange","notAllowed"].forEach(function(c){dayElem.classList.remove(c)});if(elem!==undefined){elem.classList.add(hoverDate<=self.selectedDates[0].getTime()?"startRange":"endRange");if(initialDatehoverDate&×tamp===initialDate)dayElem.classList.add("endRange");if(timestamp>=minRange&&(maxRange===0||timestamp<=maxRange)&&isBetween(timestamp,initialDate,hoverDate))dayElem.classList.add("inRange")}};for(var i=0,l=month.children.length;i0||dateObj.getMinutes()>0||dateObj.getSeconds()>0}if(self.selectedDates){self.selectedDates=self.selectedDates.filter(function(d){return isEnabled(d)});if(!self.selectedDates.length&&type==="min")setHoursFromDate(dateObj);updateValue()}if(self.daysContainer){redraw();if(dateObj!==undefined)self.currentYearElement[type]=dateObj.getFullYear().toString();else self.currentYearElement.removeAttribute(type);self.currentYearElement.disabled=!!inverseDateObj&&dateObj!==undefined&&inverseDateObj.getFullYear()===dateObj.getFullYear()}}}function parseConfig(){var boolOpts=["wrap","weekNumbers","allowInput","clickOpens","time_24hr","enableTime","noCalendar","altInput","shorthandCurrentMonth","inline","static","enableSeconds","disableMobile"];var userConfig=__assign({},instanceConfig,JSON.parse(JSON.stringify(element.dataset||{})));var formats={};self.config.parseDate=userConfig.parseDate;self.config.formatDate=userConfig.formatDate;Object.defineProperty(self.config,"enable",{get:function(){return self.config._enable},set:function(dates){self.config._enable=parseDateRules(dates)}});Object.defineProperty(self.config,"disable",{get:function(){return self.config._disable},set:function(dates){self.config._disable=parseDateRules(dates)}});var timeMode=userConfig.mode==="time";if(!userConfig.dateFormat&&(userConfig.enableTime||timeMode)){var defaultDateFormat=flatpickr.defaultConfig.dateFormat||defaults.dateFormat;formats.dateFormat=userConfig.noCalendar||timeMode?"H:i"+(userConfig.enableSeconds?":S":""):defaultDateFormat+" H:i"+(userConfig.enableSeconds?":S":"")}if(userConfig.altInput&&(userConfig.enableTime||timeMode)&&!userConfig.altFormat){var defaultAltFormat=flatpickr.defaultConfig.altFormat||defaults.altFormat;formats.altFormat=userConfig.noCalendar||timeMode?"h:i"+(userConfig.enableSeconds?":S K":" K"):defaultAltFormat+(" h:i"+(userConfig.enableSeconds?":S":"")+" K")}if(!userConfig.altInputClass){self.config.altInputClass=self.input.className+" "+self.config.altInputClass}Object.defineProperty(self.config,"minDate",{get:function(){return self.config._minDate},set:minMaxDateSetter("min")});Object.defineProperty(self.config,"maxDate",{get:function(){return self.config._maxDate},set:minMaxDateSetter("max")});var minMaxTimeSetter=function(type){return function(val){self.config[type==="min"?"_minTime":"_maxTime"]=self.parseDate(val,"H:i")}};Object.defineProperty(self.config,"minTime",{get:function(){return self.config._minTime},set:minMaxTimeSetter("min")});Object.defineProperty(self.config,"maxTime",{get:function(){return self.config._maxTime},set:minMaxTimeSetter("max")});if(userConfig.mode==="time"){self.config.noCalendar=true;self.config.enableTime=true}Object.assign(self.config,formats,userConfig);for(var i=0;i-1){self.config[key]=arrayify(pluginConf[key]).map(bindToInstance).concat(self.config[key])}else if(typeof userConfig[key]==="undefined")self.config[key]=pluginConf[key]}}triggerEvent("onParseConfig")}function setupLocale(){if(typeof self.config.locale!=="object"&&typeof flatpickr.l10ns[self.config.locale]==="undefined")self.config.errorHandler(new Error("flatpickr: invalid locale "+self.config.locale));self.l10n=__assign({},flatpickr.l10ns["default"],typeof self.config.locale==="object"?self.config.locale:self.config.locale!=="default"?flatpickr.l10ns[self.config.locale]:undefined);tokenRegex.K="("+self.l10n.amPM[0]+"|"+self.l10n.amPM[1]+"|"+self.l10n.amPM[0].toLowerCase()+"|"+self.l10n.amPM[1].toLowerCase()+")";var userConfig=__assign({},instanceConfig,JSON.parse(JSON.stringify(element.dataset||{})));if(userConfig.time_24hr===undefined&&flatpickr.defaultConfig.time_24hr===undefined){self.config.time_24hr=self.l10n.time_24hr}self.formatDate=createDateFormatter(self);self.parseDate=createDateParser({config:self.config,l10n:self.l10n})}function positionCalendar(customPositionElement){if(self.calendarContainer===undefined)return;triggerEvent("onPreCalendarPosition");var positionElement=customPositionElement||self._positionElement;var calendarHeight=Array.prototype.reduce.call(self.calendarContainer.children,function(acc,child){return acc+child.offsetHeight},0),calendarWidth=self.calendarContainer.offsetWidth,configPos=self.config.position.split(" "),configPosVertical=configPos[0],configPosHorizontal=configPos.length>1?configPos[1]:null,inputBounds=positionElement.getBoundingClientRect(),distanceFromBottom=window.innerHeight-inputBounds.bottom,showOnTop=configPosVertical==="above"||configPosVertical!=="below"&&distanceFromBottomcalendarHeight;var top=window.pageYOffset+inputBounds.top+(!showOnTop?positionElement.offsetHeight+2:-calendarHeight-2);toggleClass(self.calendarContainer,"arrowTop",!showOnTop);toggleClass(self.calendarContainer,"arrowBottom",showOnTop);if(self.config.inline)return;var left=window.pageXOffset+inputBounds.left-(configPosHorizontal!=null&&configPosHorizontal==="center"?(calendarWidth-inputBounds.width)/2:0);var right=window.document.body.offsetWidth-(window.pageXOffset+inputBounds.right);var rightMost=left+calendarWidth>window.document.body.offsetWidth;var centerMost=right+calendarWidth>window.document.body.offsetWidth;toggleClass(self.calendarContainer,"rightMost",rightMost);if(self.config.static)return;self.calendarContainer.style.top=top+"px";if(!rightMost){self.calendarContainer.style.left=left+"px";self.calendarContainer.style.right="auto"}else if(!centerMost){self.calendarContainer.style.left="auto";self.calendarContainer.style.right=right+"px"}else{var doc=document.styleSheets[0];if(doc===undefined)return;var bodyWidth=window.document.body.offsetWidth;var centerLeft=Math.max(0,bodyWidth/2-calendarWidth/2);var centerBefore=".flatpickr-calendar.centerMost:before";var centerAfter=".flatpickr-calendar.centerMost:after";var centerIndex=doc.cssRules.length;var centerStyle="{left:"+inputBounds.left+"px;right:auto;}";toggleClass(self.calendarContainer,"rightMost",false);toggleClass(self.calendarContainer,"centerMost",true);doc.insertRule(centerBefore+","+centerAfter+centerStyle,centerIndex);self.calendarContainer.style.left=centerLeft+"px";self.calendarContainer.style.right="auto"}}function redraw(){if(self.config.noCalendar||self.isMobile)return;updateNavigationCurrentMonth();buildDays()}function focusAndClose(){self._input.focus();if(window.navigator.userAgent.indexOf("MSIE")!==-1||navigator.msMaxTouchPoints!==undefined){setTimeout(self.close,0)}else{self.close()}}function selectDate(e){e.preventDefault();e.stopPropagation();var isSelectable=function(day){return day.classList&&day.classList.contains("flatpickr-day")&&!day.classList.contains("flatpickr-disabled")&&!day.classList.contains("notAllowed")};var t=findParent(e.target,isSelectable);if(t===undefined)return;var target=t;var selectedDate=self.latestSelectedDateObj=new Date(target.dateObj.getTime());var shouldChangeMonth=(selectedDate.getMonth()self.currentMonth+self.config.showMonths-1)&&self.config.mode!=="range";self.selectedDateElem=target;if(self.config.mode==="single")self.selectedDates=[selectedDate];else if(self.config.mode==="multiple"){var selectedIndex=isDateSelected(selectedDate);if(selectedIndex)self.selectedDates.splice(parseInt(selectedIndex),1);else self.selectedDates.push(selectedDate)}else if(self.config.mode==="range"){if(self.selectedDates.length===2){self.clear(false,false)}self.latestSelectedDateObj=selectedDate;self.selectedDates.push(selectedDate);if(compareDates(selectedDate,self.selectedDates[0],true)!==0)self.selectedDates.sort(function(a,b){return a.getTime()-b.getTime()})}setHoursFromInputs();if(shouldChangeMonth){var isNewYear=self.currentYear!==selectedDate.getFullYear();self.currentYear=selectedDate.getFullYear();self.currentMonth=selectedDate.getMonth();if(isNewYear){triggerEvent("onYearChange");buildMonthSwitch()}triggerEvent("onMonthChange")}updateNavigationCurrentMonth();buildDays();updateValue();if(self.config.enableTime)setTimeout(function(){return self.showTimeInput=true},50);if(!shouldChangeMonth&&self.config.mode!=="range"&&self.config.showMonths===1)focusOnDayElem(target);else if(self.selectedDateElem!==undefined&&self.hourElement===undefined){self.selectedDateElem&&self.selectedDateElem.focus()}if(self.hourElement!==undefined)self.hourElement!==undefined&&self.hourElement.focus();if(self.config.closeOnSelect){var single=self.config.mode==="single"&&!self.config.enableTime;var range=self.config.mode==="range"&&self.selectedDates.length===2&&!self.config.enableTime;if(single||range){focusAndClose()}}triggerChange()}var CALLBACKS={locale:[setupLocale,updateWeekdays],showMonths:[buildMonths,setCalendarWidth,buildWeekdays],minDate:[jumpToDate],maxDate:[jumpToDate]};function set(option,value){if(option!==null&&typeof option==="object"){Object.assign(self.config,option);for(var key in option){if(CALLBACKS[key]!==undefined)CALLBACKS[key].forEach(function(x){return x()})}}else{self.config[option]=value;if(CALLBACKS[option]!==undefined)CALLBACKS[option].forEach(function(x){return x()});else if(HOOKS.indexOf(option)>-1)self.config[option]=arrayify(value)}self.redraw();updateValue(false)}function setSelectedDate(inputDate,format){var dates=[];if(inputDate instanceof Array)dates=inputDate.map(function(d){return self.parseDate(d,format)});else if(inputDate instanceof Date||typeof inputDate==="number")dates=[self.parseDate(inputDate,format)];else if(typeof inputDate==="string"){switch(self.config.mode){case"single":case"time":dates=[self.parseDate(inputDate,format)];break;case"multiple":dates=inputDate.split(self.config.conjunction).map(function(date){return self.parseDate(date,format)});break;case"range":dates=inputDate.split(self.l10n.rangeSeparator).map(function(date){return self.parseDate(date,format)});break}}else self.config.errorHandler(new Error("Invalid date supplied: "+JSON.stringify(inputDate)));self.selectedDates=dates.filter(function(d){return d instanceof Date&&isEnabled(d,false)});if(self.config.mode==="range")self.selectedDates.sort(function(a,b){return a.getTime()-b.getTime()})}function setDate(date,triggerChange,format){if(triggerChange===void 0){triggerChange=false}if(format===void 0){format=self.config.dateFormat}if(date!==0&&!date||date instanceof Array&&date.length===0)return self.clear(triggerChange);setSelectedDate(date,format);self.showTimeInput=self.selectedDates.length>0;self.latestSelectedDateObj=self.selectedDates[self.selectedDates.length-1];self.redraw();jumpToDate();setHoursFromDate();if(self.selectedDates.length===0){self.clear(false)}updateValue(triggerChange);if(triggerChange)triggerEvent("onChange")}function parseDateRules(arr){return arr.slice().map(function(rule){if(typeof rule==="string"||typeof rule==="number"||rule instanceof Date){return self.parseDate(rule,undefined,true)}else if(rule&&typeof rule==="object"&&rule.from&&rule.to)return{from:self.parseDate(rule.from,undefined),to:self.parseDate(rule.to,undefined)};return rule}).filter(function(x){return x})}function setupDates(){self.selectedDates=[];self.now=self.parseDate(self.config.now)||new Date;var preloadedDate=self.config.defaultDate||((self.input.nodeName==="INPUT"||self.input.nodeName==="TEXTAREA")&&self.input.placeholder&&self.input.value===self.input.placeholder?null:self.input.value);if(preloadedDate)setSelectedDate(preloadedDate,self.config.dateFormat);self._initialDate=self.selectedDates.length>0?self.selectedDates[0]:self.config.minDate&&self.config.minDate.getTime()>self.now.getTime()?self.config.minDate:self.config.maxDate&&self.config.maxDate.getTime()0)self.latestSelectedDateObj=self.selectedDates[0];if(self.config.minTime!==undefined)self.config.minTime=self.parseDate(self.config.minTime,"H:i");if(self.config.maxTime!==undefined)self.config.maxTime=self.parseDate(self.config.maxTime,"H:i");self.minDateHasTime=!!self.config.minDate&&(self.config.minDate.getHours()>0||self.config.minDate.getMinutes()>0||self.config.minDate.getSeconds()>0);self.maxDateHasTime=!!self.config.maxDate&&(self.config.maxDate.getHours()>0||self.config.maxDate.getMinutes()>0||self.config.maxDate.getSeconds()>0);Object.defineProperty(self,"showTimeInput",{get:function(){return self._showTimeInput},set:function(bool){self._showTimeInput=bool;if(self.calendarContainer)toggleClass(self.calendarContainer,"showTimeInput",bool);self.isOpen&&positionCalendar()}})}function setupInputs(){self.input=self.config.wrap?element.querySelector("[data-input]"):element;if(!self.input){self.config.errorHandler(new Error("Invalid input element specified"));return}self.input._type=self.input.type;self.input.type="text";self.input.classList.add("flatpickr-input");self._input=self.input;if(self.config.altInput){self.altInput=createElement(self.input.nodeName,self.config.altInputClass);self._input=self.altInput;self.altInput.placeholder=self.input.placeholder;self.altInput.disabled=self.input.disabled;self.altInput.required=self.input.required;self.altInput.tabIndex=self.input.tabIndex;self.altInput.type="text";self.input.setAttribute("type","hidden");if(!self.config.static&&self.input.parentNode)self.input.parentNode.insertBefore(self.altInput,self.input.nextSibling)}if(!self.config.allowInput)self._input.setAttribute("readonly","readonly");self._positionElement=self.config.positionElement||self._input}function setupMobile(){var inputType=self.config.enableTime?self.config.noCalendar?"time":"datetime-local":"date";self.mobileInput=createElement("input",self.input.className+" flatpickr-mobile");self.mobileInput.step=self.input.getAttribute("step")||"any";self.mobileInput.tabIndex=1;self.mobileInput.type=inputType;self.mobileInput.disabled=self.input.disabled;self.mobileInput.required=self.input.required;self.mobileInput.placeholder=self.input.placeholder;self.mobileFormatStr=inputType==="datetime-local"?"Y-m-d\\TH:i:S":inputType==="date"?"Y-m-d":"H:i:S";if(self.selectedDates.length>0){self.mobileInput.defaultValue=self.mobileInput.value=self.formatDate(self.selectedDates[0],self.mobileFormatStr)}if(self.config.minDate)self.mobileInput.min=self.formatDate(self.config.minDate,"Y-m-d");if(self.config.maxDate)self.mobileInput.max=self.formatDate(self.config.maxDate,"Y-m-d");self.input.type="hidden";if(self.altInput!==undefined)self.altInput.type="hidden";try{if(self.input.parentNode)self.input.parentNode.insertBefore(self.mobileInput,self.input.nextSibling)}catch(_a){}bind(self.mobileInput,"change",function(e){self.setDate(e.target.value,false,self.mobileFormatStr);triggerEvent("onChange");triggerEvent("onClose")})}function toggle(e){if(self.isOpen===true)return self.close();self.open(e)}function triggerEvent(event,data){if(self.config===undefined)return;var hooks=self.config[event];if(hooks!==undefined&&hooks.length>0){for(var i=0;hooks[i]&&i=0&&compareDates(date,self.selectedDates[1])<=0}function updateNavigationCurrentMonth(){if(self.config.noCalendar||self.isMobile||!self.monthNav)return;self.yearElements.forEach(function(yearElement,i){var d=new Date(self.currentYear,self.currentMonth,1);d.setMonth(self.currentMonth+i);if(self.config.showMonths>1){self.monthElements[i].textContent=monthToStr(d.getMonth(),self.config.shorthandCurrentMonth,self.l10n)+" "}else{self.monthsDropdownContainer.value=d.getMonth().toString()}yearElement.value=d.getFullYear().toString()});self._hidePrevMonthArrow=self.config.minDate!==undefined&&(self.currentYear===self.config.minDate.getFullYear()?self.currentMonth<=self.config.minDate.getMonth():self.currentYearself.config.maxDate.getMonth():self.currentYear>self.config.maxDate.getFullYear())}function getDateStr(format){return self.selectedDates.map(function(dObj){return self.formatDate(dObj,format)}).filter(function(d,i,arr){return self.config.mode!=="range"||self.config.enableTime||arr.indexOf(d)===i}).join(self.config.mode!=="range"?self.config.conjunction:self.l10n.rangeSeparator)}function updateValue(triggerChange){if(triggerChange===void 0){triggerChange=true}if(self.mobileInput!==undefined&&self.mobileFormatStr){self.mobileInput.value=self.latestSelectedDateObj!==undefined?self.formatDate(self.latestSelectedDateObj,self.mobileFormatStr):""}self.input.value=getDateStr(self.config.dateFormat);if(self.altInput!==undefined){self.altInput.value=getDateStr(self.config.altFormat)}if(triggerChange!==false)triggerEvent("onValueUpdate")}function onMonthNavClick(e){var isPrevMonth=self.prevMonthNav.contains(e.target);var isNextMonth=self.nextMonthNav.contains(e.target);if(isPrevMonth||isNextMonth){changeMonth(isPrevMonth?-1:1)}else if(self.yearElements.indexOf(e.target)>=0){e.target.select()}else if(e.target.classList.contains("arrowUp")){self.changeYear(self.currentYear+1)}else if(e.target.classList.contains("arrowDown")){self.changeYear(self.currentYear-1)}}function timeWrapper(e){e.preventDefault();var isKeyDown=e.type==="keydown",input=e.target;if(self.amPM!==undefined&&e.target===self.amPM){self.amPM.textContent=self.l10n.amPM[int(self.amPM.textContent===self.l10n.amPM[0])]}var min=parseFloat(input.getAttribute("min")),max=parseFloat(input.getAttribute("max")),step=parseFloat(input.getAttribute("step")),curValue=parseInt(input.value,10),delta=e.delta||(isKeyDown?e.which===38?1:-1:0);var newValue=curValue+step*delta;if(typeof input.value!=="undefined"&&input.value.length===2){var isHourElem=input===self.hourElement,isMinuteElem=input===self.minuteElement;if(newValuemax){newValue=input===self.hourElement?newValue-max-int(!self.amPM):min;if(isMinuteElem)incrementNumInput(undefined,1,self.hourElement)}if(self.amPM&&isHourElem&&(step===1?newValue+curValue===23:Math.abs(newValue-curValue)>step)){self.amPM.textContent=self.l10n.amPM[int(self.amPM.textContent===self.l10n.amPM[0])]}input.value=pad(newValue)}}init();return self}function _flatpickr(nodeList,config){var nodes=Array.prototype.slice.call(nodeList).filter(function(x){return x instanceof HTMLElement});var instances=[];for(var i=0;i1?_len-1:0),_key=1;_key<_len;_key++){remainder[_key-1]=arguments[_key]}if(!_onClose||_onClose.call.apply(_onClose,[this,selectedDates].concat(remainder))!==false){self._updateClassNames(calendar);self._updateInputFields(selectedDates,type)}},onChange:function onChange(){for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}if(!_onChange||_onChange.call.apply(_onChange,[this].concat(args))!==false){self._updateClassNames(calendar);if(type==="range"){if(calendar.selectedDates.length===1&&calendar.isOpen){self.element.querySelector(self.options.selectorDatePickerInputTo).classList.add(self.options.classFocused)}else{self.element.querySelector(self.options.selectorDatePickerInputTo).classList.remove(self.options.classFocused)}}}},onMonthChange:function onMonthChange(){for(var _len3=arguments.length,args=new Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3]}if(!_onMonthChange||_onMonthChange.call.apply(_onMonthChange,[this].concat(args))!==false){self._updateClassNames(calendar)}},onYearChange:function onYearChange(){for(var _len4=arguments.length,args=new Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4]}if(!_onYearChange||_onYearChange.call.apply(_onYearChange,[this].concat(args))!==false){self._updateClassNames(calendar)}},onOpen:function onOpen(){self.shouldForceOpen=true;setTimeout(function(){self.shouldForceOpen=false},0);for(var _len5=arguments.length,args=new Array(_len5),_key5=0;_key5<_len5;_key5++){args[_key5]=arguments[_key5]}if(!_onOpen||_onOpen.call.apply(_onOpen,[this].concat(args))!==false){self._updateClassNames(calendar)}},onValueUpdate:function onValueUpdate(){for(var _len6=arguments.length,args=new Array(_len6),_key6=0;_key6<_len6;_key6++){args[_key6]=arguments[_key6]}if((!_onValueUpdate||_onValueUpdate.call.apply(_onValueUpdate,[this].concat(args))!==false)&&type==="range"){self._updateInputFields(self.calendar.selectedDates,type)}},nextArrow:_this._rightArrowHTML(),prevArrow:_this._leftArrowHTML(),plugins:[].concat(_toConsumableArray(_this.options.plugins||[]),[carbonFlatpickrMonthSelectPlugin(_this.options)])}));if(type==="range"){_this._addInputLogic(_this.element.querySelector(_this.options.selectorDatePickerInputFrom),0);_this._addInputLogic(_this.element.querySelector(_this.options.selectorDatePickerInputTo),1)}_this.manage(on(_this.element.querySelector(_this.options.selectorDatePickerIcon),"click",function(){calendar.open()}));_this._updateClassNames(calendar);if(type!=="range"){_this._addInputLogic(date)}return calendar});_defineProperty(_assertThisInitialized(_this),"_addInputLogic",function(input,index){if(!isNaN(index)&&(index<0||index>1)){throw new RangeError("The index of (".concat(index,") is out of range."))}var inputField=input;_this.manage(on(inputField,"change",function(evt){if(evt.isTrusted||evt.detail&&evt.detail.isNotFromFlatpickr){var inputDate=_this.calendar.parseDate(inputField.value);if(inputDate&&!isNaN(inputDate.valueOf())){if(isNaN(index)){_this.calendar.setDate(inputDate)}else{var selectedDates=_this.calendar.selectedDates;selectedDates[index]=inputDate;_this.calendar.setDate(selectedDates)}}}_this._updateClassNames(_this.calendar)}));_this.manage(on(inputField,"keydown",function(evt){var origInput=_this.calendar._input;_this.calendar._input=evt.target;setTimeout(function(){_this.calendar._input=origInput})}))});_defineProperty(_assertThisInitialized(_this),"_updateClassNames",function(_ref){var calendarContainer=_ref.calendarContainer,selectedDates=_ref.selectedDates;if(calendarContainer){calendarContainer.classList.add(_this.options.classCalendarContainer);calendarContainer.querySelector(".flatpickr-month").classList.add(_this.options.classMonth);calendarContainer.querySelector(".flatpickr-weekdays").classList.add(_this.options.classWeekdays);calendarContainer.querySelector(".flatpickr-days").classList.add(_this.options.classDays);toArray$5(calendarContainer.querySelectorAll(".flatpickr-weekday")).forEach(function(item){var currentItem=item;currentItem.innerHTML=currentItem.innerHTML.replace(/\s+/g,"");currentItem.classList.add(_this.options.classWeekday)});toArray$5(calendarContainer.querySelectorAll(".flatpickr-day")).forEach(function(item){item.classList.add(_this.options.classDay);if(item.classList.contains("today")&&selectedDates.length>0){item.classList.add("no-border")}else if(item.classList.contains("today")&&selectedDates.length===0){item.classList.remove("no-border")}})}});_defineProperty(_assertThisInitialized(_this),"_updateInputFields",function(selectedDates,type){if(type==="range"){if(selectedDates.length===2){_this.element.querySelector(_this.options.selectorDatePickerInputFrom).value=_this._formatDate(selectedDates[0]);_this.element.querySelector(_this.options.selectorDatePickerInputTo).value=_this._formatDate(selectedDates[1])}else if(selectedDates.length===1){_this.element.querySelector(_this.options.selectorDatePickerInputFrom).value=_this._formatDate(selectedDates[0])}}else if(selectedDates.length===1){_this.element.querySelector(_this.options.selectorDatePickerInput).value=_this._formatDate(selectedDates[0])}_this._updateClassNames(_this.calendar)});_defineProperty(_assertThisInitialized(_this),"_formatDate",function(date){return _this.calendar.formatDate(date,_this.calendar.config.dateFormat)});var _type=_this.element.getAttribute(_this.options.attribType);_this.calendar=_this._initDatePicker(_type);if(_this.calendar.calendarContainer){_this.manage(on(_this.element,"keydown",function(e){if(e.which===40){e.preventDefault();(_this.calendar.selectedDateElem||_this.calendar.todayDateElem||_this.calendar.calendarContainer).focus()}}));_this.manage(on(_this.calendar.calendarContainer,"keydown",function(e){if(e.which===9&&_type==="range"){_this._updateClassNames(_this.calendar);_this.element.querySelector(_this.options.selectorDatePickerInputFrom).focus()}}))}return _this}_createClass(DatePicker,[{key:"_rightArrowHTML",value:function _rightArrowHTML(){return'\n \n \n '}},{key:"_leftArrowHTML",value:function _leftArrowHTML(){return'\n \n \n '}},{key:"release",value:function release(){if(this._rangeInput&&this._rangeInput.parentNode){this._rangeInput.parentNode.removeChild(this._rangeInput)}if(this.calendar){try{this.calendar.destroy()}catch(err){}this.calendar=null}return _get(_getPrototypeOf(DatePicker.prototype),"release",this).call(this)}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-date-picker]",selectorDatePickerInput:"[data-date-picker-input]",selectorDatePickerInputFrom:"[data-date-picker-input-from]",selectorDatePickerInputTo:"[data-date-picker-input-to]",selectorDatePickerIcon:"[data-date-picker-icon]",selectorFlatpickrMonthYearContainer:".flatpickr-current-month",selectorFlatpickrYearContainer:".numInputWrapper",selectorFlatpickrCurrentMonth:".cur-month",classCalendarContainer:"".concat(prefix,"--date-picker__calendar"),classMonth:"".concat(prefix,"--date-picker__month"),classWeekdays:"".concat(prefix,"--date-picker__weekdays"),classDays:"".concat(prefix,"--date-picker__days"),classWeekday:"".concat(prefix,"--date-picker__weekday"),classDay:"".concat(prefix,"--date-picker__day"),classFocused:"".concat(prefix,"--focused"),classVisuallyHidden:"".concat(prefix,"--visually-hidden"),classFlatpickrCurrentMonth:"cur-month",attribType:"data-date-picker-type",dateFormat:"m/d/Y"}}}]);return DatePicker}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(DatePicker,"components",new WeakMap);var Pagination=function(_mixin){_inherits(Pagination,_mixin);var _super=_createSuper(Pagination);function Pagination(element,options){var _this;_classCallCheck(this,Pagination);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_emitEvent",function(evtName,detail){var event=new CustomEvent("".concat(evtName),{bubbles:true,cancelable:true,detail:detail});_this.element.dispatchEvent(event)});_this.manage(on(_this.element,"click",function(evt){if(eventMatches(evt,_this.options.selectorPageBackward)){var detail={initialEvt:evt,element:evt.target,direction:"backward"};_this._emitEvent(_this.options.eventPageChange,detail)}else if(eventMatches(evt,_this.options.selectorPageForward)){var _detail={initialEvt:evt,element:evt.target,direction:"forward"};_this._emitEvent(_this.options.eventPageChange,_detail)}}));_this.manage(on(_this.element,"input",function(evt){if(eventMatches(evt,_this.options.selectorItemsPerPageInput)){var detail={initialEvt:evt,element:evt.target,value:evt.target.value};_this._emitEvent(_this.options.eventItemsPerPage,detail)}else if(eventMatches(evt,_this.options.selectorPageNumberInput)){var _detail2={initialEvt:evt,element:evt.target,value:evt.target.value};_this._emitEvent(_this.options.eventPageNumber,_detail2)}}));return _this}return Pagination}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(Pagination,"components",new WeakMap);_defineProperty(Pagination,"options",{selectorInit:"[data-pagination]",selectorItemsPerPageInput:"[data-items-per-page]",selectorPageNumberInput:"[data-page-number-input]",selectorPageBackward:"[data-page-backward]",selectorPageForward:"[data-page-forward]",eventItemsPerPage:"itemsPerPage",eventPageNumber:"pageNumber",eventPageChange:"pageChange"});function svgToggleClass(svg,name,forceAdd){var list=svg.getAttribute("class").trim().split(/\s+/);var uniqueList=Object.keys(list.reduce(function(o,item){return Object.assign(o,_defineProperty({},item,1))},{}));var index=uniqueList.indexOf(name);var found=index>=0;var add=forceAdd===undefined?!found:forceAdd;if(found===!add){if(add){uniqueList.push(name)}else{uniqueList.splice(index,1)}svg.setAttribute("class",uniqueList.join(" "))}}var toArray$6=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var Search=function(_mixin){_inherits(Search,_mixin);var _super=_createSuper(Search);function Search(element,options){var _this;_classCallCheck(this,Search);_this=_super.call(this,element,options);var closeIcon=_this.element.querySelector(_this.options.selectorClearIcon);var input=_this.element.querySelector(_this.options.selectorSearchInput);if(!input){throw new Error("Cannot find the search input.")}if(closeIcon){_this.manage(on(closeIcon,"click",function(){svgToggleClass(closeIcon,_this.options.classClearHidden,true);input.value="";input.focus()}))}_this.manage(on(_this.element,"click",function(evt){var toggleItem=eventMatches(evt,_this.options.selectorIconContainer);if(toggleItem)_this.toggleLayout(toggleItem)}));_this.manage(on(input,"input",function(evt){if(closeIcon)_this.showClear(evt.target.value,closeIcon)}));return _this}_createClass(Search,[{key:"toggleLayout",value:function toggleLayout(element){var _this2=this;toArray$6(element.querySelectorAll(this.options.selectorSearchView)).forEach(function(item){item.classList.toggle(_this2.options.classLayoutHidden)})}},{key:"showClear",value:function showClear(value,icon){svgToggleClass(icon,this.options.classClearHidden,value.length===0)}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-search]",selectorSearchView:"[data-search-view]",selectorSearchInput:".".concat(prefix,"--search-input"),selectorClearIcon:".".concat(prefix,"--search-close"),selectorIconContainer:".".concat(prefix,"--search-button[data-search-toggle]"),classClearHidden:"".concat(prefix,"--search-close--hidden"),classLayoutHidden:"".concat(prefix,"--search-view--hidden")}}}]);return Search}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(Search,"components",new WeakMap);var Accordion=function(_mixin){_inherits(Accordion,_mixin);var _super=_createSuper(Accordion);function Accordion(element,options){var _this;_classCallCheck(this,Accordion);_this=_super.call(this,element,options);_this.manage(on(_this.element,"click",function(event){var item=eventMatches(event,_this.options.selectorAccordionItem);if(item&&!eventMatches(event,_this.options.selectorAccordionContent)){_this._toggle(item)}}));if(!_this._checkIfButton()){_this.manage(on(_this.element,"keypress",function(event){var item=eventMatches(event,_this.options.selectorAccordionItem);if(item&&!eventMatches(event,_this.options.selectorAccordionContent)){_this._handleKeypress(event)}}))}return _this}_createClass(Accordion,[{key:"_checkIfButton",value:function _checkIfButton(){return this.element.firstElementChild.firstElementChild.nodeName==="BUTTON"}},{key:"_handleKeypress",value:function _handleKeypress(event){if(event.which===13||event.which===32){this._toggle(event.target)}}},{key:"_toggle",value:function _toggle(element){var heading=element.querySelector(this.options.selectorAccordionItemHeading);var expanded=heading.getAttribute("aria-expanded");if(expanded!==null){heading.setAttribute("aria-expanded",expanded==="true"?"false":"true")}element.classList.toggle(this.options.classActive)}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-accordion]",selectorAccordionItem:".".concat(prefix,"--accordion__item"),selectorAccordionItemHeading:".".concat(prefix,"--accordion__heading"),selectorAccordionContent:".".concat(prefix,"--accordion__content"),classActive:"".concat(prefix,"--accordion__item--active")}}}]);return Accordion}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(Accordion,"components",new WeakMap);var CopyButton=function(_mixin){_inherits(CopyButton,_mixin);var _super=_createSuper(CopyButton);function CopyButton(element,options){var _this;_classCallCheck(this,CopyButton);_this=_super.call(this,element,options);_this.manage(on(_this.element,"click",function(){return _this.handleClick()}));_this.manage(on(_this.element,"animationend",function(event){return _this.handleAnimationEnd(event)}));return _this}_createClass(CopyButton,[{key:"handleAnimationEnd",value:function handleAnimationEnd(event){if(event.animationName==="hide-feedback"){this.element.classList.remove(this.options.classAnimating);this.element.classList.remove(this.options.classFadeOut)}}},{key:"handleClick",value:function handleClick(){var _this2=this;var feedback=this.element.querySelector(this.options.feedbackTooltip);if(feedback){feedback.classList.add(this.options.classShowFeedback);setTimeout(function(){feedback.classList.remove(_this2.options.classShowFeedback)},this.options.timeoutValue)}else{this.element.classList.add(this.options.classAnimating);this.element.classList.add(this.options.classFadeIn);setTimeout(function(){_this2.element.classList.remove(_this2.options.classFadeIn);_this2.element.classList.add(_this2.options.classFadeOut)},this.options.timeoutValue)}}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-copy-btn]",feedbackTooltip:"[data-feedback]",classShowFeedback:"".concat(prefix,"--btn--copy__feedback--displayed"),classAnimating:"".concat(prefix,"--copy-btn--animating"),classFadeIn:"".concat(prefix,"--copy-btn--fade-in"),classFadeOut:"".concat(prefix,"--copy-btn--fade-out"),timeoutValue:2e3}}}]);return CopyButton}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(CopyButton,"components",new WeakMap);var Notification=function(_mixin){_inherits(Notification,_mixin);var _super=_createSuper(Notification);function Notification(element,options){var _this;_classCallCheck(this,Notification);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_changeState",function(state,callback){if(state==="delete-notification"){_this.element.parentNode.removeChild(_this.element);_this.release()}callback()});_this.button=element.querySelector(_this.options.selectorButton);if(_this.button){_this.manage(on(_this.button,"click",function(evt){if(evt.currentTarget===_this.button){_this.remove()}}))}return _this}_createClass(Notification,[{key:"remove",value:function remove(){this.changeState("delete-notification")}}]);return Notification}(mixin(createComponent,initComponentBySearch,eventedState,handles));_defineProperty(Notification,"components",new WeakMap);_defineProperty(Notification,"options",{selectorInit:"[data-notification]",selectorButton:"[data-notification-btn]",eventBeforeDeleteNotification:"notification-before-delete",eventAfterDeleteNotification:"notification-after-delete"});var toArray$7=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var Toolbar=function(_mixin){_inherits(Toolbar,_mixin);var _super=_createSuper(Toolbar);function Toolbar(element,options){var _this;_classCallCheck(this,Toolbar);_this=_super.call(this,element,options);if(!_this.element.dataset.tableTarget){console.warn("There is no table bound to this toolbar!")}else{var boundTable=_this.element.ownerDocument.querySelector(_this.element.dataset.tableTarget);var rowHeightBtns=_this.element.querySelector(_this.options.selectorRowHeight);if(rowHeightBtns){_this.manage(on(rowHeightBtns,"click",function(event){_this._handleRowHeightChange(event,boundTable)}))}}_this.manage(on(_this.element.ownerDocument,"keydown",function(evt){_this._handleKeyDown(evt)}));_this.manage(on(_this.element.ownerDocument,"click",function(evt){_this._handleDocumentClick(evt)}));return _this}_createClass(Toolbar,[{key:"_handleDocumentClick",value:function _handleDocumentClick(event){var _this2=this;var searchInput=eventMatches(event,this.options.selectorSearch);var isOfSelfSearchInput=searchInput&&this.element.contains(searchInput);if(isOfSelfSearchInput){var shouldBeOpen=isOfSelfSearchInput&&!this.element.classList.contains(this.options.classSearchActive);searchInput.classList.toggle(this.options.classSearchActive,shouldBeOpen);if(shouldBeOpen){searchInput.querySelector("input").focus()}}var targetComponentElement=eventMatches(event,this.options.selectorInit);toArray$7(this.element.ownerDocument.querySelectorAll(this.options.selectorSearch)).forEach(function(item){if(!targetComponentElement||!targetComponentElement.contains(item)){item.classList.remove(_this2.options.classSearchActive)}})}},{key:"_handleKeyDown",value:function _handleKeyDown(event){var searchInput=eventMatches(event,this.options.selectorSearch);if(searchInput&&event.which===27){searchInput.classList.remove(this.options.classSearchActive)}}},{key:"_handleRowHeightChange",value:function _handleRowHeightChange(event,boundTable){var _event$currentTarget$=event.currentTarget.querySelector("input:checked"),value=_event$currentTarget$.value;if(value==="tall"){boundTable.classList.add(this.options.classTallRows)}else{boundTable.classList.remove(this.options.classTallRows)}}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-toolbar]",selectorSearch:"[data-toolbar-search]",selectorRowHeight:"[data-row-height]",classTallRows:"".concat(prefix,"--responsive-table--tall"),classSearchActive:"".concat(prefix,"--toolbar-search--active")}}}]);return Toolbar}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(Toolbar,"components",new WeakMap);function initComponentByEvent(ToMix){var InitComponentByEvent=function(_ToMix){_inherits(InitComponentByEvent,_ToMix);var _super=_createSuper(InitComponentByEvent);function InitComponentByEvent(){_classCallCheck(this,InitComponentByEvent);return _super.apply(this,arguments)}_createClass(InitComponentByEvent,null,[{key:"init",value:function init(){var _this=this;var target=arguments.length>0&&arguments[0]!==undefined?arguments[0]:document;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var effectiveOptions=Object.assign(Object.create(this.options),options);if(!target||target.nodeType!==Node.ELEMENT_NODE&&target.nodeType!==Node.DOCUMENT_NODE){throw new TypeError("DOM document or DOM element should be given to search for and initialize this widget.")}if(target.nodeType===Node.ELEMENT_NODE&&target.matches(effectiveOptions.selectorInit)){this.create(target,options)}else{var hasFocusin="onfocusin"in(target.nodeType===Node.ELEMENT_NODE?target.ownerDocument:target).defaultView;var handles=effectiveOptions.initEventNames.map(function(name){var eventName=name==="focus"&&hasFocusin?"focusin":name;return on(target,eventName,function(event){var element=eventMatches(event,effectiveOptions.selectorInit);if(element&&!_this.components.has(element)){var component=_this.create(element,options);if(typeof component.createdByEvent==="function"){component.createdByEvent(event)}}},name==="focus"&&!hasFocusin)});return{release:function release(){for(var handle=handles.pop();handle;handle=handles.pop()){handle.release()}}}}return""}}]);return InitComponentByEvent}(ToMix);_defineProperty(InitComponentByEvent,"forLazyInit",true);return InitComponentByEvent}var getMenuOffset$1=function getMenuOffset(menuBody,menuDirection){var _DIRECTION_LEFT$DIREC,_DIRECTION_LEFT$DIREC2;var arrowStyle=menuBody.ownerDocument.defaultView.getComputedStyle(menuBody,":before");var arrowPositionProp=(_DIRECTION_LEFT$DIREC={},_defineProperty(_DIRECTION_LEFT$DIREC,DIRECTION_LEFT,"right"),_defineProperty(_DIRECTION_LEFT$DIREC,DIRECTION_TOP,"bottom"),_defineProperty(_DIRECTION_LEFT$DIREC,DIRECTION_RIGHT,"left"),_defineProperty(_DIRECTION_LEFT$DIREC,DIRECTION_BOTTOM,"top"),_DIRECTION_LEFT$DIREC)[menuDirection];var menuPositionAdjustmentProp=(_DIRECTION_LEFT$DIREC2={},_defineProperty(_DIRECTION_LEFT$DIREC2,DIRECTION_LEFT,"left"),_defineProperty(_DIRECTION_LEFT$DIREC2,DIRECTION_TOP,"top"),_defineProperty(_DIRECTION_LEFT$DIREC2,DIRECTION_RIGHT,"left"),_defineProperty(_DIRECTION_LEFT$DIREC2,DIRECTION_BOTTOM,"top"),_DIRECTION_LEFT$DIREC2)[menuDirection];var values=[arrowPositionProp,"border-bottom-width"].reduce(function(o,name){return _objectSpread2(_objectSpread2({},o),{},_defineProperty({},name,Number((/^([\d-.]+)px$/.exec(arrowStyle.getPropertyValue(name))||[])[1])))},{});var margin=0;if(menuDirection!==DIRECTION_BOTTOM){var style=menuBody.ownerDocument.defaultView.getComputedStyle(menuBody);margin=Number((/^([\d-.]+)px$/.exec(style.getPropertyValue("margin-top"))||[])[1])}values[arrowPositionProp]=values[arrowPositionProp]||-6;if(Object.keys(values).every(function(name){return!isNaN(values[name])})){var arrowPosition=values[arrowPositionProp],borderBottomWidth=values["border-bottom-width"];return _defineProperty({left:0,top:0},menuPositionAdjustmentProp,Math.sqrt(Math.pow(borderBottomWidth,2)*2)-arrowPosition+margin*(menuDirection===DIRECTION_TOP?2:1))}return undefined};var allowedOpenKeys=[32,13];var Tooltip=function(_mixin){_inherits(Tooltip,_mixin);var _super=_createSuper(Tooltip);function Tooltip(element,options){var _this;_classCallCheck(this,Tooltip);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_hasContextMenu",false);_this._hookOn(element);return _this}_createClass(Tooltip,[{key:"createdByEvent",value:function createdByEvent(event){var relatedTarget=event.relatedTarget,type=event.type,which=event.which;if(type==="click"||allowedOpenKeys.includes(which)){this._handleClick({relatedTarget:relatedTarget,type:type,details:getLaunchingDetails(event)})}}},{key:"changeState",value:function changeState(state,detail,callback){if(!this.tooltip){var tooltip=this.element.ownerDocument.querySelector(this.element.getAttribute(this.options.attribTooltipTarget));if(!tooltip){throw new Error("Cannot find the target tooltip.")}this.tooltip=FloatingMenu.create(tooltip,{refNode:this.element,classShown:this.options.classShown,offset:this.options.objMenuOffset,contentNode:tooltip.querySelector(this.options.selectorContent)});this._hookOn(tooltip);this.children.push(this.tooltip)}this.tooltip.changeState(state,Object.assign(detail,{delegatorNode:this.element}),callback)}},{key:"_hookOn",value:function _hookOn(element){var _this2=this;var handleClickContextMenu=function handleClickContextMenu(evt,allowedKeys){var relatedTarget=evt.relatedTarget,type=evt.type,which=evt.which;if(typeof allowedKeys==="undefined"||allowedKeys.includes(which)){var hadContextMenu=_this2._hasContextMenu;_this2._hasContextMenu=type==="contextmenu";_this2._handleClick({relatedTarget:relatedTarget,type:type,hadContextMenu:hadContextMenu,details:getLaunchingDetails(evt)})}};this.manage(on(element,"click",handleClickContextMenu,false));if(this.element.tagName!=="BUTTON"){this.manage(on(this.element,"keydown",function(event){handleClickContextMenu(event,allowedOpenKeys)},false))}}},{key:"_handleClick",value:function _handleClick(_ref2){var relatedTarget=_ref2.relatedTarget,type=_ref2.type,hadContextMenu=_ref2.hadContextMenu,details=_ref2.details;var state={click:"shown",keydown:"shown",blur:"hidden",touchleave:"hidden",touchcancel:"hidden"}[type];var shouldPreventClose;if(type==="blur"){var wentToSelf=relatedTarget&&this.element.contains&&this.element.contains(relatedTarget)||this.tooltip&&this.tooltip.element.contains(relatedTarget);shouldPreventClose=hadContextMenu||wentToSelf}if(!shouldPreventClose){this.changeState(state,details)}}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-tooltip-trigger]",selectorContent:".".concat(prefix,"--tooltip__content"),classShown:"".concat(prefix,"--tooltip--shown"),attribTooltipTarget:"data-tooltip-target",objMenuOffset:getMenuOffset$1,initEventNames:["click","keydown"]}}}]);return Tooltip}(mixin(createComponent,initComponentByEvent,exports$1,handles));_defineProperty(Tooltip,"components",new WeakMap);var FUNC_ERROR_TEXT="Expected a function";var NAN=0/0;var symbolTag="[object Symbol]";var reTrim=/^\s+|\s+$/g;var reIsBadHex=/^[-+]0x[0-9a-f]+$/i;var reIsBinary=/^0b[01]+$/i;var reIsOctal=/^0o[0-7]+$/i;var freeParseInt=parseInt;var freeGlobal=typeof commonjsGlobal=="object"&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal;var freeSelf=typeof self=="object"&&self&&self.Object===Object&&self;var root=freeGlobal||freeSelf||Function("return this")();var objectProto=Object.prototype;var objectToString=objectProto.toString;var nativeMax=Math.max,nativeMin=Math.min;var now=function(){return root.Date.now()};function debounce(func,wait,options){var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=false,maxing=false,trailing=true;if(typeof func!="function"){throw new TypeError(FUNC_ERROR_TEXT)}wait=toNumber(wait)||0;if(isObject(options)){leading=!!options.leading;maxing="maxWait"in options;maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait;trailing="trailing"in options?!!options.trailing:trailing}function invokeFunc(time){var args=lastArgs,thisArg=lastThis;lastArgs=lastThis=undefined;lastInvokeTime=time;result=func.apply(thisArg,args);return result}function leadingEdge(time){lastInvokeTime=time;timerId=setTimeout(timerExpired,wait);return leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||timeSinceLastCall<0||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();if(shouldInvoke(time)){return trailingEdge(time)}timerId=setTimeout(timerExpired,remainingWait(time))}function trailingEdge(time){timerId=undefined;if(trailing&&lastArgs){return invokeFunc(time)}lastArgs=lastThis=undefined;return result}function cancel(){if(timerId!==undefined){clearTimeout(timerId)}lastInvokeTime=0;lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);lastArgs=arguments;lastThis=this;lastCallTime=time;if(isInvoking){if(timerId===undefined){return leadingEdge(lastCallTime)}if(maxing){timerId=setTimeout(timerExpired,wait);return invokeFunc(lastCallTime)}}if(timerId===undefined){timerId=setTimeout(timerExpired,wait)}return result}debounced.cancel=cancel;debounced.flush=flush;return debounced}function isObject(value){var type=typeof value;return!!value&&(type=="object"||type=="function")}function isObjectLike(value){return!!value&&typeof value=="object"}function isSymbol(value){return typeof value=="symbol"||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toNumber(value){if(typeof value=="number"){return value}if(isSymbol(value)){return NAN}if(isObject(value)){var other=typeof value.valueOf=="function"?value.valueOf():value;value=isObject(other)?other+"":other}if(typeof value!="string"){return value===0?value:+value}value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}var lodash_debounce=debounce;var TooltipSimple=function(_mixin){_inherits(TooltipSimple,_mixin);var _super=_createSuper(TooltipSimple);function TooltipSimple(element,options){var _this;_classCallCheck(this,TooltipSimple);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"tooltipFadeOut",lodash_debounce(function(){var tooltipTriggerButton=_this.getTooltipTriggerButton();if(tooltipTriggerButton){tooltipTriggerButton.classList.remove(_this.options.classTooltipVisible)}},100));_defineProperty(_assertThisInitialized(_this),"getTooltipTriggerButton",function(){return _this.element.matches(_this.options.selectorTriggerButton)?_this.element:_this.element.querySelector(_this.options.selectorTriggerButton)});_defineProperty(_assertThisInitialized(_this),"allowTooltipVisibility",function(_ref){var visible=_ref.visible;var tooltipTriggerButton=_this.getTooltipTriggerButton();if(!tooltipTriggerButton){return}if(visible){tooltipTriggerButton.classList.remove(_this.options.classTooltipHidden)}else{tooltipTriggerButton.classList.add(_this.options.classTooltipHidden)}});_this.manage(on(_this.element.ownerDocument,"keydown",function(event){if(event.which===27){_this.allowTooltipVisibility({visible:false});var tooltipTriggerButton=_this.getTooltipTriggerButton();if(tooltipTriggerButton){tooltipTriggerButton.classList.remove(_this.options.classTooltipVisible)}}}));_this.manage(on(_this.element,"mouseenter",function(){_this.tooltipFadeOut.cancel();_this.allowTooltipVisibility({visible:true});var tooltipTriggerButton=_this.getTooltipTriggerButton();if(tooltipTriggerButton){tooltipTriggerButton.classList.add(_this.options.classTooltipVisible)}}));_this.manage(on(_this.element,"mouseleave",_this.tooltipFadeOut));_this.manage(on(_this.element,"focusin",function(event){if(eventMatches(event,_this.options.selectorTriggerButton)){_this.allowTooltipVisibility({visible:true})}}));return _this}_createClass(TooltipSimple,null,[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-tooltip-definition],[data-tooltip-icon]",selectorTriggerButton:".".concat(prefix,"--tooltip__trigger.").concat(prefix,"--tooltip--a11y"),classTooltipHidden:"".concat(prefix,"--tooltip--hidden"),classTooltipVisible:"".concat(prefix,"--tooltip--visible")}}}]);return TooltipSimple}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(TooltipSimple,"components",new WeakMap);var toArray$8=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var ProgressIndicator=function(_mixin){_inherits(ProgressIndicator,_mixin);var _super=_createSuper(ProgressIndicator);function ProgressIndicator(element,options){var _this;_classCallCheck(this,ProgressIndicator);_this=_super.call(this,element,options);_this.state={currentIndex:_this.getCurrent().index,totalSteps:_this.getSteps().length};_this.addOverflowTooltip();return _this}_createClass(ProgressIndicator,[{key:"getSteps",value:function getSteps(){return toArray$8(this.element.querySelectorAll(this.options.selectorStepElement)).map(function(element,index){return{element:element,index:index}})}},{key:"getCurrent",value:function getCurrent(){var currentEl=this.element.querySelector(this.options.selectorCurrent);return this.getSteps().filter(function(step){return step.element===currentEl})[0]}},{key:"setCurrent",value:function setCurrent(){var _this2=this;var newCurrentStep=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this.state.currentIndex;var changed=false;if(newCurrentStep!==this.state.currentIndex){this.state.currentIndex=newCurrentStep;changed=true}if(changed){this.getSteps().forEach(function(step){if(step.indexnewCurrentStep){_this2._updateStep({element:step.element,className:_this2.options.classIncomplete,html:_this2._getIncompleteSVG()})}})}}},{key:"_updateStep",value:function _updateStep(args){var element=args.element,className=args.className,html=args.html;if(element.firstElementChild){element.removeChild(element.firstElementChild)}if(!element.classList.contains(className)){element.setAttribute("class",this.options.classStep);element.classList.add(className)}element.insertAdjacentHTML("afterbegin",html)}},{key:"_getSVGComplete",value:function _getSVGComplete(){return'\n \n \n '}},{key:"_getCurrentSVG",value:function _getCurrentSVG(){return'\n \n \n '}},{key:"_getIncompleteSVG",value:function _getIncompleteSVG(){return'\n \n '}},{key:"addOverflowTooltip",value:function addOverflowTooltip(){var _this3=this;var stepLabels=toArray$8(this.element.querySelectorAll(this.options.selectorLabel));var tooltips=toArray$8(this.element.querySelectorAll(this.options.selectorTooltip));stepLabels.forEach(function(step){if(step.scrollWidth>_this3.options.maxWidth){step.classList.add(_this3.options.classOverflowLabel)}});tooltips.forEach(function(tooltip){var childText=tooltip.querySelector(_this3.options.selectorTooltipText);if(childText.scrollHeight>_this3.options.tooltipMaxHeight){tooltip.classList.add(_this3.options.classTooltipMulti)}})}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-progress]",selectorStepElement:".".concat(prefix,"--progress-step"),selectorCurrent:".".concat(prefix,"--progress-step--current"),selectorIncomplete:".".concat(prefix,"--progress-step--incomplete"),selectorComplete:".".concat(prefix,"--progress-step--complete"),selectorLabel:".".concat(prefix,"--progress-label"),selectorTooltip:".".concat(prefix,"--tooltip"),selectorTooltipText:".".concat(prefix,"--tooltip__text"),classStep:"".concat(prefix,"--progress-step"),classComplete:"".concat(prefix,"--progress-step--complete"),classCurrent:"".concat(prefix,"--progress-step--current"),classIncomplete:"".concat(prefix,"--progress-step--incomplete"),classOverflowLabel:"".concat(prefix,"--progress-label-overflow"),classTooltipMulti:"".concat(prefix,"--tooltip_multi"),maxWidth:87,tooltipMaxHeight:21}}}]);return ProgressIndicator}(mixin(createComponent,initComponentBySearch));_defineProperty(ProgressIndicator,"components",new WeakMap);var toArray$9=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var StructuredList=function(_mixin){_inherits(StructuredList,_mixin);var _super=_createSuper(StructuredList);function StructuredList(element,options){var _this;_classCallCheck(this,StructuredList);_this=_super.call(this,element,options);_this.manage(on(_this.element,"keydown",function(evt){if(evt.which===37||evt.which===38||evt.which===39||evt.which===40){_this._handleKeydownArrow(evt)}if(evt.which===13||evt.which===32){_this._handleKeydownChecked(evt)}}));_this.manage(on(_this.element,"click",function(evt){_this._handleClick(evt)}));return _this}_createClass(StructuredList,[{key:"_direction",value:function _direction(evt){return{37:-1,38:-1,39:1,40:1}[evt.which]}},{key:"_nextIndex",value:function _nextIndex(array,arrayItem,direction){return array.indexOf(arrayItem)+direction}},{key:"_getInput",value:function _getInput(index){var rows=toArray$9(this.element.querySelectorAll(this.options.selectorRow));return this.element.ownerDocument.querySelector(this.options.selectorListInput(rows[index].getAttribute("for")))}},{key:"_handleInputChecked",value:function _handleInputChecked(index){var rows=this.element.querySelectorAll(this.options.selectorRow);var input=this.getInput(index)||rows[index].querySelector("input");input.checked=true}},{key:"_handleClick",value:function _handleClick(evt){var _this2=this;var selectedRow=eventMatches(evt,this.options.selectorRow);toArray$9(this.element.querySelectorAll(this.options.selectorRow)).forEach(function(row){return row.classList.remove(_this2.options.classActive)});if(selectedRow){selectedRow.classList.add(this.options.classActive)}}},{key:"_handleKeydownChecked",value:function _handleKeydownChecked(evt){var _this3=this;evt.preventDefault();var selectedRow=eventMatches(evt,this.options.selectorRow);toArray$9(this.element.querySelectorAll(this.options.selectorRow)).forEach(function(row){return row.classList.remove(_this3.options.classActive)});if(selectedRow){selectedRow.classList.add(this.options.classActive);var input=selectedRow.querySelector(this.options.selectorListInput(selectedRow.getAttribute("for")))||selectedRow.querySelector("input");input.checked=true}}},{key:"_handleKeydownArrow",value:function _handleKeydownArrow(evt){var _this4=this;evt.preventDefault();var selectedRow=eventMatches(evt,this.options.selectorRow);var direction=this._direction(evt);if(direction&&selectedRow!==undefined){var rows=toArray$9(this.element.querySelectorAll(this.options.selectorRow));rows.forEach(function(row){return row.classList.remove(_this4.options.classActive)});var firstIndex=0;var nextIndex=this._nextIndex(rows,selectedRow,direction);var lastIndex=rows.length-1;var getSelectedIndex=function getSelectedIndex(){switch(nextIndex){case-1:return lastIndex;case rows.length:return firstIndex;default:return nextIndex}};var selectedIndex=getSelectedIndex();rows[selectedIndex].classList.add(this.options.classActive);rows[selectedIndex].focus();this._handleInputChecked(selectedIndex)}}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-structured-list]",selectorRow:"[data-structured-list] .".concat(prefix,"--structured-list-tbody > label.").concat(prefix,"--structured-list-row"),selectorListInput:function selectorListInput(id){return"#".concat(id,".").concat(prefix,"--structured-list-input")},classActive:"".concat(prefix,"--structured-list-row--selected")}}}]);return StructuredList}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(StructuredList,"components",new WeakMap);var Slider=function(_mixin){_inherits(Slider,_mixin);var _super=_createSuper(Slider);function Slider(element,options){var _this;_classCallCheck(this,Slider);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_changeState",function(state,detail,callback){callback()});_this.sliderActive=false;_this.dragging=false;_this.track=_this.element.querySelector(_this.options.selectorTrack);_this.filledTrack=_this.element.querySelector(_this.options.selectorFilledTrack);_this.thumb=_this.element.querySelector(_this.options.selectorThumb);_this.input=_this.element.querySelector(_this.options.selectorInput);if(_this.element.dataset.sliderInputBox){_this.boundInput=_this.element.ownerDocument.querySelector(_this.element.dataset.sliderInputBox);_this._updateInput();_this.manage(on(_this.boundInput,"change",function(evt){_this.setValue(evt.target.value)}));_this.manage(on(_this.boundInput,"focus",function(evt){evt.target.select()}));_this.manage(on(_this.boundInput,"mouseup",function(evt){evt.preventDefault()}))}_this._updatePosition();_this.manage(on(_this.thumb,"mousedown",function(){_this.sliderActive=true}));_this.manage(on(_this.element.ownerDocument,"mouseup",function(){_this.sliderActive=false}));_this.manage(on(_this.element.ownerDocument,"mousemove",function(evt){var disabled=_this.element.classList.contains(_this.options.classDisabled);if(_this.sliderActive===true&&!disabled){_this._updatePosition(evt)}}));_this.manage(on(_this.thumb,"keydown",function(evt){var disabled=_this.element.classList.contains(_this.options.classDisabled);if(!disabled){_this._updatePosition(evt)}}));_this.manage(on(_this.track,"click",function(evt){var disabled=_this.element.classList.contains(_this.options.classDisabled);if(!disabled){_this._updatePosition(evt)}}));return _this}_createClass(Slider,[{key:"_updatePosition",value:function _updatePosition(evt){var _this2=this;var _this$_calcValue=this._calcValue(evt),left=_this$_calcValue.left,newValue=_this$_calcValue.newValue;if(this.dragging){return}this.dragging=true;requestAnimationFrame(function(){_this2.dragging=false;_this2.thumb.style.left="".concat(left,"%");_this2.filledTrack.style.transform="translate(0%, -50%) scaleX(".concat(left/100,")");_this2.input.value=newValue;_this2._updateInput();_this2.changeState("slider-value-change",{value:newValue})})}},{key:"_calcValue",value:function _calcValue(evt){var _this$getInputProps=this.getInputProps(),value=_this$getInputProps.value,min=_this$getInputProps.min,max=_this$getInputProps.max,step=_this$getInputProps.step;var range=max-min;var valuePercentage=(value-min)/range*100;var left;var newValue;left=valuePercentage;newValue=value;if(evt){var type=evt.type;if(type==="keydown"){var direction={40:-1,37:-1,38:1,39:1}[evt.which];if(direction!==undefined){var multiplier=evt.shiftKey===true?range/step/this.options.stepMultiplier:1;var stepMultiplied=step*multiplier;var stepSize=stepMultiplied/range*100;left=valuePercentage+stepSize*direction;newValue=Number(value)+stepMultiplied*direction}}if(type==="mousemove"||type==="click"){if(type==="click"){this.element.querySelector(this.options.selectorThumb).classList.add(this.options.classThumbClicked)}else{this.element.querySelector(this.options.selectorThumb).classList.remove(this.options.classThumbClicked)}var track=this.track.getBoundingClientRect();var unrounded=(evt.clientX-track.left)/track.width;var rounded=Math.round(range*unrounded/step)*step;left=rounded/range*100;newValue=rounded+min}}if(newValue<=Number(min)){left=0;newValue=min}if(newValue>=Number(max)){left=100;newValue=max}return{left:left,newValue:newValue}}},{key:"_updateInput",value:function _updateInput(){if(this.boundInput){this.boundInput.value=this.input.value}}},{key:"getInputProps",value:function getInputProps(){var values={value:Number(this.input.value),min:Number(this.input.min),max:Number(this.input.max),step:this.input.step?Number(this.input.step):1};return values}},{key:"setValue",value:function setValue(value){this.input.value=value;this._updatePosition()}},{key:"stepUp",value:function stepUp(){this.input.stepUp();this._updatePosition()}},{key:"stepDown",value:function stepDown(){this.input.stepDown();this._updatePosition()}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-slider]",selectorTrack:".".concat(prefix,"--slider__track"),selectorFilledTrack:".".concat(prefix,"--slider__filled-track"),selectorThumb:".".concat(prefix,"--slider__thumb"),selectorInput:".".concat(prefix,"--slider__input"),classDisabled:"".concat(prefix,"--slider--disabled"),classThumbClicked:"".concat(prefix,"--slider__thumb--clicked"),eventBeforeSliderValueChange:"slider-before-value-change",eventAfterSliderValueChange:"slider-after-value-change",stepMultiplier:4}}}]);return Slider}(mixin(createComponent,initComponentBySearch,eventedState,handles));_defineProperty(Slider,"components",new WeakMap);var Tile=function(_mixin){_inherits(Tile,_mixin);var _super=_createSuper(Tile);function Tile(element,options){var _this;_classCallCheck(this,Tile);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_getClass",function(type){var typeObj={expandable:_this.options.classExpandedTile,clickable:_this.options.classClickableTile,selectable:_this.options.classSelectableTile};return typeObj[type]});_defineProperty(_assertThisInitialized(_this),"_hookActions",function(tileClass){var isExpandable=_this.tileType==="expandable";if(isExpandable){var aboveTheFold=_this.element.querySelector(_this.options.selectorAboveTheFold);var getStyle=_this.element.ownerDocument.defaultView.getComputedStyle(_this.element,null);var tilePaddingTop=parseInt(getStyle.getPropertyValue("padding-top"),10);var tilePaddingBottom=parseInt(getStyle.getPropertyValue("padding-bottom"),10);var tilePadding=tilePaddingTop+tilePaddingBottom;if(aboveTheFold){_this.tileHeight=_this.element.getBoundingClientRect().height;_this.atfHeight=aboveTheFold.getBoundingClientRect().height+tilePadding;_this.element.style.maxHeight="".concat(_this.atfHeight,"px")}if(_this.element.classList.contains(_this.options.classExpandedTile)){_this._setTileHeight()}}_this.element.addEventListener("click",function(evt){var input=eventMatches(evt,_this.options.selectorTileInput);if(!input){_this.element.classList.toggle(tileClass)}if(isExpandable){_this._setTileHeight()}});_this.element.addEventListener("keydown",function(evt){var input=_this.element.querySelector(_this.options.selectorTileInput);if(input){if(evt.which===13||evt.which===32){if(!isExpandable){_this.element.classList.toggle(tileClass);input.checked=!input.checked}}}})});_defineProperty(_assertThisInitialized(_this),"_setTileHeight",function(){var isExpanded=_this.element.classList.contains(_this.options.classExpandedTile);_this.element.style.maxHeight=isExpanded?"".concat(_this.tileHeight,"px"):"".concat(_this.atfHeight,"px")});_this.tileType=_this.element.dataset.tile;_this.tileHeight=0;_this.atfHeight=0;_this._hookActions(_this._getClass(_this.tileType));return _this}_createClass(Tile,[{key:"release",value:function release(){_get(_getPrototypeOf(Tile.prototype),"release",this).call(this)}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-tile]",selectorAboveTheFold:"[data-tile-atf]",selectorTileInput:"[data-tile-input]",classExpandedTile:"".concat(prefix,"--tile--is-expanded"),classClickableTile:"".concat(prefix,"--tile--is-clicked"),classSelectableTile:"".concat(prefix,"--tile--is-selected")}}}]);return Tile}(mixin(createComponent,initComponentBySearch));_defineProperty(Tile,"components",new WeakMap);var CodeSnippet=function(_mixin){_inherits(CodeSnippet,_mixin);var _super=_createSuper(CodeSnippet);function CodeSnippet(element,options){var _this;_classCallCheck(this,CodeSnippet);_this=_super.call(this,element,options);_this._initCodeSnippet();_this.element.querySelector(_this.options.classExpandBtn).addEventListener("click",function(evt){return _this._handleClick(evt)});return _this}_createClass(CodeSnippet,[{key:"_handleClick",value:function _handleClick(){var expandBtn=this.element.querySelector(this.options.classExpandText);this.element.classList.toggle(this.options.classExpanded);if(this.element.classList.contains(this.options.classExpanded)){expandBtn.textContent=expandBtn.getAttribute(this.options.attribShowLessText)}else{expandBtn.textContent=expandBtn.getAttribute(this.options.attribShowMoreText)}}},{key:"_initCodeSnippet",value:function _initCodeSnippet(){var expandBtn=this.element.querySelector(this.options.classExpandText);if(!expandBtn){throw new TypeError("Cannot find the expand button.")}expandBtn.textContent=expandBtn.getAttribute(this.options.attribShowMoreText);if(this.element.offsetHeight .").concat(prefix,"--assistive-text"),passwordIsVisible:"".concat(prefix,"--text-input--password-visible"),svgIconVisibilityOn:"svg.".concat(prefix,"--icon--visibility-on"),svgIconVisibilityOff:"svg.".concat(prefix,"--icon--visibility-off")}}}]);return TextInput}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(TextInput,"components",new WeakMap);var prefix=settings_1.prefix;var SideNav=function(_mixin){_inherits(SideNav,_mixin);var _super=_createSuper(SideNav);function SideNav(element,options){var _this;_classCallCheck(this,SideNav);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_handleClick",function(evt){var matchesToggle=eventMatches(evt,_this.options.selectorSideNavToggle);var matchesNavSubmenu=eventMatches(evt,_this.options.selectorSideNavSubmenu);var matchesSideNavLink=eventMatches(evt,_this.options.selectorSideNavLink);if(!matchesToggle&&!matchesNavSubmenu&&!matchesSideNavLink){return}if(matchesToggle){_this.changeState(!_this.isNavExpanded()?_this.constructor.state.EXPANDED:_this.constructor.state.COLLAPSED);return}if(matchesNavSubmenu){var isSubmenuExpanded=matchesNavSubmenu.getAttribute("aria-expanded")==="true";matchesNavSubmenu.setAttribute("aria-expanded","".concat(!isSubmenuExpanded));return}if(matchesSideNavLink){_toConsumableArray(_this.element.querySelectorAll(_this.options.selectorSideNavLinkCurrent)).forEach(function(el){el.classList.remove(_this.options.classSideNavItemActive,_this.options.classSideNavLinkCurrent);el.removeAttribute("aria-current")});matchesSideNavLink.classList.add(_this.options.classSideNavLinkCurrent);var closestSideNavItem=matchesSideNavLink.closest(_this.options.selectorSideNavItem);if(closestSideNavItem){closestSideNavItem.classList.add(_this.options.classSideNavItemActive)}}});_this.manage(on(element,"click",_this._handleClick));return _this}_createClass(SideNav,[{key:"isNavExpanded",value:function isNavExpanded(){return this.element.classList.contains(this.options.classSideNavExpanded)}},{key:"changeState",value:function changeState(state){this.element.classList.toggle(this.options.classSideNavExpanded,state===this.constructor.state.EXPANDED)}}]);return SideNav}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(SideNav,"components",new WeakMap);_defineProperty(SideNav,"state",{EXPANDED:"expanded",COLLAPSED:"collapsed"});_defineProperty(SideNav,"options",{selectorInit:"[data-side-nav]",selectorSideNavToggle:".".concat(prefix,"--side-nav__toggle"),selectorSideNavSubmenu:".".concat(prefix,"--side-nav__submenu"),selectorSideNavItem:".".concat(prefix,"--side-nav__item"),selectorSideNavLink:".".concat(prefix,"--side-nav__link"),selectorSideNavLinkCurrent:'[aria-current="page"],.'.concat(prefix,"--side-nav__link--current,.").concat(prefix,"--side-nav__item--active"),classSideNavExpanded:"".concat(prefix,"--side-nav--expanded"),classSideNavItemActive:"".concat(prefix,"--side-nav__item--active"),classSideNavLinkCurrent:"".concat(prefix,"--side-nav__link--current")});var forEach=function(){return Array.prototype.forEach}();var toArray$a=function toArray(arrayLike){return Array.prototype.slice.call(arrayLike)};var HeaderSubmenu=function(_mixin){_inherits(HeaderSubmenu,_mixin);var _super=_createSuper(HeaderSubmenu);function HeaderSubmenu(element,options){var _this;_classCallCheck(this,HeaderSubmenu);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"_getAction",function(event){var isFlyoutMenu=eventMatches(event,_this.options.selectorFlyoutMenu);if(isFlyoutMenu){return _this.constructor.actions.DELEGATE_TO_FLYOUT_MENU}switch(event.type){case"keydown":return{32:_this.constructor.actions.TOGGLE_SUBMENU_WITH_FOCUS,13:_this.constructor.actions.TOGGLE_SUBMENU_WITH_FOCUS,27:_this.constructor.actions.CLOSE_SUBMENU}[event.which];case"click":return eventMatches(event,_this.options.selectorItem)?_this.constructor.actions.CLOSE_SUBMENU:null;case"blur":case"focusout":{var isOfSelf=_this.element.contains(event.relatedTarget);return isOfSelf?null:_this.constructor.actions.CLOSE_SUBMENU}case"mouseenter":return _this.constructor.actions.OPEN_SUBMENU;case"mouseleave":return _this.constructor.actions.CLOSE_SUBMENU;default:return null}});_defineProperty(_assertThisInitialized(_this),"_getNewState",function(action){var trigger=_this.element.querySelector(_this.options.selectorTrigger);var isExpanded=trigger.getAttribute(_this.options.attribExpanded)==="true";switch(action){case _this.constructor.actions.CLOSE_SUBMENU:return false;case _this.constructor.actions.OPEN_SUBMENU:return true;case _this.constructor.actions.TOGGLE_SUBMENU_WITH_FOCUS:return!isExpanded;default:return isExpanded}});_defineProperty(_assertThisInitialized(_this),"_setState",function(_ref){var shouldBeExpanded=_ref.shouldBeExpanded,shouldFocusOnOpen=_ref.shouldFocusOnOpen;var trigger=_this.element.querySelector(_this.options.selectorTrigger);trigger.setAttribute(_this.options.attribExpanded,shouldBeExpanded);forEach.call(_this.element.querySelectorAll(_this.options.selectorItem),function(item){item.tabIndex=shouldBeExpanded?0:-1});if(shouldBeExpanded&&shouldFocusOnOpen){_this.element.querySelector(_this.options.selectorItem).focus()}});_defineProperty(_assertThisInitialized(_this),"getCurrentNavigation",function(){var focused=_this.element.ownerDocument.activeElement;return focused.nodeType===Node.ELEMENT_NODE&&focused.matches(_this.options.selectorItem)?focused:null});_defineProperty(_assertThisInitialized(_this),"navigate",function(direction){var items=toArray$a(_this.element.querySelectorAll(_this.options.selectorItem));var start=_this.getCurrentNavigation()||_this.element.querySelector(_this.options.selectorItemSelected);var getNextItem=function getNextItem(old){var handleUnderflow=function handleUnderflow(index,length){return index+(index>=0?0:length)};var handleOverflow=function handleOverflow(index,length){return index-(index=0?0:length)};var handleOverflow=function handleOverflow(index,length){return index-(index .").concat(prefix,"--header__menu-item")}}}]);return HeaderNav}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(HeaderNav,"components",new WeakMap);_defineProperty(HeaderNav,"NAVIGATE",{BACKWARD:-1,FORWARD:1});var NavigationMenuPanel=function(_mixin){_inherits(NavigationMenuPanel,_mixin);var _super=_createSuper(NavigationMenuPanel);function NavigationMenuPanel(){var _this;_classCallCheck(this,NavigationMenuPanel);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}_this=_super.call.apply(_super,[this].concat(args));_defineProperty(_assertThisInitialized(_this),"createdByLauncher",function(event){var isExpanded=!_this.element.hasAttribute("hidden");var newState=isExpanded?"collapsed":"expanded";_this.triggerButton=event.delegateTarget;_this.changeState(newState)});_defineProperty(_assertThisInitialized(_this),"shouldStateBeChanged",function(state){return state==="expanded"===_this.element.hasAttribute("hidden")});_defineProperty(_assertThisInitialized(_this),"_changeState",function(state,callback){toggleAttribute(_this.element,"hidden",state!=="expanded");if(_this.triggerButton){if(state==="expanded"){var focusableMenuItems=_this.element.querySelector(_this.options.selectorFocusableMenuItem);if(focusableMenuItems){focusableMenuItems.focus()}}var label=state==="expanded"?_this.triggerButton.getAttribute(_this.options.attribLabelCollapse):_this.triggerButton.getAttribute(_this.options.attribLabelExpand);_this.triggerButton.classList.toggle(_this.options.classNavigationMenuPanelHeaderActionActive,state==="expanded");_this.triggerButton.setAttribute("aria-label",label);_this.triggerButton.setAttribute("title",label)}callback()});return _this}_createClass(NavigationMenuPanel,null,[{key:"options",get:function get(){var prefix=settings_1.prefix;return{initEventNames:["click"],eventBeforeExpanded:"navigation-menu-being-expanded",eventAfterExpanded:"navigation-menu-expanded",eventBeforeCollapsed:"navigation-menu-being-collapsed",eventAfterCollapsed:"navigation-menu-collapsed",selectorFocusableMenuItem:".".concat(prefix,"--navigation__category-toggle, .").concat(prefix,"--navigation-link"),classNavigationMenuPanelHeaderActionActive:"".concat(prefix,"--header__action--active"),attribLabelExpand:"data-navigation-menu-panel-label-expand",attribLabelCollapse:"data-navigation-menu-panel-label-collapse"}}}]);return NavigationMenuPanel}(mixin(createComponent,initComponentByLauncher,exports$1,handles,eventedState));_defineProperty(NavigationMenuPanel,"components",new WeakMap);var NavigationMenu=function(_NavigationMenuPanel){_inherits(NavigationMenu,_NavigationMenuPanel);var _super=_createSuper(NavigationMenu);function NavigationMenu(element,options){var _this;_classCallCheck(this,NavigationMenu);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"getCurrentNavigation",function(){return _this.element.ownerDocument.activeElement});_defineProperty(_assertThisInitialized(_this),"navigate",function(direction){var items=_toConsumableArray(_this.element.querySelectorAll(_this.options.selectorFocusableNavItems));var start=_this.getCurrentNavigation();var getNextItem=function getNextItem(old){var handleUnderflow=function handleUnderflow(index,length){return index+(index>=0?0:length)};var handleOverflow=function handleOverflow(index,length){return index-(index a.").concat(prefix,"--navigation-link"),selectorShellNavLinkCurrent:".".concat(prefix,"--navigation-item--active,.").concat(prefix,"--navigation__category-item--active"),selectorFocusableNavItems:"\n .".concat(prefix,"--navigation__category-toggle,\n .").concat(prefix,"--navigation-item > .").concat(prefix,"--navigation-link,\n .").concat(prefix,'--navigation-link[tabindex="0"]\n '),selectorShellNavItem:".".concat(prefix,"--navigation-item"),selectorShellNavCategory:".".concat(prefix,"--navigation__category"),selectorShellNavNestedCategory:".".concat(prefix,"--navigation__category-item"),classShellNavItemActive:"".concat(prefix,"--navigation-item--active"),classShellNavLinkCurrent:"".concat(prefix,"--navigation__category-item--active"),classShellNavCategoryExpanded:"".concat(prefix,"--navigation__category--expanded")})}}]);return NavigationMenu}(NavigationMenuPanel);_defineProperty(NavigationMenu,"components",new WeakMap);_defineProperty(NavigationMenu,"NAVIGATE",{BACKWARD:-1,FORWARD:1});function onFocusByKeyboard(node,name,callback){var hasFocusout="onfocusout"in window;var focusinEventName=hasFocusout?"focusin":"focus";var focusoutEventName=hasFocusout?"focusout":"blur";var supportedEvents={focus:focusinEventName,blur:focusoutEventName};var eventName=supportedEvents[name];if(!eventName){throw new Error("Unsupported event!")}var clicked;var handleMousedown=function handleMousedown(){clicked=true;requestAnimationFrame(function(){clicked=false})};var handleFocusin=function handleFocusin(evt){if(!clicked){callback(evt)}};node.ownerDocument.addEventListener("mousedown",handleMousedown);node.addEventListener(eventName,handleFocusin,!hasFocusout);return{release:function release(){if(handleFocusin){node.removeEventListener(eventName,handleFocusin,!hasFocusout);handleFocusin=null}if(handleMousedown){node.ownerDocument.removeEventListener("mousedown",handleMousedown);handleMousedown=null}return null}}}var seq=0;var ProductSwitcher=function(_NavigationMenuPanel){_inherits(ProductSwitcher,_NavigationMenuPanel);var _super=_createSuper(ProductSwitcher);function ProductSwitcher(element,options){var _this;_classCallCheck(this,ProductSwitcher);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"current","");_defineProperty(_assertThisInitialized(_this),"triggerButtonIds",new Set);_defineProperty(_assertThisInitialized(_this),"_handleFocusOut",function(event){if(_this.element.contains(event.relatedTarget)){return}var currentTriggerButton=_this.element.ownerDocument.getElementById(_this.current);if(currentTriggerButton&&event.relatedTarget&&!event.relatedTarget.matches(_this.options.selectorFloatingMenus)){currentTriggerButton.focus()}});_defineProperty(_assertThisInitialized(_this),"_handleKeyDown",function(event){var isExpanded=!_this.element.hasAttribute("hidden");if(event.which===27&&isExpanded){var triggerButton=_this.current;_this.changeState(_this.constructor.SELECT_NONE);_this.element.ownerDocument.getElementById(triggerButton).focus()}});_defineProperty(_assertThisInitialized(_this),"createdByLauncher",function(event){var isExpanded=_this.element.classList.contains(_this.options.classProductSwitcherExpanded);var launcher=event.delegateTarget;if(!launcher.id){launcher.id="__carbon-product-switcher-launcher-".concat(seq++)}var current=launcher.id;_this.changeState(isExpanded&&_this.current===current?_this.constructor.SELECT_NONE:current)});_defineProperty(_assertThisInitialized(_this),"shouldStateBeChanged",function(current){return _this.current!==current});_defineProperty(_assertThisInitialized(_this),"_changeState",function(state,callback){_this.element.classList.toggle(_this.options.classProductSwitcherExpanded,state!==_this.constructor.SELECT_NONE);_this.current=state;if(_this.current!==_this.constructor.SELECT_NONE){_this.triggerButtonIds.add(_this.current)}_this.triggerButtonIds.forEach(function(id){var button=_this.element.ownerDocument.getElementById(id);var label=button.getAttribute(_this.options.attribLabelExpand);button.classList.remove(_this.options.classNavigationMenuPanelHeaderActionActive);button.setAttribute("aria-label",label);button.setAttribute("title",label)});var currentTriggerButton=_this.element.ownerDocument.getElementById(_this.current);if(currentTriggerButton){var label=currentTriggerButton.getAttribute(_this.options.attribLabelCollapse);currentTriggerButton.classList.toggle(_this.options.classNavigationMenuPanelHeaderActionActive);currentTriggerButton.setAttribute("aria-label",label);currentTriggerButton.setAttribute("title",label)}if(state!==_this.constructor.SELECT_NONE){_this.element.setAttribute("tabindex","0");_this.element.focus()}else{_this.element.setAttribute("tabindex","-1")}callback()});_this.manage(on(element,"keydown",_this._handleKeyDown));_this.manage(onFocusByKeyboard(element,"blur",_this._handleFocusOut));return _this}_createClass(ProductSwitcher,[{key:"release",value:function release(){this.triggerButtonIds.clear();return _get(_getPrototypeOf(ProductSwitcher.prototype),"release",this).call(this)}}],[{key:"options",get:function get(){var prefix=settings_1.prefix;return Object.assign(Object.create(NavigationMenuPanel.options),{selectorInit:"[data-product-switcher]",selectorFloatingMenus:"\n .".concat(prefix,"--overflow-menu-options,\n .").concat(prefix,"--overflow-menu-options *,\n .").concat(prefix,"--tooltip,\n .").concat(prefix,"--tooltip *,\n .flatpicker-calendar,\n .flatpicker-calendar *\n "),attribInitTarget:"data-product-switcher-target",classProductSwitcherExpanded:"".concat(prefix,"--panel--expanded")})}}]);return ProductSwitcher}(NavigationMenuPanel);_defineProperty(ProductSwitcher,"SELECT_NONE","__carbon-product-switcher-launcher-NONE");_defineProperty(ProductSwitcher,"components",new WeakMap);var PaginationNav=function(_mixin){_inherits(PaginationNav,_mixin);var _super=_createSuper(PaginationNav);function PaginationNav(element,options){var _this;_classCallCheck(this,PaginationNav);_this=_super.call(this,element,options);_defineProperty(_assertThisInitialized(_this),"getActivePageNumber",function(){var pageNum;var activePageElement=_this.element.querySelector(_this.options.selectorPageActive);if(activePageElement){pageNum=Number(activePageElement.getAttribute(_this.options.attribPage))}return pageNum});_defineProperty(_assertThisInitialized(_this),"clearActivePage",function(evt){var pageButtonNodeList=_this.element.querySelectorAll(_this.options.selectorPageButton);var pageSelectElement=_this.element.querySelector(_this.options.selectorPageSelect);Array.prototype.forEach.call(pageButtonNodeList,function(el){el.classList.remove(_this.options.classActive,_this.options.classDisabled);el.removeAttribute(_this.options.attribActive);el.removeAttribute("aria-disabled");el.removeAttribute("aria-current")});if(pageSelectElement){pageSelectElement.removeAttribute("aria-current");var pageSelectElementOptions=pageSelectElement.options;Array.prototype.forEach.call(pageSelectElementOptions,function(el){el.removeAttribute(_this.options.attribActive)});if(!evt.target.matches(_this.options.selectorPageSelect)){pageSelectElement.classList.remove(_this.options.classActive);pageSelectElement.value=""}}});_defineProperty(_assertThisInitialized(_this),"handleClick",function(evt){if(!evt.target.getAttribute("aria-disabled")===true){var nextActivePageNumber=_this.getActivePageNumber();var pageElementNodeList=_this.element.querySelectorAll(_this.options.selectorPageElement);var pageSelectElement=_this.element.querySelector(_this.options.selectorPageSelect);_this.clearActivePage(evt);if(evt.target.matches(_this.options.selectorPageButton)){nextActivePageNumber=Number(evt.target.getAttribute(_this.options.attribPage))}if(evt.target.matches(_this.options.selectorPagePrevious)){nextActivePageNumber-=1}if(evt.target.matches(_this.options.selectorPageNext)){nextActivePageNumber+=1}var pageTargetElement=pageElementNodeList[nextActivePageNumber-1];pageTargetElement.setAttribute(_this.options.attribActive,true);if(pageTargetElement.tagName==="OPTION"){pageSelectElement.value=_this.getActivePageNumber();pageSelectElement.classList.add(_this.options.classActive);pageSelectElement.setAttribute("aria-current","page")}else{pageTargetElement.classList.add(_this.options.classActive,_this.options.classDisabled);pageTargetElement.setAttribute("aria-disabled",true);pageTargetElement.setAttribute("aria-current","page")}_this.setPrevNextStates()}});_defineProperty(_assertThisInitialized(_this),"handleSelectChange",function(evt){_this.clearActivePage(evt);var pageSelectElement=_this.element.querySelector(_this.options.selectorPageSelect);var pageSelectElementOptions=pageSelectElement.options;pageSelectElementOptions[pageSelectElementOptions.selectedIndex].setAttribute(_this.options.attribActive,true);evt.target.setAttribute("aria-current","page");evt.target.classList.add(_this.options.classActive);_this.setPrevNextStates()});_defineProperty(_assertThisInitialized(_this),"setPrevNextStates",function(){var pageElementNodeList=_this.element.querySelectorAll(_this.options.selectorPageElement);var totalPages=pageElementNodeList.length;var pageDirectionElementPrevious=_this.element.querySelector(_this.options.selectorPagePrevious);var pageDirectionElementNext=_this.element.querySelector(_this.options.selectorPageNext);if(pageDirectionElementPrevious){if(_this.getActivePageNumber()<=1){pageDirectionElementPrevious.setAttribute("aria-disabled",true);pageDirectionElementPrevious.classList.add(_this.options.classDisabled)}else{pageDirectionElementPrevious.removeAttribute("aria-disabled");pageDirectionElementPrevious.classList.remove(_this.options.classDisabled)}}if(pageDirectionElementNext){if(_this.getActivePageNumber()>=totalPages){pageDirectionElementNext.setAttribute("aria-disabled",true);pageDirectionElementNext.classList.add(_this.options.classDisabled)}else{pageDirectionElementNext.removeAttribute("aria-disabled");pageDirectionElementNext.classList.remove(_this.options.classDisabled)}}});_this.manage(on(_this.element,"click",function(evt){return _this.handleClick(evt)}));_this.manage(on(_this.element,"change",function(evt){if(evt.target.matches(_this.options.selectorPageSelect)){_this.handleSelectChange(evt)}}));return _this}_createClass(PaginationNav,null,[{key:"options",get:function get(){var prefix=settings_1.prefix;return{selectorInit:"[data-pagination-nav]",selectorPageElement:"[data-page]",selectorPageButton:"[data-page-button]",selectorPagePrevious:"[data-page-previous]",selectorPageNext:"[data-page-next]",selectorPageSelect:"[data-page-select]",selectorPageActive:'[data-page-active="true"]',attribPage:"data-page",attribActive:"data-page-active",classActive:"".concat(prefix,"--pagination-nav__page--active"),classDisabled:"".concat(prefix,"--pagination-nav__page--disabled")}}}]);return PaginationNav}(mixin(createComponent,initComponentBySearch,handles));_defineProperty(PaginationNav,"components",new WeakMap);var components=Object.freeze({__proto__:null,Checkbox:Checkbox,FileUploader:FileUploader,ContentSwitcher:ContentSwitcher,Tab:Tab,OverflowMenu:OverflowMenu,Modal:Modal,Loading:Loading,InlineLoading:InlineLoading,Dropdown:Dropdown,NumberInput:NumberInput,DataTableV2:DataTable,DataTable:DataTable,DatePicker:DatePicker,Pagination:Pagination,Search:Search,Accordion:Accordion,CopyButton:CopyButton,Notification:Notification,Toolbar:Toolbar,Tooltip:Tooltip,TooltipSimple:TooltipSimple,ProgressIndicator:ProgressIndicator,FloatingMenu:FloatingMenu,StructuredList:StructuredList,Slider:Slider,Tile:Tile,CodeSnippet:CodeSnippet,TextInput:TextInput,SideNav:SideNav,HeaderSubmenu:HeaderSubmenu,HeaderNav:HeaderNav,NavigationMenu:NavigationMenu,ProductSwitcher:ProductSwitcher,PaginationNav:PaginationNav});var components$1=components;var init=function init(){var componentClasses=Object.keys(components$1).map(function(key){return components$1[key]}).filter(function(component){return typeof component.init==="function"});if(!settings_1.disableAutoInit){componentClasses.forEach(function(Clz){var h=Clz.init()})}};if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",init)}else{setTimeout(init,0)}var forEach$1=Array.prototype.forEach;var createAndReleaseComponentsUponDOMMutation=function createAndReleaseComponentsUponDOMMutation(records,componentClasses,componentClassesForWatchInit,options){records.forEach(function(record){forEach$1.call(record.addedNodes,function(node){if(node.nodeType===Node.ELEMENT_NODE){componentClassesForWatchInit.forEach(function(Clz){Clz.init(node,options)})}});forEach$1.call(record.removedNodes,function(node){if(node.nodeType===Node.ELEMENT_NODE){componentClasses.forEach(function(Clz){if(node.matches(Clz.options.selectorInit)){var instance=Clz.components.get(node);if(instance){instance.release()}}else{forEach$1.call(node.querySelectorAll(Clz.options.selectorInit),function(element){var instance=Clz.components.get(element);if(instance){instance.release()}})}})}})})};function watch(){var target=arguments.length>0&&arguments[0]!==undefined?arguments[0]:document;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(target.nodeType!==Node.ELEMENT_NODE&&target.nodeType!==Node.DOCUMENT_NODE){throw new TypeError("DOM document or DOM element should be given to watch for DOM node to create/release components.")}var componentClasses=Object.keys(components).map(function(key){return components[key]}).filter(function(component){return typeof component.init==="function"});var handles=componentClasses.map(function(Clz){return Clz.init(target,options)}).filter(Boolean);var componentClassesForWatchInit=componentClasses.filter(function(Clz){return!Clz.forLazyInit});var observer=new MutationObserver(function(records){createAndReleaseComponentsUponDOMMutation(records,componentClasses,componentClassesForWatchInit,options)});observer.observe(target,{childList:true,subtree:true});return{release:function release(){for(var handle=handles.pop();handle;handle=handles.pop()){handle.release()}if(observer){observer.disconnect();observer=null}}}}exports.Accordion=Accordion;exports.Checkbox=Checkbox;exports.CodeSnippet=CodeSnippet;exports.ContentSwitcher=ContentSwitcher;exports.CopyButton=CopyButton;exports.DataTable=DataTable;exports.DataTableV2=DataTable;exports.DatePicker=DatePicker;exports.Dropdown=Dropdown;exports.FileUploader=FileUploader;exports.FloatingMenu=FloatingMenu;exports.HeaderNav=HeaderNav;exports.HeaderSubmenu=HeaderSubmenu;exports.InlineLoading=InlineLoading;exports.Loading=Loading;exports.Modal=Modal;exports.NavigationMenu=NavigationMenu;exports.Notification=Notification;exports.NumberInput=NumberInput;exports.OverflowMenu=OverflowMenu;exports.Pagination=Pagination;exports.PaginationNav=PaginationNav;exports.ProductSwitcher=ProductSwitcher;exports.ProgressIndicator=ProgressIndicator;exports.Search=Search;exports.SideNav=SideNav;exports.Slider=Slider;exports.StructuredList=StructuredList;exports.Tab=Tab;exports.TextInput=TextInput;exports.Tile=Tile;exports.Toolbar=Toolbar;exports.Tooltip=Tooltip;exports.TooltipSimple=TooltipSimple;exports.settings=settings_1;exports.watch=watch;return exports}({});
diff --git a/basxbread/static/js/htmx.js b/basxbread/static/js/htmx.js
index 27e57bc7..de5f0f1a 100644
--- a/basxbread/static/js/htmx.js
+++ b/basxbread/static/js/htmx.js
@@ -1,3123 +1 @@
-//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
- //** @type {import("./htmx").HtmxApi} */
- // TODO: list all methods in 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,
- inlineScriptNonce:'',
- attributesToSettle:["class", "style", "width", "height"],
- withCredentials:false,
- timeout:0,
- wsReconnectDelay: 'full-jitter',
- disableSelector: "[hx-disable], [data-hx-disable]",
- useTemplateFragments: false,
- scrollBehavior: 'smooth',
- defaultFocusScroll: false,
- },
- parseInterval:parseInterval,
- _:internalEval,
- createEventSource: function(url){
- return new EventSource(url, {withCredentials:true})
- },
- createWebSocket: function(url){
- return new WebSocket(url, []);
- },
- version: "1.7.0"
- };
-
- /** @type {import("./htmx").HtmxInternalApi} */
- var internalAPI = {
- bodyContains: bodyContains,
- filterValues: filterValues,
- hasAttribute: hasAttribute,
- getAttributeValue: getAttributeValue,
- getClosestMatch: getClosestMatch,
- getExpressionVars: getExpressionVars,
- getHeaders: getHeaders,
- getInputValues: getInputValues,
- getInternalData: getInternalData,
- getSwapSpecification: getSwapSpecification,
- getTriggerSpecs: getTriggerSpecs,
- getTarget: getTarget,
- makeFragment: makeFragment,
- mergeObjects: mergeObjects,
- makeSettleInfo: makeSettleInfo,
- oobSwap: oobSwap,
- selectAndSwap: selectAndSwap,
- settleImmediately: settleImmediately,
- shouldCancel: shouldCancel,
- triggerEvent: triggerEvent,
- triggerErrorEvent: triggerErrorEvent,
- withExtensions: withExtensions,
- }
-
- 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
- }
-
- /**
- * @param {HTMLElement} elt
- * @param {string} name
- * @returns {(string | null)}
- */
- 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));
- }
-
- /**
- *
- * @param {HTMLElement} elt
- * @param {string} qualifiedName
- * @returns {(string | null)}
- */
- function getAttributeValue(elt, qualifiedName) {
- return getRawAttribute(elt, qualifiedName) || getRawAttribute(elt, "data-" + qualifiedName);
- }
-
- /**
- * @param {HTMLElement} elt
- * @returns {HTMLElement | null}
- */
- function parentElt(elt) {
- return elt.parentElement;
- }
-
- /**
- * @returns {Document}
- */
- function getDocument() {
- return document;
- }
-
- /**
- * @param {HTMLElement} elt
- * @param {(e:HTMLElement) => boolean} condition
- * @returns {HTMLElement | null}
- */
- function getClosestMatch(elt, condition) {
- if (condition(elt)) {
- return elt;
- } else if (parentElt(elt)) {
- return getClosestMatch(parentElt(elt), condition);
- } else {
- return null;
- }
- }
-
- function getAttributeValueWithDisinheritance(initialElement, ancestor, attributeName){
- var attributeValue = getAttributeValue(ancestor, attributeName);
- var disinherit = getAttributeValue(ancestor, "hx-disinherit");
- if (initialElement !== ancestor && disinherit && (disinherit === "*" || disinherit.split(" ").indexOf(attributeName) >= 0)) {
- return "unset";
- } else {
- return attributeValue
- }
- }
-
- /**
- * @param {HTMLElement} elt
- * @param {string} attributeName
- * @returns {string | null}
- */
- function getClosestAttributeValue(elt, attributeName) {
- var closestAttr = null;
- getClosestMatch(elt, function (e) {
- return closestAttr = getAttributeValueWithDisinheritance(elt, e, attributeName);
- });
- if (closestAttr !== "unset") {
- return closestAttr;
- }
- }
-
- /**
- * @param {HTMLElement} elt
- * @param {string} selector
- * @returns {boolean}
- */
- function matches(elt, selector) {
- // @ts-ignore: non-standard properties for browser compatability
- // noinspection JSUnresolvedVariable
- var matchesFunction = elt.matches || elt.matchesSelector || elt.msMatchesSelector || elt.mozMatchesSelector || elt.webkitMatchesSelector || elt.oMatchesSelector;
- return matchesFunction && matchesFunction.call(elt, selector);
- }
-
- /**
- * @param {string} str
- * @returns {string}
- */
- 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 "";
- }
- }
-
- /**
- *
- * @param {string} resp
- * @param {number} depth
- * @returns {Element}
- */
- function parseHTML(resp, depth) {
- var parser = new DOMParser();
- var responseDoc = parser.parseFromString(resp, "text/html");
-
- /** @type {Element} */
- var responseNode = responseDoc.body;
- while (depth > 0) {
- depth--;
- // @ts-ignore
- responseNode = responseNode.firstChild;
- }
- if (responseNode == null) {
- // @ts-ignore
- responseNode = getDocument().createDocumentFragment();
- }
- return responseNode;
- }
-
- /**
- *
- * @param {string} resp
- * @returns {Element}
- */
- function makeFragment(resp) {
- if (htmx.config.useTemplateFragments) {
- var documentFragment = parseHTML("" + resp + "", 0);
- // @ts-ignore type mismatch between DocumentFragment and Element.
- // TODO: Are these close enough for htmx to use interchangably?
- return documentFragment.querySelector('template').content;
- } else {
- var startTag = getStartTag(resp);
- switch (startTag) {
- case "thead":
- case "tbody":
- case "tfoot":
- case "colgroup":
- case "caption":
- return parseHTML("", 1);
- case "col":
- return parseHTML("", 2);
- case "tr":
- return parseHTML("", 2);
- case "td":
- case "th":
- return parseHTML("", 3);
- case "script":
- return parseHTML("" + resp + "
", 1);
- default:
- return parseHTML(resp, 0);
- }
- }
- }
-
- /**
- * @param {Function} func
- */
- function maybeCall(func){
- if(func) {
- func();
- }
- }
-
- /**
- * @param {any} o
- * @param {string} type
- * @returns
- */
- function isType(o, type) {
- return Object.prototype.toString.call(o) === "[object " + type + "]";
- }
-
- /**
- * @param {*} o
- * @returns {o is Function}
- */
- function isFunction(o) {
- return isType(o, "Function");
- }
-
- /**
- * @param {*} o
- * @returns {o is Object}
- */
- function isRawObject(o) {
- return isType(o, "Object");
- }
-
- /**
- * getInternalData retrieves "private" data stored by htmx within an element
- * @param {HTMLElement} elt
- * @returns {*}
- */
- function getInternalData(elt) {
- var dataProp = 'htmx-internal-data';
- var data = elt[dataProp];
- if (!data) {
- data = elt[dataProp] = {};
- }
- return data;
- }
-
- /**
- * toArray converts an ArrayLike object into a real array.
- * @param {ArrayLike} arr
- * @returns {any[]}
- */
- 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+/);
- }
-
- /**
- * mergeObjects takes all of the keys from
- * obj2 and duplicates them into obj1
- * @param {Object} obj1
- * @param {Object} obj2
- * @returns {Object}
- */
- 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
- //====================================================================
-
- var DUMMY_ELT = getDocument().createElement("output"); // dummy element for bad selectors
- function findAttributeTargets(elt, attrName) {
- var attrTarget = getClosestAttributeValue(elt, attrName);
- if (attrTarget) {
- if (attrTarget === "this") {
- return [findThisElement(elt, attrName)];
- } else {
- var result = querySelectorAllExt(elt, attrTarget);
- if (result.length === 0) {
- logError('The selector "' + attrTarget + '" on ' + attrName + " returned no matches!");
- return [DUMMY_ELT]
- } else {
- return result;
- }
- }
- }
- }
-
- function findThisElement(elt, attribute){
- return getClosestMatch(elt, function (elt) {
- return getAttributeValue(elt, attribute) != null;
- })
- }
-
- function getTarget(elt) {
- var targetStr = getClosestAttributeValue(elt, "hx-target");
- if (targetStr) {
- if (targetStr === "this") {
- return findThisElement(elt,'hx-target');
- } 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";
- }
-
- /**
- *
- * @param {string} oobValue
- * @param {HTMLElement} oobElement
- * @param {*} settleInfo
- * @returns
- */
- 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 targets = getDocument().querySelectorAll(selector);
- if (targets) {
- forEach(
- targets,
- function (target) {
- var fragment;
- var oobElementClone = oobElement.cloneNode(true);
- fragment = getDocument().createDocumentFragment();
- fragment.appendChild(oobElementClone);
- if (!isInlineSwap(swapStyle, target)) {
- fragment = oobElementClone; // if this is not an inline swap, we use the content of the node, not the node itself
- }
-
- var beforeSwapDetails = {shouldSwap: true, target: target, fragment:fragment };
- if (!triggerEvent(target, 'htmx:oobBeforeSwap', beforeSwapDetails)) return;
-
- target = beforeSwapDetails.target; // allow re-targeting
- if (beforeSwapDetails['shouldSwap']){
- swap(swapStyle, target, target, fragment, settleInfo);
- }
- forEach(settleInfo.elts, function (elt) {
- triggerEvent(elt, 'htmx:oobAfterSwap', beforeSwapDetails);
- });
- }
- );
- oobElement.parentNode.removeChild(oobElement);
- } 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();
- }
-
- triggerEvent(element, "htmx:beforeCleanupElement")
-
- 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 {
- // @type {HTMLElement}
- var newElt
- var eltBeforeNewContent = target.previousSibling;
- insertNodesBefore(parentElt(target), target, fragment, settleInfo);
- if (eltBeforeNewContent == null) {
- newElt = parentElt(target).firstChild;
- } else {
- 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 swapDelete(target, fragment, settleInfo) {
- cleanUpElement(target);
- return parentElt(target).removeChild(target);
- }
-
- 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;
- case "delete":
- swapDelete(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);
- }
- }
- if (swapStyle === "innerHTML") {
- swapInnerHTML(target, fragment, settleInfo);
- } else {
- swap(htmx.config.defaultSwapStyle, elt, target, fragment, settleInfo);
- }
- }
- }
-
- function findTitle(content) {
- if (content.indexOf(' -1) {
- var contentWithSvgsRemoved = content.replace(/]*>|>)([\s\S]*?)<\/svg>/gim, '');
- var result = contentWithSvgsRemoved.match(/]*>|>)([\s\S]*?)<\/title>/im);
-
- if (result) {
- return result[2];
- }
- }
- }
-
- function selectAndSwap(swapStyle, target, elt, responseText, settleInfo) {
- settleInfo.title = findTitle(responseText);
- 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';
-
- /**
- * @param {HTMLElement} elt
- * @returns {import("./htmx").HtmxTriggerSpecification[]}
- */
- 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, target:elt}))) {
- 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);
- });
- }
- }
-
- /**
- *
- * @param {Event} evt
- * @param {HTMLElement} elt
- * @returns
- */
- 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});
- }
- }
- }
-
- //====================================================================
- // Web Sockets
- //====================================================================
-
- 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;
- if (htmx.config.inlineScriptNonce) {
- newScript.nonce = htmx.config.inlineScriptNonce;
- }
- 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 hasChanceOfBeingBoosted() {
- return document.querySelector("[hx-boost], [data-hx-boost]");
- }
-
- function findElementsToProcess(elt) {
- if (elt.querySelectorAll) {
- var boostedElts = hasChanceOfBeingBoosted() ? ", 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"
- }
-
- /**
- * `withExtensions` locates all active extensions for a provided element, then
- * executes the provided function using each of the active extensions. It should
- * be called internally at every extendable execution point in htmx.
- *
- * @param {HTMLElement} elt
- * @param {(extension:import("./htmx").HtmxExtension) => void} toDo
- * @returns void
- */
- 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 saveCurrentPageToHistory() {
- 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) {
- saveCurrentPageToHistory();
- 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) {
-
- // @ts-ignore: optional parameter in reload() function throws error
- 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 indicators = findAttributeTargets(elt, 'hx-indicator');
- if (indicators == null) {
- 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})
- }
- }
- }
-
- /**
- * @param {HTMLElement} elt
- * @param {string} verb
- */
- function getInputValues(elt, verb) {
- var processed = [];
- var values = {};
- var formValues = {};
- var errors = [];
- var internalData = getInternalData(elt);
-
- // only validate when form is directly submitted and novalidate or formnovalidate are not set
- var validate = matches(elt, 'form') && elt.noValidate !== true;
- if (internalData.lastButtonClicked) {
- validate = validate && internalData.lastButtonClicked.formNoValidate !== 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
- if (internalData.lastButtonClicked) {
- var name = getRawAttribute(internalData.lastButtonClicked,"name");
- if (name) {
- values[name] = internalData.lastButtonClicked.value;
- }
- }
-
- // include any explicit includes
- var includes = findAttributeTargets(elt, "hx-include");
- forEach(includes, 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 += "&";
- }
- if (String(realValue) === "[object Object]") {
- realValue = JSON.stringify(realValue);
- }
- var s = encodeURIComponent(realValue);
- returnStr += encodeURIComponent(name) + "=" + s;
- 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
- //====================================================================
-
- /**
- * @param {HTMLElement} elt
- * @param {HTMLElement} target
- * @param {string} prompt
- * @returns {Object} // TODO: Define/Improve HtmxHeaderSpecification
- */
- 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;
- }
-
- /**
- * filterValues takes an object containing form input values
- * and returns a new object that only contains keys that are
- * specified by the closest "hx-params" attribute
- * @param {Object} inputValues
- * @param {HTMLElement} elt
- * @returns {Object}
- */
- 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
- }
-
- /**
- *
- * @param {HTMLElement} elt
- * @param {string} swapInfoOverride
- * @returns {import("./htmx").HtmxSwapSpecification}
- */
- function getSwapSpecification(elt, swapInfoOverride) {
- var swapInfo = swapInfoOverride ? swapInfoOverride : 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;
- }
- if (modifier.indexOf("focus-scroll:") === 0) {
- var focusScrollVal = modifier.substr("focus-scroll:".length);
- swapSpec["focusScroll"] = focusScrollVal == "true";
- }
- }
- }
- }
- 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);
- }
- }
- }
-
- /**
- *
- * @param {Element} target
- * @returns {import("./htmx").HtmxSettleInfo}
- */
- 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});
- }
- }
- }
-
- /**
- * @param {HTMLElement} elt
- * @param {string} attr
- * @param {boolean=} evalAsDefault
- * @param {Object=} values
- * @returns {Object}
- */
- 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;
- }
- }
-
- /**
- * @param {HTMLElement} elt
- * @param {*} expressionVars
- * @returns
- */
- function getHXVarsForElement(elt, expressionVars) {
- return getValuesForElement(elt, "hx-vars", true, expressionVars);
- }
-
- /**
- * @param {HTMLElement} elt
- * @param {*} expressionVars
- * @returns
- */
- function getHXValsForElement(elt, expressionVars) {
- return getValuesForElement(elt, "hx-vals", false, expressionVars);
- }
-
- /**
- * @param {HTMLElement} elt
- * @returns {Object}
- */
- 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),
- swapOverride: context.swap,
- 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 || target == DUMMY_ELT) {
- triggerErrorEvent(elt, 'htmx:targetError', {target: getAttributeValue(elt, "hx-target")});
- return;
- }
-
- var syncElt = elt;
- var eltData = getInternalData(elt);
- var syncStrategy = getClosestAttributeValue(elt, "hx-sync");
- var queueStrategy = null;
- var abortable = false;
- if (syncStrategy) {
- var syncStrings = syncStrategy.split(":");
- var selector = syncStrings[0].trim();
- if (selector === "this") {
- syncElt = findThisElement(elt, 'hx-sync');
- } else {
- syncElt = querySelectorExt(elt, selector);
- }
- // default to the drop strategy
- syncStrategy = (syncStrings[1] || 'drop').trim();
- eltData = getInternalData(syncElt);
- if (syncStrategy === "drop" && eltData.xhr && eltData.abortable !== true) {
- return;
- } else if (syncStrategy === "abort") {
- if (eltData.xhr) {
- return;
- } else {
- abortable = true;
- }
- } else if (syncStrategy === "replace") {
- triggerEvent(syncElt, 'htmx:abort'); // abort the current request and continue
- } else if (syncStrategy.indexOf("queue") === 0) {
- var queueStrArray = syncStrategy.split(" ");
- queueStrategy = (queueStrArray[1] || "last").trim();
- }
- }
-
- if (eltData.xhr) {
- if (eltData.abortable) {
- triggerEvent(syncElt, 'htmx:abort'); // abort the current request and continue
- } else {
- if(queueStrategy == null){
- if (event) {
- var eventData = getInternalData(event);
- if (eventData && eventData.triggerSpec && eventData.triggerSpec.queue) {
- queueStrategy = eventData.triggerSpec.queue;
- }
- }
- if (queueStrategy == null) {
- queueStrategy = "last";
- }
- }
- 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;
- }
- }
-
- var xhr = new XMLHttpRequest();
- eltData.xhr = xhr;
- eltData.abortable = abortable;
- var endRequestLock = function(){
- eltData.xhr = null;
- eltData.abortable = 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 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, etc:etc, 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;
- var etc = responseInfo.etc;
-
- 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"));
- }
-
- /** @type {boolean} */
- var shouldSaveHistory
- if (pushedUrl == "false") {
- shouldSaveHistory = false
- } else {
- 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) {
- saveCurrentPageToHistory();
- }
-
- var swapOverride = etc.swapOverride;
- var swapSpec = getSwapSpecification(elt, swapOverride);
-
- 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);
- var focusOptions = { preventScroll: swapSpec.focusScroll !== undefined ? !swapSpec.focusScroll : !htmx.config.defaultFocusScroll };
- if (newActiveElt) {
- // @ts-ignore
- if (selectionInfo.start && newActiveElt.setSelectionRange) {
- // @ts-ignore
- newActiveElt.setSelectionRange(selectionInfo.start, selectionInfo.end);
- }
- newActiveElt.focus(focusOptions);
- }
- }
-
- 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});
- }
-
- if(settleInfo.title) {
- var titleElt = find("title");
- if(titleElt) {
- titleElt.innerHTML = settleInfo.title;
- } else {
- window.document.title = settleInfo.title;
- }
- }
-
- 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
- //====================================================================
-
- /** @type {Object} */
- var extensions = {};
-
- /**
- * extensionBase defines the default functions for all extensions.
- * @returns {import("./htmx").HtmxExtension}
- */
- function extensionBase() {
- return {
- init: function(api) {return null;},
- 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;}
- }
- }
-
- /**
- * defineExtension initializes the extension and adds it to the htmx registry
- *
- * @param {string} name
- * @param {import("./htmx").HtmxExtension} extension
- */
- function defineExtension(name, extension) {
- if(extension.init) {
- extension.init(internalAPI)
- }
- extensions[name] = mergeObjects(extensionBase(), extension);
- }
-
- /**
- * removeExtension removes an extension from the htmx registry
- *
- * @param {string} name
- */
- function removeExtension(name) {
- delete extensions[name];
- }
-
- /**
- * getExtensions searches up the DOM tree to return all extensions that can be applied to a given element
- *
- * @param {HTMLElement} elt
- * @param {import("./htmx").HtmxExtension[]=} extensionsToReturn
- * @param {import("./htmx").HtmxExtension[]=} extensionsToIgnore
- */
- 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",
- "");
- }
- }
-
- 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);
- var restoredElts = getDocument().querySelectorAll(
- "[hx-trigger='restored'],[data-hx-trigger='restored']"
- );
- body.addEventListener("htmx:abort", function (evt) {
- var target = evt.target;
- var internalData = getInternalData(target);
- if (internalData && internalData.xhr) {
- internalData.xhr.abort();
- }
- });
- window.onpopstate = function (event) {
- if (event.state && event.state.htmx) {
- restoreHistory();
- forEach(restoredElts, function(elt){
- triggerEvent(elt, 'htmx:restored', {
- 'document': getDocument(),
- 'triggerEvent': triggerEvent
- });
- });
- }
- };
- setTimeout(function () {
- triggerEvent(body, 'htmx:load', {}); // give ready handlers a chance to load up before firing this event
- }, 0);
- })
-
- return htmx;
- }
-)()
-}));
+(function(e,t){if(typeof define==="function"&&define.amd){define([],t)}else if(typeof module==="object"&&module.exports){module.exports=t()}else{e.htmx=e.htmx||t()}})(typeof self!=="undefined"?self:this,function(){return function(){"use strict";var Q={onLoad:F,process:zt,on:de,off:ge,trigger:ce,ajax:Nr,find:C,findAll:f,closest:v,values:function(e,t){var r=dr(e,t||"post");return r.values},remove:_,addClass:z,removeClass:n,toggleClass:$,takeClass:W,defineExtension:Ur,removeExtension:Br,logAll:V,logNone:j,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,allowScriptTags:true,inlineScriptNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",useTemplateFragments:false,scrollBehavior:"smooth",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get"],selfRequestsOnly:false,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null},parseInterval:d,_:t,createEventSource:function(e){return new EventSource(e,{withCredentials:true})},createWebSocket:function(e){var t=new WebSocket(e,[]);t.binaryType=Q.config.wsBinaryType;return t},version:"1.9.12"};var r={addTriggerHandler:Lt,bodyContains:se,canAccessLocalStorage:U,findThisElement:xe,filterValues:yr,hasAttribute:o,getAttributeValue:te,getClosestAttributeValue:ne,getClosestMatch:c,getExpressionVars:Hr,getHeaders:xr,getInputValues:dr,getInternalData:ae,getSwapSpecification:wr,getTriggerSpecs:it,getTarget:ye,makeFragment:l,mergeObjects:le,makeSettleInfo:T,oobSwap:Ee,querySelectorExt:ue,selectAndSwap:je,settleImmediately:nr,shouldCancel:ut,triggerEvent:ce,triggerErrorEvent:fe,withExtensions:R};var w=["get","post","put","delete","patch"];var i=w.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");var S=e("head"),q=e("title"),H=e("svg",true);function e(e,t){return new RegExp("<"+e+"(\\s[^>]*>|>)([\\s\\S]*?)<\\/"+e+">",!!t?"gim":"im")}function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e.getAttribute&&e.getAttribute(t)}function o(e,t){return e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){return e.parentElement}function re(){return document}function c(e,t){while(e&&!t(e)){e=u(e)}return e?e:null}function L(e,t,r){var n=te(t,r);var i=te(t,"hx-disinherit");if(e!==t&&i&&(i==="*"||i.split(" ").indexOf(r)>=0)){return"unset"}else{return n}}function ne(t,r){var n=null;c(t,function(e){return n=L(t,e,r)});if(n!=="unset"){return n}}function h(e,t){var r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;return r&&r.call(e,t)}function A(e){var t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;var r=t.exec(e);if(r){return r[1].toLowerCase()}else{return""}}function s(e,t){var r=new DOMParser;var n=r.parseFromString(e,"text/html");var i=n.body;while(t>0){t--;i=i.firstChild}if(i==null){i=re().createDocumentFragment()}return i}function N(e){return/"+n+"",0);var a=i.querySelector("template").content;if(Q.config.allowScriptTags){oe(a.querySelectorAll("script"),function(e){if(Q.config.inlineScriptNonce){e.nonce=Q.config.inlineScriptNonce}e.htmxExecuted=navigator.userAgent.indexOf("Firefox")===-1})}else{oe(a.querySelectorAll("script"),function(e){_(e)})}return a}switch(r){case"thead":case"tbody":case"tfoot":case"colgroup":case"caption":return s("",1);case"col":return s("",2);case"tr":return s("",2);case"td":case"th":return s("",3);case"script":case"style":return s(""+n+"
",1);default:return s(n,0)}}function ie(e){if(e){e()}}function I(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return I(e,"Function")}function P(e){return I(e,"Object")}function ae(e){var t="htmx-internal-data";var r=e[t];if(!r){r=e[t]={}}return r}function M(e){var t=[];if(e){for(var r=0;r=0}function se(e){if(e.getRootNode&&e.getRootNode()instanceof window.ShadowRoot){return re().body.contains(e.getRootNode().host)}else{return re().body.contains(e)}}function D(e){return e.trim().split(/\s+/)}function le(e,t){for(var r in t){if(t.hasOwnProperty(r)){e[r]=t[r]}}return e}function E(e){try{return JSON.parse(e)}catch(e){b(e);return null}}function U(){var e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function B(t){try{var e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function t(e){return Tr(re().body,function(){return eval(e)})}function F(t){var e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,r){if(console){console.log(t,e,r)}}}function j(){Q.logger=null}function C(e,t){if(t){return e.querySelector(t)}else{return C(re(),e)}}function f(e,t){if(t){return e.querySelectorAll(t)}else{return f(re(),e)}}function _(e,t){e=p(e);if(t){setTimeout(function(){_(e);e=null},t)}else{e.parentElement.removeChild(e)}}function z(e,t,r){e=p(e);if(r){setTimeout(function(){z(e,t);e=null},r)}else{e.classList&&e.classList.add(t)}}function n(e,t,r){e=p(e);if(r){setTimeout(function(){n(e,t);e=null},r)}else{if(e.classList){e.classList.remove(t);if(e.classList.length===0){e.removeAttribute("class")}}}}function $(e,t){e=p(e);e.classList.toggle(t)}function W(e,t){e=p(e);oe(e.parentElement.children,function(e){n(e,t)});z(e,t)}function v(e,t){e=p(e);if(e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&u(e));return null}}function g(e,t){return e.substring(0,t.length)===t}function G(e,t){return e.substring(e.length-t.length)===t}function J(e){var t=e.trim();if(g(t,"<")&&G(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function Z(e,t){if(t.indexOf("closest ")===0){return[v(e,J(t.substr(8)))]}else if(t.indexOf("find ")===0){return[C(e,J(t.substr(5)))]}else if(t==="next"){return[e.nextElementSibling]}else if(t.indexOf("next ")===0){return[K(e,J(t.substr(5)))]}else if(t==="previous"){return[e.previousElementSibling]}else if(t.indexOf("previous ")===0){return[Y(e,J(t.substr(9)))]}else if(t==="document"){return[document]}else if(t==="window"){return[window]}else if(t==="body"){return[document.body]}else{return re().querySelectorAll(J(t))}}var K=function(e,t){var r=re().querySelectorAll(t);for(var n=0;n=0;n--){var i=r[n];if(i.compareDocumentPosition(e)===Node.DOCUMENT_POSITION_FOLLOWING){return i}}};function ue(e,t){if(t){return Z(e,t)[0]}else{return Z(re().body,e)[0]}}function p(e){if(I(e,"String")){return C(e)}else{return e}}function ve(e,t,r){if(k(t)){return{target:re().body,event:e,listener:t}}else{return{target:p(e),event:t,listener:r}}}function de(t,r,n){jr(function(){var e=ve(t,r,n);e.target.addEventListener(e.event,e.listener)});var e=k(r);return e?r:n}function ge(t,r,n){jr(function(){var e=ve(t,r,n);e.target.removeEventListener(e.event,e.listener)});return k(r)?r:n}var pe=re().createElement("output");function me(e,t){var r=ne(e,t);if(r){if(r==="this"){return[xe(e,t)]}else{var n=Z(e,r);if(n.length===0){b('The selector "'+r+'" on '+t+" returned no matches!");return[pe]}else{return n}}}}function xe(e,t){return c(e,function(e){return te(e,t)!=null})}function ye(e){var t=ne(e,"hx-target");if(t){if(t==="this"){return xe(e,"hx-target")}else{return ue(e,t)}}else{var r=ae(e);if(r.boosted){return re().body}else{return e}}}function be(e){var t=Q.config.attributesToSettle;for(var r=0;r0){o=e.substr(0,e.indexOf(":"));t=e.substr(e.indexOf(":")+1,e.length)}else{o=e}var r=re().querySelectorAll(t);if(r){oe(r,function(e){var t;var r=i.cloneNode(true);t=re().createDocumentFragment();t.appendChild(r);if(!Se(o,e)){t=r}var n={shouldSwap:true,target:e,fragment:t};if(!ce(e,"htmx:oobBeforeSwap",n))return;e=n.target;if(n["shouldSwap"]){Fe(o,e,e,t,a)}oe(a.elts,function(e){ce(e,"htmx:oobAfterSwap",n)})});i.parentNode.removeChild(i)}else{i.parentNode.removeChild(i);fe(re().body,"htmx:oobErrorNoTarget",{content:i})}return e}function Ce(e,t,r){var n=ne(e,"hx-select-oob");if(n){var i=n.split(",");for(var a=0;a0){var r=t.replace("'","\\'");var n=e.tagName.replace(":","\\:");var i=o.querySelector(n+"[id='"+r+"']");if(i&&i!==o){var a=e.cloneNode();we(e,i);s.tasks.push(function(){we(e,a)})}}})}function Oe(e){return function(){n(e,Q.config.addedClass);zt(e);Nt(e);qe(e);ce(e,"htmx:load")}}function qe(e){var t="[autofocus]";var r=h(e,t)?e:e.querySelector(t);if(r!=null){r.focus()}}function a(e,t,r,n){Te(e,r,n);while(r.childNodes.length>0){var i=r.firstChild;z(i,Q.config.addedClass);e.insertBefore(i,t);if(i.nodeType!==Node.TEXT_NODE&&i.nodeType!==Node.COMMENT_NODE){n.tasks.push(Oe(i))}}}function He(e,t){var r=0;while(r-1){var t=e.replace(H,"");var r=t.match(q);if(r){return r[2]}}}function je(e,t,r,n,i,a){i.title=Ve(n);var o=l(n);if(o){Ce(r,o,i);o=Be(r,o,a);Re(o);return Fe(e,r,t,o,i)}}function _e(e,t,r){var n=e.getResponseHeader(t);if(n.indexOf("{")===0){var i=E(n);for(var a in i){if(i.hasOwnProperty(a)){var o=i[a];if(!P(o)){o={value:o}}ce(r,a,o)}}}else{var s=n.split(",");for(var l=0;l0){var o=t[0];if(o==="]"){n--;if(n===0){if(a===null){i=i+"true"}t.shift();i+=")})";try{var s=Tr(e,function(){return Function(i)()},function(){return true});s.source=i;return s}catch(e){fe(re().body,"htmx:syntax:error",{error:e,source:i});return null}}}else if(o==="["){n++}if(Qe(o,a,r)){i+="(("+r+"."+o+") ? ("+r+"."+o+") : (window."+o+"))"}else{i=i+o}a=t.shift()}}}function y(e,t){var r="";while(e.length>0&&!t.test(e[0])){r+=e.shift()}return r}function tt(e){var t;if(e.length>0&&Ze.test(e[0])){e.shift();t=y(e,Ke).trim();e.shift()}else{t=y(e,x)}return t}var rt="input, textarea, select";function nt(e,t,r){var n=[];var i=Ye(t);do{y(i,Je);var a=i.length;var o=y(i,/[,\[\s]/);if(o!==""){if(o==="every"){var s={trigger:"every"};y(i,Je);s.pollInterval=d(y(i,/[,\[\s]/));y(i,Je);var l=et(e,i,"event");if(l){s.eventFilter=l}n.push(s)}else if(o.indexOf("sse:")===0){n.push({trigger:"sse",sseEvent:o.substr(4)})}else{var u={trigger:o};var l=et(e,i,"event");if(l){u.eventFilter=l}while(i.length>0&&i[0]!==","){y(i,Je);var f=i.shift();if(f==="changed"){u.changed=true}else if(f==="once"){u.once=true}else if(f==="consume"){u.consume=true}else if(f==="delay"&&i[0]===":"){i.shift();u.delay=d(y(i,x))}else if(f==="from"&&i[0]===":"){i.shift();if(Ze.test(i[0])){var c=tt(i)}else{var c=y(i,x);if(c==="closest"||c==="find"||c==="next"||c==="previous"){i.shift();var h=tt(i);if(h.length>0){c+=" "+h}}}u.from=c}else if(f==="target"&&i[0]===":"){i.shift();u.target=tt(i)}else if(f==="throttle"&&i[0]===":"){i.shift();u.throttle=d(y(i,x))}else if(f==="queue"&&i[0]===":"){i.shift();u.queue=y(i,x)}else if(f==="root"&&i[0]===":"){i.shift();u[f]=tt(i)}else if(f==="threshold"&&i[0]===":"){i.shift();u[f]=y(i,x)}else{fe(e,"htmx:syntax:error",{token:i.shift()})}}n.push(u)}}if(i.length===a){fe(e,"htmx:syntax:error",{token:i.shift()})}y(i,Je)}while(i[0]===","&&i.shift());if(r){r[t]=n}return n}function it(e){var t=te(e,"hx-trigger");var r=[];if(t){var n=Q.config.triggerSpecsCache;r=n&&n[t]||nt(e,t,n)}if(r.length>0){return r}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,rt)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function at(e){ae(e).cancelled=true}function ot(e,t,r){var n=ae(e);n.timeout=setTimeout(function(){if(se(e)&&n.cancelled!==true){if(!ct(r,e,Wt("hx:poll:trigger",{triggerSpec:r,target:e}))){t(e)}ot(e,t,r)}},r.pollInterval)}function st(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function lt(t,r,e){if(t.tagName==="A"&&st(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"){r.boosted=true;var n,i;if(t.tagName==="A"){n="get";i=ee(t,"href")}else{var a=ee(t,"method");n=a?a.toLowerCase():"get";if(n==="get"){}i=ee(t,"action")}e.forEach(function(e){ht(t,function(e,t){if(v(e,Q.config.disableSelector)){m(e);return}he(n,i,e,t)},r,e,true)})}}function ut(e,t){if(e.type==="submit"||e.type==="click"){if(t.tagName==="FORM"){return true}if(h(t,'input[type="submit"], button')&&v(t,"form")!==null){return true}if(t.tagName==="A"&&t.href&&(t.getAttribute("href")==="#"||t.getAttribute("href").indexOf("#")!==0)){return true}}return false}function ft(e,t){return ae(e).boosted&&e.tagName==="A"&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function ct(e,t,r){var n=e.eventFilter;if(n){try{return n.call(t,r)!==true}catch(e){fe(re().body,"htmx:eventFilter:error",{error:e,source:n.source});return true}}return false}function ht(a,o,e,s,l){var u=ae(a);var t;if(s.from){t=Z(a,s.from)}else{t=[a]}if(s.changed){t.forEach(function(e){var t=ae(e);t.lastValue=e.value})}oe(t,function(n){var i=function(e){if(!se(a)){n.removeEventListener(s.trigger,i);return}if(ft(a,e)){return}if(l||ut(e,a)){e.preventDefault()}if(ct(s,a,e)){return}var t=ae(e);t.triggerSpec=s;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(a)<0){t.handledFor.push(a);if(s.consume){e.stopPropagation()}if(s.target&&e.target){if(!h(e.target,s.target)){return}}if(s.once){if(u.triggeredOnce){return}else{u.triggeredOnce=true}}if(s.changed){var r=ae(n);if(r.lastValue===n.value){return}r.lastValue=n.value}if(u.delayed){clearTimeout(u.delayed)}if(u.throttle){return}if(s.throttle>0){if(!u.throttle){o(a,e);u.throttle=setTimeout(function(){u.throttle=null},s.throttle)}}else if(s.delay>0){u.delayed=setTimeout(function(){o(a,e)},s.delay)}else{ce(a,"htmx:trigger");o(a,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:s.trigger,listener:i,on:n});n.addEventListener(s.trigger,i)})}var vt=false;var dt=null;function gt(){if(!dt){dt=function(){vt=true};window.addEventListener("scroll",dt);setInterval(function(){if(vt){vt=false;oe(re().querySelectorAll("[hx-trigger='revealed'],[data-hx-trigger='revealed']"),function(e){pt(e)})}},200)}}function pt(t){if(!o(t,"data-hx-revealed")&&X(t)){t.setAttribute("data-hx-revealed","true");var e=ae(t);if(e.initHash){ce(t,"revealed")}else{t.addEventListener("htmx:afterProcessNode",function(e){ce(t,"revealed")},{once:true})}}}function mt(e,t,r){var n=D(r);for(var i=0;i=0){var t=wt(n);setTimeout(function(){xt(s,r,n+1)},t)}};t.onopen=function(e){n=0};ae(s).webSocket=t;t.addEventListener("message",function(e){if(yt(s)){return}var t=e.data;R(s,function(e){t=e.transformResponse(t,null,s)});var r=T(s);var n=l(t);var i=M(n.children);for(var a=0;a0){ce(u,"htmx:validation:halted",i);return}t.send(JSON.stringify(l));if(ut(e,u)){e.preventDefault()}})}else{fe(u,"htmx:noWebSocketSourceError")}}function wt(e){var t=Q.config.wsReconnectDelay;if(typeof t==="function"){return t(e)}if(t==="full-jitter"){var r=Math.min(e,6);var n=1e3*Math.pow(2,r);return n*Math.random()}b('htmx.config.wsReconnectDelay must either be a function or the string "full-jitter"')}function St(e,t,r){var n=D(r);for(var i=0;i0){setTimeout(i,n)}else{i()}}function Ht(t,i,e){var a=false;oe(w,function(r){if(o(t,"hx-"+r)){var n=te(t,"hx-"+r);a=true;i.path=n;i.verb=r;e.forEach(function(e){Lt(t,e,i,function(e,t){if(v(e,Q.config.disableSelector)){m(e);return}he(r,n,e,t)})})}});return a}function Lt(n,e,t,r){if(e.sseEvent){Rt(n,r,e.sseEvent)}else if(e.trigger==="revealed"){gt();ht(n,r,t,e);pt(n)}else if(e.trigger==="intersect"){var i={};if(e.root){i.root=ue(n,e.root)}if(e.threshold){i.threshold=parseFloat(e.threshold)}var a=new IntersectionObserver(function(e){for(var t=0;t0){t.polling=true;ot(n,r,e)}else{ht(n,r,t,e)}}function At(e){if(!e.htmxExecuted&&Q.config.allowScriptTags&&(e.type==="text/javascript"||e.type==="module"||e.type==="")){var t=re().createElement("script");oe(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}var r=e.parentElement;try{r.insertBefore(t,e)}catch(e){b(e)}finally{if(e.parentElement){e.parentElement.removeChild(e)}}}}function Nt(e){if(h(e,"script")){At(e)}oe(f(e,"script"),function(e){At(e)})}function It(e){var t=e.attributes;if(!t){return false}for(var r=0;r0){var o=n.shift();var s=o.match(/^\s*([a-zA-Z:\-\.]+:)(.*)/);if(a===0&&s){o.split(":");i=s[1].slice(0,-1);r[i]=s[2]}else{r[i]+=o}a+=Bt(o)}for(var l in r){Ft(e,l,r[l])}}}function jt(e){Ae(e);for(var t=0;tQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(re().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Yt(e){if(!U()){return null}e=B(e);var t=E(localStorage.getItem("htmx-history-cache"))||[];for(var r=0;r=200&&this.status<400){ce(re().body,"htmx:historyCacheMissLoad",o);var e=l(this.response);e=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;var t=Zt();var r=T(t);var n=Ve(this.response);if(n){var i=C("title");if(i){i.innerHTML=n}else{window.document.title=n}}Ue(t,e,r);nr(r.tasks);Jt=a;ce(re().body,"htmx:historyRestore",{path:a,cacheMiss:true,serverResponse:this.response})}else{fe(re().body,"htmx:historyCacheMissLoadError",o)}};e.send()}function ar(e){er();e=e||location.pathname+location.search;var t=Yt(e);if(t){var r=l(t.content);var n=Zt();var i=T(n);Ue(n,r,i);nr(i.tasks);document.title=t.title;setTimeout(function(){window.scrollTo(0,t.scroll)},0);Jt=e;ce(re().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{ir(e)}}}function or(e){var t=me(e,"hx-indicator");if(t==null){t=[e]}oe(t,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)+1;e.classList["add"].call(e.classList,Q.config.requestClass)});return t}function sr(e){var t=me(e,"hx-disabled-elt");if(t==null){t=[]}oe(t,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","")});return t}function lr(e,t){oe(e,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)-1;if(t.requestCount===0){e.classList["remove"].call(e.classList,Q.config.requestClass)}});oe(t,function(e){var t=ae(e);t.requestCount=(t.requestCount||0)-1;if(t.requestCount===0){e.removeAttribute("disabled")}})}function ur(e,t){for(var r=0;r=0}function wr(e,t){var r=t?t:ne(e,"hx-swap");var n={swapStyle:ae(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ae(e).boosted&&!br(e)){n["show"]="top"}if(r){var i=D(r);if(i.length>0){for(var a=0;a0?l.join(":"):null;n["scroll"]=u;n["scrollTarget"]=f}else if(o.indexOf("show:")===0){var c=o.substr(5);var l=c.split(":");var h=l.pop();var f=l.length>0?l.join(":"):null;n["show"]=h;n["showTarget"]=f}else if(o.indexOf("focus-scroll:")===0){var v=o.substr("focus-scroll:".length);n["focusScroll"]=v=="true"}else if(a==0){n["swapStyle"]=o}else{b("Unknown modifier in hx-swap: "+o)}}}}return n}function Sr(e){return ne(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function Er(t,r,n){var i=null;R(r,function(e){if(i==null){i=e.encodeParameters(t,n,r)}});if(i!=null){return i}else{if(Sr(r)){return mr(n)}else{return pr(n)}}}function T(e){return{tasks:[],elts:[e]}}function Cr(e,t){var r=e[0];var n=e[e.length-1];if(t.scroll){var i=null;if(t.scrollTarget){i=ue(r,t.scrollTarget)}if(t.scroll==="top"&&(r||i)){i=i||r;i.scrollTop=0}if(t.scroll==="bottom"&&(n||i)){i=i||n;i.scrollTop=i.scrollHeight}}if(t.show){var i=null;if(t.showTarget){var a=t.showTarget;if(t.showTarget==="window"){a="body"}i=ue(r,a)}if(t.show==="top"&&(r||i)){i=i||r;i.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(n||i)){i=i||n;i.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function Rr(e,t,r,n){if(n==null){n={}}if(e==null){return n}var i=te(e,t);if(i){var a=i.trim();var o=r;if(a==="unset"){return null}if(a.indexOf("javascript:")===0){a=a.substr(11);o=true}else if(a.indexOf("js:")===0){a=a.substr(3);o=true}if(a.indexOf("{")!==0){a="{"+a+"}"}var s;if(o){s=Tr(e,function(){return Function("return ("+a+")")()},{})}else{s=E(a)}for(var l in s){if(s.hasOwnProperty(l)){if(n[l]==null){n[l]=s[l]}}}}return Rr(u(e),t,r,n)}function Tr(e,t,r){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return r}}function Or(e,t){return Rr(e,"hx-vars",true,t)}function qr(e,t){return Rr(e,"hx-vals",false,t)}function Hr(e){return le(Or(e),qr(e))}function Lr(t,r,n){if(n!==null){try{t.setRequestHeader(r,n)}catch(e){t.setRequestHeader(r,encodeURIComponent(n));t.setRequestHeader(r+"-URI-AutoEncoded","true")}}}function Ar(t){if(t.responseURL&&typeof URL!=="undefined"){try{var e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(re().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function O(e,t){return t.test(e.getAllResponseHeaders())}function Nr(e,t,r){e=e.toLowerCase();if(r){if(r instanceof Element||I(r,"String")){return he(e,t,null,null,{targetOverride:p(r),returnPromise:true})}else{return he(e,t,p(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:p(r.target),swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return he(e,t,null,null,{returnPromise:true})}}function Ir(e){var t=[];while(e){t.push(e);e=e.parentElement}return t}function kr(e,t,r){var n;var i;if(typeof URL==="function"){i=new URL(t,document.location.href);var a=document.location.origin;n=a===i.origin}else{i=t;n=g(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!n){return false}}return ce(e,"htmx:validateUrl",le({url:i,sameHost:n},r))}function he(t,r,n,i,a,e){var o=null;var s=null;a=a!=null?a:{};if(a.returnPromise&&typeof Promise!=="undefined"){var l=new Promise(function(e,t){o=e;s=t})}if(n==null){n=re().body}var M=a.handler||Mr;var X=a.select||null;if(!se(n)){ie(o);return l}var u=a.targetOverride||ye(n);if(u==null||u==pe){fe(n,"htmx:targetError",{target:te(n,"hx-target")});ie(s);return l}var f=ae(n);var c=f.lastButtonClicked;if(c){var h=ee(c,"formaction");if(h!=null){r=h}var v=ee(c,"formmethod");if(v!=null){if(v.toLowerCase()!=="dialog"){t=v}}}var d=ne(n,"hx-confirm");if(e===undefined){var D=function(e){return he(t,r,n,i,a,!!e)};var U={target:u,elt:n,path:r,verb:t,triggeringEvent:i,etc:a,issueRequest:D,question:d};if(ce(n,"htmx:confirm",U)===false){ie(o);return l}}var g=n;var p=ne(n,"hx-sync");var m=null;var x=false;if(p){var B=p.split(":");var F=B[0].trim();if(F==="this"){g=xe(n,"hx-sync")}else{g=ue(n,F)}p=(B[1]||"drop").trim();f=ae(g);if(p==="drop"&&f.xhr&&f.abortable!==true){ie(o);return l}else if(p==="abort"){if(f.xhr){ie(o);return l}else{x=true}}else if(p==="replace"){ce(g,"htmx:abort")}else if(p.indexOf("queue")===0){var V=p.split(" ");m=(V[1]||"last").trim()}}if(f.xhr){if(f.abortable){ce(g,"htmx:abort")}else{if(m==null){if(i){var y=ae(i);if(y&&y.triggerSpec&&y.triggerSpec.queue){m=y.triggerSpec.queue}}if(m==null){m="last"}}if(f.queuedRequests==null){f.queuedRequests=[]}if(m==="first"&&f.queuedRequests.length===0){f.queuedRequests.push(function(){he(t,r,n,i,a)})}else if(m==="all"){f.queuedRequests.push(function(){he(t,r,n,i,a)})}else if(m==="last"){f.queuedRequests=[];f.queuedRequests.push(function(){he(t,r,n,i,a)})}ie(o);return l}}var b=new XMLHttpRequest;f.xhr=b;f.abortable=x;var w=function(){f.xhr=null;f.abortable=false;if(f.queuedRequests!=null&&f.queuedRequests.length>0){var e=f.queuedRequests.shift();e()}};var j=ne(n,"hx-prompt");if(j){var S=prompt(j);if(S===null||!ce(n,"htmx:prompt",{prompt:S,target:u})){ie(o);w();return l}}if(d&&!e){if(!confirm(d)){ie(o);w();return l}}var E=xr(n,u,S);if(t!=="get"&&!Sr(n)){E["Content-Type"]="application/x-www-form-urlencoded"}if(a.headers){E=le(E,a.headers)}var _=dr(n,t);var C=_.errors;var R=_.values;if(a.values){R=le(R,a.values)}var z=Hr(n);var $=le(R,z);var T=yr($,n);if(Q.config.getCacheBusterParam&&t==="get"){T["org.htmx.cache-buster"]=ee(u,"id")||"true"}if(r==null||r===""){r=re().location.href}var O=Rr(n,"hx-request");var W=ae(n).boosted;var q=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;var H={boosted:W,useUrlParams:q,parameters:T,unfilteredParameters:$,headers:E,target:u,verb:t,errors:C,withCredentials:a.credentials||O.credentials||Q.config.withCredentials,timeout:a.timeout||O.timeout||Q.config.timeout,path:r,triggeringEvent:i};if(!ce(n,"htmx:configRequest",H)){ie(o);w();return l}r=H.path;t=H.verb;E=H.headers;T=H.parameters;C=H.errors;q=H.useUrlParams;if(C&&C.length>0){ce(n,"htmx:validation:halted",H);ie(o);w();return l}var G=r.split("#");var J=G[0];var L=G[1];var A=r;if(q){A=J;var Z=Object.keys(T).length!==0;if(Z){if(A.indexOf("?")<0){A+="?"}else{A+="&"}A+=pr(T);if(L){A+="#"+L}}}if(!kr(n,A,H)){fe(n,"htmx:invalidPath",H);ie(s);return l}b.open(t.toUpperCase(),A,true);b.overrideMimeType("text/html");b.withCredentials=H.withCredentials;b.timeout=H.timeout;if(O.noHeaders){}else{for(var N in E){if(E.hasOwnProperty(N)){var K=E[N];Lr(b,N,K)}}}var I={xhr:b,target:u,requestConfig:H,etc:a,boosted:W,select:X,pathInfo:{requestPath:r,finalRequestPath:A,anchor:L}};b.onload=function(){try{var e=Ir(n);I.pathInfo.responsePath=Ar(b);M(n,I);lr(k,P);ce(n,"htmx:afterRequest",I);ce(n,"htmx:afterOnLoad",I);if(!se(n)){var t=null;while(e.length>0&&t==null){var r=e.shift();if(se(r)){t=r}}if(t){ce(t,"htmx:afterRequest",I);ce(t,"htmx:afterOnLoad",I)}}ie(o);w()}catch(e){fe(n,"htmx:onLoadError",le({error:e},I));throw e}};b.onerror=function(){lr(k,P);fe(n,"htmx:afterRequest",I);fe(n,"htmx:sendError",I);ie(s);w()};b.onabort=function(){lr(k,P);fe(n,"htmx:afterRequest",I);fe(n,"htmx:sendAbort",I);ie(s);w()};b.ontimeout=function(){lr(k,P);fe(n,"htmx:afterRequest",I);fe(n,"htmx:timeout",I);ie(s);w()};if(!ce(n,"htmx:beforeRequest",I)){ie(o);w();return l}var k=or(n);var P=sr(n);oe(["loadstart","loadend","progress","abort"],function(t){oe([b,b.upload],function(e){e.addEventListener(t,function(e){ce(n,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ce(n,"htmx:beforeSend",I);var Y=q?null:Er(b,n,T);b.send(Y);return l}function Pr(e,t){var r=t.xhr;var n=null;var i=null;if(O(r,/HX-Push:/i)){n=r.getResponseHeader("HX-Push");i="push"}else if(O(r,/HX-Push-Url:/i)){n=r.getResponseHeader("HX-Push-Url");i="push"}else if(O(r,/HX-Replace-Url:/i)){n=r.getResponseHeader("HX-Replace-Url");i="replace"}if(n){if(n==="false"){return{}}else{return{type:i,path:n}}}var a=t.pathInfo.finalRequestPath;var o=t.pathInfo.responsePath;var s=ne(e,"hx-push-url");var l=ne(e,"hx-replace-url");var u=ae(e).boosted;var f=null;var c=null;if(s){f="push";c=s}else if(l){f="replace";c=l}else if(u){f="push";c=o||a}if(c){if(c==="false"){return{}}if(c==="true"){c=o||a}if(t.pathInfo.anchor&&c.indexOf("#")===-1){c=c+"#"+t.pathInfo.anchor}return{type:f,path:c}}else{return{}}}function Mr(l,u){var f=u.xhr;var c=u.target;var e=u.etc;var t=u.requestConfig;var h=u.select;if(!ce(l,"htmx:beforeOnLoad",u))return;if(O(f,/HX-Trigger:/i)){_e(f,"HX-Trigger",l)}if(O(f,/HX-Location:/i)){er();var r=f.getResponseHeader("HX-Location");var v;if(r.indexOf("{")===0){v=E(r);r=v["path"];delete v["path"]}Nr("GET",r,v).then(function(){tr(r)});return}var n=O(f,/HX-Refresh:/i)&&"true"===f.getResponseHeader("HX-Refresh");if(O(f,/HX-Redirect:/i)){location.href=f.getResponseHeader("HX-Redirect");n&&location.reload();return}if(n){location.reload();return}if(O(f,/HX-Retarget:/i)){if(f.getResponseHeader("HX-Retarget")==="this"){u.target=l}else{u.target=ue(l,f.getResponseHeader("HX-Retarget"))}}var d=Pr(l,u);var i=f.status>=200&&f.status<400&&f.status!==204;var g=f.response;var a=f.status>=400;var p=Q.config.ignoreTitle;var o=le({shouldSwap:i,serverResponse:g,isError:a,ignoreTitle:p},u);if(!ce(c,"htmx:beforeSwap",o))return;c=o.target;g=o.serverResponse;a=o.isError;p=o.ignoreTitle;u.target=c;u.failed=a;u.successful=!a;if(o.shouldSwap){if(f.status===286){at(l)}R(l,function(e){g=e.transformResponse(g,f,l)});if(d.type){er()}var s=e.swapOverride;if(O(f,/HX-Reswap:/i)){s=f.getResponseHeader("HX-Reswap")}var v=wr(l,s);if(v.hasOwnProperty("ignoreTitle")){p=v.ignoreTitle}c.classList.add(Q.config.swappingClass);var m=null;var x=null;var y=function(){try{var e=document.activeElement;var t={};try{t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null}}catch(e){}var r;if(h){r=h}if(O(f,/HX-Reselect:/i)){r=f.getResponseHeader("HX-Reselect")}if(d.type){ce(re().body,"htmx:beforeHistoryUpdate",le({history:d},u));if(d.type==="push"){tr(d.path);ce(re().body,"htmx:pushedIntoHistory",{path:d.path})}else{rr(d.path);ce(re().body,"htmx:replacedInHistory",{path:d.path})}}var n=T(c);je(v.swapStyle,c,l,g,n,r);if(t.elt&&!se(t.elt)&&ee(t.elt,"id")){var i=document.getElementById(ee(t.elt,"id"));var a={preventScroll:v.focusScroll!==undefined?!v.focusScroll:!Q.config.defaultFocusScroll};if(i){if(t.start&&i.setSelectionRange){try{i.setSelectionRange(t.start,t.end)}catch(e){}}i.focus(a)}}c.classList.remove(Q.config.swappingClass);oe(n.elts,function(e){if(e.classList){e.classList.add(Q.config.settlingClass)}ce(e,"htmx:afterSwap",u)});if(O(f,/HX-Trigger-After-Swap:/i)){var o=l;if(!se(l)){o=re().body}_e(f,"HX-Trigger-After-Swap",o)}var s=function(){oe(n.tasks,function(e){e.call()});oe(n.elts,function(e){if(e.classList){e.classList.remove(Q.config.settlingClass)}ce(e,"htmx:afterSettle",u)});if(u.pathInfo.anchor){var e=re().getElementById(u.pathInfo.anchor);if(e){e.scrollIntoView({block:"start",behavior:"auto"})}}if(n.title&&!p){var t=C("title");if(t){t.innerHTML=n.title}else{window.document.title=n.title}}Cr(n.elts,v);if(O(f,/HX-Trigger-After-Settle:/i)){var r=l;if(!se(l)){r=re().body}_e(f,"HX-Trigger-After-Settle",r)}ie(m)};if(v.settleDelay>0){setTimeout(s,v.settleDelay)}else{s()}}catch(e){fe(l,"htmx:swapError",u);ie(x);throw e}};var b=Q.config.globalViewTransitions;if(v.hasOwnProperty("transition")){b=v.transition}if(b&&ce(l,"htmx:beforeTransition",u)&&typeof Promise!=="undefined"&&document.startViewTransition){var w=new Promise(function(e,t){m=e;x=t});var S=y;y=function(){document.startViewTransition(function(){S();return w})}}if(v.swapDelay>0){setTimeout(y,v.swapDelay)}else{y()}}if(a){fe(l,"htmx:responseError",le({error:"Response Status Error Code "+f.status+" from "+u.pathInfo.requestPath},u))}}var Xr={};function Dr(){return{init:function(e){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,r){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,r,n){return false},encodeParameters:function(e,t,r){return null}}}function Ur(e,t){if(t.init){t.init(r)}Xr[e]=le(Dr(),t)}function Br(e){delete Xr[e]}function Fr(e,r,n){if(e==undefined){return r}if(r==undefined){r=[]}if(n==undefined){n=[]}var t=te(e,"hx-ext");if(t){oe(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){n.push(e.slice(7));return}if(n.indexOf(e)<0){var t=Xr[e];if(t&&r.indexOf(t)<0){r.push(t)}}})}return Fr(u(e),r,n)}var Vr=false;re().addEventListener("DOMContentLoaded",function(){Vr=true});function jr(e){if(Vr||re().readyState==="complete"){e()}else{re().addEventListener("DOMContentLoaded",e)}}function _r(){if(Q.config.includeIndicatorStyles!==false){re().head.insertAdjacentHTML("beforeend","")}}function zr(){var e=re().querySelector('meta[name="htmx-config"]');if(e){return E(e.content)}else{return null}}function $r(){var e=zr();if(e){Q.config=le(Q.config,e)}}jr(function(){$r();_r();var e=re().body;zt(e);var t=re().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){var t=e.target;var r=ae(t);if(r&&r.xhr){r.xhr.abort()}});const r=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){ar();oe(t,function(e){ce(e,"htmx:restored",{document:re(),triggerEvent:ce})})}else{if(r){r(e)}}};setTimeout(function(){ce(e,"htmx:load",{});e=null},0)});return Q}()});
\ No newline at end of file
diff --git a/basxbread/utils/urls.py b/basxbread/utils/urls.py
index 333ae63c..4cc66ca9 100644
--- a/basxbread/utils/urls.py
+++ b/basxbread/utils/urls.py
@@ -6,8 +6,10 @@
from typing import Optional
import htmlgenerator as hg
+from django.apps import apps
from django.conf import settings
from django.contrib.auth.decorators import user_passes_test
+from django.contrib.contenttypes.fields import GenericForeignKey
from django.db import models
from django.http import HttpResponse
from django.urls import path as djangopath
@@ -15,8 +17,10 @@
from django.utils.functional import Promise
from django.utils.http import urlencode
from django.utils.text import format_lazy
+from djangoql.exceptions import DjangoQLParserError
+from guardian.shortcuts import get_objects_for_user
-from .model_helpers import get_concrete_instance
+from .model_helpers import get_concrete_instance, permissionname
def reverse(*args, query: Optional[dict] = None, **kwargs):
@@ -38,7 +42,12 @@ def reverse(*args, query: Optional[dict] = None, **kwargs):
def model_urlname(model, action):
"""Generates a canonical url for a certain action/view on a model"""
- return f"{model._meta.label_lower}.{action}"
+ if isinstance(model, str):
+ modelname = model.lower()
+ else:
+ modelname = model._meta.label_lower
+
+ return f"{modelname}.{action}"
def reverse_model(model, action, *args, **kwargs):
@@ -324,6 +333,158 @@ def default_model_paths(
return ret
+def quicksearch_url(model):
+ return model_urlname(model, "quicksearch")
+
+
+def quicksearch_fk_url(model, field):
+ return model_urlname(model, f"quicksearch-{field}")
+
+
+def quicksearch_fk(
+ model,
+ field,
+ limit=20,
+ order_by=[],
+ result_fields=None,
+ search_fields=None,
+ formatter=None,
+):
+ if isinstance(model, str):
+ model = apps.get_model(*model.split("."))
+ f = model._meta.get_field(field)
+
+ return quicksearch(
+ f.related_model.objects.filter(f.get_limit_choices_to()),
+ limit=limit,
+ order_by=order_by,
+ result_fields=result_fields,
+ search_fields=search_fields,
+ formatter=formatter,
+ url=quicksearch_fk_url(model, field),
+ )
+
+
+def quicksearch(
+ model,
+ filter=None,
+ limit=20,
+ order_by=[],
+ result_fields=None,
+ search_fields=None,
+ formatter=None,
+ url=None,
+):
+ from .. import layout
+
+ if isinstance(model, str):
+ model = apps.get_model(*model.split("."))
+ baseqs = model.objects.all()
+ elif isinstance(model, models.QuerySet):
+ baseqs = model
+ model = model.model
+ else:
+ baseqs = model.objects.all()
+
+ if search_fields is None:
+ search_fields = [f.name for f in model._meta.get_fields()]
+
+ def view(request):
+ _limit = limit
+ _order_by = order_by
+ _result_fields = None
+ _search_fields = search_fields
+
+ query = request.GET.get("query", "")
+ if request.GET.get("limit", "").isdigit():
+ _limit = min(int(request.GET["limit"]), limit)
+ if request.GET.get("order_by") is not None:
+ _order_by = request.GET["order_by"].split(",")
+ if request.GET.get("search_fields") is not None:
+ _search_fields = request.GET["search_fields"].split(",")
+ if request.GET.get("result_fields") is not None:
+ _result_fields = request.GET["result_fields"].split(",")
+
+ result = baseqs
+
+ if len(query) > 0:
+ q = models.Q()
+ for fieldname in _search_fields:
+ field = model._meta.get_field(fieldname.split("__", 1)[0])
+ if (
+ field.is_relation
+ and field.related_model is not None
+ and field.related_model != model
+ and "__" not in fieldname
+ ):
+ for subfield in field.related_model._meta.get_fields():
+ # span max 1 relationship
+ if not subfield.is_relation and not isinstance(
+ subfield, GenericForeignKey
+ ):
+ q |= models.Q(
+ **{f"{fieldname}__{subfield.name}__icontains": query}
+ )
+ elif isinstance(field, GenericForeignKey):
+ q |= models.Q(**{f"{fieldname}__icontains": query})
+ else:
+ q |= models.Q(**{f"{fieldname}__icontains": query})
+ result = result.filter(q)
+ else:
+ result = result.none()
+ result = get_objects_for_user(
+ request.user,
+ permissionname(result.model, "view"),
+ result,
+ with_superuser=True,
+ )
+
+ if len(_order_by) > 0:
+ result = result.order_by(*_order_by)
+
+ def format(c):
+ # query-supplied fields have 1st priority
+ if _result_fields is not None:
+ return ", ".join(
+ str(getattr(c["i"], field)) for field in _result_fields
+ )
+ # format_string from server-side has 2nd priority
+ if formatter is not None:
+ return formatter(c["i"])
+
+ # result_fields from server-side has 3rd priority
+ if result_fields is not None:
+ return ", ".join(str(getattr(c["i"], field)) for field in result_fields)
+
+ return c["i"]
+
+ return layout.render(
+ request,
+ hg.BaseElement(
+ hg.STYLE(
+ ".result-item { padding: 4px; cursor: pointer } .result-item:hover { background-color: #e5e5e5; } .result-list { list-style: none; padding: 4px; }"
+ ),
+ hg.UL(
+ hg.Iterator(
+ result[:_limit],
+ "i",
+ hg.LI(
+ hg.F(format),
+ _class="result-item",
+ value=hg.C("i").pk,
+ ),
+ ),
+ _class="result-list",
+ ),
+ ),
+ )
+
+ return autopath(
+ view,
+ url or quicksearch_url(model),
+ )
+
+
# Helpers for the autopath function
class slug:
pass