Debian Codegraph @

www/public/src/htmx.js

raw symbols SCIP
1 var htmx = (function() {
2 'use strict'
3
4 // Public API
5 const htmx = {
6 // Tsc madness here, assigning the functions directly results in an invalid TypeScript output, but reassigning is fine
7 /* Event processing */
8 /** @type {typeof onLoadHelper} */
9 onLoad: null,
10 /** @type {typeof processNode} */
11 process: null,
12 /** @type {typeof addEventListenerImpl} */
13 on: null,
14 /** @type {typeof removeEventListenerImpl} */
15 off: null,
16 /** @type {typeof triggerEvent} */
17 trigger: null,
18 /** @type {typeof ajaxHelper} */
19 ajax: null,
20 /* DOM querying helpers */
21 /** @type {typeof find} */
22 find: null,
23 /** @type {typeof findAll} */
24 findAll: null,
25 /** @type {typeof closest} */
26 closest: null,
27 /**
28 * Returns the input values that would resolve for a given element via the htmx value resolution mechanism
29 *
30 * @see https://htmx.org/api/#values
31 *
32 * @param {Element} elt the element to resolve values on
33 * @param {HttpVerb} type the request type (e.g. **get** or **post**) non-GET's will include the enclosing form of the element. Defaults to **post**
34 * @returns {Object}
35 */
36 values: function(elt, type) {
37 const inputValues = getInputValues(elt, type || 'post')
38 return inputValues.values
39 },
40 /* DOM manipulation helpers */
41 /** @type {typeof removeElement} */
42 remove: null,
43 /** @type {typeof addClassToElement} */
44 addClass: null,
45 /** @type {typeof removeClassFromElement} */
46 removeClass: null,
47 /** @type {typeof toggleClassOnElement} */
48 toggleClass: null,
49 /** @type {typeof takeClassForElement} */
50 takeClass: null,
51 /** @type {typeof swap} */
52 swap: null,
53 /* Extension entrypoints */
54 /** @type {typeof defineExtension} */
55 defineExtension: null,
56 /** @type {typeof removeExtension} */
57 removeExtension: null,
58 /* Debugging */
59 /** @type {typeof logAll} */
60 logAll: null,
61 /** @type {typeof logNone} */
62 logNone: null,
63 /* Debugging */
64 /**
65 * The logger htmx uses to log with
66 *
67 * @see https://htmx.org/api/#logger
68 */
69 logger: null,
70 /**
71 * A property holding the configuration htmx uses at runtime.
72 *
73 * Note that using a [meta tag](https://htmx.org/docs/#config) is the preferred mechanism for setting these properties.
74 *
75 * @see https://htmx.org/api/#config
76 */
77 config: {
78 /**
79 * Whether to use history.
80 * @type boolean
81 * @default true
82 */
83 historyEnabled: true,
84 /**
85 * The number of pages to keep in **sessionStorage** for history support.
86 * @type number
87 * @default 10
88 */
89 historyCacheSize: 10,
90 /**
91 * @type boolean
92 * @default false
93 */
94 refreshOnHistoryMiss: false,
95 /**
96 * The default swap style to use if **[hx-swap](https://htmx.org/attributes/hx-swap)** is omitted.
97 * @type HtmxSwapStyle
98 * @default 'innerHTML'
99 */
100 defaultSwapStyle: 'innerHTML',
101 /**
102 * The default delay between receiving a response from the server and doing the swap.
103 * @type number
104 * @default 0
105 */
106 defaultSwapDelay: 0,
107 /**
108 * The default delay between completing the content swap and settling attributes.
109 * @type number
110 * @default 20
111 */
112 defaultSettleDelay: 20,
113 /**
114 * If true, htmx will inject a small amount of CSS into the page to make indicators invisible unless the **htmx-indicator** class is present.
115 * @type boolean
116 * @default true
117 */
118 includeIndicatorStyles: true,
119 /**
120 * The class to place on indicators when a request is in flight.
121 * @type string
122 * @default 'htmx-indicator'
123 */
124 indicatorClass: 'htmx-indicator',
125 /**
126 * The class to place on triggering elements when a request is in flight.
127 * @type string
128 * @default 'htmx-request'
129 */
130 requestClass: 'htmx-request',
131 /**
132 * The class to temporarily place on elements that htmx has added to the DOM.
133 * @type string
134 * @default 'htmx-added'
135 */
136 addedClass: 'htmx-added',
137 /**
138 * The class to place on target elements when htmx is in the settling phase.
139 * @type string
140 * @default 'htmx-settling'
141 */
142 settlingClass: 'htmx-settling',
143 /**
144 * The class to place on target elements when htmx is in the swapping phase.
145 * @type string
146 * @default 'htmx-swapping'
147 */
148 swappingClass: 'htmx-swapping',
149 /**
150 * Allows the use of eval-like functionality in htmx, to enable **hx-vars**, trigger conditions & script tag evaluation. Can be set to **false** for CSP compatibility.
151 * @type boolean
152 * @default true
153 */
154 allowEval: true,
155 /**
156 * If set to false, disables the interpretation of script tags.
157 * @type boolean
158 * @default true
159 */
160 allowScriptTags: true,
161 /**
162 * If set, the nonce will be added to inline scripts.
163 * @type string
164 * @default ''
165 */
166 inlineScriptNonce: '',
167 /**
168 * If set, the nonce will be added to inline styles.
169 * @type string
170 * @default ''
171 */
172 inlineStyleNonce: '',
173 /**
174 * The attributes to settle during the settling phase.
175 * @type string[]
176 * @default ['class', 'style', 'width', 'height']
177 */
178 attributesToSettle: ['class', 'style', 'width', 'height'],
179 /**
180 * Allow cross-site Access-Control requests using credentials such as cookies, authorization headers or TLS client certificates.
181 * @type boolean
182 * @default false
183 */
184 withCredentials: false,
185 /**
186 * @type number
187 * @default 0
188 */
189 timeout: 0,
190 /**
191 * The default implementation of **getWebSocketReconnectDelay** for reconnecting after unexpected connection loss by the event code **Abnormal Closure**, **Service Restart** or **Try Again Later**.
192 * @type {'full-jitter' | ((retryCount:number) => number)}
193 * @default "full-jitter"
194 */
195 wsReconnectDelay: 'full-jitter',
196 /**
197 * The type of binary data being received over the WebSocket connection
198 * @type BinaryType
199 * @default 'blob'
200 */
201 wsBinaryType: 'blob',
202 /**
203 * @type string
204 * @default '[hx-disable], [data-hx-disable]'
205 */
206 disableSelector: '[hx-disable], [data-hx-disable]',
207 /**
208 * @type {'auto' | 'instant' | 'smooth'}
209 * @default 'instant'
210 */
211 scrollBehavior: 'instant',
212 /**
213 * If the focused element should be scrolled into view.
214 * @type boolean
215 * @default false
216 */
217 defaultFocusScroll: false,
218 /**
219 * If set to true htmx will include a cache-busting parameter in GET requests to avoid caching partial responses by the browser
220 * @type boolean
221 * @default false
222 */
223 getCacheBusterParam: false,
224 /**
225 * If set to true, htmx will use the View Transition API when swapping in new content.
226 * @type boolean
227 * @default false
228 */
229 globalViewTransitions: false,
230 /**
231 * htmx will format requests with these methods by encoding their parameters in the URL, not the request body
232 * @type {(HttpVerb)[]}
233 * @default ['get', 'delete']
234 */
235 methodsThatUseUrlParams: ['get', 'delete'],
236 /**
237 * If set to true, disables htmx-based requests to non-origin hosts.
238 * @type boolean
239 * @default false
240 */
241 selfRequestsOnly: true,
242 /**
243 * If set to true htmx will not update the title of the document when a title tag is found in new content
244 * @type boolean
245 * @default false
246 */
247 ignoreTitle: false,
248 /**
249 * Whether the target of a boosted element is scrolled into the viewport.
250 * @type boolean
251 * @default true
252 */
253 scrollIntoViewOnBoost: true,
254 /**
255 * The cache to store evaluated trigger specifications into.
256 * You may define a simple object to use a never-clearing cache, or implement your own system using a [proxy object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy)
257 * @type {Object|null}
258 * @default null
259 */
260 triggerSpecsCache: null,
261 /** @type boolean */
262 disableInheritance: false,
263 /** @type HtmxResponseHandlingConfig[] */
264 responseHandling: [
265 { code: '204', swap: false },
266 { code: '[23]..', swap: true },
267 { code: '[45]..', swap: false, error: true }
268 ],
269 /**
270 * Whether to process OOB swaps on elements that are nested within the main response element.
271 * @type boolean
272 * @default true
273 */
274 allowNestedOobSwaps: true,
275 /**
276 * Whether to treat history cache miss full page reload requests as a "HX-Request" by returning this response header
277 * This should always be disabled when using HX-Request header to optionally return partial responses
278 * @type boolean
279 * @default true
280 */
281 historyRestoreAsHxRequest: true,
282 /**
283 * Whether to report input validation errors to the end user and update focus to the first input that fails validation.
284 * This should always be enabled as this matches default browser form submit behaviour
285 * @type boolean
286 * @default false
287 */
288 reportValidityOfForms: false
289 },
290 /** @type {typeof parseInterval} */
291 parseInterval: null,
292 /**
293 * proxy of window.location used for page reload functions
294 * @type location
295 */
296 location,
297 /** @type {typeof internalEval} */
298 _: null,
299 version: '2.0.8'
300 }
301 // Tsc madness part 2
302 htmx.onLoad = onLoadHelper
303 htmx.process = processNode
304 htmx.on = addEventListenerImpl
305 htmx.off = removeEventListenerImpl
306 htmx.trigger = triggerEvent
307 htmx.ajax = ajaxHelper
308 htmx.find = find
309 htmx.findAll = findAll
310 htmx.closest = closest
311 htmx.remove = removeElement
312 htmx.addClass = addClassToElement
313 htmx.removeClass = removeClassFromElement
314 htmx.toggleClass = toggleClassOnElement
315 htmx.takeClass = takeClassForElement
316 htmx.swap = swap
317 htmx.defineExtension = defineExtension
318 htmx.removeExtension = removeExtension
319 htmx.logAll = logAll
320 htmx.logNone = logNone
321 htmx.parseInterval = parseInterval
322 htmx._ = internalEval
323
324 const internalAPI = {
325 addTriggerHandler,
326 bodyContains,
327 canAccessLocalStorage,
328 findThisElement,
329 filterValues,
330 swap,
331 hasAttribute,
332 getAttributeValue,
333 getClosestAttributeValue,
334 getClosestMatch,
335 getExpressionVars,
336 getHeaders,
337 getInputValues,
338 getInternalData,
339 getSwapSpecification,
340 getTriggerSpecs,
341 getTarget,
342 makeFragment,
343 mergeObjects,
344 makeSettleInfo,
345 oobSwap,
346 querySelectorExt,
347 settleImmediately,
348 shouldCancel,
349 triggerEvent,
350 triggerErrorEvent,
351 withExtensions
352 }
353
354 const VERBS = ['get', 'post', 'put', 'delete', 'patch']
355 const VERB_SELECTOR = VERBS.map(function(verb) {
356 return '[hx-' + verb + '], [data-hx-' + verb + ']'
357 }).join(', ')
358
359 //= ===================================================================
360 // Utilities
361 //= ===================================================================
362
363 /**
364 * Parses an interval string consistent with the way htmx does. Useful for plugins that have timing-related attributes.
365 *
366 * Caution: Accepts an int followed by either **s** or **ms**. All other values use **parseFloat**
367 *
368 * @see https://htmx.org/api/#parseInterval
369 *
370 * @param {string} str timing string
371 * @returns {number|undefined}
372 */
373 function parseInterval(str) {
374 if (str == undefined) {
375 return undefined
376 }
377
378 let interval = NaN
379 if (str.slice(-2) == 'ms') {
380 interval = parseFloat(str.slice(0, -2))
381 } else if (str.slice(-1) == 's') {
382 interval = parseFloat(str.slice(0, -1)) * 1000
383 } else if (str.slice(-1) == 'm') {
384 interval = parseFloat(str.slice(0, -1)) * 1000 * 60
385 } else {
386 interval = parseFloat(str)
387 }
388 return isNaN(interval) ? undefined : interval
389 }
390
391 /**
392 * @param {Node} elt
393 * @param {string} name
394 * @returns {(string | null)}
395 */
396 function getRawAttribute(elt, name) {
397 return elt instanceof Element && elt.getAttribute(name)
398 }
399
400 /**
401 * @param {Element} elt
402 * @param {string} qualifiedName
403 * @returns {boolean}
404 */
405 // resolve with both hx and data-hx prefixes
406 function hasAttribute(elt, qualifiedName) {
407 return !!elt.hasAttribute && (elt.hasAttribute(qualifiedName) ||
408 elt.hasAttribute('data-' + qualifiedName))
409 }
410
411 /**
412 *
413 * @param {Node} elt
414 * @param {string} qualifiedName
415 * @returns {(string | null)}
416 */
417 function getAttributeValue(elt, qualifiedName) {
418 return getRawAttribute(elt, qualifiedName) || getRawAttribute(elt, 'data-' + qualifiedName)
419 }
420
421 /**
422 * @param {Node} elt
423 * @returns {Node | null}
424 */
425 function parentElt(elt) {
426 const parent = elt.parentElement
427 if (!parent && elt.parentNode instanceof ShadowRoot) return elt.parentNode
428 return parent
429 }
430
431 /**
432 * @returns {Document}
433 */
434 function getDocument() {
435 return document
436 }
437
438 /**
439 * @param {Node} elt
440 * @param {boolean} global
441 * @returns {Node|Document}
442 */
443 function getRootNode(elt, global) {
444 return elt.getRootNode ? elt.getRootNode({ composed: global }) : getDocument()
445 }
446
447 /**
448 * @param {Node} elt
449 * @param {(e:Node) => boolean} condition
450 * @returns {Node | null}
451 */
452 function getClosestMatch(elt, condition) {
453 while (elt && !condition(elt)) {
454 elt = parentElt(elt)
455 }
456
457 return elt || null
458 }
459
460 /**
461 * @param {Element} initialElement
462 * @param {Element} ancestor
463 * @param {string} attributeName
464 * @returns {string|null}
465 */
466 function getAttributeValueWithDisinheritance(initialElement, ancestor, attributeName) {
467 const attributeValue = getAttributeValue(ancestor, attributeName)
468 const disinherit = getAttributeValue(ancestor, 'hx-disinherit')
469 var inherit = getAttributeValue(ancestor, 'hx-inherit')
470 if (initialElement !== ancestor) {
471 if (htmx.config.disableInheritance) {
472 if (inherit && (inherit === '*' || inherit.split(' ').indexOf(attributeName) >= 0)) {
473 return attributeValue
474 } else {
475 return null
476 }
477 }
478 if (disinherit && (disinherit === '*' || disinherit.split(' ').indexOf(attributeName) >= 0)) {
479 return 'unset'
480 }
481 }
482 return attributeValue
483 }
484
485 /**
486 * @param {Element} elt
487 * @param {string} attributeName
488 * @returns {string | null}
489 */
490 function getClosestAttributeValue(elt, attributeName) {
491 let closestAttr = null
492 getClosestMatch(elt, function(e) {
493 return !!(closestAttr = getAttributeValueWithDisinheritance(elt, asElement(e), attributeName))
494 })
495 if (closestAttr !== 'unset') {
496 return closestAttr
497 }
498 }
499
500 /**
501 * @param {Node} elt
502 * @param {string} selector
503 * @returns {boolean}
504 */
505 function matches(elt, selector) {
506 return elt instanceof Element && elt.matches(selector)
507 }
508
509 /**
510 * @param {string} str
511 * @returns {string}
512 */
513 function getStartTag(str) {
514 const tagMatcher = /<([a-z][^\/\0>\x20\t\r\n\f]*)/i
515 const match = tagMatcher.exec(str)
516 if (match) {
517 return match[1].toLowerCase()
518 } else {
519 return ''
520 }
521 }
522
523 /**
524 * @param {string} resp
525 * @returns {Document}
526 */
527 function parseHTML(resp) {
528 if ('parseHTMLUnsafe' in Document) {
529 return Document.parseHTMLUnsafe(resp)
530 }
531 const parser = new DOMParser()
532 return parser.parseFromString(resp, 'text/html')
533 }
534
535 /**
536 * @param {DocumentFragment} fragment
537 * @param {Node} elt
538 */
539 function takeChildrenFor(fragment, elt) {
540 while (elt.childNodes.length > 0) {
541 fragment.append(elt.childNodes[0])
542 }
543 }
544
545 /**
546 * @param {HTMLScriptElement} script
547 * @returns {HTMLScriptElement}
548 */
549 function duplicateScript(script) {
550 const newScript = getDocument().createElement('script')
551 forEach(script.attributes, function(attr) {
552 newScript.setAttribute(attr.name, attr.value)
553 })
554 newScript.textContent = script.textContent
555 newScript.async = false
556 if (htmx.config.inlineScriptNonce) {
557 newScript.nonce = htmx.config.inlineScriptNonce
558 }
559 return newScript
560 }
561
562 /**
563 * @param {HTMLScriptElement} script
564 * @returns {boolean}
565 */
566 function isJavaScriptScriptNode(script) {
567 return script.matches('script') && (script.type === 'text/javascript' || script.type === 'module' || script.type === '')
568 }
569
570 /**
571 * we have to make new copies of script tags that we are going to insert because
572 * SOME browsers (not saying who, but it involves an element and an animal) don't
573 * execute scripts created in <template> tags when they are inserted into the DOM
574 * and all the others do lmao
575 * @param {DocumentFragment} fragment
576 */
577 function normalizeScriptTags(fragment) {
578 Array.from(fragment.querySelectorAll('script')).forEach(/** @param {HTMLScriptElement} script */ (script) => {
579 if (isJavaScriptScriptNode(script)) {
580 const newScript = duplicateScript(script)
581 const parent = script.parentNode
582 try {
583 parent.insertBefore(newScript, script)
584 } catch (e) {
585 logError(e)
586 } finally {
587 script.remove()
588 }
589 }
590 })
591 }
592
593 /**
594 * @typedef {DocumentFragment & {title?: string}} DocumentFragmentWithTitle
595 * @description a document fragment representing the response HTML, including
596 * a `title` property for any title information found
597 */
598
599 /**
600 * @param {string} response HTML
601 * @returns {DocumentFragmentWithTitle}
602 */
603 function makeFragment(response) {
604 // strip head tag to determine shape of response we are dealing with
605 const responseWithNoHead = response.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i, '')
606 const startTag = getStartTag(responseWithNoHead)
607 /** @type DocumentFragmentWithTitle */
608 let fragment
609 if (startTag === 'html') {
610 // if it is a full document, parse it and return the body
611 fragment = /** @type DocumentFragmentWithTitle */ (new DocumentFragment())
612 const doc = parseHTML(response)
613 takeChildrenFor(fragment, doc.body)
614 fragment.title = doc.title
615 } else if (startTag === 'body') {
616 // parse body w/o wrapping in template
617 fragment = /** @type DocumentFragmentWithTitle */ (new DocumentFragment())
618 const doc = parseHTML(responseWithNoHead)
619 takeChildrenFor(fragment, doc.body)
620 fragment.title = doc.title
621 } else {
622 // otherwise we have non-body partial HTML content, so wrap it in a template to maximize parsing flexibility
623 const doc = parseHTML('<body><template class="internal-htmx-wrapper">' + responseWithNoHead + '</template></body>')
624 fragment = /** @type DocumentFragmentWithTitle */ (doc.querySelector('template').content)
625 // extract title into fragment for later processing
626 fragment.title = doc.title
627
628 // for legacy reasons we support a title tag at the root level of non-body responses, so we need to handle it
629 var titleElement = fragment.querySelector('title')
630 if (titleElement && titleElement.parentNode === fragment) {
631 titleElement.remove()
632 fragment.title = titleElement.innerText
633 }
634 }
635 if (fragment) {
636 if (htmx.config.allowScriptTags) {
637 normalizeScriptTags(fragment)
638 } else {
639 // remove all script tags if scripts are disabled
640 fragment.querySelectorAll('script').forEach((script) => script.remove())
641 }
642 }
643 return fragment
644 }
645
646 /**
647 * @param {Function} func
648 */
649 function maybeCall(func) {
650 if (func) {
651 func()
652 }
653 }
654
655 /**
656 * @param {any} o
657 * @param {string} type
658 * @returns
659 */
660 function isType(o, type) {
661 return Object.prototype.toString.call(o) === '[object ' + type + ']'
662 }
663
664 /**
665 * @param {*} o
666 * @returns {o is Function}
667 */
668 function isFunction(o) {
669 return typeof o === 'function'
670 }
671
672 /**
673 * @param {*} o
674 * @returns {o is Object}
675 */
676 function isRawObject(o) {
677 return isType(o, 'Object')
678 }
679
680 /**
681 * @typedef {Object} OnHandler
682 * @property {(keyof HTMLElementEventMap)|string} event
683 * @property {EventListener} listener
684 */
685
686 /**
687 * @typedef {Object} ListenerInfo
688 * @property {string} trigger
689 * @property {EventListener} listener
690 * @property {EventTarget} on
691 */
692
693 /**
694 * @typedef {Object} HtmxNodeInternalData
695 * Element data
696 * @property {number} [initHash]
697 * @property {boolean} [boosted]
698 * @property {OnHandler[]} [onHandlers]
699 * @property {number} [timeout]
700 * @property {ListenerInfo[]} [listenerInfos]
701 * @property {boolean} [cancelled]
702 * @property {boolean} [triggeredOnce]
703 * @property {number} [delayed]
704 * @property {number|null} [throttle]
705 * @property {WeakMap<HtmxTriggerSpecification,WeakMap<EventTarget,string>>} [lastValue]
706 * @property {boolean} [loaded]
707 * @property {string} [path]
708 * @property {string} [verb]
709 * @property {boolean} [polling]
710 * @property {HTMLButtonElement|HTMLInputElement|null} [lastButtonClicked]
711 * @property {number} [requestCount]
712 * @property {XMLHttpRequest} [xhr]
713 * @property {(() => void)[]} [queuedRequests]
714 * @property {boolean} [abortable]
715 * @property {boolean} [firstInitCompleted]
716 *
717 * Event data
718 * @property {HtmxTriggerSpecification} [triggerSpec]
719 * @property {EventTarget[]} [handledFor]
720 */
721
722 /**
723 * getInternalData retrieves "private" data stored by htmx within an element
724 * @param {EventTarget|Event} elt
725 * @returns {HtmxNodeInternalData}
726 */
727 function getInternalData(elt) {
728 const dataProp = 'htmx-internal-data'
729 let data = elt[dataProp]
730 if (!data) {
731 data = elt[dataProp] = {}
732 }
733 return data
734 }
735
736 /**
737 * toArray converts an ArrayLike object into a real array.
738 * @template T
739 * @param {ArrayLike<T>} arr
740 * @returns {T[]}
741 */
742 function toArray(arr) {
743 const returnArr = []
744 if (arr) {
745 for (let i = 0; i < arr.length; i++) {
746 returnArr.push(arr[i])
747 }
748 }
749 return returnArr
750 }
751
752 /**
753 * @template T
754 * @param {T[]|NamedNodeMap|HTMLCollection|HTMLFormControlsCollection|ArrayLike<T>} arr
755 * @param {(T) => void} func
756 */
757 function forEach(arr, func) {
758 if (arr) {
759 for (let i = 0; i < arr.length; i++) {
760 func(arr[i])
761 }
762 }
763 }
764
765 /**
766 * @param {Element} el
767 * @returns {boolean}
768 */
769 function isScrolledIntoView(el) {
770 const rect = el.getBoundingClientRect()
771 const elemTop = rect.top
772 const elemBottom = rect.bottom
773 return elemTop < window.innerHeight && elemBottom >= 0
774 }
775
776 /**
777 * Checks whether the element is in the document (includes shadow roots).
778 * This function this is a slight misnomer; it will return true even for elements in the head.
779 *
780 * @param {Node} elt
781 * @returns {boolean}
782 */
783 function bodyContains(elt) {
784 return elt.getRootNode({ composed: true }) === document
785 }
786
787 /**
788 * @param {string} trigger
789 * @returns {string[]}
790 */
791 function splitOnWhitespace(trigger) {
792 return trigger.trim().split(/\s+/)
793 }
794
795 /**
796 * mergeObjects takes all the keys from
797 * obj2 and duplicates them into obj1
798 * @template T1
799 * @template T2
800 * @param {T1} obj1
801 * @param {T2} obj2
802 * @returns {T1 & T2}
803 */
804 function mergeObjects(obj1, obj2) {
805 for (const key in obj2) {
806 if (obj2.hasOwnProperty(key)) {
807 // @ts-ignore tsc doesn't seem to properly handle types merging
808 obj1[key] = obj2[key]
809 }
810 }
811 // @ts-ignore tsc doesn't seem to properly handle types merging
812 return obj1
813 }
814
815 /**
816 * @param {string} jString
817 * @returns {any|null}
818 */
819 function parseJSON(jString) {
820 try {
821 return JSON.parse(jString)
822 } catch (error) {
823 logError(error)
824 return null
825 }
826 }
827
828 /**
829 * @returns {boolean}
830 */
831 function canAccessLocalStorage() {
832 const test = 'htmx:sessionStorageTest'
833 try {
834 sessionStorage.setItem(test, test)
835 sessionStorage.removeItem(test)
836 return true
837 } catch (e) {
838 return false
839 }
840 }
841
842 /**
843 * @param {string} path
844 * @returns {string}
845 */
846 function normalizePath(path) {
847 // use dummy base URL to allow normalize on path only
848 const url = new URL(path, 'http://x')
849 if (url) {
850 path = url.pathname + url.search
851 }
852 // remove trailing slash, unless index page
853 if (path != '/') {
854 path = path.replace(/\/+$/, '')
855 }
856 return path
857 }
858
859 //= =========================================================================================
860 // public API
861 //= =========================================================================================
862
863 /**
864 * @param {string} str
865 * @returns {any}
866 */
867 function internalEval(str) {
868 return maybeEval(getDocument().body, function() {
869 return eval(str)
870 })
871 }
872
873 /**
874 * Adds a callback for the **htmx:load** event. This can be used to process new content, for example initializing the content with a javascript library
875 *
876 * @see https://htmx.org/api/#onLoad
877 *
878 * @param {(elt: Node) => void} callback the callback to call on newly loaded content
879 * @returns {EventListener}
880 */
881 function onLoadHelper(callback) {
882 const value = htmx.on('htmx:load', /** @param {CustomEvent} evt */ function(evt) {
883 callback(evt.detail.elt)
884 })
885 return value
886 }
887
888 /**
889 * Log all htmx events, useful for debugging.
890 *
891 * @see https://htmx.org/api/#logAll
892 */
893 function logAll() {
894 htmx.logger = function(elt, event, data) {
895 if (console) {
896 console.log(event, elt, data)
897 }
898 }
899 }
900
901 function logNone() {
902 htmx.logger = null
903 }
904
905 /**
906 * Finds an element matching the selector
907 *
908 * @see https://htmx.org/api/#find
909 *
910 * @param {ParentNode|string} eltOrSelector the root element to find the matching element in, inclusive | the selector to match
911 * @param {string} [selector] the selector to match
912 * @returns {Element|null}
913 */
914 function find(eltOrSelector, selector) {
915 if (typeof eltOrSelector !== 'string') {
916 return eltOrSelector.querySelector(selector)
917 } else {
918 return find(getDocument(), eltOrSelector)
919 }
920 }
921
922 /**
923 * Finds all elements matching the selector
924 *
925 * @see https://htmx.org/api/#findAll
926 *
927 * @param {ParentNode|string} eltOrSelector the root element to find the matching elements in, inclusive | the selector to match
928 * @param {string} [selector] the selector to match
929 * @returns {NodeListOf<Element>}
930 */
931 function findAll(eltOrSelector, selector) {
932 if (typeof eltOrSelector !== 'string') {
933 return eltOrSelector.querySelectorAll(selector)
934 } else {
935 return findAll(getDocument(), eltOrSelector)
936 }
937 }
938
939 /**
940 * @returns Window
941 */
942 function getWindow() {
943 return window
944 }
945
946 /**
947 * Removes an element from the DOM
948 *
949 * @see https://htmx.org/api/#remove
950 *
951 * @param {Node} elt
952 * @param {number} [delay]
953 */
954 function removeElement(elt, delay) {
955 elt = resolveTarget(elt)
956 if (delay) {
957 getWindow().setTimeout(function() {
958 removeElement(elt)
959 elt = null
960 }, delay)
961 } else {
962 parentElt(elt).removeChild(elt)
963 }
964 }
965
966 /**
967 * @param {any} elt
968 * @return {Element|null}
969 */
970 function asElement(elt) {
971 return elt instanceof Element ? elt : null
972 }
973
974 /**
975 * @param {any} elt
976 * @return {HTMLElement|null}
977 */
978 function asHtmlElement(elt) {
979 return elt instanceof HTMLElement ? elt : null
980 }
981
982 /**
983 * @param {any} value
984 * @return {string|null}
985 */
986 function asString(value) {
987 return typeof value === 'string' ? value : null
988 }
989
990 /**
991 * @param {EventTarget} elt
992 * @return {ParentNode|null}
993 */
994 function asParentNode(elt) {
995 return elt instanceof Element || elt instanceof Document || elt instanceof DocumentFragment ? elt : null
996 }
997
998 /**
999 * This method adds a class to the given element.
1000 *
1001 * @see https://htmx.org/api/#addClass
1002 *
1003 * @param {Element|string} elt the element to add the class to
1004 * @param {string} clazz the class to add
1005 * @param {number} [delay] the delay (in milliseconds) before class is added
1006 */
1007 function addClassToElement(elt, clazz, delay) {
1008 elt = asElement(resolveTarget(elt))
1009 if (!elt) {
1010 return
1011 }
1012 if (delay) {
1013 getWindow().setTimeout(function() {
1014 addClassToElement(elt, clazz)
1015 elt = null
1016 }, delay)
1017 } else {
1018 elt.classList && elt.classList.add(clazz)
1019 }
1020 }
1021
1022 /**
1023 * Removes a class from the given element
1024 *
1025 * @see https://htmx.org/api/#removeClass
1026 *
1027 * @param {Node|string} node element to remove the class from
1028 * @param {string} clazz the class to remove
1029 * @param {number} [delay] the delay (in milliseconds before class is removed)
1030 */
1031 function removeClassFromElement(node, clazz, delay) {
1032 let elt = asElement(resolveTarget(node))
1033 if (!elt) {
1034 return
1035 }
1036 if (delay) {
1037 getWindow().setTimeout(function() {
1038 removeClassFromElement(elt, clazz)
1039 elt = null
1040 }, delay)
1041 } else {
1042 if (elt.classList) {
1043 elt.classList.remove(clazz)
1044 // if there are no classes left, remove the class attribute
1045 if (elt.classList.length === 0) {
1046 elt.removeAttribute('class')
1047 }
1048 }
1049 }
1050 }
1051
1052 /**
1053 * Toggles the given class on an element
1054 *
1055 * @see https://htmx.org/api/#toggleClass
1056 *
1057 * @param {Element|string} elt the element to toggle the class on
1058 * @param {string} clazz the class to toggle
1059 */
1060 function toggleClassOnElement(elt, clazz) {
1061 elt = resolveTarget(elt)
1062 elt.classList.toggle(clazz)
1063 }
1064
1065 /**
1066 * Takes the given class from its siblings, so that among its siblings, only the given element will have the class.
1067 *
1068 * @see https://htmx.org/api/#takeClass
1069 *
1070 * @param {Node|string} elt the element that will take the class
1071 * @param {string} clazz the class to take
1072 */
1073 function takeClassForElement(elt, clazz) {
1074 elt = resolveTarget(elt)
1075 forEach(elt.parentElement.children, function(child) {
1076 removeClassFromElement(child, clazz)
1077 })
1078 addClassToElement(asElement(elt), clazz)
1079 }
1080
1081 /**
1082 * Finds the closest matching element in the given elements parentage, inclusive of the element
1083 *
1084 * @see https://htmx.org/api/#closest
1085 *
1086 * @param {Element|string} elt the element to find the selector from
1087 * @param {string} selector the selector to find
1088 * @returns {Element|null}
1089 */
1090 function closest(elt, selector) {
1091 elt = asElement(resolveTarget(elt))
1092 if (elt) {
1093 return elt.closest(selector)
1094 }
1095 return null
1096 }
1097
1098 /**
1099 * @param {string} str
1100 * @param {string} prefix
1101 * @returns {boolean}
1102 */
1103 function startsWith(str, prefix) {
1104 return str.substring(0, prefix.length) === prefix
1105 }
1106
1107 /**
1108 * @param {string} str
1109 * @param {string} suffix
1110 * @returns {boolean}
1111 */
1112 function endsWith(str, suffix) {
1113 return str.substring(str.length - suffix.length) === suffix
1114 }
1115
1116 /**
1117 * @param {string} selector
1118 * @returns {string}
1119 */
1120 function normalizeSelector(selector) {
1121 const trimmedSelector = selector.trim()
1122 if (startsWith(trimmedSelector, '<') && endsWith(trimmedSelector, '/>')) {
1123 return trimmedSelector.substring(1, trimmedSelector.length - 2)
1124 } else {
1125 return trimmedSelector
1126 }
1127 }
1128
1129 /**
1130 * @param {Node|Element|Document|string} elt
1131 * @param {string} selector
1132 * @param {boolean=} global
1133 * @returns {(Node|Window)[]}
1134 */
1135 function querySelectorAllExt(elt, selector, global) {
1136 if (selector.indexOf('global ') === 0) {
1137 return querySelectorAllExt(elt, selector.slice(7), true)
1138 }
1139
1140 elt = resolveTarget(elt)
1141
1142 const parts = []
1143 {
1144 let chevronsCount = 0
1145 let offset = 0
1146 for (let i = 0; i < selector.length; i++) {
1147 const char = selector[i]
1148 if (char === ',' && chevronsCount === 0) {
1149 parts.push(selector.substring(offset, i))
1150 offset = i + 1
1151 continue
1152 }
1153 if (char === '<') {
1154 chevronsCount++
1155 } else if (char === '/' && i < selector.length - 1 && selector[i + 1] === '>') {
1156 chevronsCount--
1157 }
1158 }
1159 if (offset < selector.length) {
1160 parts.push(selector.substring(offset))
1161 }
1162 }
1163
1164 const result = []
1165 const unprocessedParts = []
1166 while (parts.length > 0) {
1167 const selector = normalizeSelector(parts.shift())
1168 let item
1169 if (selector.indexOf('closest ') === 0) {
1170 item = closest(asElement(elt), normalizeSelector(selector.slice(8)))
1171 } else if (selector.indexOf('find ') === 0) {
1172 item = find(asParentNode(elt), normalizeSelector(selector.slice(5)))
1173 } else if (selector === 'next' || selector === 'nextElementSibling') {
1174 item = asElement(elt).nextElementSibling
1175 } else if (selector.indexOf('next ') === 0) {
1176 item = scanForwardQuery(elt, normalizeSelector(selector.slice(5)), !!global)
1177 } else if (selector === 'previous' || selector === 'previousElementSibling') {
1178 item = asElement(elt).previousElementSibling
1179 } else if (selector.indexOf('previous ') === 0) {
1180 item = scanBackwardsQuery(elt, normalizeSelector(selector.slice(9)), !!global)
1181 } else if (selector === 'document') {
1182 item = document
1183 } else if (selector === 'window') {
1184 item = window
1185 } else if (selector === 'body') {
1186 item = document.body
1187 } else if (selector === 'root') {
1188 item = getRootNode(elt, !!global)
1189 } else if (selector === 'host') {
1190 item = (/** @type ShadowRoot */(elt.getRootNode())).host
1191 } else {
1192 unprocessedParts.push(selector)
1193 }
1194
1195 if (item) {
1196 result.push(item)
1197 }
1198 }
1199
1200 if (unprocessedParts.length > 0) {
1201 const standardSelector = unprocessedParts.join(',')
1202 const rootNode = asParentNode(getRootNode(elt, !!global))
1203 result.push(...toArray(rootNode.querySelectorAll(standardSelector)))
1204 }
1205
1206 return result
1207 }
1208
1209 /**
1210 * @param {Node} start
1211 * @param {string} match
1212 * @param {boolean} global
1213 * @returns {Element}
1214 */
1215 var scanForwardQuery = function(start, match, global) {
1216 const results = asParentNode(getRootNode(start, global)).querySelectorAll(match)
1217 for (let i = 0; i < results.length; i++) {
1218 const elt = results[i]
1219 if (elt.compareDocumentPosition(start) === Node.DOCUMENT_POSITION_PRECEDING) {
1220 return elt
1221 }
1222 }
1223 }
1224
1225 /**
1226 * @param {Node} start
1227 * @param {string} match
1228 * @param {boolean} global
1229 * @returns {Element}
1230 */
1231 var scanBackwardsQuery = function(start, match, global) {
1232 const results = asParentNode(getRootNode(start, global)).querySelectorAll(match)
1233 for (let i = results.length - 1; i >= 0; i--) {
1234 const elt = results[i]
1235 if (elt.compareDocumentPosition(start) === Node.DOCUMENT_POSITION_FOLLOWING) {
1236 return elt
1237 }
1238 }
1239 }
1240
1241 /**
1242 * @param {Node|string} eltOrSelector
1243 * @param {string=} selector
1244 * @returns {Node|Window}
1245 */
1246 function querySelectorExt(eltOrSelector, selector) {
1247 if (typeof eltOrSelector !== 'string') {
1248 return querySelectorAllExt(eltOrSelector, selector)[0]
1249 } else {
1250 return querySelectorAllExt(getDocument().body, eltOrSelector)[0]
1251 }
1252 }
1253
1254 /**
1255 * @template {EventTarget} T
1256 * @param {T|string} eltOrSelector
1257 * @param {T} [context]
1258 * @returns {Element|T|null}
1259 */
1260 function resolveTarget(eltOrSelector, context) {
1261 if (typeof eltOrSelector === 'string') {
1262 return find(asParentNode(context) || document, eltOrSelector)
1263 } else {
1264 return eltOrSelector
1265 }
1266 }
1267
1268 /**
1269 * @typedef {keyof HTMLElementEventMap|string} AnyEventName
1270 */
1271
1272 /**
1273 * @typedef {Object} EventArgs
1274 * @property {EventTarget} target
1275 * @property {AnyEventName} event
1276 * @property {EventListener} listener
1277 * @property {Object|boolean} options
1278 */
1279
1280 /**
1281 * @param {EventTarget|AnyEventName} arg1
1282 * @param {AnyEventName|EventListener} arg2
1283 * @param {EventListener|Object|boolean} [arg3]
1284 * @param {Object|boolean} [arg4]
1285 * @returns {EventArgs}
1286 */
1287 function processEventArgs(arg1, arg2, arg3, arg4) {
1288 if (isFunction(arg2)) {
1289 return {
1290 target: getDocument().body,
1291 event: asString(arg1),
1292 listener: arg2,
1293 options: arg3
1294 }
1295 } else {
1296 return {
1297 target: resolveTarget(arg1),
1298 event: asString(arg2),
1299 listener: arg3,
1300 options: arg4
1301 }
1302 }
1303 }
1304
1305 /**
1306 * Adds an event listener to an element
1307 *
1308 * @see https://htmx.org/api/#on
1309 *
1310 * @param {EventTarget|string} arg1 the element to add the listener to | the event name to add the listener for
1311 * @param {string|EventListener} arg2 the event name to add the listener for | the listener to add
1312 * @param {EventListener|Object|boolean} [arg3] the listener to add | options to add
1313 * @param {Object|boolean} [arg4] options to add
1314 * @returns {EventListener}
1315 */
1316 function addEventListenerImpl(arg1, arg2, arg3, arg4) {
1317 ready(function() {
1318 const eventArgs = processEventArgs(arg1, arg2, arg3, arg4)
1319 eventArgs.target.addEventListener(eventArgs.event, eventArgs.listener, eventArgs.options)
1320 })
1321 const b = isFunction(arg2)
1322 return b ? arg2 : arg3
1323 }
1324
1325 /**
1326 * Removes an event listener from an element
1327 *
1328 * @see https://htmx.org/api/#off
1329 *
1330 * @param {EventTarget|string} arg1 the element to remove the listener from | the event name to remove the listener from
1331 * @param {string|EventListener} arg2 the event name to remove the listener from | the listener to remove
1332 * @param {EventListener} [arg3] the listener to remove
1333 * @returns {EventListener}
1334 */
1335 function removeEventListenerImpl(arg1, arg2, arg3) {
1336 ready(function() {
1337 const eventArgs = processEventArgs(arg1, arg2, arg3)
1338 eventArgs.target.removeEventListener(eventArgs.event, eventArgs.listener)
1339 })
1340 return isFunction(arg2) ? arg2 : arg3
1341 }
1342
1343 //= ===================================================================
1344 // Node processing
1345 //= ===================================================================
1346
1347 const DUMMY_ELT = getDocument().createElement('output') // dummy element for bad selectors
1348 /**
1349 * @param {Element} elt
1350 * @param {string} attrName
1351 * @returns {(Node|Window)[]}
1352 */
1353 function findAttributeTargets(elt, attrName) {
1354 const attrTarget = getClosestAttributeValue(elt, attrName)
1355 if (attrTarget) {
1356 if (attrTarget === 'this') {
1357 return [findThisElement(elt, attrName)]
1358 } else {
1359 const result = querySelectorAllExt(elt, attrTarget)
1360 // find `inherit` whole word in value, make sure it's surrounded by commas or is at the start/end of string
1361 const shouldInherit = /(^|,)(\s*)inherit(\s*)($|,)/.test(attrTarget)
1362 if (shouldInherit) {
1363 const eltToInheritFrom = asElement(getClosestMatch(elt, function(parent) {
1364 return parent !== elt && hasAttribute(asElement(parent), attrName)
1365 }))
1366 if (eltToInheritFrom) {
1367 result.push(...findAttributeTargets(eltToInheritFrom, attrName))
1368 }
1369 }
1370 if (result.length === 0) {
1371 logError('The selector "' + attrTarget + '" on ' + attrName + ' returned no matches!')
1372 return [DUMMY_ELT]
1373 } else {
1374 return result
1375 }
1376 }
1377 }
1378 }
1379
1380 /**
1381 * @param {Element} elt
1382 * @param {string} attribute
1383 * @returns {Element|null}
1384 */
1385 function findThisElement(elt, attribute) {
1386 return asElement(getClosestMatch(elt, function(elt) {
1387 return getAttributeValue(asElement(elt), attribute) != null
1388 }))
1389 }
1390
1391 /**
1392 * @param {Element} elt
1393 * @returns {Node|Window|null}
1394 */
1395 function getTarget(elt) {
1396 const targetStr = getClosestAttributeValue(elt, 'hx-target')
1397 if (targetStr) {
1398 if (targetStr === 'this') {
1399 return findThisElement(elt, 'hx-target')
1400 } else {
1401 return querySelectorExt(elt, targetStr)
1402 }
1403 } else {
1404 const data = getInternalData(elt)
1405 if (data.boosted) {
1406 return getDocument().body
1407 } else {
1408 return elt
1409 }
1410 }
1411 }
1412
1413 /**
1414 * @param {string} name
1415 * @returns {boolean}
1416 */
1417 function shouldSettleAttribute(name) {
1418 return htmx.config.attributesToSettle.includes(name)
1419 }
1420
1421 /**
1422 * @param {Element} mergeTo
1423 * @param {Element} mergeFrom
1424 */
1425 function cloneAttributes(mergeTo, mergeFrom) {
1426 forEach(Array.from(mergeTo.attributes), function(attr) {
1427 if (!mergeFrom.hasAttribute(attr.name) && shouldSettleAttribute(attr.name)) {
1428 mergeTo.removeAttribute(attr.name)
1429 }
1430 })
1431 forEach(mergeFrom.attributes, function(attr) {
1432 if (shouldSettleAttribute(attr.name)) {
1433 mergeTo.setAttribute(attr.name, attr.value)
1434 }
1435 })
1436 }
1437
1438 /**
1439 * @param {HtmxSwapStyle} swapStyle
1440 * @param {Element} target
1441 * @returns {boolean}
1442 */
1443 function isInlineSwap(swapStyle, target) {
1444 const extensions = getExtensions(target)
1445 for (let i = 0; i < extensions.length; i++) {
1446 const extension = extensions[i]
1447 try {
1448 if (extension.isInlineSwap(swapStyle)) {
1449 return true
1450 }
1451 } catch (e) {
1452 logError(e)
1453 }
1454 }
1455 return swapStyle === 'outerHTML'
1456 }
1457
1458 /**
1459 * @param {string} oobValue
1460 * @param {Element} oobElement
1461 * @param {HtmxSettleInfo} settleInfo
1462 * @param {Node|Document} [rootNode]
1463 * @returns
1464 */
1465 function oobSwap(oobValue, oobElement, settleInfo, rootNode) {
1466 rootNode = rootNode || getDocument()
1467 let selector = '#' + CSS.escape(getRawAttribute(oobElement, 'id'))
1468 /** @type HtmxSwapStyle */
1469 let swapStyle = 'outerHTML'
1470 if (oobValue === 'true') {
1471 // do nothing
1472 } else if (oobValue.indexOf(':') > 0) {
1473 swapStyle = oobValue.substring(0, oobValue.indexOf(':'))
1474 selector = oobValue.substring(oobValue.indexOf(':') + 1)
1475 } else {
1476 swapStyle = oobValue
1477 }
1478 oobElement.removeAttribute('hx-swap-oob')
1479 oobElement.removeAttribute('data-hx-swap-oob')
1480
1481 const targets = querySelectorAllExt(rootNode, selector, false)
1482 if (targets.length) {
1483 forEach(
1484 targets,
1485 function(target) {
1486 let fragment
1487 const oobElementClone = oobElement.cloneNode(true)
1488 fragment = getDocument().createDocumentFragment()
1489 fragment.appendChild(oobElementClone)
1490 if (!isInlineSwap(swapStyle, target)) {
1491 fragment = asParentNode(oobElementClone) // if this is not an inline swap, we use the content of the node, not the node itself
1492 }
1493
1494 const beforeSwapDetails = { shouldSwap: true, target, fragment }
1495 if (!triggerEvent(target, 'htmx:oobBeforeSwap', beforeSwapDetails)) return
1496
1497 target = beforeSwapDetails.target // allow re-targeting
1498 if (beforeSwapDetails.shouldSwap) {
1499 handlePreservedElements(fragment)
1500 swapWithStyle(swapStyle, target, target, fragment, settleInfo)
1501 restorePreservedElements()
1502 }
1503 forEach(settleInfo.elts, function(elt) {
1504 triggerEvent(elt, 'htmx:oobAfterSwap', beforeSwapDetails)
1505 })
1506 }
1507 )
1508 oobElement.parentNode.removeChild(oobElement)
1509 } else {
1510 oobElement.parentNode.removeChild(oobElement)
1511 triggerErrorEvent(getDocument().body, 'htmx:oobErrorNoTarget', { content: oobElement })
1512 }
1513 return oobValue
1514 }
1515
1516 function restorePreservedElements() {
1517 const pantry = find('#--htmx-preserve-pantry--')
1518 if (pantry) {
1519 for (const preservedElt of [...pantry.children]) {
1520 const existingElement = find('#' + preservedElt.id)
1521 // @ts-ignore - use proposed moveBefore feature
1522 existingElement.parentNode.moveBefore(preservedElt, existingElement)
1523 existingElement.remove()
1524 }
1525 pantry.remove()
1526 }
1527 }
1528
1529 /**
1530 * @param {DocumentFragment|ParentNode} fragment
1531 */
1532 function handlePreservedElements(fragment) {
1533 forEach(findAll(fragment, '[hx-preserve], [data-hx-preserve]'), function(preservedElt) {
1534 const id = getAttributeValue(preservedElt, 'id')
1535 const existingElement = getDocument().getElementById(id)
1536 if (existingElement != null) {
1537 if (preservedElt.moveBefore) { // if the moveBefore API exists, use it
1538 // get or create a storage spot for stuff
1539 let pantry = find('#--htmx-preserve-pantry--')
1540 if (pantry == null) {
1541 getDocument().body.insertAdjacentHTML('afterend', "<div id='--htmx-preserve-pantry--'></div>")
1542 pantry = find('#--htmx-preserve-pantry--')
1543 }
1544 // @ts-ignore - use proposed moveBefore feature
1545 pantry.moveBefore(existingElement, null)
1546 } else {
1547 preservedElt.parentNode.replaceChild(existingElement, preservedElt)
1548 }
1549 }
1550 })
1551 }
1552
1553 /**
1554 * @param {Node} parentNode
1555 * @param {ParentNode} fragment
1556 * @param {HtmxSettleInfo} settleInfo
1557 */
1558 function handleAttributes(parentNode, fragment, settleInfo) {
1559 forEach(fragment.querySelectorAll('[id]'), function(newNode) {
1560 const id = getRawAttribute(newNode, 'id')
1561 if (id && id.length > 0) {
1562 const normalizedId = id.replace("'", "\\'")
1563 const normalizedTag = newNode.tagName.replace(':', '\\:')
1564 const parentElt = asParentNode(parentNode)
1565 const oldNode = parentElt && parentElt.querySelector(normalizedTag + "[id='" + normalizedId + "']")
1566 if (oldNode && oldNode !== parentElt) {
1567 const newAttributes = newNode.cloneNode()
1568 cloneAttributes(newNode, oldNode)
1569 settleInfo.tasks.push(function() {
1570 cloneAttributes(newNode, newAttributes)
1571 })
1572 }
1573 }
1574 })
1575 }
1576
1577 /**
1578 * @param {Node} child
1579 * @returns {HtmxSettleTask}
1580 */
1581 function makeAjaxLoadTask(child) {
1582 return function() {
1583 removeClassFromElement(child, htmx.config.addedClass)
1584 processNode(asElement(child))
1585 processFocus(asParentNode(child))
1586 triggerEvent(child, 'htmx:load')
1587 }
1588 }
1589
1590 /**
1591 * @param {ParentNode} child
1592 */
1593 function processFocus(child) {
1594 const autofocus = '[autofocus]'
1595 const autoFocusedElt = asHtmlElement(matches(child, autofocus) ? child : child.querySelector(autofocus))
1596 if (autoFocusedElt != null) {
1597 autoFocusedElt.focus()
1598 }
1599 }
1600
1601 /**
1602 * @param {Node} parentNode
1603 * @param {Node} insertBefore
1604 * @param {ParentNode} fragment
1605 * @param {HtmxSettleInfo} settleInfo
1606 */
1607 function insertNodesBefore(parentNode, insertBefore, fragment, settleInfo) {
1608 handleAttributes(parentNode, fragment, settleInfo)
1609 while (fragment.childNodes.length > 0) {
1610 const child = fragment.firstChild
1611 addClassToElement(asElement(child), htmx.config.addedClass)
1612 parentNode.insertBefore(child, insertBefore)
1613 if (child.nodeType !== Node.TEXT_NODE && child.nodeType !== Node.COMMENT_NODE) {
1614 settleInfo.tasks.push(makeAjaxLoadTask(child))
1615 }
1616 }
1617 }
1618
1619 /**
1620 * based on https://gist.github.com/hyamamoto/fd435505d29ebfa3d9716fd2be8d42f0,
1621 * derived from Java's string hashcode implementation
1622 * @param {string} string
1623 * @param {number} hash
1624 * @returns {number}
1625 */
1626 function stringHash(string, hash) {
1627 let char = 0
1628 while (char < string.length) {
1629 hash = (hash << 5) - hash + string.charCodeAt(char++) | 0 // bitwise or ensures we have a 32-bit int
1630 }
1631 return hash
1632 }
1633
1634 /**
1635 * @param {Element} elt
1636 * @returns {number}
1637 */
1638 function attributeHash(elt) {
1639 let hash = 0
1640 for (let i = 0; i < elt.attributes.length; i++) {
1641 const attribute = elt.attributes[i]
1642 if (attribute.value) { // only include attributes w/ actual values (empty is same as non-existent)
1643 hash = stringHash(attribute.name, hash)
1644 hash = stringHash(attribute.value, hash)
1645 }
1646 }
1647 return hash
1648 }
1649
1650 /**
1651 * @param {EventTarget} elt
1652 */
1653 function deInitOnHandlers(elt) {
1654 const internalData = getInternalData(elt)
1655 if (internalData.onHandlers) {
1656 for (let i = 0; i < internalData.onHandlers.length; i++) {
1657 const handlerInfo = internalData.onHandlers[i]
1658 removeEventListenerImpl(elt, handlerInfo.event, handlerInfo.listener)
1659 }
1660 delete internalData.onHandlers
1661 }
1662 }
1663
1664 /**
1665 * @param {Node} element
1666 */
1667 function deInitNode(element) {
1668 const internalData = getInternalData(element)
1669 if (internalData.timeout) {
1670 clearTimeout(internalData.timeout)
1671 }
1672 if (internalData.listenerInfos) {
1673 forEach(internalData.listenerInfos, function(info) {
1674 if (info.on) {
1675 removeEventListenerImpl(info.on, info.trigger, info.listener)
1676 }
1677 })
1678 }
1679 deInitOnHandlers(element)
1680 forEach(Object.keys(internalData), function(key) { if (key !== 'firstInitCompleted') delete internalData[key] })
1681 }
1682
1683 /**
1684 * @param {Node} element
1685 */
1686 function cleanUpElement(element) {
1687 triggerEvent(element, 'htmx:beforeCleanupElement')
1688 deInitNode(element)
1689 // @ts-ignore
1690 forEach(element.children, function(child) { cleanUpElement(child) })
1691 }
1692
1693 /**
1694 * @param {Element} target
1695 * @param {ParentNode} fragment
1696 * @param {HtmxSettleInfo} settleInfo
1697 */
1698 function swapOuterHTML(target, fragment, settleInfo) {
1699 if (target.tagName === 'BODY') { // special case the body to innerHTML because DocumentFragments can't contain a body elt unfortunately
1700 return swapInnerHTML(target, fragment, settleInfo)
1701 }
1702 /** @type {Node} */
1703 let newElt
1704 const eltBeforeNewContent = target.previousSibling
1705 const parentNode = parentElt(target)
1706 if (!parentNode) { // when parent node disappears, we can't do anything
1707 return
1708 }
1709 insertNodesBefore(parentNode, target, fragment, settleInfo)
1710 if (eltBeforeNewContent == null) {
1711 newElt = parentNode.firstChild
1712 } else {
1713 newElt = eltBeforeNewContent.nextSibling
1714 }
1715 settleInfo.elts = settleInfo.elts.filter(function(e) { return e !== target })
1716 // scan through all newly added content and add all elements to the settle info so we trigger
1717 // events properly on them
1718 while (newElt && newElt !== target) {
1719 if (newElt instanceof Element) {
1720 settleInfo.elts.push(newElt)
1721 }
1722 newElt = newElt.nextSibling
1723 }
1724 cleanUpElement(target)
1725 target.remove()
1726 }
1727
1728 /**
1729 * @param {Element} target
1730 * @param {ParentNode} fragment
1731 * @param {HtmxSettleInfo} settleInfo
1732 */
1733 function swapAfterBegin(target, fragment, settleInfo) {
1734 return insertNodesBefore(target, target.firstChild, fragment, settleInfo)
1735 }
1736
1737 /**
1738 * @param {Element} target
1739 * @param {ParentNode} fragment
1740 * @param {HtmxSettleInfo} settleInfo
1741 */
1742 function swapBeforeBegin(target, fragment, settleInfo) {
1743 return insertNodesBefore(parentElt(target), target, fragment, settleInfo)
1744 }
1745
1746 /**
1747 * @param {Element} target
1748 * @param {ParentNode} fragment
1749 * @param {HtmxSettleInfo} settleInfo
1750 */
1751 function swapBeforeEnd(target, fragment, settleInfo) {
1752 return insertNodesBefore(target, null, fragment, settleInfo)
1753 }
1754
1755 /**
1756 * @param {Element} target
1757 * @param {ParentNode} fragment
1758 * @param {HtmxSettleInfo} settleInfo
1759 */
1760 function swapAfterEnd(target, fragment, settleInfo) {
1761 return insertNodesBefore(parentElt(target), target.nextSibling, fragment, settleInfo)
1762 }
1763
1764 /**
1765 * @param {Element} target
1766 */
1767 function swapDelete(target) {
1768 cleanUpElement(target)
1769 const parent = parentElt(target)
1770 if (parent) {
1771 return parent.removeChild(target)
1772 }
1773 }
1774
1775 /**
1776 * @param {Element} target
1777 * @param {ParentNode} fragment
1778 * @param {HtmxSettleInfo} settleInfo
1779 */
1780 function swapInnerHTML(target, fragment, settleInfo) {
1781 const firstChild = target.firstChild
1782 insertNodesBefore(target, firstChild, fragment, settleInfo)
1783 if (firstChild) {
1784 while (firstChild.nextSibling) {
1785 cleanUpElement(firstChild.nextSibling)
1786 target.removeChild(firstChild.nextSibling)
1787 }
1788 cleanUpElement(firstChild)
1789 target.removeChild(firstChild)
1790 }
1791 }
1792
1793 /**
1794 * @param {HtmxSwapStyle} swapStyle
1795 * @param {Element} elt
1796 * @param {Element} target
1797 * @param {ParentNode} fragment
1798 * @param {HtmxSettleInfo} settleInfo
1799 */
1800 function swapWithStyle(swapStyle, elt, target, fragment, settleInfo) {
1801 switch (swapStyle) {
1802 case 'none':
1803 return
1804 case 'outerHTML':
1805 swapOuterHTML(target, fragment, settleInfo)
1806 return
1807 case 'afterbegin':
1808 swapAfterBegin(target, fragment, settleInfo)
1809 return
1810 case 'beforebegin':
1811 swapBeforeBegin(target, fragment, settleInfo)
1812 return
1813 case 'beforeend':
1814 swapBeforeEnd(target, fragment, settleInfo)
1815 return
1816 case 'afterend':
1817 swapAfterEnd(target, fragment, settleInfo)
1818 return
1819 case 'delete':
1820 swapDelete(target)
1821 return
1822 default:
1823 var extensions = getExtensions(elt)
1824 for (let i = 0; i < extensions.length; i++) {
1825 const ext = extensions[i]
1826 try {
1827 const newElements = ext.handleSwap(swapStyle, target, fragment, settleInfo)
1828 if (newElements) {
1829 if (Array.isArray(newElements)) {
1830 // if handleSwap returns an array (like) of elements, we handle them
1831 for (let j = 0; j < newElements.length; j++) {
1832 const child = newElements[j]
1833 if (child.nodeType !== Node.TEXT_NODE && child.nodeType !== Node.COMMENT_NODE) {
1834 settleInfo.tasks.push(makeAjaxLoadTask(child))
1835 }
1836 }
1837 }
1838 return
1839 }
1840 } catch (e) {
1841 logError(e)
1842 }
1843 }
1844 if (swapStyle === 'innerHTML') {
1845 swapInnerHTML(target, fragment, settleInfo)
1846 } else {
1847 swapWithStyle(htmx.config.defaultSwapStyle, elt, target, fragment, settleInfo)
1848 }
1849 }
1850 }
1851
1852 /**
1853 * @param {DocumentFragment} fragment
1854 * @param {HtmxSettleInfo} settleInfo
1855 * @param {Node|Document} [rootNode]
1856 */
1857 function findAndSwapOobElements(fragment, settleInfo, rootNode) {
1858 var oobElts = findAll(fragment, '[hx-swap-oob], [data-hx-swap-oob]')
1859 forEach(oobElts, function(oobElement) {
1860 if (htmx.config.allowNestedOobSwaps || oobElement.parentElement === null) {
1861 const oobValue = getAttributeValue(oobElement, 'hx-swap-oob')
1862 if (oobValue != null) {
1863 oobSwap(oobValue, oobElement, settleInfo, rootNode)
1864 }
1865 } else {
1866 oobElement.removeAttribute('hx-swap-oob')
1867 oobElement.removeAttribute('data-hx-swap-oob')
1868 }
1869 })
1870 return oobElts.length > 0
1871 }
1872
1873 /**
1874 * Implements complete swapping pipeline, including: delay, view transitions, focus and selection preservation,
1875 * title updates, scroll, OOB swapping, normal swapping and settling
1876 * @param {string|Element} target
1877 * @param {string} content
1878 * @param {HtmxSwapSpecification} swapSpec
1879 * @param {SwapOptions} [swapOptions]
1880 */
1881 function swap(target, content, swapSpec, swapOptions) {
1882 if (!swapOptions) {
1883 swapOptions = {}
1884 }
1885 // optional transition API promise callbacks
1886 let settleResolve = null
1887 let settleReject = null
1888
1889 let doSwap = function() {
1890 maybeCall(swapOptions.beforeSwapCallback)
1891
1892 target = resolveTarget(target)
1893 const rootNode = swapOptions.contextElement ? getRootNode(swapOptions.contextElement, false) : getDocument()
1894
1895 // preserve focus and selection
1896 const activeElt = document.activeElement
1897 let selectionInfo = {}
1898 selectionInfo = {
1899 elt: activeElt,
1900 // @ts-ignore
1901 start: activeElt ? activeElt.selectionStart : null,
1902 // @ts-ignore
1903 end: activeElt ? activeElt.selectionEnd : null
1904 }
1905 const settleInfo = makeSettleInfo(target)
1906
1907 // For text content swaps, don't parse the response as HTML, just insert it
1908 if (swapSpec.swapStyle === 'textContent') {
1909 target.textContent = content
1910 // Otherwise, make the fragment and process it
1911 } else {
1912 let fragment = makeFragment(content)
1913
1914 settleInfo.title = swapOptions.title || fragment.title
1915 if (swapOptions.historyRequest) {
1916 // @ts-ignore fragment can be a parentNode Element
1917 fragment = fragment.querySelector('[hx-history-elt],[data-hx-history-elt]') || fragment
1918 }
1919
1920 // select-oob swaps
1921 if (swapOptions.selectOOB) {
1922 const oobSelectValues = swapOptions.selectOOB.split(',')
1923 for (let i = 0; i < oobSelectValues.length; i++) {
1924 const oobSelectValue = oobSelectValues[i].split(':', 2)
1925 let id = oobSelectValue[0].trim()
1926 if (id.indexOf('#') === 0) {
1927 id = id.substring(1)
1928 }
1929 const oobValue = oobSelectValue[1] || 'true'
1930 const oobElement = fragment.querySelector('#' + id)
1931 if (oobElement) {
1932 oobSwap(oobValue, oobElement, settleInfo, rootNode)
1933 }
1934 }
1935 }
1936 // oob swaps
1937 findAndSwapOobElements(fragment, settleInfo, rootNode)
1938 forEach(findAll(fragment, 'template'), /** @param {HTMLTemplateElement} template */function(template) {
1939 if (template.content && findAndSwapOobElements(template.content, settleInfo, rootNode)) {
1940 // Avoid polluting the DOM with empty templates that were only used to encapsulate oob swap
1941 template.remove()
1942 }
1943 })
1944
1945 // normal swap
1946 if (swapOptions.select) {
1947 const newFragment = getDocument().createDocumentFragment()
1948 forEach(fragment.querySelectorAll(swapOptions.select), function(node) {
1949 newFragment.appendChild(node)
1950 })
1951 fragment = newFragment
1952 }
1953 handlePreservedElements(fragment)
1954 swapWithStyle(swapSpec.swapStyle, swapOptions.contextElement, target, fragment, settleInfo)
1955 restorePreservedElements()
1956 }
1957
1958 // apply saved focus and selection information to swapped content
1959 if (selectionInfo.elt &&
1960 !bodyContains(selectionInfo.elt) &&
1961 getRawAttribute(selectionInfo.elt, 'id')) {
1962 const newActiveElt = document.getElementById(getRawAttribute(selectionInfo.elt, 'id'))
1963 const focusOptions = { preventScroll: swapSpec.focusScroll !== undefined ? !swapSpec.focusScroll : !htmx.config.defaultFocusScroll }
1964 if (newActiveElt) {
1965 // @ts-ignore
1966 if (selectionInfo.start && newActiveElt.setSelectionRange) {
1967 try {
1968 // @ts-ignore
1969 newActiveElt.setSelectionRange(selectionInfo.start, selectionInfo.end)
1970 } catch (e) {
1971 // the setSelectionRange method is present on fields that don't support it, so just let this fail
1972 }
1973 }
1974 newActiveElt.focus(focusOptions)
1975 }
1976 }
1977
1978 target.classList.remove(htmx.config.swappingClass)
1979 forEach(settleInfo.elts, function(elt) {
1980 if (elt.classList) {
1981 elt.classList.add(htmx.config.settlingClass)
1982 }
1983 triggerEvent(elt, 'htmx:afterSwap', swapOptions.eventInfo)
1984 })
1985 maybeCall(swapOptions.afterSwapCallback)
1986
1987 // merge in new title after swap but before settle
1988 if (!swapSpec.ignoreTitle) {
1989 handleTitle(settleInfo.title)
1990 }
1991
1992 // settle
1993 const doSettle = function() {
1994 forEach(settleInfo.tasks, function(task) {
1995 task.call()
1996 })
1997 forEach(settleInfo.elts, function(elt) {
1998 if (elt.classList) {
1999 elt.classList.remove(htmx.config.settlingClass)
2000 }
2001 triggerEvent(elt, 'htmx:afterSettle', swapOptions.eventInfo)
2002 })
2003
2004 if (swapOptions.anchor) {
2005 const anchorTarget = asElement(resolveTarget('#' + swapOptions.anchor))
2006 if (anchorTarget) {
2007 anchorTarget.scrollIntoView({ block: 'start', behavior: 'auto' })
2008 }
2009 }
2010
2011 updateScrollState(settleInfo.elts, swapSpec)
2012 maybeCall(swapOptions.afterSettleCallback)
2013 maybeCall(settleResolve)
2014 }
2015
2016 if (swapSpec.settleDelay > 0) {
2017 getWindow().setTimeout(doSettle, swapSpec.settleDelay)
2018 } else {
2019 doSettle()
2020 }
2021 }
2022 let shouldTransition = htmx.config.globalViewTransitions
2023 if (swapSpec.hasOwnProperty('transition')) {
2024 shouldTransition = swapSpec.transition
2025 }
2026
2027 const elt = swapOptions.contextElement || getDocument()
2028
2029 if (shouldTransition &&
2030 triggerEvent(elt, 'htmx:beforeTransition', swapOptions.eventInfo) &&
2031 typeof Promise !== 'undefined' &&
2032 // @ts-ignore experimental feature atm
2033 document.startViewTransition) {
2034 const settlePromise = new Promise(function(_resolve, _reject) {
2035 settleResolve = _resolve
2036 settleReject = _reject
2037 })
2038 // wrap the original doSwap() in a call to startViewTransition()
2039 const innerDoSwap = doSwap
2040 doSwap = function() {
2041 // @ts-ignore experimental feature atm
2042 document.startViewTransition(function() {
2043 innerDoSwap()
2044 return settlePromise
2045 })
2046 }
2047 }
2048
2049 try {
2050 if (swapSpec?.swapDelay && swapSpec.swapDelay > 0) {
2051 getWindow().setTimeout(doSwap, swapSpec.swapDelay)
2052 } else {
2053 doSwap()
2054 }
2055 } catch (e) {
2056 triggerErrorEvent(elt, 'htmx:swapError', swapOptions.eventInfo)
2057 maybeCall(settleReject)
2058 throw e
2059 }
2060 }
2061
2062 /**
2063 * @param {XMLHttpRequest} xhr
2064 * @param {string} header
2065 * @param {EventTarget} elt
2066 */
2067 function handleTriggerHeader(xhr, header, elt) {
2068 const triggerBody = xhr.getResponseHeader(header)
2069 if (triggerBody.indexOf('{') === 0) {
2070 const triggers = parseJSON(triggerBody)
2071 for (const eventName in triggers) {
2072 if (triggers.hasOwnProperty(eventName)) {
2073 let detail = triggers[eventName]
2074 if (isRawObject(detail)) {
2075 // @ts-ignore
2076 elt = detail.target !== undefined ? detail.target : elt
2077 } else {
2078 detail = { value: detail }
2079 }
2080 triggerEvent(elt, eventName, detail)
2081 }
2082 }
2083 } else {
2084 const eventNames = triggerBody.split(',')
2085 for (let i = 0; i < eventNames.length; i++) {
2086 triggerEvent(elt, eventNames[i].trim(), [])
2087 }
2088 }
2089 }
2090
2091 const WHITESPACE = /\s/
2092 const WHITESPACE_OR_COMMA = /[\s,]/
2093 const SYMBOL_START = /[_$a-zA-Z]/
2094 const SYMBOL_CONT = /[_$a-zA-Z0-9]/
2095 const STRINGISH_START = ['"', "'", '/']
2096 const NOT_WHITESPACE = /[^\s]/
2097 const COMBINED_SELECTOR_START = /[{(]/
2098 const COMBINED_SELECTOR_END = /[})]/
2099
2100 /**
2101 * @param {string} str
2102 * @returns {string[]}
2103 */
2104 function tokenizeString(str) {
2105 /** @type string[] */
2106 const tokens = []
2107 let position = 0
2108 while (position < str.length) {
2109 if (SYMBOL_START.exec(str.charAt(position))) {
2110 var startPosition = position
2111 while (SYMBOL_CONT.exec(str.charAt(position + 1))) {
2112 position++
2113 }
2114 tokens.push(str.substring(startPosition, position + 1))
2115 } else if (STRINGISH_START.indexOf(str.charAt(position)) !== -1) {
2116 const startChar = str.charAt(position)
2117 var startPosition = position
2118 position++
2119 while (position < str.length && str.charAt(position) !== startChar) {
2120 if (str.charAt(position) === '\\') {
2121 position++
2122 }
2123 position++
2124 }
2125 tokens.push(str.substring(startPosition, position + 1))
2126 } else {
2127 const symbol = str.charAt(position)
2128 tokens.push(symbol)
2129 }
2130 position++
2131 }
2132 return tokens
2133 }
2134
2135 /**
2136 * @param {string} token
2137 * @param {string|null} last
2138 * @param {string} paramName
2139 * @returns {boolean}
2140 */
2141 function isPossibleRelativeReference(token, last, paramName) {
2142 return SYMBOL_START.exec(token.charAt(0)) &&
2143 token !== 'true' &&
2144 token !== 'false' &&
2145 token !== 'this' &&
2146 token !== paramName &&
2147 last !== '.'
2148 }
2149
2150 /**
2151 * @param {EventTarget|string} elt
2152 * @param {string[]} tokens
2153 * @param {string} paramName
2154 * @returns {ConditionalFunction|null}
2155 */
2156 function maybeGenerateConditional(elt, tokens, paramName) {
2157 if (tokens[0] === '[') {
2158 tokens.shift()
2159 let bracketCount = 1
2160 let conditionalSource = ' return (function(' + paramName + '){ return ('
2161 let last = null
2162 while (tokens.length > 0) {
2163 const token = tokens[0]
2164 // @ts-ignore For some reason tsc doesn't understand the shift call, and thinks we're comparing the same value here, i.e. '[' vs ']'
2165 if (token === ']') {
2166 bracketCount--
2167 if (bracketCount === 0) {
2168 if (last === null) {
2169 conditionalSource = conditionalSource + 'true'
2170 }
2171 tokens.shift()
2172 conditionalSource += ')})'
2173 try {
2174 const conditionFunction = maybeEval(elt, function() {
2175 return Function(conditionalSource)()
2176 },
2177 function() { return true })
2178 conditionFunction.source = conditionalSource
2179 return conditionFunction
2180 } catch (e) {
2181 triggerErrorEvent(getDocument().body, 'htmx:syntax:error', { error: e, source: conditionalSource })
2182 return null
2183 }
2184 }
2185 } else if (token === '[') {
2186 bracketCount++
2187 }
2188 if (isPossibleRelativeReference(token, last, paramName)) {
2189 conditionalSource += '((' + paramName + '.' + token + ') ? (' + paramName + '.' + token + ') : (window.' + token + '))'
2190 } else {
2191 conditionalSource = conditionalSource + token
2192 }
2193 last = tokens.shift()
2194 }
2195 }
2196 }
2197
2198 /**
2199 * @param {string[]} tokens
2200 * @param {RegExp} match
2201 * @returns {string}
2202 */
2203 function consumeUntil(tokens, match) {
2204 let result = ''
2205 while (tokens.length > 0 && !match.test(tokens[0])) {
2206 result += tokens.shift()
2207 }
2208 return result
2209 }
2210
2211 /**
2212 * @param {string[]} tokens
2213 * @returns {string}
2214 */
2215 function consumeCSSSelector(tokens) {
2216 let result
2217 if (tokens.length > 0 && COMBINED_SELECTOR_START.test(tokens[0])) {
2218 tokens.shift()
2219 result = consumeUntil(tokens, COMBINED_SELECTOR_END).trim()
2220 tokens.shift()
2221 } else {
2222 result = consumeUntil(tokens, WHITESPACE_OR_COMMA)
2223 }
2224 return result
2225 }
2226
2227 const INPUT_SELECTOR = 'input, textarea, select'
2228
2229 /**
2230 * @param {Element} elt
2231 * @param {string} explicitTrigger
2232 * @param {Object} cache for trigger specs
2233 * @returns {HtmxTriggerSpecification[]}
2234 */
2235 function parseAndCacheTrigger(elt, explicitTrigger, cache) {
2236 /** @type HtmxTriggerSpecification[] */
2237 const triggerSpecs = []
2238 const tokens = tokenizeString(explicitTrigger)
2239 do {
2240 consumeUntil(tokens, NOT_WHITESPACE)
2241 const initialLength = tokens.length
2242 const trigger = consumeUntil(tokens, /[,\[\s]/)
2243 if (trigger !== '') {
2244 if (trigger === 'every') {
2245 /** @type HtmxTriggerSpecification */
2246 const every = { trigger: 'every' }
2247 consumeUntil(tokens, NOT_WHITESPACE)
2248 every.pollInterval = parseInterval(consumeUntil(tokens, /[,\[\s]/))
2249 consumeUntil(tokens, NOT_WHITESPACE)
2250 var eventFilter = maybeGenerateConditional(elt, tokens, 'event')
2251 if (eventFilter) {
2252 every.eventFilter = eventFilter
2253 }
2254 triggerSpecs.push(every)
2255 } else {
2256 /** @type HtmxTriggerSpecification */
2257 const triggerSpec = { trigger }
2258 var eventFilter = maybeGenerateConditional(elt, tokens, 'event')
2259 if (eventFilter) {
2260 triggerSpec.eventFilter = eventFilter
2261 }
2262 consumeUntil(tokens, NOT_WHITESPACE)
2263 while (tokens.length > 0 && tokens[0] !== ',') {
2264 const token = tokens.shift()
2265 if (token === 'changed') {
2266 triggerSpec.changed = true
2267 } else if (token === 'once') {
2268 triggerSpec.once = true
2269 } else if (token === 'consume') {
2270 triggerSpec.consume = true
2271 } else if (token === 'delay' && tokens[0] === ':') {
2272 tokens.shift()
2273 triggerSpec.delay = parseInterval(consumeUntil(tokens, WHITESPACE_OR_COMMA))
2274 } else if (token === 'from' && tokens[0] === ':') {
2275 tokens.shift()
2276 if (COMBINED_SELECTOR_START.test(tokens[0])) {
2277 var from_arg = consumeCSSSelector(tokens)
2278 } else {
2279 var from_arg = consumeUntil(tokens, WHITESPACE_OR_COMMA)
2280 if (from_arg === 'closest' || from_arg === 'find' || from_arg === 'next' || from_arg === 'previous') {
2281 tokens.shift()
2282 const selector = consumeCSSSelector(tokens)
2283 // `next` and `previous` allow a selector-less syntax
2284 if (selector.length > 0) {
2285 from_arg += ' ' + selector
2286 }
2287 }
2288 }
2289 triggerSpec.from = from_arg
2290 } else if (token === 'target' && tokens[0] === ':') {
2291 tokens.shift()
2292 triggerSpec.target = consumeCSSSelector(tokens)
2293 } else if (token === 'throttle' && tokens[0] === ':') {
2294 tokens.shift()
2295 triggerSpec.throttle = parseInterval(consumeUntil(tokens, WHITESPACE_OR_COMMA))
2296 } else if (token === 'queue' && tokens[0] === ':') {
2297 tokens.shift()
2298 triggerSpec.queue = consumeUntil(tokens, WHITESPACE_OR_COMMA)
2299 } else if (token === 'root' && tokens[0] === ':') {
2300 tokens.shift()
2301 triggerSpec[token] = consumeCSSSelector(tokens)
2302 } else if (token === 'threshold' && tokens[0] === ':') {
2303 tokens.shift()
2304 triggerSpec[token] = consumeUntil(tokens, WHITESPACE_OR_COMMA)
2305 } else {
2306 triggerErrorEvent(elt, 'htmx:syntax:error', { token: tokens.shift() })
2307 }
2308 consumeUntil(tokens, NOT_WHITESPACE)
2309 }
2310 triggerSpecs.push(triggerSpec)
2311 }
2312 }
2313 if (tokens.length === initialLength) {
2314 triggerErrorEvent(elt, 'htmx:syntax:error', { token: tokens.shift() })
2315 }
2316 consumeUntil(tokens, NOT_WHITESPACE)
2317 } while (tokens[0] === ',' && tokens.shift())
2318 if (cache) {
2319 cache[explicitTrigger] = triggerSpecs
2320 }
2321 return triggerSpecs
2322 }
2323
2324 /**
2325 * @param {Element} elt
2326 * @returns {HtmxTriggerSpecification[]}
2327 */
2328 function getTriggerSpecs(elt) {
2329 const explicitTrigger = getAttributeValue(elt, 'hx-trigger')
2330 let triggerSpecs = []
2331 if (explicitTrigger) {
2332 const cache = htmx.config.triggerSpecsCache
2333 triggerSpecs = (cache && cache[explicitTrigger]) || parseAndCacheTrigger(elt, explicitTrigger, cache)
2334 }
2335
2336 if (triggerSpecs.length > 0) {
2337 return triggerSpecs
2338 } else if (matches(elt, 'form')) {
2339 return [{ trigger: 'submit' }]
2340 } else if (matches(elt, 'input[type="button"], input[type="submit"]')) {
2341 return [{ trigger: 'click' }]
2342 } else if (matches(elt, INPUT_SELECTOR)) {
2343 return [{ trigger: 'change' }]
2344 } else {
2345 return [{ trigger: 'click' }]
2346 }
2347 }
2348
2349 /**
2350 * @param {Element} elt
2351 */
2352 function cancelPolling(elt) {
2353 getInternalData(elt).cancelled = true
2354 }
2355
2356 /**
2357 * @param {Element} elt
2358 * @param {TriggerHandler} handler
2359 * @param {HtmxTriggerSpecification} spec
2360 */
2361 function processPolling(elt, handler, spec) {
2362 const nodeData = getInternalData(elt)
2363 nodeData.timeout = getWindow().setTimeout(function() {
2364 if (bodyContains(elt) && nodeData.cancelled !== true) {
2365 if (!maybeFilterEvent(spec, elt, makeEvent('hx:poll:trigger', {
2366 triggerSpec: spec,
2367 target: elt
2368 }))) {
2369 handler(elt)
2370 }
2371 processPolling(elt, handler, spec)
2372 }
2373 }, spec.pollInterval)
2374 }
2375
2376 /**
2377 * @param {HTMLAnchorElement} elt
2378 * @returns {boolean}
2379 */
2380 function isLocalLink(elt) {
2381 return location.hostname === elt.hostname &&
2382 getRawAttribute(elt, 'href') &&
2383 getRawAttribute(elt, 'href').indexOf('#') !== 0
2384 }
2385
2386 /**
2387 * @param {Element} elt
2388 */
2389 function eltIsDisabled(elt) {
2390 return closest(elt, htmx.config.disableSelector)
2391 }
2392
2393 /**
2394 * @param {Element} elt
2395 * @param {HtmxNodeInternalData} nodeData
2396 * @param {HtmxTriggerSpecification[]} triggerSpecs
2397 */
2398 function boostElement(elt, nodeData, triggerSpecs) {
2399 if ((elt instanceof HTMLAnchorElement && isLocalLink(elt) && (elt.target === '' || elt.target === '_self')) || (elt.tagName === 'FORM' && String(getRawAttribute(elt, 'method')).toLowerCase() !== 'dialog')) {
2400 nodeData.boosted = true
2401 let verb, path
2402 if (elt.tagName === 'A') {
2403 verb = (/** @type HttpVerb */('get'))
2404 path = getRawAttribute(elt, 'href')
2405 } else {
2406 const rawAttribute = getRawAttribute(elt, 'method')
2407 verb = (/** @type HttpVerb */(rawAttribute ? rawAttribute.toLowerCase() : 'get'))
2408 path = getRawAttribute(elt, 'action')
2409 if (path == null || path === '') {
2410 // if there is no action attribute on the form set path to current href before the
2411 // following logic to properly clear parameters on a GET (not on a POST!)
2412 path = location.href
2413 }
2414 if (verb === 'get' && path.includes('?')) {
2415 path = path.replace(/\?[^#]+/, '')
2416 }
2417 }
2418 triggerSpecs.forEach(function(triggerSpec) {
2419 addEventListener(elt, function(node, evt) {
2420 const elt = asElement(node)
2421 if (eltIsDisabled(elt)) {
2422 cleanUpElement(elt)
2423 return
2424 }
2425 issueAjaxRequest(verb, path, elt, evt)
2426 }, nodeData, triggerSpec, true)
2427 })
2428 }
2429 }
2430
2431 /**
2432 * @param {Event} evt
2433 * @param {Element} elt
2434 * @returns {boolean}
2435 */
2436 function shouldCancel(evt, elt) {
2437 if (evt.type === 'submit' && elt.tagName === 'FORM') {
2438 return true
2439 } else if (evt.type === 'click') {
2440 // find button wrapping the trigger element
2441 const btn = /** @type {HTMLButtonElement|HTMLInputElement|null} */ (elt.closest('input[type="submit"], button'))
2442 // Do not cancel on buttons that 1) don't have a related form or 2) have a type attribute of 'reset'/'button'.
2443 if (btn && btn.form && btn.type === 'submit') {
2444 return true
2445 }
2446
2447 // find link wrapping the trigger element
2448 const link = elt.closest('a')
2449 // Allow links with href="#fragment" (anchors with content after #) to perform normal fragment navigation.
2450 // Cancel default action for links with href="#" (bare hash) to prevent scrolling to top and unwanted URL changes.
2451 const samePageAnchor = /^#.+/
2452 if (link && link.href && !samePageAnchor.test(link.getAttribute('href'))) {
2453 return true
2454 }
2455 }
2456 return false
2457 }
2458
2459 /**
2460 * @param {Node} elt
2461 * @param {Event|MouseEvent|KeyboardEvent|TouchEvent} evt
2462 * @returns {boolean}
2463 */
2464 function ignoreBoostedAnchorCtrlClick(elt, evt) {
2465 return getInternalData(elt).boosted && elt instanceof HTMLAnchorElement && evt.type === 'click' &&
2466 // @ts-ignore this will resolve to undefined for events that don't define those properties, which is fine
2467 (evt.ctrlKey || evt.metaKey)
2468 }
2469
2470 /**
2471 * @param {HtmxTriggerSpecification} triggerSpec
2472 * @param {Node} elt
2473 * @param {Event} evt
2474 * @returns {boolean}
2475 */
2476 function maybeFilterEvent(triggerSpec, elt, evt) {
2477 const eventFilter = triggerSpec.eventFilter
2478 if (eventFilter) {
2479 try {
2480 return eventFilter.call(elt, evt) !== true
2481 } catch (e) {
2482 const source = eventFilter.source
2483 triggerErrorEvent(getDocument().body, 'htmx:eventFilter:error', { error: e, source })
2484 return true
2485 }
2486 }
2487 return false
2488 }
2489
2490 /**
2491 * @param {Element} elt
2492 * @param {TriggerHandler} handler
2493 * @param {HtmxNodeInternalData} nodeData
2494 * @param {HtmxTriggerSpecification} triggerSpec
2495 * @param {boolean} [explicitCancel]
2496 */
2497 function addEventListener(elt, handler, nodeData, triggerSpec, explicitCancel) {
2498 const elementData = getInternalData(elt)
2499 /** @type {(Node|Window)[]} */
2500 let eltsToListenOn
2501 if (triggerSpec.from) {
2502 eltsToListenOn = querySelectorAllExt(elt, triggerSpec.from)
2503 } else {
2504 eltsToListenOn = [elt]
2505 }
2506 // store the initial values of the elements, so we can tell if they change
2507 if (triggerSpec.changed) {
2508 if (!('lastValue' in elementData)) {
2509 elementData.lastValue = new WeakMap()
2510 }
2511 eltsToListenOn.forEach(function(eltToListenOn) {
2512 if (!elementData.lastValue.has(triggerSpec)) {
2513 elementData.lastValue.set(triggerSpec, new WeakMap())
2514 }
2515 // @ts-ignore value will be undefined for non-input elements, which is fine
2516 elementData.lastValue.get(triggerSpec).set(eltToListenOn, eltToListenOn.value)
2517 })
2518 }
2519 forEach(eltsToListenOn, function(eltToListenOn) {
2520 /** @type EventListener */
2521 const eventListener = function(evt) {
2522 if (!bodyContains(elt)) {
2523 eltToListenOn.removeEventListener(triggerSpec.trigger, eventListener)
2524 return
2525 }
2526 if (ignoreBoostedAnchorCtrlClick(elt, evt)) {
2527 return
2528 }
2529 if (explicitCancel || shouldCancel(evt, eltToListenOn)) {
2530 evt.preventDefault()
2531 }
2532 if (maybeFilterEvent(triggerSpec, elt, evt)) {
2533 return
2534 }
2535 const eventData = getInternalData(evt)
2536 eventData.triggerSpec = triggerSpec
2537 if (eventData.handledFor == null) {
2538 eventData.handledFor = []
2539 }
2540 if (eventData.handledFor.indexOf(elt) < 0) {
2541 eventData.handledFor.push(elt)
2542 if (triggerSpec.consume) {
2543 evt.stopPropagation()
2544 }
2545 if (triggerSpec.target && evt.target) {
2546 if (!matches(asElement(evt.target), triggerSpec.target)) {
2547 return
2548 }
2549 }
2550 if (triggerSpec.once) {
2551 if (elementData.triggeredOnce) {
2552 return
2553 } else {
2554 elementData.triggeredOnce = true
2555 }
2556 }
2557 if (triggerSpec.changed) {
2558 const node = evt.target
2559 // @ts-ignore value will be undefined for non-input elements, which is fine
2560 const value = node.value
2561 const lastValue = elementData.lastValue.get(triggerSpec)
2562 if (lastValue.has(node) && lastValue.get(node) === value) {
2563 return
2564 }
2565 lastValue.set(node, value)
2566 }
2567 if (elementData.delayed) {
2568 clearTimeout(elementData.delayed)
2569 }
2570 if (elementData.throttle) {
2571 return
2572 }
2573
2574 if (triggerSpec.throttle > 0) {
2575 if (!elementData.throttle) {
2576 triggerEvent(elt, 'htmx:trigger')
2577 handler(elt, evt)
2578 elementData.throttle = getWindow().setTimeout(function() {
2579 elementData.throttle = null
2580 }, triggerSpec.throttle)
2581 }
2582 } else if (triggerSpec.delay > 0) {
2583 elementData.delayed = getWindow().setTimeout(function() {
2584 triggerEvent(elt, 'htmx:trigger')
2585 handler(elt, evt)
2586 }, triggerSpec.delay)
2587 } else {
2588 triggerEvent(elt, 'htmx:trigger')
2589 handler(elt, evt)
2590 }
2591 }
2592 }
2593 if (nodeData.listenerInfos == null) {
2594 nodeData.listenerInfos = []
2595 }
2596 nodeData.listenerInfos.push({
2597 trigger: triggerSpec.trigger,
2598 listener: eventListener,
2599 on: eltToListenOn
2600 })
2601 eltToListenOn.addEventListener(triggerSpec.trigger, eventListener)
2602 })
2603 }
2604
2605 let windowIsScrolling = false // used by initScrollHandler
2606 let scrollHandler = null
2607 function initScrollHandler() {
2608 if (!scrollHandler) {
2609 scrollHandler = function() {
2610 windowIsScrolling = true
2611 }
2612 window.addEventListener('scroll', scrollHandler)
2613 window.addEventListener('resize', scrollHandler)
2614 setInterval(function() {
2615 if (windowIsScrolling) {
2616 windowIsScrolling = false
2617 forEach(getDocument().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"), function(elt) {
2618 maybeReveal(elt)
2619 })
2620 }
2621 }, 200)
2622 }
2623 }
2624
2625 /**
2626 * @param {Element} elt
2627 */
2628 function maybeReveal(elt) {
2629 if (!hasAttribute(elt, 'data-hx-revealed') && isScrolledIntoView(elt)) {
2630 elt.setAttribute('data-hx-revealed', 'true')
2631 const nodeData = getInternalData(elt)
2632 if (nodeData.initHash) {
2633 triggerEvent(elt, 'revealed')
2634 } else {
2635 // if the node isn't initialized, wait for it before triggering the request
2636 elt.addEventListener('htmx:afterProcessNode', function() { triggerEvent(elt, 'revealed') }, { once: true })
2637 }
2638 }
2639 }
2640
2641 //= ===================================================================
2642
2643 /**
2644 * @param {Element} elt
2645 * @param {TriggerHandler} handler
2646 * @param {HtmxNodeInternalData} nodeData
2647 * @param {number} delay
2648 */
2649 function loadImmediately(elt, handler, nodeData, delay) {
2650 const load = function() {
2651 if (!nodeData.loaded) {
2652 nodeData.loaded = true
2653 triggerEvent(elt, 'htmx:trigger')
2654 handler(elt)
2655 }
2656 }
2657 if (delay > 0) {
2658 getWindow().setTimeout(load, delay)
2659 } else {
2660 load()
2661 }
2662 }
2663
2664 /**
2665 * @param {Element} elt
2666 * @param {HtmxNodeInternalData} nodeData
2667 * @param {HtmxTriggerSpecification[]} triggerSpecs
2668 * @returns {boolean}
2669 */
2670 function processVerbs(elt, nodeData, triggerSpecs) {
2671 let explicitAction = false
2672 forEach(VERBS, function(verb) {
2673 if (hasAttribute(elt, 'hx-' + verb)) {
2674 const path = getAttributeValue(elt, 'hx-' + verb)
2675 explicitAction = true
2676 nodeData.path = path
2677 nodeData.verb = verb
2678 triggerSpecs.forEach(function(triggerSpec) {
2679 addTriggerHandler(elt, triggerSpec, nodeData, function(node, evt) {
2680 const elt = asElement(node)
2681 if (eltIsDisabled(elt)) {
2682 cleanUpElement(elt)
2683 return
2684 }
2685 issueAjaxRequest(verb, path, elt, evt)
2686 })
2687 })
2688 }
2689 })
2690 return explicitAction
2691 }
2692
2693 /**
2694 * @callback TriggerHandler
2695 * @param {Element} elt
2696 * @param {Event} [evt]
2697 */
2698
2699 /**
2700 * @param {Element} elt
2701 * @param {HtmxTriggerSpecification} triggerSpec
2702 * @param {HtmxNodeInternalData} nodeData
2703 * @param {TriggerHandler} handler
2704 */
2705 function addTriggerHandler(elt, triggerSpec, nodeData, handler) {
2706 if (triggerSpec.trigger === 'revealed') {
2707 initScrollHandler()
2708 addEventListener(elt, handler, nodeData, triggerSpec)
2709 maybeReveal(asElement(elt))
2710 } else if (triggerSpec.trigger === 'intersect') {
2711 const observerOptions = {}
2712 if (triggerSpec.root) {
2713 observerOptions.root = querySelectorExt(elt, triggerSpec.root)
2714 }
2715 if (triggerSpec.threshold) {
2716 observerOptions.threshold = parseFloat(triggerSpec.threshold)
2717 }
2718 const observer = new IntersectionObserver(function(entries) {
2719 for (let i = 0; i < entries.length; i++) {
2720 const entry = entries[i]
2721 if (entry.isIntersecting) {
2722 triggerEvent(elt, 'intersect')
2723 break
2724 }
2725 }
2726 }, observerOptions)
2727 observer.observe(asElement(elt))
2728 addEventListener(asElement(elt), handler, nodeData, triggerSpec)
2729 } else if (!nodeData.firstInitCompleted && triggerSpec.trigger === 'load') {
2730 if (!maybeFilterEvent(triggerSpec, elt, makeEvent('load', { elt }))) {
2731 loadImmediately(asElement(elt), handler, nodeData, triggerSpec.delay)
2732 }
2733 } else if (triggerSpec.pollInterval > 0) {
2734 nodeData.polling = true
2735 processPolling(asElement(elt), handler, triggerSpec)
2736 } else {
2737 addEventListener(elt, handler, nodeData, triggerSpec)
2738 }
2739 }
2740
2741 /**
2742 * @param {Node} node
2743 * @returns {boolean}
2744 */
2745 function shouldProcessHxOn(node) {
2746 const elt = asElement(node)
2747 if (!elt) {
2748 return false
2749 }
2750 const attributes = elt.attributes
2751 for (let j = 0; j < attributes.length; j++) {
2752 const attrName = attributes[j].name
2753 if (startsWith(attrName, 'hx-on:') || startsWith(attrName, 'data-hx-on:') ||
2754 startsWith(attrName, 'hx-on-') || startsWith(attrName, 'data-hx-on-')) {
2755 return true
2756 }
2757 }
2758 return false
2759 }
2760
2761 /**
2762 * @param {Node} elt
2763 * @returns {Element[]}
2764 */
2765 const HX_ON_QUERY = new XPathEvaluator()
2766 .createExpression('.//*[@*[ starts-with(name(), "hx-on:") or starts-with(name(), "data-hx-on:") or' +
2767 ' starts-with(name(), "hx-on-") or starts-with(name(), "data-hx-on-") ]]')
2768
2769 function processHXOnRoot(elt, elements) {
2770 if (shouldProcessHxOn(elt)) {
2771 elements.push(asElement(elt))
2772 }
2773 const iter = HX_ON_QUERY.evaluate(elt)
2774 let node = null
2775 while (node = iter.iterateNext()) elements.push(asElement(node))
2776 }
2777
2778 function findHxOnWildcardElements(elt) {
2779 /** @type {Element[]} */
2780 const elements = []
2781 if (elt instanceof DocumentFragment) {
2782 for (const child of elt.childNodes) {
2783 processHXOnRoot(child, elements)
2784 }
2785 } else {
2786 processHXOnRoot(elt, elements)
2787 }
2788 return elements
2789 }
2790
2791 /**
2792 * @param {Element} elt
2793 * @returns {NodeListOf<Element>|[]}
2794 */
2795 function findElementsToProcess(elt) {
2796 if (elt.querySelectorAll) {
2797 const boostedSelector = ', [hx-boost] a, [data-hx-boost] a, a[hx-boost], a[data-hx-boost]'
2798
2799 const extensionSelectors = []
2800 for (const e in extensions) {
2801 const extension = extensions[e]
2802 if (extension.getSelectors) {
2803 var selectors = extension.getSelectors()
2804 if (selectors) {
2805 extensionSelectors.push(selectors)
2806 }
2807 }
2808 }
2809
2810 const results = elt.querySelectorAll(VERB_SELECTOR + boostedSelector + ", form, [type='submit']," +
2811 ' [hx-ext], [data-hx-ext], [hx-trigger], [data-hx-trigger]' + extensionSelectors.flat().map(s => ', ' + s).join(''))
2812
2813 return results
2814 } else {
2815 return []
2816 }
2817 }
2818
2819 /**
2820 * Handle submit buttons/inputs that have the form attribute set
2821 * see https://developer.mozilla.org/docs/Web/HTML/Element/button
2822 * @param {Event} evt
2823 */
2824 function maybeSetLastButtonClicked(evt) {
2825 const elt = getTargetButton(evt.target)
2826 const internalData = getRelatedFormData(evt)
2827 if (internalData) {
2828 internalData.lastButtonClicked = elt
2829 }
2830 }
2831
2832 /**
2833 * @param {Event} evt
2834 */
2835 function maybeUnsetLastButtonClicked(evt) {
2836 const internalData = getRelatedFormData(evt)
2837 if (internalData) {
2838 internalData.lastButtonClicked = null
2839 }
2840 }
2841
2842 /**
2843 * @param {EventTarget} target
2844 * @returns {HTMLButtonElement|HTMLInputElement|null}
2845 */
2846 function getTargetButton(target) {
2847 return /** @type {HTMLButtonElement|HTMLInputElement|null} */ (closest(asElement(target), "button, input[type='submit']"))
2848 }
2849
2850 /**
2851 * @param {Element} elt
2852 * @returns {HTMLFormElement|null}
2853 */
2854 function getRelatedForm(elt) {
2855 // @ts-ignore Get the related form if available, else find the closest parent form
2856 return elt.form || closest(elt, 'form')
2857 }
2858
2859 /**
2860 * @param {Event} evt
2861 * @returns {HtmxNodeInternalData|undefined}
2862 */
2863 function getRelatedFormData(evt) {
2864 const elt = getTargetButton(evt.target)
2865 if (!elt) {
2866 return
2867 }
2868 const form = getRelatedForm(elt)
2869 if (!form) {
2870 return
2871 }
2872 return getInternalData(form)
2873 }
2874
2875 /**
2876 * @param {EventTarget} elt
2877 */
2878 function initButtonTracking(elt) {
2879 // need to handle both click and focus in:
2880 // focusin - in case someone tabs in to a button and hits the space bar
2881 // click - on OSX buttons do not focus on click see https://bugs.webkit.org/show_bug.cgi?id=13724
2882 elt.addEventListener('click', maybeSetLastButtonClicked)
2883 elt.addEventListener('focusin', maybeSetLastButtonClicked)
2884 elt.addEventListener('focusout', maybeUnsetLastButtonClicked)
2885 }
2886
2887 /**
2888 * @param {Element} elt
2889 * @param {string} eventName
2890 * @param {string} code
2891 */
2892 function addHxOnEventHandler(elt, eventName, code) {
2893 const nodeData = getInternalData(elt)
2894 if (!Array.isArray(nodeData.onHandlers)) {
2895 nodeData.onHandlers = []
2896 }
2897 let func
2898 /** @type EventListener */
2899 const listener = function(e) {
2900 maybeEval(elt, function() {
2901 if (eltIsDisabled(elt)) {
2902 return
2903 }
2904 if (!func) {
2905 func = new Function('event', code)
2906 }
2907 func.call(elt, e)
2908 })
2909 }
2910 elt.addEventListener(eventName, listener)
2911 nodeData.onHandlers.push({ event: eventName, listener })
2912 }
2913
2914 /**
2915 * @param {Element} elt
2916 */
2917 function processHxOnWildcard(elt) {
2918 // wipe any previous on handlers so that this function takes precedence
2919 deInitOnHandlers(elt)
2920
2921 for (let i = 0; i < elt.attributes.length; i++) {
2922 const name = elt.attributes[i].name
2923 const value = elt.attributes[i].value
2924 if (startsWith(name, 'hx-on') || startsWith(name, 'data-hx-on')) {
2925 const afterOnPosition = name.indexOf('-on') + 3
2926 const nextChar = name.slice(afterOnPosition, afterOnPosition + 1)
2927 if (nextChar === '-' || nextChar === ':') {
2928 let eventName = name.slice(afterOnPosition + 1)
2929 // if the eventName starts with a colon or dash, prepend "htmx" for shorthand support
2930 if (startsWith(eventName, ':')) {
2931 eventName = 'htmx' + eventName
2932 } else if (startsWith(eventName, '-')) {
2933 eventName = 'htmx:' + eventName.slice(1)
2934 } else if (startsWith(eventName, 'htmx-')) {
2935 eventName = 'htmx:' + eventName.slice(5)
2936 }
2937
2938 addHxOnEventHandler(elt, eventName, value)
2939 }
2940 }
2941 }
2942 }
2943
2944 /**
2945 * @param {Element|HTMLInputElement} elt
2946 */
2947 function initNode(elt) {
2948 triggerEvent(elt, 'htmx:beforeProcessNode')
2949
2950 const nodeData = getInternalData(elt)
2951 const triggerSpecs = getTriggerSpecs(elt)
2952 const hasExplicitHttpAction = processVerbs(elt, nodeData, triggerSpecs)
2953
2954 if (!hasExplicitHttpAction) {
2955 if (getClosestAttributeValue(elt, 'hx-boost') === 'true') {
2956 boostElement(elt, nodeData, triggerSpecs)
2957 } else if (hasAttribute(elt, 'hx-trigger')) {
2958 triggerSpecs.forEach(function(triggerSpec) {
2959 // For "naked" triggers, don't do anything at all
2960 addTriggerHandler(elt, triggerSpec, nodeData, function() {
2961 })
2962 })
2963 }
2964 }
2965
2966 // Handle submit buttons/inputs that have the form attribute set
2967 // see https://developer.mozilla.org/docs/Web/HTML/Element/button
2968 if (elt.tagName === 'FORM' || (getRawAttribute(elt, 'type') === 'submit' && hasAttribute(elt, 'form'))) {
2969 initButtonTracking(elt)
2970 }
2971
2972 nodeData.firstInitCompleted = true
2973 triggerEvent(elt, 'htmx:afterProcessNode')
2974 }
2975
2976 /**
2977 * @param {Element} elt
2978 * @returns {boolean}
2979 */
2980 function maybeDeInitAndHash(elt) {
2981 // Ensure only valid Elements and not shadow DOM roots are inited
2982 if (!(elt instanceof Element)) {
2983 return false
2984 }
2985
2986 const nodeData = getInternalData(elt)
2987 const hash = attributeHash(elt)
2988 if (nodeData.initHash !== hash) {
2989 deInitNode(elt)
2990 nodeData.initHash = hash
2991 return true
2992 }
2993 return false
2994 }
2995
2996 /**
2997 * Processes new content, enabling htmx behavior. This can be useful if you have content that is added to the DOM outside of the normal htmx request cycle but still want htmx attributes to work.
2998 *
2999 * @see https://htmx.org/api/#process
3000 *
3001 * @param {Element|string} elt element to process
3002 */
3003 function processNode(elt) {
3004 elt = resolveTarget(elt)
3005 if (eltIsDisabled(elt)) {
3006 cleanUpElement(elt)
3007 return
3008 }
3009
3010 const elementsToInit = []
3011 if (maybeDeInitAndHash(elt)) {
3012 elementsToInit.push(elt)
3013 }
3014 forEach(findElementsToProcess(elt), function(child) {
3015 if (eltIsDisabled(child)) {
3016 cleanUpElement(child)
3017 return
3018 }
3019 if (maybeDeInitAndHash(child)) {
3020 elementsToInit.push(child)
3021 }
3022 })
3023
3024 forEach(findHxOnWildcardElements(elt), processHxOnWildcard)
3025 forEach(elementsToInit, initNode)
3026 }
3027
3028 //= ===================================================================
3029 // Event/Log Support
3030 //= ===================================================================
3031
3032 /**
3033 * @param {string} str
3034 * @returns {string}
3035 */
3036 function kebabEventName(str) {
3037 return str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()
3038 }
3039
3040 /**
3041 * @param {string} eventName
3042 * @param {any} detail
3043 * @returns {CustomEvent}
3044 */
3045 function makeEvent(eventName, detail) {
3046 // TODO: `composed: true` here is a hack to make global event handlers work with events in shadow DOM
3047 // This breaks expected encapsulation but needs to be here until decided otherwise by core devs
3048 return new CustomEvent(eventName, { bubbles: true, cancelable: true, composed: true, detail })
3049 }
3050
3051 /**
3052 * @param {EventTarget|string} elt
3053 * @param {string} eventName
3054 * @param {any=} detail
3055 */
3056 function triggerErrorEvent(elt, eventName, detail) {
3057 triggerEvent(elt, eventName, mergeObjects({ error: eventName }, detail))
3058 }
3059
3060 /**
3061 * @param {string} eventName
3062 * @returns {boolean}
3063 */
3064 function ignoreEventForLogging(eventName) {
3065 return eventName === 'htmx:afterProcessNode'
3066 }
3067
3068 /**
3069 * `withExtensions` locates all active extensions for a provided element, then
3070 * executes the provided function using each of the active extensions. You can filter
3071 * the element's extensions by giving it a list of extensions to ignore. It should
3072 * be called internally at every extendable execution point in htmx.
3073 *
3074 * @param {Element} elt
3075 * @param {(extension:HtmxExtension) => void} toDo
3076 * @param {string[]=} extensionsToIgnore
3077 * @returns void
3078 */
3079 function withExtensions(elt, toDo, extensionsToIgnore) {
3080 forEach(getExtensions(elt, [], extensionsToIgnore), function(extension) {
3081 try {
3082 toDo(extension)
3083 } catch (e) {
3084 logError(e)
3085 }
3086 })
3087 }
3088
3089 function logError(msg) {
3090 console.error(msg)
3091 }
3092
3093 /**
3094 * Triggers a given event on an element
3095 *
3096 * @see https://htmx.org/api/#trigger
3097 *
3098 * @param {EventTarget|string} elt the element to trigger the event on
3099 * @param {string} eventName the name of the event to trigger
3100 * @param {any=} detail details for the event
3101 * @returns {boolean}
3102 */
3103 function triggerEvent(elt, eventName, detail) {
3104 elt = resolveTarget(elt)
3105 if (detail == null) {
3106 detail = {}
3107 }
3108 detail.elt = elt
3109 const event = makeEvent(eventName, detail)
3110 if (htmx.logger && !ignoreEventForLogging(eventName)) {
3111 htmx.logger(elt, eventName, detail)
3112 }
3113 if (detail.error) {
3114 logError(detail.error)
3115 triggerEvent(elt, 'htmx:error', { errorInfo: detail })
3116 }
3117 let eventResult = elt.dispatchEvent(event)
3118 const kebabName = kebabEventName(eventName)
3119 if (eventResult && kebabName !== eventName) {
3120 const kebabedEvent = makeEvent(kebabName, event.detail)
3121 eventResult = eventResult && elt.dispatchEvent(kebabedEvent)
3122 }
3123 withExtensions(asElement(elt), function(extension) {
3124 eventResult = eventResult && (extension.onEvent(eventName, event) !== false && !event.defaultPrevented)
3125 })
3126 return eventResult
3127 }
3128
3129 //= ===================================================================
3130 // History Support
3131 //= ===================================================================
3132 let currentPathForHistory
3133
3134 /**
3135 * @param {string} path
3136 */
3137 function setCurrentPathForHistory(path) {
3138 currentPathForHistory = path
3139 if (canAccessLocalStorage()) {
3140 sessionStorage.setItem('htmx-current-path-for-history', path)
3141 }
3142 }
3143
3144 setCurrentPathForHistory(location.pathname + location.search)
3145
3146 /**
3147 * @returns {Element}
3148 */
3149 function getHistoryElement() {
3150 const historyElt = getDocument().querySelector('[hx-history-elt],[data-hx-history-elt]')
3151 return historyElt || getDocument().body
3152 }
3153
3154 /**
3155 * @param {string} url
3156 * @param {Element} rootElt
3157 */
3158 function saveToHistoryCache(url, rootElt) {
3159 if (!canAccessLocalStorage()) {
3160 return
3161 }
3162
3163 // get state to save
3164 const innerHTML = cleanInnerHtmlForHistory(rootElt)
3165 const title = getDocument().title
3166 const scroll = window.scrollY
3167
3168 if (htmx.config.historyCacheSize <= 0) {
3169 // make sure that an eventually already existing cache is purged
3170 sessionStorage.removeItem('htmx-history-cache')
3171 return
3172 }
3173
3174 url = normalizePath(url)
3175
3176 const historyCache = parseJSON(sessionStorage.getItem('htmx-history-cache')) || []
3177 for (let i = 0; i < historyCache.length; i++) {
3178 if (historyCache[i].url === url) {
3179 historyCache.splice(i, 1)
3180 break
3181 }
3182 }
3183
3184 /** @type HtmxHistoryItem */
3185 const newHistoryItem = { url, content: innerHTML, title, scroll }
3186
3187 triggerEvent(getDocument().body, 'htmx:historyItemCreated', { item: newHistoryItem, cache: historyCache })
3188
3189 historyCache.push(newHistoryItem)
3190 while (historyCache.length > htmx.config.historyCacheSize) {
3191 historyCache.shift()
3192 }
3193
3194 // keep trying to save the cache until it succeeds or is empty
3195 while (historyCache.length > 0) {
3196 try {
3197 sessionStorage.setItem('htmx-history-cache', JSON.stringify(historyCache))
3198 break
3199 } catch (e) {
3200 triggerErrorEvent(getDocument().body, 'htmx:historyCacheError', { cause: e, cache: historyCache })
3201 historyCache.shift() // shrink the cache and retry
3202 }
3203 }
3204 }
3205
3206 /**
3207 * @typedef {Object} HtmxHistoryItem
3208 * @property {string} url
3209 * @property {string} content
3210 * @property {string} title
3211 * @property {number} scroll
3212 */
3213
3214 /**
3215 * @param {string} url
3216 * @returns {HtmxHistoryItem|null}
3217 */
3218 function getCachedHistory(url) {
3219 if (!canAccessLocalStorage()) {
3220 return null
3221 }
3222
3223 url = normalizePath(url)
3224
3225 const historyCache = parseJSON(sessionStorage.getItem('htmx-history-cache')) || []
3226 for (let i = 0; i < historyCache.length; i++) {
3227 if (historyCache[i].url === url) {
3228 return historyCache[i]
3229 }
3230 }
3231 return null
3232 }
3233
3234 /**
3235 * @param {Element} elt
3236 * @returns {string}
3237 */
3238 function cleanInnerHtmlForHistory(elt) {
3239 const className = htmx.config.requestClass
3240 const clone = /** @type Element */ (elt.cloneNode(true))
3241 forEach(findAll(clone, '.' + className), function(child) {
3242 removeClassFromElement(child, className)
3243 })
3244 // remove the disabled attribute for any element disabled due to an htmx request
3245 forEach(findAll(clone, '[data-disabled-by-htmx]'), function(child) {
3246 child.removeAttribute('disabled')
3247 })
3248 return clone.innerHTML
3249 }
3250
3251 function saveCurrentPageToHistory() {
3252 const elt = getHistoryElement()
3253 let path = currentPathForHistory
3254 if (canAccessLocalStorage()) {
3255 path = sessionStorage.getItem('htmx-current-path-for-history')
3256 }
3257 path = path || location.pathname + location.search
3258
3259 // Allow history snapshot feature to be disabled where hx-history="false"
3260 // is present *anywhere* in the current document we're about to save,
3261 // so we can prevent privileged data entering the cache.
3262 // The page will still be reachable as a history entry, but htmx will fetch it
3263 // live from the server onpopstate rather than look in the sessionStorage cache
3264 const disableHistoryCache = getDocument().querySelector('[hx-history="false" i],[data-hx-history="false" i]')
3265 if (!disableHistoryCache) {
3266 triggerEvent(getDocument().body, 'htmx:beforeHistorySave', { path, historyElt: elt })
3267 saveToHistoryCache(path, elt)
3268 }
3269
3270 if (htmx.config.historyEnabled) history.replaceState({ htmx: true }, getDocument().title, location.href)
3271 }
3272
3273 /**
3274 * @param {string} path
3275 */
3276 function pushUrlIntoHistory(path) {
3277 // remove the cache buster parameter, if any
3278 if (htmx.config.getCacheBusterParam) {
3279 path = path.replace(/org\.htmx\.cache-buster=[^&]*&?/, '')
3280 if (endsWith(path, '&') || endsWith(path, '?')) {
3281 path = path.slice(0, -1)
3282 }
3283 }
3284 if (htmx.config.historyEnabled) {
3285 history.pushState({ htmx: true }, '', path)
3286 }
3287 setCurrentPathForHistory(path)
3288 }
3289
3290 /**
3291 * @param {string} path
3292 */
3293 function replaceUrlInHistory(path) {
3294 if (htmx.config.historyEnabled) history.replaceState({ htmx: true }, '', path)
3295 setCurrentPathForHistory(path)
3296 }
3297
3298 /**
3299 * @param {HtmxSettleTask[]} tasks
3300 */
3301 function settleImmediately(tasks) {
3302 forEach(tasks, function(task) {
3303 task.call(undefined)
3304 })
3305 }
3306
3307 /**
3308 * @param {string} path
3309 */
3310 function loadHistoryFromServer(path) {
3311 const request = new XMLHttpRequest()
3312 const swapSpec = { swapStyle: 'innerHTML', swapDelay: 0, settleDelay: 0 }
3313 const details = { path, xhr: request, historyElt: getHistoryElement(), swapSpec }
3314 request.open('GET', path, true)
3315 if (htmx.config.historyRestoreAsHxRequest) {
3316 request.setRequestHeader('HX-Request', 'true')
3317 }
3318 request.setRequestHeader('HX-History-Restore-Request', 'true')
3319 request.setRequestHeader('HX-Current-URL', location.href)
3320 request.onload = function() {
3321 if (this.status >= 200 && this.status < 400) {
3322 details.response = this.response
3323 triggerEvent(getDocument().body, 'htmx:historyCacheMissLoad', details)
3324 swap(details.historyElt, details.response, swapSpec, {
3325 contextElement: details.historyElt,
3326 historyRequest: true
3327 })
3328 setCurrentPathForHistory(details.path)
3329 triggerEvent(getDocument().body, 'htmx:historyRestore', { path, cacheMiss: true, serverResponse: details.response })
3330 } else {
3331 triggerErrorEvent(getDocument().body, 'htmx:historyCacheMissLoadError', details)
3332 }
3333 }
3334 if (triggerEvent(getDocument().body, 'htmx:historyCacheMiss', details)) {
3335 request.send() // only send request if event not prevented
3336 }
3337 }
3338
3339 /**
3340 * @param {string} [path]
3341 */
3342 function restoreHistory(path) {
3343 saveCurrentPageToHistory()
3344 path = path || location.pathname + location.search
3345 const cached = getCachedHistory(path)
3346 if (cached) {
3347 const swapSpec = { swapStyle: 'innerHTML', swapDelay: 0, settleDelay: 0, scroll: cached.scroll }
3348 const details = { path, item: cached, historyElt: getHistoryElement(), swapSpec }
3349 if (triggerEvent(getDocument().body, 'htmx:historyCacheHit', details)) {
3350 swap(details.historyElt, cached.content, swapSpec, {
3351 contextElement: details.historyElt,
3352 title: cached.title
3353 })
3354 setCurrentPathForHistory(details.path)
3355 triggerEvent(getDocument().body, 'htmx:historyRestore', details)
3356 }
3357 } else {
3358 if (htmx.config.refreshOnHistoryMiss) {
3359 // @ts-ignore: optional parameter in reload() function throws error
3360 // noinspection JSUnresolvedReference
3361 htmx.location.reload(true)
3362 } else {
3363 loadHistoryFromServer(path)
3364 }
3365 }
3366 }
3367
3368 /**
3369 * @param {Element} elt
3370 * @returns {Element[]}
3371 */
3372 function addRequestIndicatorClasses(elt) {
3373 let indicators = /** @type Element[] */ (findAttributeTargets(elt, 'hx-indicator'))
3374 if (indicators == null) {
3375 indicators = [elt]
3376 }
3377 forEach(indicators, function(ic) {
3378 const internalData = getInternalData(ic)
3379 internalData.requestCount = (internalData.requestCount || 0) + 1
3380 ic.classList.add.call(ic.classList, htmx.config.requestClass)
3381 })
3382 return indicators
3383 }
3384
3385 /**
3386 * @param {Element} elt
3387 * @returns {Element[]}
3388 */
3389 function disableElements(elt) {
3390 let disabledElts = /** @type Element[] */ (findAttributeTargets(elt, 'hx-disabled-elt'))
3391 if (disabledElts == null) {
3392 disabledElts = []
3393 }
3394 forEach(disabledElts, function(disabledElement) {
3395 const internalData = getInternalData(disabledElement)
3396 internalData.requestCount = (internalData.requestCount || 0) + 1
3397 disabledElement.setAttribute('disabled', '')
3398 disabledElement.setAttribute('data-disabled-by-htmx', '')
3399 })
3400 return disabledElts
3401 }
3402
3403 /**
3404 * @param {Element[]} indicators
3405 * @param {Element[]} disabled
3406 */
3407 function removeRequestIndicators(indicators, disabled) {
3408 forEach(indicators.concat(disabled), function(ele) {
3409 const internalData = getInternalData(ele)
3410 internalData.requestCount = (internalData.requestCount || 1) - 1
3411 })
3412 forEach(indicators, function(ic) {
3413 const internalData = getInternalData(ic)
3414 if (internalData.requestCount === 0) {
3415 ic.classList.remove.call(ic.classList, htmx.config.requestClass)
3416 }
3417 })
3418 forEach(disabled, function(disabledElement) {
3419 const internalData = getInternalData(disabledElement)
3420 if (internalData.requestCount === 0) {
3421 disabledElement.removeAttribute('disabled')
3422 disabledElement.removeAttribute('data-disabled-by-htmx')
3423 }
3424 })
3425 }
3426
3427 //= ===================================================================
3428 // Input Value Processing
3429 //= ===================================================================
3430
3431 /**
3432 * @param {Element[]} processed
3433 * @param {Element} elt
3434 * @returns {boolean}
3435 */
3436 function haveSeenNode(processed, elt) {
3437 for (let i = 0; i < processed.length; i++) {
3438 const node = processed[i]
3439 if (node.isSameNode(elt)) {
3440 return true
3441 }
3442 }
3443 return false
3444 }
3445
3446 /**
3447 * @param {Element} element
3448 * @return {boolean}
3449 */
3450 function shouldInclude(element) {
3451 // Cast to trick tsc, undefined values will work fine here
3452 const elt = /** @type {HTMLInputElement} */ (element)
3453 if (elt.name === '' || elt.name == null || elt.disabled || closest(elt, 'fieldset[disabled]')) {
3454 return false
3455 }
3456 // ignore "submitter" types (see jQuery src/serialize.js)
3457 if (elt.type === 'button' || elt.type === 'submit' || elt.tagName === 'image' || elt.tagName === 'reset' || elt.tagName === 'file') {
3458 return false
3459 }
3460 if (elt.type === 'checkbox' || elt.type === 'radio') {
3461 return elt.checked
3462 }
3463 return true
3464 }
3465
3466 /**
3467 * @param {string} name
3468 * @param {string|Array|FormDataEntryValue} value
3469 * @param {FormData} formData */
3470 function addValueToFormData(name, value, formData) {
3471 if (name != null && value != null) {
3472 if (Array.isArray(value)) {
3473 value.forEach(function(v) { formData.append(name, v) })
3474 } else {
3475 formData.append(name, value)
3476 }
3477 }
3478 }
3479
3480 /**
3481 * @param {string} name
3482 * @param {string|Array} value
3483 * @param {FormData} formData */
3484 function removeValueFromFormData(name, value, formData) {
3485 if (name != null && value != null) {
3486 let values = formData.getAll(name)
3487 if (Array.isArray(value)) {
3488 values = values.filter(v => value.indexOf(v) < 0)
3489 } else {
3490 values = values.filter(v => v !== value)
3491 }
3492 formData.delete(name)
3493 forEach(values, v => formData.append(name, v))
3494 }
3495 }
3496
3497 /**
3498 * @param {Element} elt
3499 * @returns {string|Array}
3500 */
3501 function getValueFromInput(elt) {
3502 if (elt instanceof HTMLSelectElement && elt.multiple) {
3503 return toArray(elt.querySelectorAll('option:checked')).map(function(e) { return (/** @type HTMLOptionElement */(e)).value })
3504 }
3505 // include file inputs
3506 if (elt instanceof HTMLInputElement && elt.files) {
3507 return toArray(elt.files)
3508 }
3509 // @ts-ignore value will be undefined for non-input elements, which is fine
3510 return elt.value
3511 }
3512
3513 /**
3514 * @param {Element[]} processed
3515 * @param {FormData} formData
3516 * @param {HtmxElementValidationError[]} errors
3517 * @param {Element|HTMLInputElement|HTMLSelectElement|HTMLFormElement} elt
3518 * @param {boolean} validate
3519 */
3520 function processInputValue(processed, formData, errors, elt, validate) {
3521 if (elt == null || haveSeenNode(processed, elt)) {
3522 return
3523 } else {
3524 processed.push(elt)
3525 }
3526 if (shouldInclude(elt)) {
3527 const name = getRawAttribute(elt, 'name')
3528 addValueToFormData(name, getValueFromInput(elt), formData)
3529 if (validate) {
3530 validateElement(elt, errors)
3531 }
3532 }
3533 if (elt instanceof HTMLFormElement) {
3534 forEach(elt.elements, function(input) {
3535 if (processed.indexOf(input) >= 0) {
3536 // The input has already been processed and added to the values, but the FormData that will be
3537 // constructed right after on the form, will include it once again. So remove that input's value
3538 // now to avoid duplicates
3539 removeValueFromFormData(input.name, getValueFromInput(input), formData)
3540 } else {
3541 processed.push(input)
3542 }
3543 if (validate) {
3544 validateElement(input, errors)
3545 }
3546 })
3547 new FormData(elt).forEach(function(value, name) {
3548 if (value instanceof File && value.name === '') {
3549 return // ignore no-name files
3550 }
3551 addValueToFormData(name, value, formData)
3552 })
3553 }
3554 }
3555
3556 /**
3557 * @param {Element} elt
3558 * @param {HtmxElementValidationError[]} errors
3559 */
3560 function validateElement(elt, errors) {
3561 const element = /** @type {HTMLElement & ElementInternals} */ (elt)
3562 if (element.willValidate) {
3563 triggerEvent(element, 'htmx:validation:validate')
3564 if (!element.checkValidity()) {
3565 if (
3566 triggerEvent(element, 'htmx:validation:failed', {
3567 message: element.validationMessage,
3568 validity: element.validity
3569 }) &&
3570 !errors.length &&
3571 htmx.config.reportValidityOfForms
3572 ) {
3573 element.reportValidity()
3574 }
3575 errors.push({ elt: element, message: element.validationMessage, validity: element.validity })
3576 }
3577 }
3578 }
3579
3580 /**
3581 * Override values in the one FormData with those from another.
3582 * @param {FormData} receiver the formdata that will be mutated
3583 * @param {FormData} donor the formdata that will provide the overriding values
3584 * @returns {FormData} the {@linkcode receiver}
3585 */
3586 function overrideFormData(receiver, donor) {
3587 for (const key of donor.keys()) {
3588 receiver.delete(key)
3589 }
3590 donor.forEach(function(value, key) {
3591 receiver.append(key, value)
3592 })
3593 return receiver
3594 }
3595
3596 /**
3597 * @param {Element|HTMLFormElement} elt
3598 * @param {HttpVerb} verb
3599 * @returns {{errors: HtmxElementValidationError[], formData: FormData, values: Object}}
3600 */
3601 function getInputValues(elt, verb) {
3602 /** @type Element[] */
3603 const processed = []
3604 const formData = new FormData()
3605 const priorityFormData = new FormData()
3606 /** @type HtmxElementValidationError[] */
3607 const errors = []
3608 const internalData = getInternalData(elt)
3609 if (internalData.lastButtonClicked && !bodyContains(internalData.lastButtonClicked)) {
3610 internalData.lastButtonClicked = null
3611 }
3612
3613 // only validate when form is directly submitted and novalidate or formnovalidate are not set
3614 // or if the element has an explicit hx-validate="true" on it
3615 let validate = (elt instanceof HTMLFormElement && elt.noValidate !== true) || getAttributeValue(elt, 'hx-validate') === 'true'
3616 if (internalData.lastButtonClicked) {
3617 validate = validate && internalData.lastButtonClicked.formNoValidate !== true
3618 }
3619
3620 // for a non-GET include the related form, which may or may not be a parent element of elt
3621 if (verb !== 'get') {
3622 processInputValue(processed, priorityFormData, errors, getRelatedForm(elt), validate)
3623 }
3624
3625 // include the element itself
3626 processInputValue(processed, formData, errors, elt, validate)
3627
3628 // if a button or submit was clicked last, include its value
3629 if (internalData.lastButtonClicked || elt.tagName === 'BUTTON' ||
3630 (elt.tagName === 'INPUT' && getRawAttribute(elt, 'type') === 'submit')) {
3631 const button = internalData.lastButtonClicked || (/** @type HTMLInputElement|HTMLButtonElement */(elt))
3632 const name = getRawAttribute(button, 'name')
3633 addValueToFormData(name, button.value, priorityFormData)
3634 }
3635
3636 // include any explicit includes
3637 const includes = findAttributeTargets(elt, 'hx-include')
3638 forEach(includes, function(node) {
3639 processInputValue(processed, formData, errors, asElement(node), validate)
3640 // if a non-form is included, include any input values within it
3641 if (!matches(node, 'form')) {
3642 forEach(asParentNode(node).querySelectorAll(INPUT_SELECTOR), function(descendant) {
3643 processInputValue(processed, formData, errors, descendant, validate)
3644 })
3645 }
3646 })
3647
3648 // values from a <form> take precedence, overriding the regular values
3649 overrideFormData(formData, priorityFormData)
3650
3651 return { errors, formData, values: formDataProxy(formData) }
3652 }
3653
3654 /**
3655 * @param {string} returnStr
3656 * @param {string} name
3657 * @param {any} realValue
3658 * @returns {string}
3659 */
3660 function appendParam(returnStr, name, realValue) {
3661 if (returnStr !== '') {
3662 returnStr += '&'
3663 }
3664 if (String(realValue) === '[object Object]') {
3665 realValue = JSON.stringify(realValue)
3666 }
3667 const s = encodeURIComponent(realValue)
3668 returnStr += encodeURIComponent(name) + '=' + s
3669 return returnStr
3670 }
3671
3672 /**
3673 * @param {FormData|Object} values
3674 * @returns string
3675 */
3676 function urlEncode(values) {
3677 values = formDataFromObject(values)
3678 let returnStr = ''
3679 values.forEach(function(value, key) {
3680 returnStr = appendParam(returnStr, key, value)
3681 })
3682 return returnStr
3683 }
3684
3685 //= ===================================================================
3686 // Ajax
3687 //= ===================================================================
3688
3689 /**
3690 * @param {Element} elt
3691 * @param {Element} target
3692 * @param {string} prompt
3693 * @returns {HtmxHeaderSpecification}
3694 */
3695 function getHeaders(elt, target, prompt) {
3696 /** @type HtmxHeaderSpecification */
3697 const headers = {
3698 'HX-Request': 'true',
3699 'HX-Trigger': getRawAttribute(elt, 'id'),
3700 'HX-Trigger-Name': getRawAttribute(elt, 'name'),
3701 'HX-Target': getAttributeValue(target, 'id'),
3702 'HX-Current-URL': location.href
3703 }
3704 getValuesForElement(elt, 'hx-headers', false, headers)
3705 if (prompt !== undefined) {
3706 headers['HX-Prompt'] = prompt
3707 }
3708 if (getInternalData(elt).boosted) {
3709 headers['HX-Boosted'] = 'true'
3710 }
3711 return headers
3712 }
3713
3714 /**
3715 * filterValues takes an object containing form input values
3716 * and returns a new object that only contains keys that are
3717 * specified by the closest "hx-params" attribute
3718 * @param {FormData} inputValues
3719 * @param {Element} elt
3720 * @returns {FormData}
3721 */
3722 function filterValues(inputValues, elt) {
3723 const paramsValue = getClosestAttributeValue(elt, 'hx-params')
3724 if (paramsValue) {
3725 if (paramsValue === 'none') {
3726 return new FormData()
3727 } else if (paramsValue === '*') {
3728 return inputValues
3729 } else if (paramsValue.indexOf('not ') === 0) {
3730 forEach(paramsValue.slice(4).split(','), function(name) {
3731 name = name.trim()
3732 inputValues.delete(name)
3733 })
3734 return inputValues
3735 } else {
3736 const newValues = new FormData()
3737 forEach(paramsValue.split(','), function(name) {
3738 name = name.trim()
3739 if (inputValues.has(name)) {
3740 inputValues.getAll(name).forEach(function(value) { newValues.append(name, value) })
3741 }
3742 })
3743 return newValues
3744 }
3745 } else {
3746 return inputValues
3747 }
3748 }
3749
3750 /**
3751 * @param {Element} elt
3752 * @return {boolean}
3753 */
3754 function isAnchorLink(elt) {
3755 return !!getRawAttribute(elt, 'href') && getRawAttribute(elt, 'href').indexOf('#') >= 0
3756 }
3757
3758 /**
3759 * @param {Element} elt
3760 * @param {HtmxSwapStyle} [swapInfoOverride]
3761 * @returns {HtmxSwapSpecification}
3762 */
3763 function getSwapSpecification(elt, swapInfoOverride) {
3764 const swapInfo = swapInfoOverride || getClosestAttributeValue(elt, 'hx-swap')
3765 /** @type HtmxSwapSpecification */
3766 const swapSpec = {
3767 swapStyle: getInternalData(elt).boosted ? 'innerHTML' : htmx.config.defaultSwapStyle,
3768 swapDelay: htmx.config.defaultSwapDelay,
3769 settleDelay: htmx.config.defaultSettleDelay
3770 }
3771 if (htmx.config.scrollIntoViewOnBoost && getInternalData(elt).boosted && !isAnchorLink(elt)) {
3772 swapSpec.show = 'top'
3773 }
3774 if (swapInfo) {
3775 const split = splitOnWhitespace(swapInfo)
3776 if (split.length > 0) {
3777 for (let i = 0; i < split.length; i++) {
3778 const value = split[i]
3779 if (value.indexOf('swap:') === 0) {
3780 swapSpec.swapDelay = parseInterval(value.slice(5))
3781 } else if (value.indexOf('settle:') === 0) {
3782 swapSpec.settleDelay = parseInterval(value.slice(7))
3783 } else if (value.indexOf('transition:') === 0) {
3784 swapSpec.transition = value.slice(11) === 'true'
3785 } else if (value.indexOf('ignoreTitle:') === 0) {
3786 swapSpec.ignoreTitle = value.slice(12) === 'true'
3787 } else if (value.indexOf('scroll:') === 0) {
3788 const scrollSpec = value.slice(7)
3789 var splitSpec = scrollSpec.split(':')
3790 const scrollVal = splitSpec.pop()
3791 var selectorVal = splitSpec.length > 0 ? splitSpec.join(':') : null
3792 // @ts-ignore
3793 swapSpec.scroll = scrollVal
3794 swapSpec.scrollTarget = selectorVal
3795 } else if (value.indexOf('show:') === 0) {
3796 const showSpec = value.slice(5)
3797 var splitSpec = showSpec.split(':')
3798 const showVal = splitSpec.pop()
3799 var selectorVal = splitSpec.length > 0 ? splitSpec.join(':') : null
3800 swapSpec.show = showVal
3801 swapSpec.showTarget = selectorVal
3802 } else if (value.indexOf('focus-scroll:') === 0) {
3803 const focusScrollVal = value.slice('focus-scroll:'.length)
3804 swapSpec.focusScroll = focusScrollVal == 'true'
3805 } else if (i == 0) {
3806 swapSpec.swapStyle = value
3807 } else {
3808 logError('Unknown modifier in hx-swap: ' + value)
3809 }
3810 }
3811 }
3812 }
3813 return swapSpec
3814 }
3815
3816 /**
3817 * @param {Element} elt
3818 * @return {boolean}
3819 */
3820 function usesFormData(elt) {
3821 return getClosestAttributeValue(elt, 'hx-encoding') === 'multipart/form-data' ||
3822 (matches(elt, 'form') && getRawAttribute(elt, 'enctype') === 'multipart/form-data')
3823 }
3824
3825 /**
3826 * @param {XMLHttpRequest} xhr
3827 * @param {Element} elt
3828 * @param {FormData} filteredParameters
3829 * @returns {*|string|null}
3830 */
3831 function encodeParamsForBody(xhr, elt, filteredParameters) {
3832 let encodedParameters = null
3833 withExtensions(elt, function(extension) {
3834 if (encodedParameters == null) {
3835 encodedParameters = extension.encodeParameters(xhr, filteredParameters, elt)
3836 }
3837 })
3838 if (encodedParameters != null) {
3839 return encodedParameters
3840 } else {
3841 if (usesFormData(elt)) {
3842 // Force conversion to an actual FormData object in case filteredParameters is a formDataProxy
3843 // See https://github.com/bigskysoftware/htmx/issues/2317
3844 return overrideFormData(new FormData(), formDataFromObject(filteredParameters))
3845 } else {
3846 return urlEncode(filteredParameters)
3847 }
3848 }
3849 }
3850
3851 /**
3852 *
3853 * @param {Element} target
3854 * @returns {HtmxSettleInfo}
3855 */
3856 function makeSettleInfo(target) {
3857 return { tasks: [], elts: [target] }
3858 }
3859
3860 /**
3861 * @param {Element[]} content
3862 * @param {HtmxSwapSpecification} swapSpec
3863 */
3864 function updateScrollState(content, swapSpec) {
3865 const first = content[0]
3866 const last = content[content.length - 1]
3867 if (swapSpec.scroll) {
3868 var target = null
3869 if (swapSpec.scrollTarget) {
3870 target = asElement(querySelectorExt(first, swapSpec.scrollTarget))
3871 }
3872 if (swapSpec.scroll === 'top' && (first || target)) {
3873 target = target || first
3874 target.scrollTop = 0
3875 }
3876 if (swapSpec.scroll === 'bottom' && (last || target)) {
3877 target = target || last
3878 target.scrollTop = target.scrollHeight
3879 }
3880 if (typeof swapSpec.scroll === 'number') {
3881 getWindow().setTimeout(function() {
3882 window.scrollTo(0, /** @type number */ (swapSpec.scroll))
3883 }, 0) // next 'tick', so browser has time to render layout
3884 }
3885 }
3886 if (swapSpec.show) {
3887 var target = null
3888 if (swapSpec.showTarget) {
3889 let targetStr = swapSpec.showTarget
3890 if (swapSpec.showTarget === 'window') {
3891 targetStr = 'body'
3892 }
3893 target = asElement(querySelectorExt(first, targetStr))
3894 }
3895 if (swapSpec.show === 'top' && (first || target)) {
3896 target = target || first
3897 // @ts-ignore For some reason tsc doesn't recognize "instant" as a valid option for now
3898 target.scrollIntoView({ block: 'start', behavior: htmx.config.scrollBehavior })
3899 }
3900 if (swapSpec.show === 'bottom' && (last || target)) {
3901 target = target || last
3902 // @ts-ignore For some reason tsc doesn't recognize "instant" as a valid option for now
3903 target.scrollIntoView({ block: 'end', behavior: htmx.config.scrollBehavior })
3904 }
3905 }
3906 }
3907
3908 /**
3909 * @param {Element} elt
3910 * @param {string} attr
3911 * @param {boolean=} evalAsDefault
3912 * @param {Object=} values
3913 * @param {Event=} event
3914 * @returns {Object}
3915 */
3916 function getValuesForElement(elt, attr, evalAsDefault, values, event) {
3917 if (values == null) {
3918 values = {}
3919 }
3920 if (elt == null) {
3921 return values
3922 }
3923 const attributeValue = getAttributeValue(elt, attr)
3924 if (attributeValue) {
3925 let str = attributeValue.trim()
3926 let evaluateValue = evalAsDefault
3927 if (str === 'unset') {
3928 return null
3929 }
3930 if (str.indexOf('javascript:') === 0) {
3931 str = str.slice(11)
3932 evaluateValue = true
3933 } else if (str.indexOf('js:') === 0) {
3934 str = str.slice(3)
3935 evaluateValue = true
3936 }
3937 if (str.indexOf('{') !== 0) {
3938 str = '{' + str + '}'
3939 }
3940 let varsValues
3941 if (evaluateValue) {
3942 varsValues = maybeEval(elt, function() {
3943 if (event) {
3944 return Function('event', 'return (' + str + ')').call(elt, event)
3945 } else { // allow window.event to be accessible
3946 return Function('return (' + str + ')').call(elt)
3947 }
3948 }, {})
3949 } else {
3950 varsValues = parseJSON(str)
3951 }
3952 for (const key in varsValues) {
3953 if (varsValues.hasOwnProperty(key)) {
3954 if (values[key] == null) {
3955 values[key] = varsValues[key]
3956 }
3957 }
3958 }
3959 }
3960 return getValuesForElement(asElement(parentElt(elt)), attr, evalAsDefault, values, event)
3961 }
3962
3963 /**
3964 * @param {EventTarget|string} elt
3965 * @param {() => any} toEval
3966 * @param {any=} defaultVal
3967 * @returns {any}
3968 */
3969 function maybeEval(elt, toEval, defaultVal) {
3970 if (htmx.config.allowEval) {
3971 return toEval()
3972 } else {
3973 triggerErrorEvent(elt, 'htmx:evalDisallowedError')
3974 return defaultVal
3975 }
3976 }
3977
3978 /**
3979 * @param {Element} elt
3980 * @param {Event=} event
3981 * @param {*?=} expressionVars
3982 * @returns
3983 */
3984 function getHXVarsForElement(elt, event, expressionVars) {
3985 return getValuesForElement(elt, 'hx-vars', true, expressionVars, event)
3986 }
3987
3988 /**
3989 * @param {Element} elt
3990 * @param {Event=} event
3991 * @param {*?=} expressionVars
3992 * @returns
3993 */
3994 function getHXValsForElement(elt, event, expressionVars) {
3995 return getValuesForElement(elt, 'hx-vals', false, expressionVars, event)
3996 }
3997
3998 /**
3999 * @param {Element} elt
4000 * @param {Event=} event
4001 * @returns {FormData}
4002 */
4003 function getExpressionVars(elt, event) {
4004 return mergeObjects(getHXVarsForElement(elt, event), getHXValsForElement(elt, event))
4005 }
4006
4007 /**
4008 * @param {XMLHttpRequest} xhr
4009 * @param {string} header
4010 * @param {string|null} headerValue
4011 */
4012 function safelySetHeaderValue(xhr, header, headerValue) {
4013 if (headerValue !== null) {
4014 try {
4015 xhr.setRequestHeader(header, headerValue)
4016 } catch (e) {
4017 // On an exception, try to set the header URI encoded instead
4018 xhr.setRequestHeader(header, encodeURIComponent(headerValue))
4019 xhr.setRequestHeader(header + '-URI-AutoEncoded', 'true')
4020 }
4021 }
4022 }
4023
4024 /**
4025 * @param {XMLHttpRequest} xhr
4026 * @return {string}
4027 */
4028 function getPathFromResponse(xhr) {
4029 if (xhr.responseURL) {
4030 try {
4031 const url = new URL(xhr.responseURL)
4032 return url.pathname + url.search
4033 } catch (e) {
4034 triggerErrorEvent(getDocument().body, 'htmx:badResponseUrl', { url: xhr.responseURL })
4035 }
4036 }
4037 }
4038
4039 /**
4040 * @param {XMLHttpRequest} xhr
4041 * @param {RegExp} regexp
4042 * @return {boolean}
4043 */
4044 function hasHeader(xhr, regexp) {
4045 return regexp.test(xhr.getAllResponseHeaders())
4046 }
4047
4048 /**
4049 * Issues an htmx-style AJAX request
4050 *
4051 * @see https://htmx.org/api/#ajax
4052 *
4053 * @param {HttpVerb} verb
4054 * @param {string} path the URL path to make the AJAX
4055 * @param {Element|string|HtmxAjaxHelperContext} context the element to target (defaults to the **body**) | a selector for the target | a context object that contains any of the following
4056 * @return {Promise<void>} Promise that resolves immediately if no request is sent, or when the request is complete
4057 */
4058 function ajaxHelper(verb, path, context) {
4059 verb = (/** @type HttpVerb */(verb.toLowerCase()))
4060 if (context) {
4061 if (context instanceof Element || typeof context === 'string') {
4062 return issueAjaxRequest(verb, path, null, null, {
4063 targetOverride: resolveTarget(context) || DUMMY_ELT,
4064 returnPromise: true
4065 })
4066 } else {
4067 let resolvedTarget = resolveTarget(context.target)
4068 // If target is supplied but can't resolve OR source is supplied but both target and source can't be resolved
4069 // then use DUMMY_ELT to abort the request with htmx:targetError to avoid it replacing body by mistake
4070 if ((context.target && !resolvedTarget) || (context.source && !resolvedTarget && !resolveTarget(context.source))) {
4071 resolvedTarget = DUMMY_ELT
4072 }
4073 return issueAjaxRequest(verb, path, resolveTarget(context.source), context.event,
4074 {
4075 handler: context.handler,
4076 headers: context.headers,
4077 values: context.values,
4078 targetOverride: resolvedTarget,
4079 swapOverride: context.swap,
4080 select: context.select,
4081 returnPromise: true,
4082 push: context.push,
4083 replace: context.replace,
4084 selectOOB: context.selectOOB
4085 })
4086 }
4087 } else {
4088 return issueAjaxRequest(verb, path, null, null, {
4089 returnPromise: true
4090 })
4091 }
4092 }
4093
4094 /**
4095 * @param {Element} elt
4096 * @return {Element[]}
4097 */
4098 function hierarchyForElt(elt) {
4099 const arr = []
4100 while (elt) {
4101 arr.push(elt)
4102 elt = elt.parentElement
4103 }
4104 return arr
4105 }
4106
4107 /**
4108 * @param {Element} elt
4109 * @param {string} path
4110 * @param {HtmxRequestConfig} requestConfig
4111 * @return {boolean}
4112 */
4113 function verifyPath(elt, path, requestConfig) {
4114 const url = new URL(path, location.protocol !== 'about:' ? location.href : window.origin)
4115 const origin = location.protocol !== 'about:' ? location.origin : window.origin
4116 const sameHost = origin === url.origin
4117
4118 if (htmx.config.selfRequestsOnly) {
4119 if (!sameHost) {
4120 return false
4121 }
4122 }
4123 return triggerEvent(elt, 'htmx:validateUrl', mergeObjects({ url, sameHost }, requestConfig))
4124 }
4125
4126 /**
4127 * @param {Object|FormData} obj
4128 * @return {FormData}
4129 */
4130 function formDataFromObject(obj) {
4131 if (obj instanceof FormData) return obj
4132 const formData = new FormData()
4133 for (const key in obj) {
4134 if (obj.hasOwnProperty(key)) {
4135 if (obj[key] && typeof obj[key].forEach === 'function') {
4136 obj[key].forEach(function(v) { formData.append(key, v) })
4137 } else if (typeof obj[key] === 'object' && !(obj[key] instanceof Blob)) {
4138 formData.append(key, JSON.stringify(obj[key]))
4139 } else {
4140 formData.append(key, obj[key])
4141 }
4142 }
4143 }
4144 return formData
4145 }
4146
4147 /**
4148 * @param {FormData} formData
4149 * @param {string} name
4150 * @param {Array} array
4151 * @returns {Array}
4152 */
4153 function formDataArrayProxy(formData, name, array) {
4154 // mutating the array should mutate the underlying form data
4155 return new Proxy(array, {
4156 get: function(target, key) {
4157 if (typeof key === 'number') return target[key]
4158 if (key === 'length') return target.length
4159 if (key === 'push') {
4160 return function(value) {
4161 target.push(value)
4162 formData.append(name, value)
4163 }
4164 }
4165 if (typeof target[key] === 'function') {
4166 return function() {
4167 target[key].apply(target, arguments)
4168 formData.delete(name)
4169 target.forEach(function(v) { formData.append(name, v) })
4170 }
4171 }
4172
4173 if (target[key] && target[key].length === 1) {
4174 return target[key][0]
4175 } else {
4176 return target[key]
4177 }
4178 },
4179 set: function(target, index, value) {
4180 target[index] = value
4181 formData.delete(name)
4182 target.forEach(function(v) { formData.append(name, v) })
4183 return true
4184 }
4185 })
4186 }
4187
4188 /**
4189 * @param {FormData} formData
4190 * @returns {Object}
4191 */
4192 function formDataProxy(formData) {
4193 return new Proxy(formData, {
4194 get: function(target, name) {
4195 if (typeof name === 'symbol') {
4196 // Forward symbol calls to the FormData itself directly
4197 const result = Reflect.get(target, name)
4198 // Wrap in function with apply to correctly bind the FormData context, as a direct call would result in an illegal invocation error
4199 if (typeof result === 'function') {
4200 return function() {
4201 return result.apply(formData, arguments)
4202 }
4203 } else {
4204 return result
4205 }
4206 }
4207 if (name === 'toJSON') {
4208 // Support JSON.stringify call on proxy
4209 return () => Object.fromEntries(formData)
4210 }
4211 if (name in target) {
4212 // Wrap in function with apply to correctly bind the FormData context, as a direct call would result in an illegal invocation error
4213 if (typeof target[name] === 'function') {
4214 return function() {
4215 return formData[name].apply(formData, arguments)
4216 }
4217 }
4218 }
4219 const array = formData.getAll(name)
4220 // Those 2 undefined & single value returns are for retro-compatibility as we weren't using FormData before
4221 if (array.length === 0) {
4222 return undefined
4223 } else if (array.length === 1) {
4224 return array[0]
4225 } else {
4226 return formDataArrayProxy(target, name, array)
4227 }
4228 },
4229 set: function(target, name, value) {
4230 if (typeof name !== 'string') {
4231 return false
4232 }
4233 target.delete(name)
4234 if (value && typeof value.forEach === 'function') {
4235 value.forEach(function(v) { target.append(name, v) })
4236 } else if (typeof value === 'object' && !(value instanceof Blob)) {
4237 target.append(name, JSON.stringify(value))
4238 } else {
4239 target.append(name, value)
4240 }
4241 return true
4242 },
4243 deleteProperty: function(target, name) {
4244 if (typeof name === 'string') {
4245 target.delete(name)
4246 }
4247 return true
4248 },
4249 // Support Object.assign call from proxy
4250 ownKeys: function(target) {
4251 return Reflect.ownKeys(Object.fromEntries(target))
4252 },
4253 getOwnPropertyDescriptor: function(target, prop) {
4254 return Reflect.getOwnPropertyDescriptor(Object.fromEntries(target), prop)
4255 }
4256 })
4257 }
4258
4259 /**
4260 * @param {HttpVerb} verb
4261 * @param {string} path
4262 * @param {Element} elt
4263 * @param {Event} event
4264 * @param {HtmxAjaxEtc} [etc]
4265 * @param {boolean} [confirmed]
4266 * @return {Promise<void>}
4267 */
4268 function issueAjaxRequest(verb, path, elt, event, etc, confirmed) {
4269 let resolve = null
4270 let reject = null
4271 etc = etc != null ? etc : {}
4272 if (etc.returnPromise && typeof Promise !== 'undefined') {
4273 var promise = new Promise(function(_resolve, _reject) {
4274 resolve = _resolve
4275 reject = _reject
4276 })
4277 }
4278 if (elt == null) {
4279 elt = getDocument().body
4280 }
4281 const responseHandler = etc.handler || handleAjaxResponse
4282 const select = etc.select || null
4283
4284 if (!bodyContains(elt)) {
4285 // do not issue requests for elements removed from the DOM
4286 maybeCall(resolve)
4287 return promise
4288 }
4289 const target = etc.targetOverride || asElement(getTarget(elt))
4290 if (target == null || target == DUMMY_ELT) {
4291 triggerErrorEvent(elt, 'htmx:targetError', { target: getClosestAttributeValue(elt, 'hx-target') })
4292 maybeCall(reject)
4293 return promise
4294 }
4295
4296 let eltData = getInternalData(elt)
4297 const submitter = eltData.lastButtonClicked
4298
4299 if (submitter) {
4300 const buttonPath = getRawAttribute(submitter, 'formaction')
4301 if (buttonPath != null) {
4302 path = buttonPath
4303 }
4304
4305 const buttonVerb = getRawAttribute(submitter, 'formmethod')
4306 if (buttonVerb != null) {
4307 if (VERBS.includes(buttonVerb.toLowerCase())) {
4308 verb = (/** @type HttpVerb */(buttonVerb))
4309 } else {
4310 maybeCall(resolve)
4311 return promise
4312 }
4313 }
4314 }
4315
4316 const confirmQuestion = getClosestAttributeValue(elt, 'hx-confirm')
4317 // allow event-based confirmation w/ a callback
4318 if (confirmed === undefined) {
4319 const issueRequest = function(skipConfirmation) {
4320 return issueAjaxRequest(verb, path, elt, event, etc, !!skipConfirmation)
4321 }
4322 const confirmDetails = { target, elt, path, verb, triggeringEvent: event, etc, issueRequest, question: confirmQuestion }
4323 if (triggerEvent(elt, 'htmx:confirm', confirmDetails) === false) {
4324 maybeCall(resolve)
4325 return promise
4326 }
4327 }
4328
4329 let syncElt = elt
4330 let syncStrategy = getClosestAttributeValue(elt, 'hx-sync')
4331 let queueStrategy = null
4332 let abortable = false
4333 if (syncStrategy) {
4334 const syncStrings = syncStrategy.split(':')
4335 const selector = syncStrings[0].trim()
4336 if (selector === 'this') {
4337 syncElt = findThisElement(elt, 'hx-sync')
4338 } else {
4339 syncElt = asElement(querySelectorExt(elt, selector))
4340 }
4341 // default to the drop strategy
4342 syncStrategy = (syncStrings[1] || 'drop').trim()
4343 eltData = getInternalData(syncElt)
4344 if (syncStrategy === 'drop' && eltData.xhr && eltData.abortable !== true) {
4345 maybeCall(resolve)
4346 return promise
4347 } else if (syncStrategy === 'abort') {
4348 if (eltData.xhr) {
4349 maybeCall(resolve)
4350 return promise
4351 } else {
4352 abortable = true
4353 }
4354 } else if (syncStrategy === 'replace') {
4355 triggerEvent(syncElt, 'htmx:abort') // abort the current request and continue
4356 } else if (syncStrategy.indexOf('queue') === 0) {
4357 const queueStrArray = syncStrategy.split(' ')
4358 queueStrategy = (queueStrArray[1] || 'last').trim()
4359 }
4360 }
4361
4362 if (eltData.xhr) {
4363 if (eltData.abortable) {
4364 triggerEvent(syncElt, 'htmx:abort') // abort the current request and continue
4365 } else {
4366 if (queueStrategy == null) {
4367 if (event) {
4368 const eventData = getInternalData(event)
4369 if (eventData && eventData.triggerSpec && eventData.triggerSpec.queue) {
4370 queueStrategy = eventData.triggerSpec.queue
4371 }
4372 }
4373 if (queueStrategy == null) {
4374 queueStrategy = 'last'
4375 }
4376 }
4377 if (eltData.queuedRequests == null) {
4378 eltData.queuedRequests = []
4379 }
4380 if (queueStrategy === 'first' && eltData.queuedRequests.length === 0) {
4381 eltData.queuedRequests.push(function() {
4382 issueAjaxRequest(verb, path, elt, event, etc)
4383 })
4384 } else if (queueStrategy === 'all') {
4385 eltData.queuedRequests.push(function() {
4386 issueAjaxRequest(verb, path, elt, event, etc)
4387 })
4388 } else if (queueStrategy === 'last') {
4389 eltData.queuedRequests = [] // dump existing queue
4390 eltData.queuedRequests.push(function() {
4391 issueAjaxRequest(verb, path, elt, event, etc)
4392 })
4393 }
4394 maybeCall(resolve)
4395 return promise
4396 }
4397 }
4398
4399 const xhr = new XMLHttpRequest()
4400 eltData.xhr = xhr
4401 eltData.abortable = abortable
4402 const endRequestLock = function() {
4403 eltData.xhr = null
4404 eltData.abortable = false
4405 if (eltData.queuedRequests != null &&
4406 eltData.queuedRequests.length > 0) {
4407 const queuedRequest = eltData.queuedRequests.shift()
4408 queuedRequest()
4409 }
4410 }
4411 const promptQuestion = getClosestAttributeValue(elt, 'hx-prompt')
4412 if (promptQuestion) {
4413 var promptResponse = prompt(promptQuestion)
4414 // prompt returns null if cancelled and empty string if accepted with no entry
4415 if (promptResponse === null ||
4416 !triggerEvent(elt, 'htmx:prompt', { prompt: promptResponse, target })) {
4417 maybeCall(resolve)
4418 endRequestLock()
4419 return promise
4420 }
4421 }
4422
4423 if (confirmQuestion && !confirmed) {
4424 if (!confirm(confirmQuestion)) {
4425 maybeCall(resolve)
4426 endRequestLock()
4427 return promise
4428 }
4429 }
4430
4431 let headers = getHeaders(elt, target, promptResponse)
4432
4433 if (verb !== 'get' && !usesFormData(elt)) {
4434 headers['Content-Type'] = 'application/x-www-form-urlencoded'
4435 }
4436
4437 if (etc.headers) {
4438 headers = mergeObjects(headers, etc.headers)
4439 }
4440 const results = getInputValues(elt, verb)
4441 let errors = results.errors
4442 const rawFormData = results.formData
4443 if (etc.values) {
4444 overrideFormData(rawFormData, formDataFromObject(etc.values))
4445 }
4446 const expressionVars = formDataFromObject(getExpressionVars(elt, event))
4447 const allFormData = overrideFormData(rawFormData, expressionVars)
4448 let filteredFormData = filterValues(allFormData, elt)
4449
4450 if (htmx.config.getCacheBusterParam && verb === 'get') {
4451 filteredFormData.set('org.htmx.cache-buster', getRawAttribute(target, 'id') || 'true')
4452 }
4453
4454 // behavior of anchors w/ empty href is to use the current URL
4455 if (path == null || path === '') {
4456 path = location.href
4457 }
4458
4459 /**
4460 * @type {Object}
4461 * @property {boolean} [credentials]
4462 * @property {number} [timeout]
4463 * @property {boolean} [noHeaders]
4464 */
4465 const requestAttrValues = getValuesForElement(elt, 'hx-request')
4466
4467 const eltIsBoosted = getInternalData(elt).boosted
4468
4469 let useUrlParams = htmx.config.methodsThatUseUrlParams.indexOf(verb) >= 0
4470
4471 /** @type HtmxRequestConfig */
4472 const requestConfig = {
4473 boosted: eltIsBoosted,
4474 useUrlParams,
4475 formData: filteredFormData,
4476 parameters: formDataProxy(filteredFormData),
4477 unfilteredFormData: allFormData,
4478 unfilteredParameters: formDataProxy(allFormData),
4479 headers,
4480 elt,
4481 target,
4482 verb,
4483 errors,
4484 withCredentials: etc.credentials || requestAttrValues.credentials || htmx.config.withCredentials,
4485 timeout: etc.timeout || requestAttrValues.timeout || htmx.config.timeout,
4486 path,
4487 triggeringEvent: event
4488 }
4489
4490 if (!triggerEvent(elt, 'htmx:configRequest', requestConfig)) {
4491 maybeCall(resolve)
4492 endRequestLock()
4493 return promise
4494 }
4495
4496 // copy out in case the object was overwritten
4497 path = requestConfig.path
4498 verb = requestConfig.verb
4499 headers = requestConfig.headers
4500 filteredFormData = formDataFromObject(requestConfig.parameters)
4501 errors = requestConfig.errors
4502 useUrlParams = requestConfig.useUrlParams
4503
4504 if (errors && errors.length > 0) {
4505 triggerEvent(elt, 'htmx:validation:halted', requestConfig)
4506 maybeCall(resolve)
4507 endRequestLock()
4508 return promise
4509 }
4510
4511 const splitPath = path.split('#')
4512 const pathNoAnchor = splitPath[0]
4513 const anchor = splitPath[1]
4514
4515 let finalPath = path
4516 if (useUrlParams) {
4517 finalPath = pathNoAnchor
4518 const hasValues = !filteredFormData.keys().next().done
4519 if (hasValues) {
4520 if (finalPath.indexOf('?') < 0) {
4521 finalPath += '?'
4522 } else {
4523 finalPath += '&'
4524 }
4525 finalPath += urlEncode(filteredFormData)
4526 if (anchor) {
4527 finalPath += '#' + anchor
4528 }
4529 }
4530 }
4531
4532 if (!verifyPath(elt, finalPath, requestConfig)) {
4533 triggerErrorEvent(elt, 'htmx:invalidPath', requestConfig)
4534 maybeCall(reject)
4535 endRequestLock()
4536 return promise
4537 }
4538
4539 xhr.open(verb.toUpperCase(), finalPath, true)
4540 xhr.overrideMimeType('text/html')
4541 xhr.withCredentials = requestConfig.withCredentials
4542 xhr.timeout = requestConfig.timeout
4543
4544 // request headers
4545 if (requestAttrValues.noHeaders) {
4546 // ignore all headers
4547 } else {
4548 for (const header in headers) {
4549 if (headers.hasOwnProperty(header)) {
4550 const headerValue = headers[header]
4551 safelySetHeaderValue(xhr, header, headerValue)
4552 }
4553 }
4554 }
4555
4556 /** @type {HtmxResponseInfo} */
4557 const responseInfo = {
4558 xhr,
4559 target,
4560 requestConfig,
4561 etc,
4562 boosted: eltIsBoosted,
4563 select,
4564 pathInfo: {
4565 requestPath: path,
4566 finalRequestPath: finalPath,
4567 responsePath: null,
4568 anchor
4569 }
4570 }
4571
4572 xhr.onload = function() {
4573 try {
4574 const hierarchy = hierarchyForElt(elt)
4575 responseInfo.pathInfo.responsePath = getPathFromResponse(xhr)
4576 responseHandler(elt, responseInfo)
4577 if (responseInfo.keepIndicators !== true) {
4578 removeRequestIndicators(indicators, disableElts)
4579 }
4580 triggerEvent(elt, 'htmx:afterRequest', responseInfo)
4581 triggerEvent(elt, 'htmx:afterOnLoad', responseInfo)
4582 // if the body no longer contains the element, trigger the event on the closest parent
4583 // remaining in the DOM
4584 if (!bodyContains(elt)) {
4585 let secondaryTriggerElt = null
4586 while (hierarchy.length > 0 && secondaryTriggerElt == null) {
4587 const parentEltInHierarchy = hierarchy.shift()
4588 if (bodyContains(parentEltInHierarchy)) {
4589 secondaryTriggerElt = parentEltInHierarchy
4590 }
4591 }
4592 if (secondaryTriggerElt) {
4593 triggerEvent(secondaryTriggerElt, 'htmx:afterRequest', responseInfo)
4594 triggerEvent(secondaryTriggerElt, 'htmx:afterOnLoad', responseInfo)
4595 }
4596 }
4597 maybeCall(resolve)
4598 } catch (e) {
4599 triggerErrorEvent(elt, 'htmx:onLoadError', mergeObjects({ error: e }, responseInfo))
4600 throw e
4601 } finally {
4602 endRequestLock()
4603 }
4604 }
4605 xhr.onerror = function() {
4606 removeRequestIndicators(indicators, disableElts)
4607 triggerErrorEvent(elt, 'htmx:afterRequest', responseInfo)
4608 triggerErrorEvent(elt, 'htmx:sendError', responseInfo)
4609 maybeCall(reject)
4610 endRequestLock()
4611 }
4612 xhr.onabort = function() {
4613 removeRequestIndicators(indicators, disableElts)
4614 triggerErrorEvent(elt, 'htmx:afterRequest', responseInfo)
4615 triggerErrorEvent(elt, 'htmx:sendAbort', responseInfo)
4616 maybeCall(reject)
4617 endRequestLock()
4618 }
4619 xhr.ontimeout = function() {
4620 removeRequestIndicators(indicators, disableElts)
4621 triggerErrorEvent(elt, 'htmx:afterRequest', responseInfo)
4622 triggerErrorEvent(elt, 'htmx:timeout', responseInfo)
4623 maybeCall(reject)
4624 endRequestLock()
4625 }
4626 if (!triggerEvent(elt, 'htmx:beforeRequest', responseInfo)) {
4627 maybeCall(resolve)
4628 endRequestLock()
4629 return promise
4630 }
4631 var indicators = addRequestIndicatorClasses(elt)
4632 var disableElts = disableElements(elt)
4633
4634 forEach(['loadstart', 'loadend', 'progress', 'abort'], function(eventName) {
4635 forEach([xhr, xhr.upload], function(target) {
4636 target.addEventListener(eventName, function(event) {
4637 triggerEvent(elt, 'htmx:xhr:' + eventName, {
4638 lengthComputable: event.lengthComputable,
4639 loaded: event.loaded,
4640 total: event.total
4641 })
4642 })
4643 })
4644 })
4645 triggerEvent(elt, 'htmx:beforeSend', responseInfo)
4646 const params = useUrlParams ? null : encodeParamsForBody(xhr, elt, filteredFormData)
4647 xhr.send(params)
4648 return promise
4649 }
4650
4651 /**
4652 * @typedef {Object} HtmxHistoryUpdate
4653 * @property {string|null} [type]
4654 * @property {string|null} [path]
4655 */
4656
4657 /**
4658 * @param {Element} elt
4659 * @param {HtmxResponseInfo} responseInfo
4660 * @return {HtmxHistoryUpdate}
4661 */
4662 function determineHistoryUpdates(elt, responseInfo) {
4663 const xhr = responseInfo.xhr
4664
4665 //= ==========================================
4666 // First consult response headers
4667 //= ==========================================
4668 let pathFromHeaders = null
4669 let typeFromHeaders = null
4670 if (hasHeader(xhr, /HX-Push:/i)) {
4671 pathFromHeaders = xhr.getResponseHeader('HX-Push')
4672 typeFromHeaders = 'push'
4673 } else if (hasHeader(xhr, /HX-Push-Url:/i)) {
4674 pathFromHeaders = xhr.getResponseHeader('HX-Push-Url')
4675 typeFromHeaders = 'push'
4676 } else if (hasHeader(xhr, /HX-Replace-Url:/i)) {
4677 pathFromHeaders = xhr.getResponseHeader('HX-Replace-Url')
4678 typeFromHeaders = 'replace'
4679 }
4680
4681 // if there was a response header, that has priority
4682 if (pathFromHeaders) {
4683 if (pathFromHeaders === 'false') {
4684 return {}
4685 } else {
4686 return {
4687 type: typeFromHeaders,
4688 path: pathFromHeaders
4689 }
4690 }
4691 }
4692
4693 //= ==========================================
4694 // Next resolve via DOM values
4695 //= ==========================================
4696 const requestPath = responseInfo.pathInfo.finalRequestPath
4697 const responsePath = responseInfo.pathInfo.responsePath
4698
4699 const pushUrl = responseInfo.etc.push || getClosestAttributeValue(elt, 'hx-push-url')
4700 const replaceUrl = responseInfo.etc.replace || getClosestAttributeValue(elt, 'hx-replace-url')
4701 const elementIsBoosted = getInternalData(elt).boosted
4702
4703 let saveType = null
4704 let path = null
4705
4706 if (pushUrl) {
4707 saveType = 'push'
4708 path = pushUrl
4709 } else if (replaceUrl) {
4710 saveType = 'replace'
4711 path = replaceUrl
4712 } else if (elementIsBoosted) {
4713 saveType = 'push'
4714 path = responsePath || requestPath // if there is no response path, go with the original request path
4715 }
4716
4717 if (path) {
4718 // false indicates no push, return empty object
4719 if (path === 'false') {
4720 return {}
4721 }
4722
4723 // true indicates we want to follow wherever the server ended up sending us
4724 if (path === 'true') {
4725 path = responsePath || requestPath // if there is no response path, go with the original request path
4726 }
4727
4728 // restore any anchor associated with the request
4729 if (responseInfo.pathInfo.anchor && path.indexOf('#') === -1) {
4730 path = path + '#' + responseInfo.pathInfo.anchor
4731 }
4732
4733 return {
4734 type: saveType,
4735 path
4736 }
4737 } else {
4738 return {}
4739 }
4740 }
4741
4742 /**
4743 * @param {HtmxResponseHandlingConfig} responseHandlingConfig
4744 * @param {number} status
4745 * @return {boolean}
4746 */
4747 function codeMatches(responseHandlingConfig, status) {
4748 var regExp = new RegExp(responseHandlingConfig.code)
4749 return regExp.test(status.toString(10))
4750 }
4751
4752 /**
4753 * @param {XMLHttpRequest} xhr
4754 * @return {HtmxResponseHandlingConfig}
4755 */
4756 function resolveResponseHandling(xhr) {
4757 for (var i = 0; i < htmx.config.responseHandling.length; i++) {
4758 /** @type HtmxResponseHandlingConfig */
4759 var responseHandlingElement = htmx.config.responseHandling[i]
4760 if (codeMatches(responseHandlingElement, xhr.status)) {
4761 return responseHandlingElement
4762 }
4763 }
4764 // no matches, return no swap
4765 return {
4766 swap: false
4767 }
4768 }
4769
4770 /**
4771 * @param {string} title
4772 */
4773 function handleTitle(title) {
4774 if (title) {
4775 const titleElt = find('title')
4776 if (titleElt) {
4777 titleElt.textContent = title
4778 } else {
4779 window.document.title = title
4780 }
4781 }
4782 }
4783
4784 /**
4785 * Resove the Retarget selector and throw if not found
4786 * @param {Element} elt
4787 * @param {String} target
4788 * @returns {Element}
4789 */
4790 function resolveRetarget(elt, target) {
4791 if (target === 'this') {
4792 return elt
4793 }
4794 const resolvedTarget = asElement(querySelectorExt(elt, target))
4795 if (resolvedTarget == null) {
4796 triggerErrorEvent(elt, 'htmx:targetError', { target })
4797 throw new Error(`Invalid re-target ${target}`)
4798 }
4799 return resolvedTarget
4800 }
4801
4802 /**
4803 * @param {Element} elt
4804 * @param {HtmxResponseInfo} responseInfo
4805 */
4806 function handleAjaxResponse(elt, responseInfo) {
4807 const xhr = responseInfo.xhr
4808 let target = responseInfo.target
4809 const etc = responseInfo.etc
4810 const responseInfoSelect = responseInfo.select
4811
4812 if (!triggerEvent(elt, 'htmx:beforeOnLoad', responseInfo)) return
4813
4814 if (hasHeader(xhr, /HX-Trigger:/i)) {
4815 handleTriggerHeader(xhr, 'HX-Trigger', elt)
4816 }
4817
4818 if (hasHeader(xhr, /HX-Location:/i)) {
4819 let redirectPath = xhr.getResponseHeader('HX-Location')
4820 /** @type {HtmxAjaxHelperContext&{path?:string}} */
4821 var redirectSwapSpec = {}
4822 if (redirectPath.indexOf('{') === 0) {
4823 redirectSwapSpec = parseJSON(redirectPath)
4824 // what's the best way to throw an error if the user didn't include this
4825 redirectPath = redirectSwapSpec.path
4826 delete redirectSwapSpec.path
4827 }
4828 redirectSwapSpec.push = redirectSwapSpec.push || 'true'
4829 ajaxHelper('get', redirectPath, redirectSwapSpec)
4830 return
4831 }
4832
4833 const shouldRefresh = hasHeader(xhr, /HX-Refresh:/i) && xhr.getResponseHeader('HX-Refresh') === 'true'
4834
4835 if (hasHeader(xhr, /HX-Redirect:/i)) {
4836 responseInfo.keepIndicators = true
4837 htmx.location.href = xhr.getResponseHeader('HX-Redirect')
4838 shouldRefresh && htmx.location.reload()
4839 return
4840 }
4841
4842 if (shouldRefresh) {
4843 responseInfo.keepIndicators = true
4844 htmx.location.reload()
4845 return
4846 }
4847
4848 const historyUpdate = determineHistoryUpdates(elt, responseInfo)
4849
4850 const responseHandling = resolveResponseHandling(xhr)
4851 const shouldSwap = responseHandling.swap
4852 let isError = !!responseHandling.error
4853 let ignoreTitle = htmx.config.ignoreTitle || responseHandling.ignoreTitle
4854 let selectOverride = responseHandling.select
4855 if (responseHandling.target) {
4856 responseInfo.target = resolveRetarget(elt, responseHandling.target)
4857 }
4858 var swapOverride = etc.swapOverride
4859 if (swapOverride == null && responseHandling.swapOverride) {
4860 swapOverride = responseHandling.swapOverride
4861 }
4862
4863 // response headers override response handling config
4864 if (hasHeader(xhr, /HX-Retarget:/i)) {
4865 responseInfo.target = resolveRetarget(elt, xhr.getResponseHeader('HX-Retarget'))
4866 }
4867
4868 if (hasHeader(xhr, /HX-Reswap:/i)) {
4869 swapOverride = xhr.getResponseHeader('HX-Reswap')
4870 }
4871
4872 var serverResponse = xhr.response
4873 /** @type HtmxBeforeSwapDetails */
4874 var beforeSwapDetails = mergeObjects({
4875 shouldSwap,
4876 serverResponse,
4877 isError,
4878 ignoreTitle,
4879 selectOverride,
4880 swapOverride
4881 }, responseInfo)
4882
4883 if (responseHandling.event && !triggerEvent(target, responseHandling.event, beforeSwapDetails)) return
4884
4885 if (!triggerEvent(target, 'htmx:beforeSwap', beforeSwapDetails)) return
4886
4887 target = beforeSwapDetails.target // allow re-targeting
4888 serverResponse = beforeSwapDetails.serverResponse // allow updating content
4889 isError = beforeSwapDetails.isError // allow updating error
4890 ignoreTitle = beforeSwapDetails.ignoreTitle // allow updating ignoring title
4891 selectOverride = beforeSwapDetails.selectOverride // allow updating select override
4892 swapOverride = beforeSwapDetails.swapOverride // allow updating swap override
4893
4894 responseInfo.target = target // Make updated target available to response events
4895 responseInfo.failed = isError // Make failed property available to response events
4896 responseInfo.successful = !isError // Make successful property available to response events
4897
4898 if (beforeSwapDetails.shouldSwap) {
4899 if (xhr.status === 286) {
4900 cancelPolling(elt)
4901 }
4902
4903 withExtensions(elt, function(extension) {
4904 serverResponse = extension.transformResponse(serverResponse, xhr, elt)
4905 })
4906
4907 // Save current page if there will be a history update
4908 if (historyUpdate.type) {
4909 saveCurrentPageToHistory()
4910 }
4911
4912 var swapSpec = getSwapSpecification(elt, swapOverride)
4913
4914 if (!swapSpec.hasOwnProperty('ignoreTitle')) {
4915 swapSpec.ignoreTitle = ignoreTitle
4916 }
4917
4918 target.classList.add(htmx.config.swappingClass)
4919
4920 if (responseInfoSelect) {
4921 selectOverride = responseInfoSelect
4922 }
4923
4924 if (hasHeader(xhr, /HX-Reselect:/i)) {
4925 selectOverride = xhr.getResponseHeader('HX-Reselect')
4926 }
4927
4928 const selectOOB = etc.selectOOB || getClosestAttributeValue(elt, 'hx-select-oob')
4929 const select = getClosestAttributeValue(elt, 'hx-select')
4930
4931 swap(target, serverResponse, swapSpec, {
4932 select: selectOverride === 'unset' ? null : selectOverride || select,
4933 selectOOB,
4934 eventInfo: responseInfo,
4935 anchor: responseInfo.pathInfo.anchor,
4936 contextElement: elt,
4937 afterSwapCallback: function() {
4938 if (hasHeader(xhr, /HX-Trigger-After-Swap:/i)) {
4939 let finalElt = elt
4940 if (!bodyContains(elt)) {
4941 finalElt = getDocument().body
4942 }
4943 handleTriggerHeader(xhr, 'HX-Trigger-After-Swap', finalElt)
4944 }
4945 },
4946 afterSettleCallback: function() {
4947 if (hasHeader(xhr, /HX-Trigger-After-Settle:/i)) {
4948 let finalElt = elt
4949 if (!bodyContains(elt)) {
4950 finalElt = getDocument().body
4951 }
4952 handleTriggerHeader(xhr, 'HX-Trigger-After-Settle', finalElt)
4953 }
4954 },
4955 beforeSwapCallback: function() {
4956 // if we need to save history, do so, before swapping so that relative resources have the correct base URL
4957 if (historyUpdate.type) {
4958 triggerEvent(getDocument().body, 'htmx:beforeHistoryUpdate', mergeObjects({ history: historyUpdate }, responseInfo))
4959 if (historyUpdate.type === 'push') {
4960 pushUrlIntoHistory(historyUpdate.path)
4961 triggerEvent(getDocument().body, 'htmx:pushedIntoHistory', { path: historyUpdate.path })
4962 } else {
4963 replaceUrlInHistory(historyUpdate.path)
4964 triggerEvent(getDocument().body, 'htmx:replacedInHistory', { path: historyUpdate.path })
4965 }
4966 }
4967 }
4968 })
4969 }
4970 if (isError) {
4971 triggerErrorEvent(elt, 'htmx:responseError', mergeObjects({ error: 'Response Status Error Code ' + xhr.status + ' from ' + responseInfo.pathInfo.requestPath }, responseInfo))
4972 }
4973 }
4974
4975 //= ===================================================================
4976 // Extensions API
4977 //= ===================================================================
4978
4979 /** @type {Object<string, HtmxExtension>} */
4980 const extensions = {}
4981
4982 /**
4983 * extensionBase defines the default functions for all extensions.
4984 * @returns {HtmxExtension}
4985 */
4986 function extensionBase() {
4987 return {
4988 init: function(api) { return null },
4989 getSelectors: function() { return null },
4990 onEvent: function(name, evt) { return true },
4991 transformResponse: function(text, xhr, elt) { return text },
4992 isInlineSwap: function(swapStyle) { return false },
4993 handleSwap: function(swapStyle, target, fragment, settleInfo) { return false },
4994 encodeParameters: function(xhr, parameters, elt) { return null }
4995 }
4996 }
4997
4998 /**
4999 * defineExtension initializes the extension and adds it to the htmx registry
5000 *
5001 * @see https://htmx.org/api/#defineExtension
5002 *
5003 * @param {string} name the extension name
5004 * @param {Partial<HtmxExtension>} extension the extension definition
5005 */
5006 function defineExtension(name, extension) {
5007 if (extension.init) {
5008 extension.init(internalAPI)
5009 }
5010 extensions[name] = mergeObjects(extensionBase(), extension)
5011 }
5012
5013 /**
5014 * removeExtension removes an extension from the htmx registry
5015 *
5016 * @see https://htmx.org/api/#removeExtension
5017 *
5018 * @param {string} name
5019 */
5020 function removeExtension(name) {
5021 delete extensions[name]
5022 }
5023
5024 /**
5025 * getExtensions searches up the DOM tree to return all extensions that can be applied to a given element
5026 *
5027 * @param {Element} elt
5028 * @param {HtmxExtension[]=} extensionsToReturn
5029 * @param {string[]=} extensionsToIgnore
5030 * @returns {HtmxExtension[]}
5031 */
5032 function getExtensions(elt, extensionsToReturn, extensionsToIgnore) {
5033 if (extensionsToReturn == undefined) {
5034 extensionsToReturn = []
5035 }
5036 if (elt == undefined) {
5037 return extensionsToReturn
5038 }
5039 if (extensionsToIgnore == undefined) {
5040 extensionsToIgnore = []
5041 }
5042 const extensionsForElement = getAttributeValue(elt, 'hx-ext')
5043 if (extensionsForElement) {
5044 forEach(extensionsForElement.split(','), function(extensionName) {
5045 extensionName = extensionName.replace(/ /g, '')
5046 if (extensionName.slice(0, 7) == 'ignore:') {
5047 extensionsToIgnore.push(extensionName.slice(7))
5048 return
5049 }
5050 if (extensionsToIgnore.indexOf(extensionName) < 0) {
5051 const extension = extensions[extensionName]
5052 if (extension && extensionsToReturn.indexOf(extension) < 0) {
5053 extensionsToReturn.push(extension)
5054 }
5055 }
5056 })
5057 }
5058 return getExtensions(asElement(parentElt(elt)), extensionsToReturn, extensionsToIgnore)
5059 }
5060
5061 //= ===================================================================
5062 // Initialization
5063 //= ===================================================================
5064 var isReady = false
5065 getDocument().addEventListener('DOMContentLoaded', function() {
5066 isReady = true
5067 })
5068
5069 /**
5070 * Execute a function now if DOMContentLoaded has fired, otherwise listen for it.
5071 *
5072 * This function uses isReady because there is no reliable way to ask the browser whether
5073 * the DOMContentLoaded event has already been fired; there's a gap between DOMContentLoaded
5074 * firing and readystate=complete.
5075 */
5076 function ready(fn) {
5077 // Checking readyState here is a failsafe in case the htmx script tag entered the DOM by
5078 // some means other than the initial page load.
5079 if (isReady || getDocument().readyState === 'complete') {
5080 fn()
5081 } else {
5082 getDocument().addEventListener('DOMContentLoaded', fn)
5083 }
5084 }
5085
5086 function insertIndicatorStyles() {
5087 if (htmx.config.includeIndicatorStyles !== false) {
5088 const nonceAttribute = htmx.config.inlineStyleNonce ? ` nonce="${htmx.config.inlineStyleNonce}"` : ''
5089 const indicator = htmx.config.indicatorClass
5090 const request = htmx.config.requestClass
5091 getDocument().head.insertAdjacentHTML('beforeend',
5092 `<style${nonceAttribute}>` +
5093 `.${indicator}{opacity:0;visibility: hidden} ` +
5094 `.${request} .${indicator}, .${request}.${indicator}{opacity:1;visibility: visible;transition: opacity 200ms ease-in}` +
5095 '</style>'
5096 )
5097 }
5098 }
5099
5100 function getMetaConfig() {
5101 /** @type HTMLMetaElement */
5102 const element = getDocument().querySelector('meta[name="htmx-config"]')
5103 if (element) {
5104 return parseJSON(element.content)
5105 } else {
5106 return null
5107 }
5108 }
5109
5110 function mergeMetaConfig() {
5111 const metaConfig = getMetaConfig()
5112 if (metaConfig) {
5113 htmx.config = mergeObjects(htmx.config, metaConfig)
5114 }
5115 }
5116
5117 // initialize the document
5118 ready(function() {
5119 mergeMetaConfig()
5120 insertIndicatorStyles()
5121 let body = getDocument().body
5122 processNode(body)
5123 const restoredElts = getDocument().querySelectorAll(
5124 "[hx-trigger='restored'],[data-hx-trigger='restored']"
5125 )
5126 body.addEventListener('htmx:abort', function(evt) {
5127 const target = (/** @type {CustomEvent} */(evt)).detail.elt || evt.target
5128 const internalData = getInternalData(target)
5129 if (internalData && internalData.xhr) {
5130 internalData.xhr.abort()
5131 }
5132 })
5133 /** @type {(ev: PopStateEvent) => any} */
5134 const originalPopstate = window.onpopstate ? window.onpopstate.bind(window) : null
5135 /** @type {(ev: PopStateEvent) => any} */
5136 window.onpopstate = function(event) {
5137 if (event.state && event.state.htmx) {
5138 restoreHistory()
5139 forEach(restoredElts, function(elt) {
5140 triggerEvent(elt, 'htmx:restored', {
5141 document: getDocument(),
5142 triggerEvent
5143 })
5144 })
5145 } else {
5146 if (originalPopstate) {
5147 originalPopstate(event)
5148 }
5149 }
5150 }
5151 getWindow().setTimeout(function() {
5152 triggerEvent(body, 'htmx:load', {}) // give ready handlers a chance to load up before firing this event
5153 body = null // kill reference for gc
5154 }, 0)
5155 })
5156
5157 return htmx
5158 })()
5159
5160 /** @typedef {'get'|'head'|'post'|'put'|'delete'|'connect'|'options'|'trace'|'patch'} HttpVerb */
5161
5162 /**
5163 * @typedef {Object} SwapOptions
5164 * @property {string} [select]
5165 * @property {string} [selectOOB]
5166 * @property {*} [eventInfo]
5167 * @property {string} [anchor]
5168 * @property {Element} [contextElement]
5169 * @property {swapCallback} [afterSwapCallback]
5170 * @property {swapCallback} [afterSettleCallback]
5171 * @property {swapCallback} [beforeSwapCallback]
5172 * @property {string} [title]
5173 * @property {boolean} [historyRequest]
5174 */
5175
5176 /**
5177 * @callback swapCallback
5178 */
5179
5180 /**
5181 * @typedef {'innerHTML' | 'outerHTML' | 'beforebegin' | 'afterbegin' | 'beforeend' | 'afterend' | 'delete' | 'none' | string} HtmxSwapStyle
5182 */
5183
5184 /**
5185 * @typedef HtmxSwapSpecification
5186 * @property {HtmxSwapStyle} swapStyle
5187 * @property {number} swapDelay
5188 * @property {number} settleDelay
5189 * @property {boolean} [transition]
5190 * @property {boolean} [ignoreTitle]
5191 * @property {string} [head]
5192 * @property {'top' | 'bottom' | number } [scroll]
5193 * @property {string} [scrollTarget]
5194 * @property {string} [show]
5195 * @property {string} [showTarget]
5196 * @property {boolean} [focusScroll]
5197 */
5198
5199 /**
5200 * @typedef {((this:Node, evt:Event) => boolean) & {source: string}} ConditionalFunction
5201 */
5202
5203 /**
5204 * @typedef {Object} HtmxTriggerSpecification
5205 * @property {string} trigger
5206 * @property {number} [pollInterval]
5207 * @property {ConditionalFunction} [eventFilter]
5208 * @property {boolean} [changed]
5209 * @property {boolean} [once]
5210 * @property {boolean} [consume]
5211 * @property {number} [delay]
5212 * @property {string} [from]
5213 * @property {string} [target]
5214 * @property {number} [throttle]
5215 * @property {string} [queue]
5216 * @property {string} [root]
5217 * @property {string} [threshold]
5218 */
5219
5220 /**
5221 * @typedef {{elt: Element, message: string, validity: ValidityState}} HtmxElementValidationError
5222 */
5223
5224 /**
5225 * @typedef {Record<string, string>} HtmxHeaderSpecification
5226 * @property {'true'} HX-Request
5227 * @property {string|null} HX-Trigger
5228 * @property {string|null} HX-Trigger-Name
5229 * @property {string|null} HX-Target
5230 * @property {string} HX-Current-URL
5231 * @property {string} [HX-Prompt]
5232 * @property {'true'} [HX-Boosted]
5233 * @property {string} [Content-Type]
5234 * @property {'true'} [HX-History-Restore-Request]
5235 */
5236
5237 /**
5238 * @typedef HtmxAjaxHelperContext
5239 * @property {Element|string} [source]
5240 * @property {Event} [event]
5241 * @property {HtmxAjaxHandler} [handler]
5242 * @property {Element|string} [target]
5243 * @property {HtmxSwapStyle} [swap]
5244 * @property {Object|FormData} [values]
5245 * @property {Record<string,string>} [headers]
5246 * @property {string} [select]
5247 * @property {string} [push]
5248 * @property {string} [replace]
5249 * @property {string} [selectOOB]
5250 */
5251
5252 /**
5253 * @typedef {Object} HtmxRequestConfig
5254 * @property {boolean} boosted
5255 * @property {boolean} useUrlParams
5256 * @property {FormData} formData
5257 * @property {Object} parameters formData proxy
5258 * @property {FormData} unfilteredFormData
5259 * @property {Object} unfilteredParameters unfilteredFormData proxy
5260 * @property {HtmxHeaderSpecification} headers
5261 * @property {Element} elt
5262 * @property {Element} target
5263 * @property {HttpVerb} verb
5264 * @property {HtmxElementValidationError[]} errors
5265 * @property {boolean} withCredentials
5266 * @property {number} timeout
5267 * @property {string} path
5268 * @property {Event} triggeringEvent
5269 */
5270
5271 /**
5272 * @typedef {Object} HtmxResponseInfo
5273 * @property {XMLHttpRequest} xhr
5274 * @property {Element} target
5275 * @property {HtmxRequestConfig} requestConfig
5276 * @property {HtmxAjaxEtc} etc
5277 * @property {boolean} boosted
5278 * @property {string} select
5279 * @property {{requestPath: string, finalRequestPath: string, responsePath: string|null, anchor: string}} pathInfo
5280 * @property {boolean} [failed]
5281 * @property {boolean} [successful]
5282 * @property {boolean} [keepIndicators]
5283 */
5284
5285 /**
5286 * @typedef {Object} HtmxAjaxEtc
5287 * @property {boolean} [returnPromise]
5288 * @property {HtmxAjaxHandler} [handler]
5289 * @property {string} [select]
5290 * @property {Element} [targetOverride]
5291 * @property {HtmxSwapStyle} [swapOverride]
5292 * @property {Record<string,string>} [headers]
5293 * @property {Object|FormData} [values]
5294 * @property {boolean} [credentials]
5295 * @property {number} [timeout]
5296 * @property {string} [push]
5297 * @property {string} [replace]
5298 * @property {string} [selectOOB]
5299 */
5300
5301 /**
5302 * @typedef {Object} HtmxResponseHandlingConfig
5303 * @property {string} [code]
5304 * @property {boolean} swap
5305 * @property {boolean} [error]
5306 * @property {boolean} [ignoreTitle]
5307 * @property {string} [select]
5308 * @property {string} [target]
5309 * @property {string} [swapOverride]
5310 * @property {string} [event]
5311 */
5312
5313 /**
5314 * @typedef {HtmxResponseInfo & {shouldSwap: boolean, serverResponse: any, isError: boolean, ignoreTitle: boolean, selectOverride:string, swapOverride:string}} HtmxBeforeSwapDetails
5315 */
5316
5317 /**
5318 * @callback HtmxAjaxHandler
5319 * @param {Element} elt
5320 * @param {HtmxResponseInfo} responseInfo
5321 */
5322
5323 /**
5324 * @typedef {(() => void)} HtmxSettleTask
5325 */
5326
5327 /**
5328 * @typedef {Object} HtmxSettleInfo
5329 * @property {HtmxSettleTask[]} tasks
5330 * @property {Element[]} elts
5331 * @property {string} [title]
5332 */
5333
5334 /**
5335 * @see https://github.com/bigskysoftware/htmx-extensions/blob/main/README.md
5336 * @typedef {Object} HtmxExtension
5337 * @property {(api: any) => void} init
5338 * @property {(name: string, event: CustomEvent) => boolean} onEvent
5339 * @property {(text: string, xhr: XMLHttpRequest, elt: Element) => string} transformResponse
5340 * @property {(swapStyle: HtmxSwapStyle) => boolean} isInlineSwap
5341 * @property {(swapStyle: HtmxSwapStyle, target: Node, fragment: Node, settleInfo: HtmxSettleInfo) => boolean|Node[]} handleSwap
5342 * @property {(xhr: XMLHttpRequest, parameters: FormData, elt: Node) => *|string|null} encodeParameters
5343 * @property {() => string[]|null} getSelectors
5344 */