Debian Codegraph @

dist/htmx.js

raw symbols SCIP
1 var htmx = (() => {
2
3 /**
4 * HCON, htmx's mini config language. Mirrors the JSON API.
5 *
6 * Used by hx-trigger, hx-swap, hx-vals, and other htmx config attributes.
7 *
8 * @see https://four.htmx.org/docs#hcon
9 */
10 const HCON = {
11 /**
12 * Parses an HCON string into an object.
13 *
14 * @example
15 * HCON.parse('foo:1 bar:true'); // {foo: 1, bar: true}
16 * HCON.parse('sse.mode:once'); // {sse: {mode: 'once'}}
17 * HCON.parse('{"foo": 1}'); // {foo: 1}
18 */
19 parse(string) {
20 if (!string) return {};
21 if (string.startsWith('{')) return JSON.parse(string);
22 let pattern = /(?:"([^"]+)"|'([^']+)'|([^\s,:]+))(?:\s*:\s*(?:"([^"]*)"|'([^']*)'|<((?:[^/]|\/(?!>))+)\/>|([^\s,]+)))?(?=\s|,|$)/g;
23 let result = {};
24 for (let match of string.matchAll(pattern)) {
25 let [,
26 doubleQuotedKey, // "key"
27 singleQuotedKey, // 'key'
28 bareKey, // key
29 doubleQuotedValue, // "value"
30 singleQuotedValue, // 'value'
31 hyperscriptValue, // <value/>
32 bareValue, // value
33 ] = match;
34
35 // pick this match's key and value forms
36 let key = doubleQuotedKey ?? singleQuotedKey ?? bareKey;
37 let value = (doubleQuotedValue ?? singleQuotedValue ?? hyperscriptValue ?? bareValue ?? 'true').trim();
38
39 // JSON-parse if possible (e.g. "5" -> 5; "abc" stays string)
40 try { value = JSON.parse(value); } catch {}
41
42 // bare a.b -> {a:{b:...}}; quoted "a.b" -> {"a.b":...}
43 let isDottedPath = bareKey?.includes('.');
44 let pair = isDottedPath
45 ? key.split('.').reduceRight((acc, segment) => ({[segment]: acc}), value)
46 : {[key]: value};
47 HCON.merge(pair, result);
48 }
49 return result;
50 },
51
52 /**
53 * Splits an HCON-aware string at top-level commas.
54 * Commas inside [], (), <.../>, "...", '...' are preserved.
55 *
56 * @example
57 * HCON.split('a:1, b:2'); // ['a:1', ' b:2']
58 * HCON.split('from:".a, .b", click'); // ['from:".a, .b"', ' click']
59 */
60 split(string) {
61 return string.split(/,(?![^\[]*\])(?![^(]*\))(?![^<]*\/>)(?=(?:[^"']|"[^"]*"|'[^']*')*$)/);
62 },
63
64 /**
65 * Deep-merges a source (HCON string or object) into a target.
66 *
67 * @example
68 * HCON.merge({a: {b: 1}}, {a: {c: 2}}); // {a: {b: 1, c: 2}}
69 * HCON.merge('a.b:1', {a: {c: 2}}); // {a: {b: 1, c: 2}}
70 */
71 merge(source, target) {
72 if (typeof source === 'string') source = HCON.parse(source);
73
74 for (let [key, val] of Object.entries(source)) {
75 if (['__proto__', 'constructor', 'prototype'].includes(key)) continue;
76
77 let sourceIsObject = val && typeof val === 'object' && !Array.isArray(val);
78 let targetIsObject = target[key] && typeof target[key] === 'object' && !Array.isArray(target[key]);
79
80 if (sourceIsObject && targetIsObject) {
81 HCON.merge(val, target[key]);
82 } else {
83 target[key] = val;
84 }
85 }
86 return target;
87 },
88 };
89
90 class ReqQ {
91 #c = null
92 #q = []
93
94 issue(ctx, queueStrategy) {
95 ctx.queueStrategy = queueStrategy
96 if (!this.#c) {
97 this.#c = ctx
98 return true
99 } else {
100 // Replace strategy OR current is abortable: abort current and issue new
101 if (queueStrategy === "replace" || (queueStrategy !== "abort" && this.#c.queueStrategy === "abort")) {
102 this.#q.forEach(value => value.status = "dropped");
103 this.#q = []
104 this.#c.request?.abort?.();
105 this.#c = ctx
106 return true
107 } else if (queueStrategy === "queue all") {
108 this.#q.push(ctx)
109 ctx.status = "queued";
110 } else if (queueStrategy === "drop") {
111 // ignore the request
112 ctx.status = "dropped";
113 } else if (queueStrategy === "queue last") {
114 this.#q.forEach(value => value.status = "dropped");
115 this.#q = [ctx]
116 ctx.status = "queued";
117 } else if (this.#q.length === 0 && queueStrategy !== "abort") {
118 // default queue first
119 this.#q.push(ctx)
120 ctx.status = "queued";
121 } else {
122 ctx.status = "dropped";
123 }
124 return false
125 }
126 }
127
128 finish() {
129 this.#c = null
130 }
131
132 next() {
133 return this.#q.shift()
134 }
135
136 abort() {
137 this.#c?.request?.abort?.()
138 }
139
140 more() {
141 return this.#q?.length
142 }
143 }
144
145 class Htmx {
146
147 #HCON = HCON
148 #extMethods = new Map();
149 #approvedExt = '';
150 #registeredExt = new Set();
151 #internalAPI;
152 #Function = Function;
153 #AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
154 #ttPolicy = { createHTML: s => s, createScript: s => s };
155 #actionSelector
156 #boostSelector = "a,form";
157 #verbs = ["get", "post", "put", "patch", "delete"];
158 #hxOnQuery
159 #transitionQueue
160 #historyAbort
161 #processingTransition
162
163 constructor() {
164 this.#initHtmxConfig();
165 this.#initRequestIndicatorCss();
166 this.#actionSelector = this.#prefixSelector('[hx-action],[hx-get],[hx-post],[hx-put],[hx-patch],[hx-delete]');
167 this.#hxOnQuery = new XPathEvaluator().createExpression(`.//*[@*[${this.#prefixes("hx-on").map(p => `starts-with(name(), "${p}")`).join(' or ')}]]`);
168 this.#internalAPI = {
169 attributeValue: this.#attributeValue.bind(this),
170 parseTriggerSpecs: this.#parseTriggerSpecs.bind(this),
171 determineMethodAndAction: this.#determineMethodAndAction.bind(this),
172 createRequestContext: this.#createRequestContext.bind(this),
173 collectFormData: this.#collectFormData.bind(this),
174 getAttributeObject: this.#getAttributeObject.bind(this),
175 insertContent: this.#insertContent.bind(this),
176 morph: this.#morph.bind(this),
177 isSoftMatch: this.#isSoftMatch.bind(this),
178 initSecurity: (ttPolicy, syncFn, asyncFn) => {
179 if (ttPolicy) this.#ttPolicy = ttPolicy;
180 if (syncFn) this.#Function = syncFn;
181 if (asyncFn) this.#AsyncFunction = asyncFn;
182 },
183 onTrigger: this.#onTrigger.bind(this),
184 htmxProp: this.#htmxProp.bind(this),
185 triggerHtmxEvent: this.#trigger.bind(this),
186 executeJavaScript: this.#executeJavaScript.bind(this)
187 };
188 let init = () => {
189 this.#initHistoryHandling()
190 this.process(document.body)
191 };
192 if (document.readyState === 'loading') {
193 document.addEventListener("DOMContentLoaded", init)
194 } else {
195 // wait a tick so extensions can register
196 setTimeout(init)
197 }
198 }
199
200 #initHtmxConfig() {
201 this.version = '4.0.0-beta5'
202 this.config = {
203 logAll: false,
204 prefix: "data-hx-",
205 transitions: false,
206 history: true,
207 mode: 'same-origin',
208 defaultSwap: "innerHTML",
209 defaultFocusScroll: false,
210 indicatorClass: "htmx-indicator",
211 requestClass: "htmx-request",
212 includeIndicatorCSS: true,
213 defaultTimeout: 60000, /* 60 second default timeout */
214 extensions: '',
215 morphIgnore: ["data-htmx-powered"],
216 morphSkip: '[hx-morph-skip]',
217 morphSkipChildren: '[hx-morph-skip-children]',
218 morphScanLimit: 10,
219 noSwap: [204, 304],
220 implicitInheritance: false,
221 defaultSettleDelay: 1
222 }
223 let metaConfig = document.querySelector('meta[name="htmx-config"]');
224 if (metaConfig) {
225 HCON.merge(metaConfig.content, this.config);
226 }
227 this.#approvedExt = this.config.extensions;
228 }
229
230 #initRequestIndicatorCss() {
231 if (this.config.includeIndicatorCSS !== false) {
232 let indicator = this.config.indicatorClass;
233 let request = this.config.requestClass;
234 let sheet = new CSSStyleSheet();
235 sheet.replaceSync(
236 `.${indicator}{opacity:0;visibility: hidden} ` +
237 `.${request} .${indicator}, .${request}.${indicator}{opacity:1;visibility: visible;transition: opacity 200ms ease-in}`
238 );
239 document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
240 }
241 }
242
243 registerExtension(name, extension) {
244 if (this.#approvedExt && !this.#approvedExt.split(/,\s*/).includes(name)) return false;
245 if (this.#registeredExt.has(name)) return false;
246 this.#registeredExt.add(name);
247 if (extension.init) extension.init(this.#internalAPI);
248 Object.entries(extension).forEach(([key, value]) => {
249 if(!this.#extMethods.get(key)?.push(value)) this.#extMethods.set(key, [value]);
250 });
251 }
252
253 #ignore(elt) {
254 let p = this.config.prefix;
255 return !elt.closest || elt.closest('[hx-ignore]') != null || (p && elt.closest(`[${p}ignore]`) != null);
256 }
257
258 #attr(elt, name) {
259 let p = this.config.prefix;
260 return elt.getAttribute(name) ?? (p ? elt.getAttribute(name.replace('hx-', p)) : null);
261 }
262
263 #attrName(elt, name) {
264 let p = this.config.prefix && name.replace('hx-', this.config.prefix);
265 return elt.hasAttribute(name) ? name : (p && elt.hasAttribute(p) ? p : null);
266 }
267
268 #prefixSelector(s) {
269 return this.#prefixes(s).join(',');
270 }
271
272 #prefixes(s) {
273 let result = [s];
274 if (this.config.prefix) result.push(s.replaceAll('hx-', this.config.prefix));
275 return result;
276 }
277
278 #queryEltAndDescendants(elt, selector) {
279 let results = [...(elt.querySelectorAll?.(selector) ?? [])];
280 if (elt.matches?.(selector)) {
281 results.unshift(elt);
282 }
283 return results;
284 }
285
286 #normalizeSwapStyle(style) {
287 return style === 'before' ? 'beforebegin' :
288 style === 'after' ? 'afterend' :
289 style === 'prepend' ? 'afterbegin' :
290 style === 'append' ? 'beforeend' : style;
291 }
292
293 #findThisElements(elt, attrName) {
294 let result = [];
295 this.#attributeValue(elt, attrName, undefined, (val, elt) => {
296 if (val?.split(/\s*[,:]\s*/).includes('this')) result.push(elt);
297 });
298 return result;
299 }
300
301 #attributeValue(elt, name, defaultVal, eltCollector) {
302 name = this.#maybeAdjustMetaCharacter(name);
303 let inherited = this.#maybeAdjustMetaCharacter(":inherited");
304 let append = this.#maybeAdjustMetaCharacter(":append");
305
306 let val = this.#attr(elt, name) ?? this.#attr(elt, name + inherited);
307 if (val != null) return eltCollector ? eltCollector(val, elt) : val;
308
309 let n1 = CSS.escape(this.config.implicitInheritance ? name : name + inherited);
310 let n2 = CSS.escape(name + inherited + append);
311 let inheritSelector = this.#prefixSelector(`[${n1}],[${n2}]`);
312 let appendName = this.#attrName(elt, name + append) ?? this.#attrName(elt, name + inherited + append);
313 if (appendName) {
314 let appendValue = elt.getAttribute(appendName);
315 let parent = elt.parentNode?.closest?.(inheritSelector);
316 if (eltCollector) eltCollector(appendValue, elt);
317 if (parent) {
318 let parentVal = this.#attributeValue(parent, name, undefined, eltCollector);
319 return parentVal ? (parentVal + "," + appendValue).replace(/[{}]/g, '') : appendValue;
320 }
321 return appendValue;
322 }
323
324 let parent = elt.parentNode?.closest?.(inheritSelector);
325 if (parent) {
326 val = this.#attributeValue(parent, name, undefined, eltCollector);
327 if (!eltCollector && val && this.config.implicitInheritance) {
328 this.#triggerExtensions(elt, "htmx:after:implicitInheritance", {elt, name, parent})
329 }
330 return val;
331 }
332 return defaultVal;
333 }
334
335 #parseTriggerSpecs(spec) {
336 return HCON.split(spec).flatMap(s => {
337 let [,name,rest] = s.match(/^\s*(\S+\[[^\]]*\]|\S+)\s*(.*?)\s*$/) ?? [];
338 if (!name) return []; // skip empty/whitespace-only tokens
339 if (/\[[^\]]*$/.test(name)) throw "unterminated:" + name; // e.g. click[ctrlKey
340 return [{name, ...HCON.parse(rest)}]; // spread modifiers (delay, throttle, etc.) onto result
341 });
342 }
343
344 #determineMethodAndAction(elt, evt) {
345 if (this.#isBoosted(elt)) {
346 return this.#boostedMethodAndAction(elt, evt)
347 } else {
348 let method = this.#attributeValue(elt, "hx-method") || "GET"
349 let action = this.#attributeValue(elt, "hx-action");
350 if (!action) {
351 for (let verb of this.#verbs) {
352 let verbAction = this.#attributeValue(elt, "hx-" + verb);
353 if (verbAction != null) {
354 action = verbAction;
355 method = verb;
356 break;
357 }
358 }
359 }
360 method = method.toUpperCase()
361 return {action, method}
362 }
363 }
364
365 #boostedMethodAndAction(elt, evt) {
366 if (elt.matches("a")) {
367 return {action: elt.getAttribute("href"), method: "GET"}
368 } else {
369 let action = evt.submitter?.getAttribute?.("formAction") || elt.getAttribute("action");
370 let method = evt.submitter?.getAttribute?.("formMethod") || elt.getAttribute("method") || "GET";
371 return {action, method: method.toUpperCase()}
372 }
373 }
374
375 #htmxProp(elt) {
376 if (!elt._htmx) {
377 elt._htmx = { listeners: [], triggerSpecs: [] };
378 elt.setAttribute('data-htmx-powered', 'true');
379 }
380 return elt._htmx;
381 }
382
383 #htmxState(elt) {
384 return elt._htmx_state ||= {};
385 }
386
387 #initializeElement(elt) {
388 if (this.#shouldInitialize(elt) && this.#trigger(elt, "htmx:before:init", {}, true)) {
389 let htmxProp = this.#htmxProp(elt);
390 htmxProp.initialized = true;
391 htmxProp.eventHandler = this.#createHtmxEventHandler(elt);
392 this.#initializeTriggers(elt);
393 this.#initializeAbortListener(elt)
394 this.#trigger(elt, "htmx:after:init", {}, true)
395 }
396 }
397
398 #createHtmxEventHandler(elt) {
399 return async (evt) => {
400 try {
401 let ctx = this.#createRequestContext(elt, evt);
402 await this.#handleTriggerEvent(ctx);
403 } catch (e) {
404 this.#trigger(elt, 'htmx:error', { error: e });
405 }
406 };
407 }
408
409 #createRequestContext(sourceElement, sourceEvent) {
410 let {action, method} = this.#determineMethodAndAction(sourceElement, sourceEvent);
411 let [fullAction, anchor] = (action || '').split('#');
412 let ac = new AbortController();
413 let ctx = {
414 sourceElement,
415 sourceEvent,
416 status: "created",
417 select: this.#attributeValue(sourceElement, "hx-select"),
418 selectOOB: this.#attributeValue(sourceElement, "hx-select-oob"),
419 target: this.#attributeValue(sourceElement, "hx-target"),
420 swap: this.#attributeValue(sourceElement, "hx-swap") ?? this.config.defaultSwap,
421 push: this.#attributeValue(sourceElement, "hx-push-url"),
422 replace: this.#attributeValue(sourceElement, "hx-replace-url"),
423 transition: this.config.transitions,
424 confirm: this.#attributeValue(sourceElement, "hx-confirm"),
425 request: {
426 validate: "true" === this.#attributeValue(sourceElement, "hx-validate", sourceElement.matches('form') && !sourceElement.noValidate && !sourceEvent.submitter?.formNoValidate ? "true" : "false"),
427 action: fullAction,
428 anchor,
429 method,
430 headers: this.#createCoreHeaders(sourceElement),
431 abort: ac.abort.bind(ac),
432 credentials: "same-origin",
433 signal: ac.signal,
434 mode: this.config.mode
435 }
436 };
437 // Apply boost config overrides
438 if (sourceElement._htmx?.boosted) {
439 HCON.merge(sourceElement._htmx.boosted, ctx);
440 }
441 ctx.target = this.#resolveTarget(sourceElement, ctx.target);
442 ctx.request.headers["HX-Request-Type"] = (ctx.target === document.body || ctx.select) ? "full" : "partial";
443 if (ctx.target) {
444 ctx.request.headers["HX-Target"] = this.#buildIdentifier(ctx.target);
445 }
446
447 // Apply hx-config overrides
448 let configAttr = this.#attributeValue(sourceElement, "hx-config");
449 if (configAttr) {
450 HCON.merge(configAttr, ctx.request);
451 ctx.request.mode = this.config.mode; // mode is security-sensitive, never allow per-element override
452 }
453 return ctx;
454 }
455
456 #buildIdentifier(elt) {
457 return `${elt.tagName.toLowerCase()}${elt.id ? '#' + encodeURI(elt.id) : ''}`;
458 }
459
460 #createCoreHeaders(elt) {
461 let headers = {
462 "HX-Request": "true",
463 "HX-Source": this.#buildIdentifier(elt),
464 "HX-Current-URL": location.href,
465 "Accept": "text/html"
466 };
467 if (this.#isBoosted(elt)) {
468 headers["HX-Boosted"] = "true"
469 }
470 return headers;
471 }
472
473 #handleHxHeaders(elt, ctx) {
474 return this.#getAttributeObject(elt, "hx-headers", obj => {
475 for (let key in obj) ctx.request.headers[key] = String(obj[key]);
476 }, {ctx});
477 }
478
479 #resolveTarget(elt, selector) {
480 if (selector instanceof Element) {
481 return selector;
482 } else if (selector != null) {
483 return this.#findOrWarn(elt, selector, "hx-target");
484 } else if (this.#isBoosted(elt)) {
485 return document.body
486 } else {
487 return elt;
488 }
489 }
490
491 #isBoosted(elt) {
492 return elt?._htmx?.boosted;
493 }
494
495 async #handleTriggerEvent(ctx) {
496 let elt = ctx.sourceElement
497 let evt = ctx.sourceEvent
498 if (!elt.isConnected) return
499
500 if (this.#isModifierKeyClick(evt)) return
501
502 if (this.#shouldCancel(evt)) evt.preventDefault()
503
504 // determine if request uses query params
505 let usesQueryParams = /GET|DELETE/.test(ctx.request.method);
506
507 // Only include *enclosing* form info for request types that do not use
508 // query parameters (can still be included explicitly with hx-include)
509 let form = usesQueryParams
510 ? (elt.matches('form') ? elt : null)
511 : (elt.form || elt.closest("form"))
512
513 // Build request body
514 let body = this.#collectFormData(elt, form, evt.submitter, ctx.request.validate, usesQueryParams)
515 if (!body) return // Validation failed
516 let valsResult = this.#getAttributeObject(elt, "hx-vals", obj => {
517 ctx.vals = obj; // make available for json extensions
518 for (let key in obj) body.set(key, obj[key]);
519 }, {ctx});
520 if (valsResult) await valsResult; // Only await if it returned a promise
521 if (ctx.values) {
522 for (let k in ctx.values) {
523 body.delete(k);
524 body.append(k, ctx.values[k]);
525 }
526 }
527
528 // Handle dynamic headers
529 let headersResult = this.#handleHxHeaders(elt, ctx)
530 if (headersResult) await headersResult // Only await if it returned a promise
531
532 // Setup event-dependent request details
533 Object.assign(ctx.request, {
534 form,
535 submitter: evt.submitter,
536 body
537 })
538
539 if (!this.#trigger(elt, "htmx:config:request", {ctx: ctx})) return
540 if (!this.#verbs.includes(ctx.request.method.toLowerCase())) return
541
542 let javascriptContent = this.#extractJavascriptContent(ctx.request.action);
543 if (javascriptContent != null) {
544 let data = Object.fromEntries(ctx.request.body);
545 await this.#executeJavaScript(ctx.sourceElement, data, javascriptContent, false);
546 return
547 } else if (usesQueryParams) {
548 let url = new URL(ctx.request.action, document.baseURI);
549
550 for (let key of ctx.request.body.keys()) {
551 url.searchParams.delete(key);
552 }
553 for (let [key, value] of ctx.request.body) {
554 url.searchParams.append(key, value);
555 }
556
557 // Keep relative if same origin, otherwise use full URL
558 if (url.origin === location.origin) {
559 ctx.request.action = url.pathname + url.search;
560 } else {
561 ctx.request.action = url.href;
562 }
563 ctx.request.body = null;
564 } else if ((this.#attributeValue(elt, "hx-encoding") ?? form?.enctype) !== "multipart/form-data") {
565 ctx.request.body = new URLSearchParams(ctx.request.body);
566 }
567
568 await this.#issueRequest(ctx);
569 }
570
571 async #issueRequest(ctx) {
572 let elt = ctx.sourceElement
573 let syncStrategy = this.#determineSyncStrategy(elt);
574 let requestQueue = this.#getRequestQueue(elt);
575
576 if (!requestQueue.issue(ctx, syncStrategy)) return
577
578 ctx.status = "issuing"
579
580 let indicators = [];
581 let disableElements = [];
582 try {
583 // Handle confirmation
584 if (ctx.confirm) {
585 let confirmed = await new Promise(resolve => {
586 let detail = {ctx, issueRequest: () => resolve(true), dropRequest: () => resolve(false)};
587 if (this.#trigger(elt, "htmx:confirm", detail)) {
588 let js = this.#extractJavascriptContent(ctx.confirm);
589 resolve(js ? this.#executeJavaScript(elt, {ctx}, js, true) : window.confirm(ctx.confirm));
590 }
591 });
592 if (!confirmed) return;
593 }
594
595 // initialize timeout & indicators after confirmation
596 this.#initTimeout(ctx);
597 indicators = this.#showIndicators(elt);
598 disableElements = this.#disableElements(elt);
599
600 ctx.fetch ||= window.fetch.bind(window)
601 if (!this.#trigger(elt, "htmx:before:request", {ctx})) return;
602
603 let response = await ctx.fetch(ctx.request.action, ctx.request);
604
605 ctx.response = {
606 raw: response,
607 status: response.status,
608 headers: response.headers,
609 }
610 this.#extractHxHeaders(ctx);
611 if (!this.#trigger(elt, "htmx:before:response", {ctx})) return;
612 ctx.text = await response.text();
613 if (!this.#trigger(elt, "htmx:after:request", {ctx})) return;
614
615 if (ctx.response.status >= 400) {
616 this.#trigger(elt, "htmx:response:error", {ctx})
617 }
618
619 if(this.#handleHeadersAndMaybeReturnEarly(ctx)){
620 ctx.keepIndicators = true;
621 return
622 }
623
624 if (ctx.status === "issuing") {
625 if (ctx.hx.retarget) ctx.target = ctx.hx.retarget; // HX-Retarget
626 if (ctx.hx.reswap) ctx.swap = ctx.hx.reswap; // HX-Reswap
627 if (ctx.hx.reselect) ctx.select = ctx.hx.reselect; // HX-Reselect
628 ctx.status = "response received";
629 this.#handleStatusCodes(ctx);
630 await this.swap(ctx);
631 ctx.status = "swapped";
632 }
633
634 } catch (error) {
635 ctx.status = "error: " + error;
636 this.#trigger(elt, "htmx:error", {ctx, error})
637 } finally {
638 clearTimeout(ctx.requestTimeout);
639 this.#trigger(elt, "htmx:finally:request", {ctx})
640 if (!ctx.keepIndicators) {
641 this.#hideIndicators(indicators);
642 this.#enableElements(disableElements);
643 }
644
645 requestQueue.finish()
646 if (requestQueue.more()) {
647 // intentionally not awaited — #issueRequest has its own try/catch
648 this.#issueRequest(requestQueue.next())
649 }
650 }
651 }
652
653 // Extract HX-* response headers into ctx.hx
654 // Maps: HX-Trigger → ctx.hx.trigger, HX-Push-Url → ctx.hx.pushurl, etc.
655 #extractHxHeaders(ctx) {
656 ctx.hx = {}
657 for (let [k, v] of ctx.response.raw.headers) {
658 if (k.toLowerCase().startsWith('hx-')) {
659 ctx.hx[k.slice(3).toLowerCase().replace(/-/g, '')] = v
660 }
661 }
662 }
663
664 // Handle response headers that abort normal swap processing.
665 // Returns true if the response was fully handled by a header.
666 #handleHeadersAndMaybeReturnEarly(ctx) {
667 if (ctx.hx.trigger) { // HX-Trigger
668 this.#handleTriggerHeader(ctx.hx.trigger, ctx.sourceElement);
669 }
670 if (ctx.hx.refresh === 'true') { // HX-Refresh
671 location.reload();
672 return true
673 }
674 if (ctx.hx.redirect) { // HX-Redirect
675 location.href = ctx.hx.redirect;
676 return true
677 }
678 if (ctx.hx.location) { // HX-Location
679 let path = ctx.hx.location, opts = {};
680 if (path[0] === '{' || /[\s,]/.test(path)) {
681 opts = HCON.parse(path);
682 path = opts.path;
683 delete opts.path;
684 }
685 opts.push ??= 'true';
686 this.ajax('GET', path, opts);
687 return true
688 }
689 }
690
691 #initTimeout(ctx) {
692 let timeout = ctx.request.timeout != null
693 ? this.parseInterval(ctx.request.timeout)
694 : this.config.defaultTimeout;
695 if (timeout) {
696 ctx.requestTimeout = setTimeout(() => ctx.request?.abort?.(), timeout);
697 }
698 }
699
700 #determineSyncStrategy(elt) {
701 let syncValue = this.#attributeValue(elt, "hx-sync");
702 if (!syncValue) return "queue first";
703 let strategy = syncValue.split(":").pop().trim();
704 return /^(drop|abort|replace|queue)/.test(strategy) ? strategy : "queue first";
705 }
706
707 #getRequestQueue(elt) {
708 let syncValue = this.#attributeValue(elt, "hx-sync");
709 let syncElt = elt
710 if (syncValue) {
711 let selector = syncValue.includes(":")
712 ? syncValue.slice(0, syncValue.lastIndexOf(":")).trim()
713 : (/^(drop|abort|replace|queue)/.test(syncValue) ? null : syncValue);
714 if (selector) syncElt = this.#findOrWarn(elt, selector, "hx-sync") || elt;
715 }
716 return this.#htmxState(syncElt).rq ||= new ReqQ()
717 }
718
719 #isModifierKeyClick(evt) {
720 return evt.type === 'click' && (evt.ctrlKey || evt.metaKey || evt.shiftKey)
721 && !!evt.currentTarget?.closest?.('a[href]')
722 }
723
724 #shouldCancel(evt) {
725 let elt = evt.currentTarget
726 let isSubmit = evt.type === 'submit' && elt?.tagName === 'FORM'
727 if (isSubmit) return true
728
729 let isClick = evt.type === 'click' && evt.button === 0
730 if (!isClick) return false
731
732 let btn = elt?.closest?.('button, input[type="submit"], input[type="image"]')
733 let form = btn?.form || btn?.closest('form')
734 let isSubmitButton = btn && !btn.disabled && form &&
735 (btn.type === 'submit' || btn.type === 'image' || (!btn.type && btn.tagName === 'BUTTON'))
736 if (isSubmitButton) return true
737
738 let link = elt?.closest?.('a')
739 if (!link || !link.href) return false
740
741 let href = link.getAttribute('href')
742 let isFragmentOnly = href && href.startsWith('#') && href.length > 1
743 return !isFragmentOnly
744 }
745
746 #initializeTriggers(elt, initialHandler = elt._htmx.eventHandler) {
747 let specString = this.#attributeValue(elt, "hx-trigger");
748 if (!specString) {
749 specString = elt.matches("form") ? "submit" :
750 elt.matches("input:not([type=button]):not([type=submit]),select,textarea") ? "change" :
751 "click";
752 }
753 this.#onTrigger(elt, specString, initialHandler)
754 }
755
756 // Wire up event listeners with full modifier support (once, prevent, stop,
757 // delay, throttle, changed, capture, passive, from, filter, etc.)
758 #onTrigger(elt, specString, handler) {
759 let specs = this.#parseTriggerSpecs(specString)
760 this.#htmxProp(elt).triggerSpecs.push(...specs)
761
762 for (let spec of specs) {
763 spec.listeners = []
764
765 let [eventName, filter] = this.#extractFilter(spec.name);
766
767 // Resolve from: elements (self listens on elt but filters by event.target in guard)
768 let fromElts = [elt];
769 if (spec.from === 'outside') fromElts = [document];
770 else if (spec.from && spec.from !== 'self') fromElts = this.#findAllExt(elt, spec.from);
771
772 // Inner: runs after delay/throttle resolves
773 let inner = (evt) => {
774 if (spec.halt || spec.prevent) evt.preventDefault();
775 if (spec.halt || spec.stop || spec.consume) evt.stopPropagation();
776 if (spec.once) {
777 for (let info of spec.listeners) info.fromElt.removeEventListener(info.eventName, info.handler, info);
778 }
779 handler(evt);
780 };
781
782 // Wrap inner with delay/throttle if needed
783 let timed = inner;
784 if (spec.delay) {
785 timed = evt => {
786 clearTimeout(spec.timeout);
787 spec.timeout = setTimeout(() => inner(evt), this.parseInterval(spec.delay));
788 };
789 } else if (spec.throttle) {
790 timed = evt => {
791 if (spec.throttled) {
792 spec.throttledEvent = evt;
793 } else {
794 spec.throttled = true;
795 inner(evt);
796 spec.throttleTimeout = setTimeout(() => {
797 spec.throttled = false;
798 if (spec.throttledEvent) {
799 let e = spec.throttledEvent;
800 spec.throttledEvent = null;
801 timed(e);
802 }
803 }, this.parseInterval(spec.throttle));
804 }
805 };
806 }
807
808 // Guarded: pre-timing checks that determine if event should proceed
809 spec.handler = (evt) => {
810 if (spec.from === 'self' && evt.target !== elt) return;
811 if (spec.from === 'outside' && elt.contains(evt.target)) return;
812 if (spec.target && !evt.target?.matches?.(spec.target)) return;
813 if (spec.changed) {
814 let values = spec.values ??= new WeakMap();
815 let changed = false;
816 for (let fromElt of fromElts) {
817 if (values.get(fromElt) !== fromElt.value) {
818 changed = true;
819 values.set(fromElt, fromElt.value);
820 }
821 }
822 if (!changed) return;
823 }
824 if (filter) {
825 if (this.#shouldCancel(evt)) evt.preventDefault();
826 let evtArgs = {}; for (let k in evt) evtArgs[k] = evt[k];
827 if (!this.#executeJavaScript(elt, evtArgs, filter, true, false)) return;
828 }
829 timed(evt);
830 };
831
832 // Intersect/revealed: set up observer
833 if (eventName === 'intersect' || eventName === 'revealed') {
834 let observerOptions = {rootMargin: spec.rootMargin};
835 if (spec.root) observerOptions.root = this.#findOrWarn(elt, spec.root);
836 if (spec.threshold) observerOptions.threshold = parseFloat(spec.threshold);
837 let isRevealed = eventName === 'revealed';
838 spec.observer = new IntersectionObserver((entries) => {
839 for (let i = 0; i < entries.length; i++) {
840 if (entries[i].isIntersecting) {
841 this.trigger(elt, 'intersect', {}, false);
842 if (isRevealed) spec.observer.disconnect();
843 break;
844 }
845 }
846 }, observerOptions);
847 eventName = 'intersect';
848 spec.observer.observe(elt);
849 }
850
851 // Every: set up interval
852 if (eventName === "every") {
853 let interval = Object.keys(spec).find(k => k !== 'name');
854 spec.interval = setInterval(() => {
855 if (elt.isConnected) this.#trigger(elt, 'every', {}, false);
856 else clearInterval(spec.interval);
857 }, this.parseInterval(interval));
858 }
859
860 // Load: fire immediately, no listener needed
861 if (eventName === 'load') {
862 spec.handler(new CustomEvent('load'));
863 continue;
864 }
865
866 // Register listeners
867 for (let fromElt of fromElts) {
868 let listenerInfo = {fromElt, eventName, handler: spec.handler,
869 capture: !!spec.capture, passive: !!spec.passive};
870 elt._htmx.listeners.push(listenerInfo);
871 spec.listeners.push(listenerInfo);
872 fromElt.addEventListener(eventName, spec.handler, listenerInfo);
873 }
874 }
875 }
876
877 #extractFilter(str) {
878 let match = str.match(/^([^\[]*)\[([^\]]*)]/);
879 if (!match) return [str, null];
880 return [match[1], match[2]];
881 }
882
883 #handleTriggerHeader(value, elt) {
884 if (value[0] === '{') {
885 let triggers = HCON.parse(value);
886 for (let name in triggers) {
887 let detail = triggers[name];
888 let target = elt;
889 if (detail?.target) {
890 target = this.find(detail.target);
891 }
892 this.trigger(target, name, typeof detail === 'object' ? detail : {value: detail});
893 }
894 } else {
895 value.split(',').forEach(name => this.trigger(elt, name.trim(), {}));
896 }
897 }
898
899 #apiMethods(thisArg) {
900 let bound = {};
901 let proto = Object.getPrototypeOf(this);
902 for (let name of Object.getOwnPropertyNames(proto)) {
903 if (name !== 'constructor' && typeof this[name] === 'function') {
904 if (["find", "findAll"].includes(name)) {
905 bound[name] = (arg1, arg2) => {
906 if (arg2 === undefined) {
907 return this[name](thisArg, arg1)
908 } else {
909 return this[name](arg1, arg2)
910 }
911 }
912 } else {
913 bound[name] = this[name].bind(this);
914 }
915 }
916 }
917 return bound;
918 }
919
920 #executeJavaScript(thisArg, obj, code, expression = true, isAsync = true) {
921 let args = {}
922 Object.assign(args, this.#apiMethods(thisArg))
923 let scope = {};
924 this.#triggerExtensions(thisArg, "htmx:scope", { scope });
925 Object.assign(args, scope);
926 Object.assign(args, obj)
927 let keys = Object.keys(args);
928 let values = Object.values(args);
929 let FunctionConstructor = isAsync ? this.#AsyncFunction : this.#Function;
930 let func = new FunctionConstructor(...keys, expression ? `return (${code})` : code);
931 return func.call(thisArg, ...values);
932 }
933
934 /**
935 * Initialize htmx attributes on root and all its descendants. When force is true, root
936 * and every powered descendant are first torn down and re-wired from their current
937 * attributes - use this after mutating hx-* attributes on an already-processed element.
938 * @see https://four.htmx.org/reference/methods/htmx-process
939 * @param {Element | ShadowRoot} root
940 * @param {boolean} [force]
941 */
942 process(root, force) {
943 if (!root?.isConnected) return;
944 if (!(root instanceof Element)) { // ShadowRoot
945 for (let elt of root.children || []) this.process(elt, force);
946 return;
947 }
948 if (force) this.#cleanup(root, true);
949 if (this.#ignore(root)) return;
950 if (!this.#trigger(root, "htmx:before:process")) return
951 let hxOnNodes = [root];
952 let iter = this.#hxOnQuery.evaluate(root)
953 let node = null
954 while (node = iter.iterateNext()) hxOnNodes.push(node)
955 for (let hxOnNode of hxOnNodes) {
956 if (!this.#ignore(hxOnNode) && this.#trigger(hxOnNode, "htmx:before:on:init", {}, true)) {
957 this.#handleHxOnAttributes(hxOnNode);
958 }
959 }
960 for (let elt of this.#queryEltAndDescendants(root, this.#actionSelector)) {
961 this.#initializeElement(elt);
962 }
963 for (let elt of this.#queryEltAndDescendants(root, this.#boostSelector)) {
964 this.#maybeBoost(elt);
965 }
966 this.#trigger(root, "htmx:after:process");
967 }
968
969 #maybeBoost(elt) {
970 let boostValue = this.#attributeValue(elt, "hx-boost");
971 if (boostValue && boostValue !== "false" && this.#shouldBoost(elt) && this.#trigger(elt, "htmx:before:init", {}, true)) {
972 let htmxProp = this.#htmxProp(elt);
973 htmxProp.initialized = true;
974 htmxProp.eventHandler = this.#createHtmxEventHandler(elt);
975 htmxProp.boosted = boostValue;
976 let eventName = elt.matches('a') ? 'click' : 'submit';
977 elt._htmx.listeners.push({fromElt: elt, eventName, handler: elt._htmx.eventHandler});
978 elt.addEventListener(eventName, elt._htmx.eventHandler);
979 this.#trigger(elt, "htmx:after:init", {}, true)
980 }
981 }
982
983 #shouldBoost(elt) {
984 if (this.#shouldInitialize(elt)) {
985 if (elt.tagName === "A") {
986 if (elt.target === '' || elt.target === '_self') {
987 return !elt.hasAttribute('download') && !elt.getAttribute('href')?.startsWith?.("#") && this.#isSameOrigin(elt.href)
988 }
989 } else if (elt.tagName === "FORM") {
990 return elt.method !== 'dialog' && this.#isSameOrigin(elt.action);
991 }
992 }
993 }
994
995 #isSameOrigin(url) {
996 try {
997 // URL constructor handles both relative and absolute URLs
998 const parsed = new URL(url, window.location.href);
999 return parsed.origin === window.location.origin;
1000 } catch (e) {
1001 // If URL parsing fails, assume not same-origin
1002 return false;
1003 }
1004 }
1005
1006 #shouldInitialize(elt) {
1007 return !elt._htmx?.initialized && !this.#ignore(elt);
1008 }
1009
1010 /**
1011 * Remove listeners, timers, and observers from elt and all its powered descendants.
1012 * When force is true, also delete their htmx state so a re-process fully re-initializes them.
1013 * @param {Element} elt
1014 * @param {boolean} [force]
1015 */
1016 #cleanup(elt, force) {
1017 let elts = [elt, ...elt.querySelectorAll?.('[data-htmx-powered]') ?? []];
1018 for (let e of elts) {
1019 if (!e._htmx) continue;
1020 this.#trigger(e, "htmx:before:cleanup")
1021 for (let spec of e._htmx.triggerSpecs || []) {
1022 if (spec.interval) clearInterval(spec.interval);
1023 if (spec.timeout) clearTimeout(spec.timeout);
1024 if (spec.throttleTimeout) clearTimeout(spec.throttleTimeout);
1025 spec.observer?.disconnect()
1026 }
1027 for (let info of e._htmx.listeners || []) {
1028 info.fromElt.removeEventListener(info.eventName, info.handler, info);
1029 }
1030 e.removeAttribute('data-htmx-powered');
1031 this.#trigger(e, "htmx:after:cleanup")
1032 if (force) delete e._htmx;
1033 }
1034 }
1035
1036 #handlePreservedElements(fragment) {
1037 let pantry = document.createElement('div');
1038 pantry.hidden = true;
1039 document.body.insertAdjacentElement('afterend', pantry);
1040 let newPreservedElts = fragment.querySelectorAll?.(this.#prefixSelector('[hx-preserve]')) || [];
1041 for (let preservedElt of newPreservedElts) {
1042 let currentElt = document.getElementById(preservedElt.id);
1043 if (currentElt) {
1044 this.#moveBefore(pantry, currentElt, null);
1045 }
1046 }
1047 return pantry
1048 }
1049
1050 #restorePreservedElements(pantry) {
1051 for (let preservedElt of [...pantry.children]) {
1052 let newElt = document.getElementById(preservedElt.id);
1053 if (newElt) {
1054 this.#moveBefore(newElt.parentNode, preservedElt, newElt);
1055 this.#cleanup(newElt)
1056 newElt.remove()
1057 }
1058 }
1059 pantry.remove();
1060 }
1061
1062 #parseHTML(resp) {
1063 let trusted = this.#ttPolicy.createHTML(resp);
1064 return Document.parseHTMLUnsafe?.(trusted) || new DOMParser().parseFromString(trusted, 'text/html');
1065 }
1066
1067 #makeFragment(text) {
1068 // Convert <hx-*> tags (e.g. <hx-partial>, <hx-oob>) to <template hx type="*">
1069 let response = text.replace(/<hx-([a-z]+)(\s+|>)/gi, '<template hx type="$1"$2').replace(/<\/hx-[a-z]+>/gi, '</template>');
1070 let title = '';
1071 response = response.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i, m => (title = this.#parseHTML(m).title, ''));
1072 let startTag = response.match(/<([a-z][^\/>\x20\t\r\n\f]*)/i)?.[1]?.toLowerCase();
1073
1074 let doc, fragment;
1075 if (startTag === 'html' || startTag === 'body') {
1076 doc = this.#parseHTML(response);
1077 fragment = document.createDocumentFragment();
1078 fragment.append(doc.body);
1079 } else {
1080 doc = this.#parseHTML(`<template>${response}</template>`);
1081 fragment = doc.querySelector('template').content;
1082 }
1083
1084 if (!title) {
1085 let titleElt = fragment.querySelector('title:not(svg title)');
1086 if (titleElt) {
1087 title = titleElt.textContent;
1088 titleElt.remove();
1089 }
1090 }
1091
1092 this.#processScripts(fragment);
1093
1094 return {
1095 fragment,
1096 title
1097 };
1098 }
1099
1100 #createOOBTask(tasks, elt, oobValue, sourceElement) {
1101 let targetSelector = elt.id ? '#' + CSS.escape(elt.id) : null;
1102 if (oobValue !== 'true' && oobValue && !oobValue.includes(' ')) {
1103 [oobValue, targetSelector = targetSelector] = oobValue.split(/:(.*)/);
1104 }
1105 if (oobValue === 'true' || !oobValue) oobValue = 'outerHTML';
1106
1107 let swapSpec = this.#parseSwapSpec(oobValue);
1108 targetSelector = swapSpec.target || targetSelector;
1109 swapSpec.strip ??= !swapSpec.style.startsWith('outer');
1110 if (!targetSelector) return;
1111 let targets = [...document.querySelectorAll(targetSelector)];
1112 for (let target of targets) {
1113 let fragment = document.createDocumentFragment();
1114 fragment.append(elt.cloneNode(true));
1115 tasks.push({type: 'oob', fragment, target, swapSpec, sourceElement});
1116 }
1117 elt.remove();
1118 }
1119
1120 #processOOB(fragment, sourceElement, selectOOB) {
1121 let tasks = [];
1122
1123 // Process hx-select-oob first (select elements from response)
1124 if (selectOOB) {
1125 for (let spec of selectOOB.split(',')) {
1126 let [selector, oobValue = 'true'] = spec.split(/:(.*)/);
1127 for (let elt of fragment.querySelectorAll(selector)) {
1128 this.#createOOBTask(tasks, elt, oobValue, sourceElement);
1129 }
1130 }
1131 }
1132
1133 // Process elements with hx-swap-oob attribute
1134 for (let oobElt of fragment.querySelectorAll(this.#prefixSelector('[hx-swap-oob]'))) {
1135 let oobAttr = this.#attrName(oobElt, 'hx-swap-oob');
1136 let oobValue = oobElt.getAttribute(oobAttr);
1137 oobElt.removeAttribute(oobAttr);
1138 this.#createOOBTask(tasks, oobElt, oobValue, sourceElement);
1139 }
1140 return tasks;
1141 }
1142
1143 #insertNodes(parent, before, fragment) {
1144 if (before) {
1145 before.before(...fragment.childNodes);
1146 } else {
1147 parent.append(...fragment.childNodes);
1148 }
1149 }
1150
1151 #parseSwapSpec(swapStr) {
1152 swapStr = swapStr.trim();
1153 let style = this.config.defaultSwap
1154 if (swapStr && !/^\S*:/.test(swapStr)) {
1155 let m = swapStr.match(/^(\S+)\s*(.*)$/);
1156 style = m[1];
1157 swapStr = m[2];
1158 }
1159 return {style: this.#normalizeSwapStyle(style), ...HCON.parse(swapStr)};
1160 }
1161
1162 #processPartials(fragment, ctx) {
1163 let tasks = [];
1164
1165 for (let templateElt of fragment.querySelectorAll('template[hx]')) {
1166 let type = templateElt.getAttribute('type');
1167
1168 if (type === 'partial') {
1169 let targetSelector = this.#attr(templateElt, 'hx-target') || (templateElt.id ? '#' + CSS.escape(templateElt.id) : null);
1170 if (targetSelector) {
1171 this.#processScripts(templateElt.content);
1172 let swapSpec = this.#parseSwapSpec(this.#attr(templateElt, 'hx-swap') || this.config.defaultSwap);
1173 for (let target of document.querySelectorAll(targetSelector)) {
1174 tasks.push({
1175 type: 'partial',
1176 fragment: templateElt.content.cloneNode(true),
1177 target,
1178 swapSpec,
1179 sourceElement: ctx.sourceElement
1180 });
1181 }
1182 }
1183 } else {
1184 this.#triggerExtensions(templateElt, 'htmx:process:' + type, { ctx, tasks });
1185 }
1186 templateElt.remove();
1187 }
1188
1189 return tasks;
1190 }
1191
1192 #setFocus(elt, options, start, end) {
1193 try {
1194 if (start != null && elt.setSelectionRange) {
1195 elt.setSelectionRange(start, end);
1196 }
1197 elt.focus(options);
1198 } catch (e) {
1199 // setSelectionRange or Web component focus may fail so ignore
1200 }
1201 }
1202
1203 #handleAutoFocus(elt) {
1204 let autofocus = this.#queryEltAndDescendants(elt, '[autofocus]')[0];
1205 if (autofocus) {
1206 this.#setFocus(autofocus);
1207 }
1208 }
1209
1210 #handleScroll(swapSpec, target) {
1211 if (swapSpec.scroll) {
1212 let scrollTarget = swapSpec.scrollTarget ? this.#findExt(swapSpec.scrollTarget) : target;
1213 if (scrollTarget) {
1214 if (swapSpec.scroll === 'top') {
1215 scrollTarget.scrollTop = 0;
1216 } else if (swapSpec.scroll === 'bottom'){
1217 scrollTarget.scrollTop = scrollTarget.scrollHeight;
1218 }
1219 }
1220 }
1221 if (swapSpec.show === 'top' || swapSpec.show === 'bottom') {
1222 let showTarget = swapSpec.showTarget ? this.#findExt(swapSpec.showTarget) : target;
1223 showTarget?.scrollIntoView(swapSpec.show === 'top')
1224 }
1225 }
1226
1227 #handleAnchorScroll(ctx) {
1228 if (ctx.request?.anchor) {
1229 document.getElementById(ctx.request.anchor)?.scrollIntoView({block: 'start', behavior: 'auto'});
1230 }
1231 }
1232
1233 #processScripts(container) {
1234 let scripts = this.#queryEltAndDescendants(container, 'script');
1235 for (let oldScript of scripts) {
1236 let newScript = document.createElement('script');
1237 for (let attr of oldScript.attributes) {
1238 newScript.setAttribute(attr.name, attr.value);
1239 }
1240 if (this.config.inlineScriptNonce) {
1241 newScript.nonce = this.config.inlineScriptNonce;
1242 }
1243 newScript.textContent = this.#ttPolicy.createScript(oldScript.textContent);
1244 oldScript.replaceWith(newScript);
1245 }
1246 }
1247
1248 //============================================================================================
1249 // Public JS API
1250 //============================================================================================
1251
1252 async swap(ctx) {
1253 try {
1254 this.#handleHistoryUpdate(ctx);
1255 let {fragment, title} = this.#makeFragment(ctx.text);
1256 ctx.title = title;
1257 let tasks = [];
1258
1259 // Process OOB and partials
1260 let oobTasks = this.#processOOB(fragment, ctx.sourceElement, ctx.selectOOB);
1261 let partialTasks = this.#processPartials(fragment, ctx);
1262 tasks.push(...oobTasks, ...partialTasks);
1263
1264 // Process main swap first
1265 let mainSwap = this.#processMainSwap(ctx, fragment, partialTasks);
1266 if (mainSwap) {
1267 tasks.unshift(mainSwap);
1268 }
1269
1270 if(!this.#trigger(ctx.sourceElement, "htmx:before:swap", {ctx, tasks})){
1271 return
1272 }
1273
1274 let swapPromises = [];
1275 let transitionTasks = [];
1276 for (let task of tasks) {
1277 if (task.swapSpec?.transition ?? mainSwap?.transition ?? ctx.transition) {
1278 transitionTasks.push(task);
1279 } else {
1280 swapPromises.push(this.#insertContent(task));
1281 }
1282 }
1283
1284 // submit all transition tasks in the transition queue w/no CSS transitions
1285 if (transitionTasks.length > 0) {
1286 let tasksWrapper = async ()=> {
1287 for (let task of transitionTasks) {
1288 await this.#insertContent(task, false)
1289 }
1290 }
1291 swapPromises.push(this.#submitTransitionTask(tasksWrapper));
1292 }
1293
1294 await Promise.all(swapPromises);
1295
1296 this.#trigger(ctx.sourceElement, "htmx:after:swap", {ctx});
1297 if (ctx.title && !mainSwap?.swapSpec?.ignoreTitle) document.title = ctx.title;
1298 this.#handleAnchorScroll(ctx);
1299 } finally {
1300 this.#trigger(ctx.sourceElement, "htmx:swap:finally", {ctx});
1301 }
1302 }
1303
1304 #processMainSwap(ctx, fragment, partialTasks) {
1305 // Create main task if needed
1306 let swapSpec = this.#parseSwapSpec(ctx.swap || this.config.defaultSwap);
1307 // skip main swap if fragment is empty after hx-partial removal but respect empty modifier
1308 if (
1309 swapSpec.style === 'delete' || // delete always runs regardless of content
1310 fragment.childElementCount > 0 || // or fragment has elements
1311 fragment.textContent.trim() || // or fragment has text
1312 (swapSpec.swapEmpty ?? this.config.defaultSwapEmpty ?? !partialTasks.length) // swapEmpty:true/false overrides, default: allow if no partials
1313 ) {
1314 if (ctx.select) {
1315 let selected = fragment.querySelectorAll(ctx.select);
1316 fragment = document.createDocumentFragment();
1317 fragment.append(...selected);
1318 }
1319 if (this.#isBoosted(ctx.sourceElement)) {
1320 swapSpec.show ||= 'top';
1321 }
1322 let mainSwap = {
1323 type: 'main',
1324 fragment,
1325 target: this.#resolveTarget(ctx.sourceElement || document.body, swapSpec.target || ctx.target),
1326 swapSpec,
1327 sourceElement: ctx.sourceElement,
1328 transition: ctx.transition && swapSpec.transition !== false
1329 };
1330 return mainSwap;
1331 }
1332 }
1333
1334 async #insertContent(task, cssTransition = true) {
1335 let {target, swapSpec, fragment} = task;
1336 if (typeof target === 'string') {
1337 target = document.querySelector(target);
1338 }
1339 if (!target) return;
1340 if (typeof swapSpec === 'string') {
1341 swapSpec = this.#parseSwapSpec(swapSpec);
1342 }
1343 let swapStyle = swapSpec.style;
1344 if (swapStyle === 'none') return;
1345 // full-page response: fragment has a <body> wrapper — upgrade outerHTML to outerSync, strip for everything else
1346 if (fragment.firstElementChild?.tagName === 'BODY') {
1347 if (swapStyle === 'outerHTML') swapStyle = 'outerSync';
1348 else if (!swapStyle.startsWith('outer')) swapSpec.strip = true;
1349 }
1350 if (swapSpec.strip && fragment.firstElementChild) {
1351 fragment = document.createDocumentFragment();
1352 fragment.append(...(task.fragment.firstElementChild.content || task.fragment.firstElementChild).childNodes);
1353 }
1354
1355 this.#addClass(target, "htmx-swapping")
1356 if (cssTransition && task.swapSpec?.swap) {
1357 await this.timeout(task.swapSpec?.swap)
1358 }
1359
1360 if (swapStyle === 'delete') {
1361 if (target.parentNode) {
1362 this.#cleanup(target);
1363 target.parentNode.removeChild(target);
1364 }
1365 return;
1366 }
1367
1368 // innerHTML/outerHTML swaps backup focus and handle CSS transitions
1369 let focusInfo;
1370 let settleTasks = []
1371 let settleDelay = swapSpec.settle ?? this.config.defaultSettleDelay;
1372 let parentNode = target.parentNode;
1373 if (swapStyle === 'innerHTML' || (swapStyle === 'outerHTML' && parentNode)) {
1374 let activeElt = document.activeElement;
1375 if (activeElt?.id) {
1376 let start, end;
1377 try { start = activeElt.selectionStart; end = activeElt.selectionEnd; } catch (e) {}
1378 focusInfo = { elt: activeElt, start, end };
1379 }
1380 settleTasks = cssTransition && settleDelay ? this.#startCSSTransitions(fragment, target) : []
1381 }
1382
1383 let pantry = this.#handlePreservedElements(fragment);
1384 let newContent = [...fragment.childNodes]
1385 try {
1386 if (swapStyle === 'innerHTML') {
1387 for (const child of target.children) {
1388 this.#cleanup(child)
1389 }
1390 target.replaceChildren(...fragment.childNodes);
1391 } else if (swapStyle === 'textContent') {
1392 for (const child of target.querySelectorAll('[data-htmx-powered]')) {
1393 this.#cleanup(child)
1394 }
1395 target.textContent = fragment.textContent;
1396 } else if (swapStyle === 'outerHTML') {
1397 if (parentNode) {
1398 this.#insertNodes(parentNode, target, fragment);
1399 this.#cleanup(target)
1400 parentNode.removeChild(target);
1401 target = newContent[0] || parentNode
1402 }
1403 } else if (swapStyle === 'outerSync') {
1404 this.#copyAttributes(target, fragment.firstElementChild);
1405 for (const child of target.children) {
1406 this.#cleanup(child)
1407 }
1408 target.replaceChildren(...fragment.firstElementChild.childNodes);
1409 newContent = [target];
1410 } else if (swapStyle === 'innerMorph') {
1411 this.#morph(target, fragment, true);
1412 newContent = [...target.childNodes];
1413 } else if (swapStyle === 'outerMorph') {
1414 this.#morph(target, fragment, false);
1415 newContent.push(target);
1416 } else if (swapStyle === 'beforebegin') {
1417 if (parentNode) {
1418 this.#insertNodes(parentNode, target, fragment);
1419 }
1420 } else if (swapStyle === 'afterbegin') {
1421 this.#insertNodes(target, target.firstChild, fragment);
1422 } else if (swapStyle === 'beforeend') {
1423 this.#insertNodes(target, null, fragment);
1424 } else if (swapStyle === 'afterend') {
1425 if (parentNode) {
1426 this.#insertNodes(parentNode, target.nextSibling, fragment);
1427 }
1428 } else {
1429 let methods = this.#extMethods.get('handle_swap') || []
1430 let handled = false;
1431 for (const method of methods) {
1432 let result = method(swapStyle, target, fragment, swapSpec);
1433 if (result) {
1434 handled = true;
1435 if (Array.isArray(result)) {
1436 newContent = result;
1437 }
1438 break;
1439 }
1440 }
1441 if (!handled) {
1442 throw new Error(`Unknown swap style: ${swapStyle}`);
1443 }
1444 }
1445 } finally {
1446 this.#removeClass(target, "htmx-swapping")
1447 }
1448 this.#restorePreservedElements(pantry);
1449 if (focusInfo && !focusInfo.elt.matches(':focus')) {
1450 let newElt = document.getElementById(focusInfo.elt.id);
1451 if (newElt) {
1452 let focusOptions = { preventScroll: swapSpec.focusScroll !== undefined ? !swapSpec.focusScroll : !this.config.defaultFocusScroll };
1453 this.#setFocus(newElt, focusOptions, focusInfo.start, focusInfo.end);
1454 }
1455 }
1456
1457 this.#trigger(target, "htmx:before:settle", {task, newContent, settleTasks})
1458
1459 for (const elt of newContent) {
1460 this.#addClass(elt, "htmx-added")
1461 }
1462
1463 if (cssTransition && settleTasks.length > 0) {
1464 this.#addClass(target, "htmx-settling")
1465 await this.timeout(settleDelay);
1466 // invoke settle tasks
1467 for (let settleTask of settleTasks) {
1468 settleTask()
1469 }
1470 this.#removeClass(target, "htmx-settling")
1471 }
1472
1473 this.#trigger(target, "htmx:after:settle", {task, newContent, settleTasks})
1474
1475 for (const elt of newContent) {
1476 this.#removeClass(elt, "htmx-added")
1477 this.process(elt);
1478 this.#handleAutoFocus(elt);
1479 }
1480
1481 this.#handleScroll(swapSpec, target);
1482 }
1483
1484 #trigger(on, eventName, detail = {}, bubbles = true) {
1485 // Convention: events with detail.error log at error level, detail.warn at warn level,
1486 // otherwise at event level (gated by config.logAll). One emit per event.
1487 if (detail.error) {
1488 let prefix = `htmx: ${eventName}: ${detail.error.message ?? detail.error}`;
1489 if (detail.error instanceof Error) console.error(prefix, detail.error, { elt: on, detail });
1490 else console.error(prefix, { elt: on, detail });
1491 } else if (detail.warn) {
1492 console.warn(`htmx: ${eventName}: ${detail.warn}`, { elt: on, detail });
1493 } else if (this.config.logAll) {
1494 console.log(`htmx: ${eventName}`, { elt: on, detail });
1495 }
1496 on = this.#normalizeElement(on)
1497 this.#triggerExtensions(on, eventName, detail);
1498 return this.trigger(on, this.#maybeAdjustMetaCharacter(eventName), detail, bubbles)
1499 }
1500
1501 #triggerExtensions(elt, eventName, detail = {}) {
1502 let methods = this.#extMethods.get(eventName.replace(/:/g, '_'))
1503 if (methods) {
1504 detail.cancelled = false;
1505 for (const fn of methods) {
1506 if (fn(elt, detail) === false || detail.cancelled) {
1507 detail.cancelled = true;
1508 return false;
1509 }
1510 }
1511 }
1512 return true;
1513 }
1514
1515 timeout(time) {
1516 time = this.parseInterval(time);
1517 if (time > 0) {
1518 return new Promise(resolve => setTimeout(resolve, time));
1519 }
1520 }
1521
1522 onLoad(callback) {
1523 this.on(this.#maybeAdjustMetaCharacter("htmx:after:process"), (evt) => {
1524 callback(evt.target)
1525 })
1526 }
1527
1528 on(eventOrElt, eventOrCallback, callback) {
1529 let event;
1530 let elt = document;
1531 if (callback === undefined) {
1532 event = eventOrElt;
1533 callback = eventOrCallback
1534 } else {
1535 elt = this.#normalizeElement(eventOrElt);
1536 event = eventOrCallback;
1537 }
1538 elt.addEventListener(event, callback);
1539 return callback;
1540 }
1541
1542 find(selectorOrElt, selector) {
1543 return this.#findExt(selectorOrElt, selector)
1544 }
1545
1546 findAll(selectorOrElt, selector) {
1547 return this.#findAllExt(selectorOrElt, selector)
1548 }
1549
1550 parseInterval(str) {
1551 if (typeof str === 'number') return str;
1552 let m = {ms: 1, s: 1000, m: 60000};
1553 let [, n, u] = str?.match(/^([\d.]+)(ms|s|m)?$/) || [];
1554 let v = parseFloat(n) * (m[u] || 1);
1555 return isNaN(v) ? undefined : v;
1556 }
1557
1558 trigger(on, eventName, detail = {}, bubbles = true) {
1559 on = this.#normalizeElement(on)
1560 let evt = new CustomEvent(eventName, {
1561 detail,
1562 cancelable: true,
1563 bubbles,
1564 composed: true
1565 });
1566 let target = on?.isConnected ? on : document;
1567 let result = !detail.cancelled && target.dispatchEvent(evt);
1568 return result
1569 }
1570 ajax(verb, path, context) {
1571 // Normalize context to object
1572 if (!context || context instanceof Element || typeof context === 'string') {
1573 context = {target: context};
1574 }
1575
1576 let sourceElt = typeof context.source === 'string' ?
1577 document.querySelector(context.source) : context.source;
1578
1579 // If source selector was provided but didn't match, reject
1580 if (typeof context.source === 'string' && !sourceElt) {
1581 return Promise.reject(new Error('Source not found'));
1582 }
1583
1584 // Resolve explicit target if provided; otherwise #createRequestContext
1585 // will resolve from hx-target on the source element
1586 if (context.target) {
1587 let target = this.#resolveTarget(document.body, context.target);
1588 if (!target) {
1589 return Promise.reject(new Error('Target not found'));
1590 }
1591 sourceElt ||= target;
1592 }
1593 sourceElt ||= document.body;
1594
1595 let ctx = this.#createRequestContext(sourceElt, context.event || {});
1596 Object.assign(ctx, context);
1597 if (context.target) ctx.target = this.#resolveTarget(document.body, context.target);
1598 Object.assign(ctx.request, {action: path, method: verb.toUpperCase()});
1599 if (context.headers) Object.assign(ctx.request.headers, context.headers);
1600
1601 return this.#handleTriggerEvent(ctx);
1602 }
1603
1604 //============================================================================================
1605 // History Support
1606 //============================================================================================
1607
1608 #initHistoryHandling() {
1609 if (!this.config.history) return;
1610 if (!history.state) {
1611 history.replaceState({htmx: true}, '', location.href);
1612 }
1613 window.addEventListener('popstate', (event) => {
1614 if (event.state && event.state.htmx) {
1615 this.#historyAbort?.abort();
1616 this.#restoreHistory();
1617 }
1618 });
1619 }
1620
1621 #pushUrlIntoHistory(path) {
1622 if (!this.config.history) return;
1623 history.pushState({htmx: true}, '', path);
1624 this.#trigger(document, "htmx:after:history:push", {path});
1625 }
1626
1627 #replaceUrlInHistory(path) {
1628 if (!this.config.history) return;
1629 history.replaceState({htmx: true}, '', path);
1630 this.#trigger(document, "htmx:after:history:replace", {path});
1631 }
1632
1633 #restoreHistory(path) {
1634 path = path || location.pathname + location.search;
1635 let historyElt = document.querySelector(this.#prefixSelector('[hx-history-elt]')) || document.body;
1636 if (this.#trigger(document, "htmx:before:history:restore", {path, cacheMiss: true})) {
1637 if (this.config.history === "reload") {
1638 location.reload();
1639 } else {
1640 this.#historyAbort = new AbortController();
1641 this.ajax('GET', path, {
1642 target: historyElt,
1643 swap: 'outerSync',
1644 select: historyElt !== document.body ? this.#prefixSelector('[hx-history-elt]') : undefined,
1645 request: {
1646 headers: {'HX-History-Restore-Request': 'true'},
1647 signal: this.#historyAbort.signal
1648 }
1649 });
1650 }
1651 }
1652 }
1653
1654 #resolveHistoryAction(ctx) {
1655 let {sourceElement, push, replace, hx, response} = ctx;
1656
1657 // allow response headers to override history action
1658 if (hx?.pushurl || hx?.replaceurl) { // HX-Push-Url, HX-Replace-Url
1659 push = hx.pushurl;
1660 replace = hx.replaceurl;
1661 }
1662
1663 // if this is a boosted element, default to pushing
1664 if (push == null && replace == null && this.#isBoosted(sourceElement)) {
1665 push = 'true';
1666 }
1667
1668 // normalize "false" to null
1669 if (push === 'false' || push === false) push = null;
1670 if (replace === 'false' || replace === false) replace = null;
1671
1672 if (!push && !replace) return null;
1673
1674 let path = push || replace;
1675 // if the path is simply "true" normalize to the current path
1676 if (path === 'true') {
1677 let finalUrl = response?.raw?.url || ctx.request.action;
1678 let url = new URL(finalUrl, location.href);
1679 path = url.pathname + url.search + (ctx.request.anchor ? '#' + ctx.request.anchor : '');
1680 }
1681
1682 let type = push ? 'push' : 'replace';
1683 return {type, path};
1684 }
1685
1686 #handleHistoryUpdate(ctx) {
1687 let action = this.#resolveHistoryAction(ctx);
1688 if (!action) return;
1689
1690 let historyDetail = {
1691 history: action,
1692 sourceElement: ctx.sourceElement,
1693 response: ctx.response
1694 };
1695 if (!this.#trigger(document, "htmx:before:history:update", historyDetail)) return;
1696 if (action.type === 'push') {
1697 this.#pushUrlIntoHistory(action.path);
1698 } else {
1699 this.#replaceUrlInHistory(action.path);
1700 }
1701 this.#trigger(document, "htmx:after:history:update", historyDetail);
1702 }
1703
1704 // hx-on:<event> binds to <event> directly
1705 // hx-on::<event> is shorthand for hx-on:htmx:<event> (htmx events)
1706 #handleHxOnAttributes(node) {
1707 if (node._htmx?.onInitialized) return;
1708 let hxOnNames = this.#prefixes("hx-on");
1709 let mc = this.config.metaCharacter || ':';
1710 let handler = (code) => async (evt) => {
1711 try {
1712 await this.#executeJavaScript(node, { event: evt },
1713 `with(event?.detail||{}){${code}}`, false);
1714 } catch (e) {
1715 if (typeof e !== 'symbol') this.#trigger(node, 'htmx:error', { error: e });
1716 }
1717 };
1718 for (let attr of node.getAttributeNames()) {
1719 let prefix = hxOnNames.find(p => attr.startsWith(p));
1720 if (!prefix) continue;
1721 this.#htmxProp(node).onInitialized = true;
1722 let rest = attr.substring(prefix.length);
1723 let value = node.getAttribute(attr);
1724 // hx-on="click once -> doA(); blur -> doB()"
1725 if (!rest) {
1726 for (let part of value.split(/;(?=[^;]*->)/)) {
1727 let idx = part.indexOf('->');
1728 if (idx !== -1) this.#onTrigger(node, part.substring(0, idx).trim(), handler(part.substring(idx + 2).trim()));
1729 }
1730 continue;
1731 }
1732 // hx-on:click="code" or hx-on::before:request="code"
1733 if (rest[0] !== mc) continue;
1734 let eventName = rest.substring(1);
1735 if (eventName.startsWith(mc)) eventName = 'htmx' + mc + eventName.substring(1);
1736 this.#onTrigger(node, eventName, handler(value));
1737 }
1738 }
1739
1740 #showIndicators(elt) {
1741 let indicatorsSelector = this.#attributeValue(elt, "hx-indicator");
1742 let indicatorElements;
1743 if (!indicatorsSelector) {
1744 indicatorElements = [elt]
1745 } else {
1746 indicatorElements = this.#findAllExt(elt, indicatorsSelector, "hx-indicator");
1747 }
1748 for (const indicator of indicatorElements) {
1749 let s = this.#htmxState(indicator);
1750 s.rc = (s.rc || 0) + 1;
1751 this.#addClass(indicator, this.config.requestClass)
1752 }
1753 return indicatorElements
1754 }
1755
1756 #hideIndicators(indicatorElements) {
1757 for (let indicator of indicatorElements) {
1758 let s = this.#htmxState(indicator);
1759 if (s.rc && --s.rc <= 0) {
1760 this.#removeClass(indicator, this.config.requestClass);
1761 delete s.rc;
1762 }
1763 }
1764 }
1765
1766 #disableElements(elt) {
1767 let disabledSelector = this.#attributeValue(elt, "hx-disable");
1768 let disabledElements = []
1769 if (disabledSelector) {
1770 disabledElements = this.#findAllExt(elt, disabledSelector, "hx-disable");
1771 for (let indicator of disabledElements) {
1772 let s = this.#htmxState(indicator);
1773 s.dc = (s.dc || 0) + 1;
1774 indicator.disabled = true
1775 }
1776 }
1777 return disabledElements
1778 }
1779
1780 #enableElements(disabledElements) {
1781 for (const indicator of disabledElements) {
1782 let s = this.#htmxState(indicator);
1783 if (s.dc && --s.dc <= 0) {
1784 indicator.disabled = false
1785 delete s.dc;
1786 }
1787 }
1788 }
1789
1790 #collectFormData(elt, form, submitter, validate, isGet) {
1791 if (validate && form && !form.reportValidity()) return
1792
1793 let formData = form ? new FormData(form) : new FormData()
1794 let included = form ? new Set(form.elements) : new Set()
1795 if (!form) {
1796 if (validate && elt.reportValidity && !elt.reportValidity()) return
1797 this.#addInputValues(elt, included, formData, isGet);
1798 }
1799 if (submitter && submitter.name) {
1800 formData.append(submitter.name, submitter.value)
1801 included.add(submitter);
1802 }
1803 let includeSelector = this.#attributeValue(elt, "hx-include");
1804 if (includeSelector) {
1805 for (let node of this.#findAllExt(elt, includeSelector)) {
1806 if (validate && node.reportValidity && !node.reportValidity()) return
1807 this.#addInputValues(node, included, formData);
1808 }
1809 }
1810 return formData
1811 }
1812
1813 #addInputValues(elt, included, formData, isGet) {
1814 let tag = elt.tagName;
1815 let inputs = [];
1816 if (tag === 'BUTTON') {
1817 inputs = [elt]; // buttons only send own value, never collect children
1818 } else if (['INPUT', 'SELECT', 'TEXTAREA', 'FIELDSET'].includes(tag) || !isGet) {
1819 inputs = this.#queryEltAndDescendants(elt, 'input, select, textarea');
1820 }
1821 // GET on non-form-control containers (div, etc.) sends nothing — use hx-include for explicit inclusion
1822
1823 for (let input of inputs) {
1824 if (!input.name || input.matches(':disabled') || included.has(input)) continue;
1825 included.add(input);
1826
1827 let type = input.type;
1828 if (type === 'checkbox' || type === 'radio') {
1829 // Only add if checked
1830 if (input.checked) {
1831 formData.append(input.name, input.value);
1832 }
1833 } else if (type === 'file') {
1834 // Add all selected files
1835 for (let file of input.files) {
1836 formData.append(input.name, file);
1837 }
1838 } else if (type === 'select-multiple') {
1839 // Add all selected options
1840 for (let option of input.selectedOptions) {
1841 formData.append(input.name, option.value);
1842 }
1843 } else {
1844 formData.append(input.name, input.value);
1845 }
1846 }
1847 }
1848
1849 #getAttributeObject(elt, attrName, callback, scope = {}) {
1850 let attrValue = this.#attributeValue(elt, attrName);
1851 if (!attrValue) return null;
1852
1853 let javascriptContent = this.#extractJavascriptContent(attrValue);
1854 if (javascriptContent) {
1855 // Wrap in braces if not already wrapped (for htmx 2.x compatibility)
1856 if (javascriptContent.indexOf('{') !== 0) {
1857 javascriptContent = '{' + javascriptContent + '}';
1858 }
1859 // Return promise for async evaluation
1860 return this.#executeJavaScript(elt, scope, javascriptContent, true).then(obj => {
1861 callback(obj);
1862 });
1863 } else {
1864 // Synchronous path - return the parsed object directly
1865 callback(HCON.parse(attrValue));
1866 }
1867 }
1868
1869 #stringHyperscriptStyleSelector(selector) {
1870 let s = selector.trim();
1871 return s.startsWith('<') && s.endsWith('/>') ? s.slice(1, -2) : s;
1872 }
1873
1874 #findAllExt(eltOrSelector, maybeSelector, thisAttr, global) {
1875 let selector = maybeSelector ?? eltOrSelector;
1876 let elt = maybeSelector ? this.#normalizeElement(eltOrSelector) : document;
1877 if (selector.startsWith('global ')) {
1878 return this.#findAllExt(elt, selector.slice(7), thisAttr, true);
1879 }
1880 let parts = selector ? HCON.split(selector) : [];
1881 let result = []
1882 let unprocessedParts = []
1883 for (const part of parts) {
1884 let selector = this.#stringHyperscriptStyleSelector(part)
1885 let item
1886 if (selector.startsWith('closest ')) {
1887 item = elt.closest(selector.slice(8))
1888 } else if (selector.startsWith('find ')) {
1889 item = elt.querySelector(selector.slice(5))
1890 } else if (selector.startsWith('findAll ')) {
1891 result.push(...elt.querySelectorAll(selector.slice(8)))
1892 } else if (selector === 'next' || selector === 'nextElementSibling') {
1893 item = elt.nextElementSibling
1894 } else if (selector.startsWith('next ')) {
1895 item = this.#scanForwardQuery(elt, selector.slice(5), !!global)
1896 } else if (selector === 'previous' || selector === 'previousElementSibling') {
1897 item = elt.previousElementSibling
1898 } else if (selector.startsWith('previous ')) {
1899 item = this.#scanBackwardsQuery(elt, selector.slice(9), !!global)
1900 } else if (selector === 'document') {
1901 item = document
1902 } else if (selector === 'window') {
1903 item = window
1904 } else if (selector === 'body') {
1905 item = document.body
1906 } else if (selector === 'host') {
1907 item = (elt.getRootNode()).host
1908 } else if (selector === 'this') {
1909 if (thisAttr) {
1910 result.push(...this.#findThisElements(elt, thisAttr));
1911 continue;
1912 }
1913 item = elt
1914 } else {
1915 unprocessedParts.push(selector)
1916 }
1917
1918 if (item) {
1919 result.push(item)
1920 }
1921 }
1922
1923 if (unprocessedParts.length > 0) {
1924 let standardSelector = unprocessedParts.join(',')
1925 let rootNode = this.#getRootNode(elt, !!global)
1926 result.push(...rootNode.querySelectorAll(standardSelector))
1927 }
1928
1929 return [...new Set(result)]
1930 }
1931
1932 #scanForwardQuery(start, match, global) {
1933 return this.#scanUntilComparison(this.#getRootNode(start, global).querySelectorAll(match), start, Node.DOCUMENT_POSITION_PRECEDING);
1934 }
1935
1936 #scanBackwardsQuery(start, match, global) {
1937 let results = [...this.#getRootNode(start, global).querySelectorAll(match)].reverse()
1938 return this.#scanUntilComparison(results, start, Node.DOCUMENT_POSITION_FOLLOWING);
1939 }
1940
1941 #scanUntilComparison(results, start, comparison) {
1942 for (const elt of results) {
1943 if (elt.compareDocumentPosition(start) === comparison) {
1944 return elt
1945 }
1946 }
1947 }
1948
1949 #getRootNode(elt, global) {
1950 if (elt.isConnected && elt.getRootNode) {
1951 return elt.getRootNode?.({composed: global})
1952 } else {
1953 return document
1954 }
1955 }
1956
1957 #findOrWarn(elt, selector, thisAttr) {
1958 let result = this.#findAllExt(elt, selector, thisAttr)[0]
1959 if (!result) {
1960 console.warn(`htmx: '${selector}' on ${thisAttr} did not match any element`,
1961 { elt, selector, attr: thisAttr });
1962 }
1963 return result
1964 }
1965
1966 #findExt(eltOrSelector, selector, thisAttr) {
1967 return this.#findAllExt(eltOrSelector, selector, thisAttr)[0]
1968 }
1969
1970 #extractJavascriptContent(string) {
1971 if (string != null) {
1972 if (string.startsWith("js:")) {
1973 return string.substring(3);
1974 } else if (string.startsWith("javascript:")) {
1975 return string.substring(11);
1976 }
1977 }
1978 }
1979
1980 #initializeAbortListener(elt) {
1981 let handler = () => {
1982 let requestQueue = this.#getRequestQueue(elt);
1983 requestQueue.abort();
1984 };
1985 elt.addEventListener("htmx:abort", handler);
1986 elt._htmx.listeners.push({fromElt: elt, eventName: "htmx:abort", handler});
1987 }
1988
1989 #morph(oldNode, fragment, innerHTML) {
1990 let {persistentIds, idMap} = this.#createIdMaps(oldNode, fragment);
1991 let pantry = document.createElement("div");
1992 pantry.hidden = true;
1993 document.body.after( pantry);
1994 let ctx = {target: oldNode, idMap, persistentIds, pantry, futureMatches: new WeakSet()};
1995
1996 if (innerHTML) {
1997 this.#morphChildren(ctx, oldNode, fragment);
1998 } else {
1999 this.#morphChildren(ctx, oldNode.parentNode, fragment, oldNode, oldNode.nextSibling);
2000 }
2001 this.#cleanup(pantry)
2002 pantry.remove();
2003 }
2004
2005 #morphChildren(ctx, oldParent, newParent, insertionPoint = null, endPoint = null) {
2006 if (oldParent instanceof HTMLTemplateElement && newParent instanceof HTMLTemplateElement) {
2007 oldParent = oldParent.content;
2008 newParent = newParent.content;
2009 }
2010 insertionPoint ||= oldParent.firstChild;
2011
2012 let newChild = newParent.firstChild;
2013 while (newChild) {
2014 let matchedNode;
2015 if (insertionPoint && insertionPoint != endPoint) {
2016 matchedNode = this.#findBestMatch(ctx, newChild, insertionPoint, endPoint);
2017 if (matchedNode) {
2018 if (matchedNode !== insertionPoint) {
2019 let cursor = insertionPoint;
2020 while (cursor && cursor !== matchedNode) {
2021 let tempNode = cursor;
2022 cursor = cursor.nextSibling;
2023 // remove nodes unless they match upcoming content in which case move them to end for later use
2024 if (tempNode instanceof Element && (ctx.idMap.has(tempNode) || this.#matchesUpcomingSibling(ctx, tempNode, newChild))) {
2025 this.#moveBefore(oldParent, tempNode, endPoint);
2026 } else {
2027 this.#removeNode(ctx, tempNode);
2028 }
2029 }
2030 }
2031 }
2032 }
2033
2034 if (!matchedNode && newChild instanceof Element && ctx.persistentIds.has(newChild.id)) {
2035 let escapedId = CSS.escape(newChild.id);
2036 matchedNode = (ctx.target.id === newChild.id && ctx.target) ||
2037 ctx.target.querySelector(`[id="${escapedId}"]`) ||
2038 ctx.pantry.querySelector(`[id="${escapedId}"]`);
2039 let element = matchedNode;
2040 while ((element = element.parentNode)) {
2041 let idSet = ctx.idMap.get(element);
2042 if (idSet) {
2043 idSet.delete(matchedNode.id);
2044 if (!idSet.size) ctx.idMap.delete(element);
2045 }
2046 }
2047 this.#moveBefore(oldParent, matchedNode, insertionPoint);
2048 }
2049
2050 if (matchedNode) {
2051 this.#morphNode(matchedNode, newChild, ctx);
2052 insertionPoint = matchedNode.nextSibling;
2053 newChild = newChild.nextSibling;
2054 continue;
2055 }
2056
2057 let nextNewChild = newChild.nextSibling;
2058 if (ctx.idMap.has(newChild)) {
2059 let placeholder = document.createElement(newChild.tagName);
2060 oldParent.insertBefore(placeholder, insertionPoint);
2061 this.#morphNode(placeholder, newChild, ctx);
2062 insertionPoint = placeholder.nextSibling;
2063 } else {
2064 oldParent.insertBefore(newChild, insertionPoint);
2065 insertionPoint = newChild.nextSibling;
2066 }
2067 newChild = nextNewChild;
2068 }
2069
2070 while (insertionPoint && insertionPoint != endPoint) {
2071 let tempNode = insertionPoint;
2072 insertionPoint = insertionPoint.nextSibling;
2073 this.#removeNode(ctx, tempNode);
2074 }
2075 }
2076
2077 #matchesUpcomingSibling(ctx, oldElt, startNode) {
2078 if (ctx.futureMatches.has(oldElt)) return true;
2079 for (let sibling = startNode.nextSibling, i = 0; sibling && i < this.config.morphScanLimit; sibling = sibling.nextSibling, i++) {
2080 if (sibling instanceof Element && oldElt.isEqualNode(sibling)) {
2081 ctx.futureMatches.add(oldElt);
2082 return true;
2083 }
2084 }
2085 return false;
2086 }
2087
2088 #findBestMatch(ctx, node, startPoint, endPoint) {
2089 // text nodes match positionally — patch in place via #morphNode, 3 = TEXT_NODE
2090 if (node.nodeType === 3) return startPoint?.nodeType === 3 ? startPoint : null;
2091 if (!(node instanceof Element)) return null;
2092 let softMatch = null, displaceMatchCount = 0, scanLimit = this.config.morphScanLimit;
2093 let newSet = ctx.idMap.get(node), nodeMatchCount = newSet?.size || 0;
2094 // If node has a non-persistent ID, insert instead of soft matching
2095 if (node.id && !newSet) return null;
2096 let cursor = startPoint;
2097 while (cursor && cursor != endPoint) {
2098 let oldSet = ctx.idMap.get(cursor);
2099 if (this.#internalAPI.isSoftMatch(cursor, node)) {
2100 // Hard match: matching IDs found in both nodes
2101 if (oldSet && newSet && [...oldSet].some(id => newSet.has(id))) return cursor;
2102 if (!oldSet) {
2103 // Exact match: nodes are identical
2104 if (scanLimit > 0 && cursor.isEqualNode(node)) return cursor;
2105 // Soft match: same tag/type, save as fallback
2106 if (!softMatch) softMatch = cursor;
2107 }
2108 }
2109 // Stop if too many ID elements would be displaced
2110 displaceMatchCount += oldSet?.size || 0;
2111 if (displaceMatchCount > nodeMatchCount) break;
2112 // Don't move elements containing a focused typeable input
2113 if (document.activeElement?.selectionStart != null && cursor.contains(document.activeElement)) break;
2114 // Stop scanning if limit reached and no IDs to match
2115 if (--scanLimit < 1 && nodeMatchCount === 0) break;
2116 cursor = cursor.nextSibling;
2117 }
2118 // Only return fallback softMatch if it does not match upcoming content
2119 if (softMatch && this.#matchesUpcomingSibling(ctx, softMatch, node)) return null;
2120 return softMatch;
2121 }
2122
2123 #isSoftMatch(oldNode, newNode) {
2124 if (!(oldNode instanceof Element) || oldNode.tagName !== newNode.tagName) {
2125 return false;
2126 }
2127 // Script tags must be identical to match - never patch a script with different content
2128 if (oldNode.tagName === 'SCRIPT' && !oldNode.isEqualNode(newNode)) return false;
2129 // If both have Alpine reactive ID bindings, ignore ID mismatch
2130 if (oldNode._x_bindings?.id && newNode.matches?.('[\\:id], [x-bind\\:id]')) {
2131 return true;
2132 }
2133 return !oldNode.id || oldNode.id === newNode.id;
2134 }
2135
2136 #removeNode(ctx, node) {
2137 if (ctx.idMap.has(node)) {
2138 this.#moveBefore(ctx.pantry, node, null);
2139 } else {
2140 this.#cleanup(node)
2141 node.remove();
2142 }
2143 }
2144
2145 #moveBefore(parentNode, element, after) {
2146 if (parentNode.moveBefore) {
2147 try {
2148 parentNode.moveBefore(element, after);
2149 return
2150 } catch (e) {
2151 // ignore and insertBefore instead
2152 }
2153 }
2154 parentNode.insertBefore(element, after);
2155 }
2156
2157 #morphNode(oldNode, newNode, ctx) {
2158 if (oldNode.nodeType === 3) { // text node
2159 if (oldNode.nodeValue !== newNode.nodeValue) oldNode.nodeValue = newNode.nodeValue;
2160 return;
2161 }
2162 if (this.config.morphSkip && oldNode.matches?.(this.config.morphSkip)) return;
2163
2164 // Trigger extension hook - if returns false, skip morphing this node
2165 if (!this.#triggerExtensions(oldNode, "htmx:before:morph:node", {oldNode, newNode})) return;
2166
2167 this.#copyAttributes(oldNode, newNode);
2168 if (oldNode instanceof HTMLTextAreaElement && oldNode.defaultValue != newNode.defaultValue) {
2169 oldNode.value = newNode.value;
2170 }
2171 let skipChildren = this.config.morphSkipChildren && oldNode.matches?.(this.config.morphSkipChildren);
2172 // isEqualNode does not detect template content diff so always morph templates
2173 if (!skipChildren && (!oldNode.isEqualNode(newNode) || newNode.tagName === 'TEMPLATE' || newNode.querySelector?.('template'))) {
2174 this.#morphChildren(ctx, oldNode, newNode);
2175 }
2176 }
2177
2178 #copyAttributes(destination, source) {
2179 let attributesToIgnore = this.config.morphIgnore || [];
2180 let needsReinit = false;
2181 let isHxAttr = name => this.#prefixes('hx-').some(p => name.startsWith(p));
2182 for (const attr of source.attributes) {
2183 if (!attributesToIgnore.some(p => attr.name.startsWith(p)) && destination.getAttribute(attr.name) !== attr.value) {
2184 if (isHxAttr(attr.name)) needsReinit = true;
2185 if (!this.#triggerExtensions(destination, 'htmx:before:morph:attr', { attrName: attr.name, newValue: attr.value })) continue;
2186 destination.setAttribute(attr.name, attr.value);
2187 if (attr.name === "value" && destination instanceof HTMLInputElement && destination.type !== "file") {
2188 destination.value = attr.value;
2189 }
2190 }
2191 }
2192 for (let i = destination.attributes.length - 1; i >= 0; i--) {
2193 let attr = destination.attributes[i];
2194 if (attr && !source.hasAttribute(attr.name) && !attributesToIgnore.some(p => attr.name.startsWith(p))) {
2195 if (isHxAttr(attr.name)) needsReinit = true;
2196 if (!this.#triggerExtensions(destination, 'htmx:before:morph:attr', { attrName: attr.name, newValue: null })) continue;
2197 destination.removeAttribute(attr.name);
2198 }
2199 }
2200 if (needsReinit) this.#cleanup(destination, true);
2201 }
2202
2203 #populateIdMapWithTree(idMap, persistentIds, root, elements) {
2204 for (const elt of elements) {
2205 if (persistentIds.has(elt.id)) {
2206 let current = elt;
2207 while (current && current !== root) {
2208 let idSet = idMap.get(current);
2209 if (idSet == null) {
2210 idSet = new Set();
2211 idMap.set(current, idSet);
2212 }
2213 idSet.add(elt.id);
2214 current = current.parentElement;
2215 }
2216 }
2217 }
2218 }
2219
2220 #createIdMaps(oldNode, newContent) {
2221 let oldIdElements = this.#queryEltAndDescendants(oldNode, "[id]");
2222 let newIdElements = newContent.querySelectorAll("[id]");
2223 let persistentIds = this.#createPersistentIds(oldIdElements, newIdElements);
2224 let idMap = new Map();
2225 this.#populateIdMapWithTree(idMap, persistentIds, oldNode.parentElement, oldIdElements);
2226 this.#populateIdMapWithTree(idMap, persistentIds, newContent, newIdElements);
2227 return {persistentIds, idMap};
2228 }
2229
2230 #createPersistentIds(oldIdElements, newIdElements) {
2231 let duplicateIds = new Set(), oldIdTagNameMap = new Map();
2232 for (const {id, tagName} of oldIdElements) {
2233 if (oldIdTagNameMap.has(id)) duplicateIds.add(id);
2234 else if (id) oldIdTagNameMap.set(id, tagName);
2235 }
2236 let persistentIds = new Set();
2237 for (const {id, tagName} of newIdElements) {
2238 if (persistentIds.has(id)) duplicateIds.add(id);
2239 else if (oldIdTagNameMap.get(id) === tagName) persistentIds.add(id);
2240 }
2241 for (const id of duplicateIds) persistentIds.delete(id);
2242 return persistentIds;
2243 }
2244
2245 #handleStatusCodes(ctx) {
2246 let status = ctx.response.raw.status;
2247 let noSwapStrings = this.config.noSwap.map(x => x + "");
2248 let str = status + ""
2249 for (let pattern of [str, str.slice(0, 2) + 'x', str[0] + 'xx']) {
2250 if (noSwapStrings.includes(pattern)) {
2251 ctx.swap = "none";
2252 return
2253 }
2254 let statusValue = this.#attributeValue(ctx.sourceElement, "hx-status:" + pattern);
2255 if (statusValue) {
2256 HCON.merge(statusValue, ctx);
2257 return;
2258 }
2259 }
2260 }
2261
2262 #submitTransitionTask(task) {
2263 return new Promise((resolve) => {
2264 this.#transitionQueue ||= [];
2265 this.#transitionQueue.push({ task, resolve });
2266 if (!this.#processingTransition) {
2267 this.#processTransitionQueue();
2268 }
2269 });
2270 }
2271
2272 async #processTransitionQueue() {
2273 if (this.#transitionQueue.length === 0 || this.#processingTransition) {
2274 return;
2275 }
2276
2277 this.#processingTransition = true;
2278 let { task, resolve } = this.#transitionQueue.shift();
2279
2280 try {
2281 if (document.startViewTransition) {
2282 this.#trigger(document, "htmx:before:viewTransition", {task})
2283 await document.startViewTransition(task).finished;
2284 this.#trigger(document, "htmx:after:viewTransition", {task})
2285 } else {
2286 await task();
2287 }
2288 } catch (e) {
2289 // Transitions can be skipped/aborted - this is normal
2290 } finally {
2291 this.#processingTransition = false;
2292 resolve();
2293 this.#processTransitionQueue();
2294 }
2295 }
2296
2297 #startCSSTransitions(fragment, root) {
2298 let idElements = root.querySelectorAll("[id]");
2299 let existingElementsById = Object.fromEntries([...idElements].map(e => [e.id, e]));
2300 let newElementsWithIds = fragment.querySelectorAll("[id]");
2301 let restoreTasks = []
2302 for (let elt of newElementsWithIds) {
2303 let existing = existingElementsById[elt.id];
2304 if (existing?.tagName === elt.tagName) {
2305 let clone = elt.cloneNode(false); // shallow clone node
2306 this.#copyAttributes(elt, existing)
2307 restoreTasks.push(()=>{
2308 this.#copyAttributes(elt, clone)
2309 })
2310 }
2311 }
2312 return restoreTasks;
2313 }
2314
2315 #addClass(elt, cls) {
2316 elt?.classList?.add?.(cls);
2317 }
2318
2319 #removeClass(elt, cls) {
2320 elt?.classList?.remove?.(cls);
2321 if (elt?.classList?.length === 0) elt.removeAttribute('class');
2322 }
2323
2324 #normalizeElement(cssOrElement) {
2325 if (typeof cssOrElement === "string") {
2326 return this.find(cssOrElement);
2327 } else {
2328 return cssOrElement
2329 }
2330 }
2331
2332 #maybeAdjustMetaCharacter(string) {
2333 if (this.config.metaCharacter) {
2334 return string.replace(/:/g, this.config.metaCharacter);
2335 } else {
2336 return string;
2337 }
2338 }
2339
2340 }
2341
2342 return new Htmx()
2343 })()
2344
2345 ;