var htmx = (() => { /** * HCON, htmx's mini config language. Mirrors the JSON API. * * Used by hx-trigger, hx-swap, hx-vals, and other htmx config attributes. * * @see https://four.htmx.org/docs#hcon */ const HCON = { /** * Parses an HCON string into an object. * * @example * HCON.parse('foo:1 bar:true'); // {foo: 1, bar: true} * HCON.parse('sse.mode:once'); // {sse: {mode: 'once'}} * HCON.parse('{"foo": 1}'); // {foo: 1} */ parse(string) { if (!string) return {}; if (string.startsWith('{')) return JSON.parse(string); let pattern = /(?:"([^"]+)"|'([^']+)'|([^\s,:]+))(?:\s*:\s*(?:"([^"]*)"|'([^']*)'|<((?:[^/]|\/(?!>))+)\/>|([^\s,]+)))?(?=\s|,|$)/g; let result = {}; for (let match of string.matchAll(pattern)) { let [, doubleQuotedKey, // "key" singleQuotedKey, // 'key' bareKey, // key doubleQuotedValue, // "value" singleQuotedValue, // 'value' hyperscriptValue, // bareValue, // value ] = match; // pick this match's key and value forms let key = doubleQuotedKey ?? singleQuotedKey ?? bareKey; let value = (doubleQuotedValue ?? singleQuotedValue ?? hyperscriptValue ?? bareValue ?? 'true').trim(); // JSON-parse if possible (e.g. "5" -> 5; "abc" stays string) try { value = JSON.parse(value); } catch {} // bare a.b -> {a:{b:...}}; quoted "a.b" -> {"a.b":...} let isDottedPath = bareKey?.includes('.'); let pair = isDottedPath ? key.split('.').reduceRight((acc, segment) => ({[segment]: acc}), value) : {[key]: value}; HCON.merge(pair, result); } return result; }, /** * Splits an HCON-aware string at top-level commas. * Commas inside [], (), <.../>, "...", '...' are preserved. * * @example * HCON.split('a:1, b:2'); // ['a:1', ' b:2'] * HCON.split('from:".a, .b", click'); // ['from:".a, .b"', ' click'] */ split(string) { return string.split(/,(?![^\[]*\])(?![^(]*\))(?![^<]*\/>)(?=(?:[^"']|"[^"]*"|'[^']*')*$)/); }, /** * Deep-merges a source (HCON string or object) into a target. * * @example * HCON.merge({a: {b: 1}}, {a: {c: 2}}); // {a: {b: 1, c: 2}} * HCON.merge('a.b:1', {a: {c: 2}}); // {a: {b: 1, c: 2}} */ merge(source, target) { if (typeof source === 'string') source = HCON.parse(source); for (let [key, val] of Object.entries(source)) { if (['__proto__', 'constructor', 'prototype'].includes(key)) continue; let sourceIsObject = val && typeof val === 'object' && !Array.isArray(val); let targetIsObject = target[key] && typeof target[key] === 'object' && !Array.isArray(target[key]); if (sourceIsObject && targetIsObject) { HCON.merge(val, target[key]); } else { target[key] = val; } } return target; }, }; class ReqQ { #c = null #q = [] issue(ctx, queueStrategy) { ctx.queueStrategy = queueStrategy if (!this.#c) { this.#c = ctx return true } else { // Replace strategy OR current is abortable: abort current and issue new if (queueStrategy === "replace" || (queueStrategy !== "abort" && this.#c.queueStrategy === "abort")) { this.#q.forEach(value => value.status = "dropped"); this.#q = [] this.#c.request?.abort?.(); this.#c = ctx return true } else if (queueStrategy === "queue all") { this.#q.push(ctx) ctx.status = "queued"; } else if (queueStrategy === "drop") { // ignore the request ctx.status = "dropped"; } else if (queueStrategy === "queue last") { this.#q.forEach(value => value.status = "dropped"); this.#q = [ctx] ctx.status = "queued"; } else if (this.#q.length === 0 && queueStrategy !== "abort") { // default queue first this.#q.push(ctx) ctx.status = "queued"; } else { ctx.status = "dropped"; } return false } } finish() { this.#c = null } next() { return this.#q.shift() } abort() { this.#c?.request?.abort?.() } more() { return this.#q?.length } } class Htmx { __HCON = HCON __extMethods = new Map(); __approvedExt = ''; __registeredExt = new Set(); #internalAPI; #Function = Function; #AsyncFunction = Object.getPrototypeOf(async function(){}).constructor; #ttPolicy = { createHTML: s => s, createScript: s => s }; #actionSelector #boostSelector = "a,form"; #verbs = ["get", "post", "put", "patch", "delete"]; #hxOnQuery #transitionQueue #historyAbort #processingTransition constructor() { this.__initHtmxConfig(); this.__initRequestIndicatorCss(); this.#actionSelector = this.__prefixSelector('[hx-action],[hx-get],[hx-post],[hx-put],[hx-patch],[hx-delete]'); this.#hxOnQuery = new XPathEvaluator().createExpression(`.//*[@*[${this.__prefixes("hx-on").map(p => `starts-with(name(), "${p}")`).join(' or ')}]]`); this.#internalAPI = { attributeValue: this.__attributeValue.bind(this), parseTriggerSpecs: this.__parseTriggerSpecs.bind(this), determineMethodAndAction: this.__determineMethodAndAction.bind(this), createRequestContext: this.__createRequestContext.bind(this), collectFormData: this.__collectFormData.bind(this), getAttributeObject: this.__getAttributeObject.bind(this), insertContent: this.__insertContent.bind(this), morph: this.__morph.bind(this), isSoftMatch: this.__isSoftMatch.bind(this), initSecurity: (ttPolicy, syncFn, asyncFn) => { if (ttPolicy) this.#ttPolicy = ttPolicy; if (syncFn) this.#Function = syncFn; if (asyncFn) this.#AsyncFunction = asyncFn; }, onTrigger: this.__onTrigger.bind(this), htmxProp: this.__htmxProp.bind(this), triggerHtmxEvent: this.__trigger.bind(this), executeJavaScript: this.__executeJavaScript.bind(this) }; let init = () => { this.__initHistoryHandling() this.process(document.body) }; if (document.readyState === 'loading') { document.addEventListener("DOMContentLoaded", init) } else { // wait a tick so extensions can register setTimeout(init) } } __initHtmxConfig() { this.version = '4.0.0-beta5' this.config = { logAll: false, prefix: "data-hx-", transitions: false, history: true, mode: 'same-origin', defaultSwap: "innerHTML", defaultFocusScroll: false, indicatorClass: "htmx-indicator", requestClass: "htmx-request", includeIndicatorCSS: true, defaultTimeout: 60000, /* 60 second default timeout */ extensions: '', morphIgnore: ["data-htmx-powered"], morphSkip: '[hx-morph-skip]', morphSkipChildren: '[hx-morph-skip-children]', morphScanLimit: 10, noSwap: [204, 304], implicitInheritance: false, defaultSettleDelay: 1 } let metaConfig = document.querySelector('meta[name="htmx-config"]'); if (metaConfig) { HCON.merge(metaConfig.content, this.config); } this.__approvedExt = this.config.extensions; } __initRequestIndicatorCss() { if (this.config.includeIndicatorCSS !== false) { let indicator = this.config.indicatorClass; let request = this.config.requestClass; let sheet = new CSSStyleSheet(); sheet.replaceSync( `.${indicator}{opacity:0;visibility: hidden} ` + `.${request} .${indicator}, .${request}.${indicator}{opacity:1;visibility: visible;transition: opacity 200ms ease-in}` ); document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet]; } } registerExtension(name, extension) { if (this.__approvedExt && !this.__approvedExt.split(/,\s*/).includes(name)) return false; if (this.__registeredExt.has(name)) return false; this.__registeredExt.add(name); if (extension.init) extension.init(this.#internalAPI); Object.entries(extension).forEach(([key, value]) => { if(!this.__extMethods.get(key)?.push(value)) this.__extMethods.set(key, [value]); }); } __ignore(elt) { let p = this.config.prefix; return !elt.closest || elt.closest('[hx-ignore]') != null || (p && elt.closest(`[${p}ignore]`) != null); } __attr(elt, name) { let p = this.config.prefix; return elt.getAttribute(name) ?? (p ? elt.getAttribute(name.replace('hx-', p)) : null); } __attrName(elt, name) { let p = this.config.prefix && name.replace('hx-', this.config.prefix); return elt.hasAttribute(name) ? name : (p && elt.hasAttribute(p) ? p : null); } __prefixSelector(s) { return this.__prefixes(s).join(','); } __prefixes(s) { let result = [s]; if (this.config.prefix) result.push(s.replaceAll('hx-', this.config.prefix)); return result; } __queryEltAndDescendants(elt, selector) { let results = [...(elt.querySelectorAll?.(selector) ?? [])]; if (elt.matches?.(selector)) { results.unshift(elt); } return results; } __normalizeSwapStyle(style) { return style === 'before' ? 'beforebegin' : style === 'after' ? 'afterend' : style === 'prepend' ? 'afterbegin' : style === 'append' ? 'beforeend' : style; } __findThisElements(elt, attrName) { let result = []; this.__attributeValue(elt, attrName, undefined, (val, elt) => { if (val?.split(/\s*[,:]\s*/).includes('this')) result.push(elt); }); return result; } __attributeValue(elt, name, defaultVal, eltCollector) { name = this.__maybeAdjustMetaCharacter(name); let inherited = this.__maybeAdjustMetaCharacter(":inherited"); let append = this.__maybeAdjustMetaCharacter(":append"); let val = this.__attr(elt, name) ?? this.__attr(elt, name + inherited); if (val != null) return eltCollector ? eltCollector(val, elt) : val; let n1 = CSS.escape(this.config.implicitInheritance ? name : name + inherited); let n2 = CSS.escape(name + inherited + append); let inheritSelector = this.__prefixSelector(`[${n1}],[${n2}]`); let appendName = this.__attrName(elt, name + append) ?? this.__attrName(elt, name + inherited + append); if (appendName) { let appendValue = elt.getAttribute(appendName); let parent = elt.parentNode?.closest?.(inheritSelector); if (eltCollector) eltCollector(appendValue, elt); if (parent) { let parentVal = this.__attributeValue(parent, name, undefined, eltCollector); return parentVal ? (parentVal + "," + appendValue).replace(/[{}]/g, '') : appendValue; } return appendValue; } let parent = elt.parentNode?.closest?.(inheritSelector); if (parent) { val = this.__attributeValue(parent, name, undefined, eltCollector); if (!eltCollector && val && this.config.implicitInheritance) { this.__triggerExtensions(elt, "htmx:after:implicitInheritance", {elt, name, parent}) } return val; } return defaultVal; } __parseTriggerSpecs(spec) { return HCON.split(spec).flatMap(s => { let [,name,rest] = s.match(/^\s*(\S+\[[^\]]*\]|\S+)\s*(.*?)\s*$/) ?? []; if (!name) return []; // skip empty/whitespace-only tokens if (/\[[^\]]*$/.test(name)) throw "unterminated:" + name; // e.g. click[ctrlKey return [{name, ...HCON.parse(rest)}]; // spread modifiers (delay, throttle, etc.) onto result }); } __determineMethodAndAction(elt, evt) { if (this.__isBoosted(elt)) { return this.__boostedMethodAndAction(elt, evt) } else { let method = this.__attributeValue(elt, "hx-method") || "GET" let action = this.__attributeValue(elt, "hx-action"); if (!action) { for (let verb of this.#verbs) { let verbAction = this.__attributeValue(elt, "hx-" + verb); if (verbAction != null) { action = verbAction; method = verb; break; } } } method = method.toUpperCase() return {action, method} } } __boostedMethodAndAction(elt, evt) { if (elt.matches("a")) { return {action: elt.getAttribute("href"), method: "GET"} } else { let action = evt.submitter?.getAttribute?.("formAction") || elt.getAttribute("action"); let method = evt.submitter?.getAttribute?.("formMethod") || elt.getAttribute("method") || "GET"; return {action, method: method.toUpperCase()} } } __htmxProp(elt) { if (!elt._htmx) { elt._htmx = { listeners: [], triggerSpecs: [] }; elt.setAttribute('data-htmx-powered', 'true'); } return elt._htmx; } __htmxState(elt) { return elt._htmx_state ||= {}; } __initializeElement(elt) { if (this.__shouldInitialize(elt) && this.__trigger(elt, "htmx:before:init", {}, true)) { let htmxProp = this.__htmxProp(elt); htmxProp.initialized = true; htmxProp.eventHandler = this.__createHtmxEventHandler(elt); this.__initializeTriggers(elt); this.__initializeAbortListener(elt) this.__trigger(elt, "htmx:after:init", {}, true) } } __createHtmxEventHandler(elt) { return async (evt) => { try { let ctx = this.__createRequestContext(elt, evt); await this.__handleTriggerEvent(ctx); } catch (e) { this.__trigger(elt, 'htmx:error', { error: e }); } }; } __createRequestContext(sourceElement, sourceEvent) { let {action, method} = this.__determineMethodAndAction(sourceElement, sourceEvent); let [fullAction, anchor] = (action || '').split('#'); let ac = new AbortController(); let ctx = { sourceElement, sourceEvent, status: "created", select: this.__attributeValue(sourceElement, "hx-select"), selectOOB: this.__attributeValue(sourceElement, "hx-select-oob"), target: this.__attributeValue(sourceElement, "hx-target"), swap: this.__attributeValue(sourceElement, "hx-swap") ?? this.config.defaultSwap, push: this.__attributeValue(sourceElement, "hx-push-url"), replace: this.__attributeValue(sourceElement, "hx-replace-url"), transition: this.config.transitions, confirm: this.__attributeValue(sourceElement, "hx-confirm"), request: { validate: "true" === this.__attributeValue(sourceElement, "hx-validate", sourceElement.matches('form') && !sourceElement.noValidate && !sourceEvent.submitter?.formNoValidate ? "true" : "false"), action: fullAction, anchor, method, headers: this.__createCoreHeaders(sourceElement), abort: ac.abort.bind(ac), credentials: "same-origin", signal: ac.signal, mode: this.config.mode } }; // Apply boost config overrides if (sourceElement._htmx?.boosted) { HCON.merge(sourceElement._htmx.boosted, ctx); } ctx.target = this.__resolveTarget(sourceElement, ctx.target); ctx.request.headers["HX-Request-Type"] = (ctx.target === document.body || ctx.select) ? "full" : "partial"; if (ctx.target) { ctx.request.headers["HX-Target"] = this.__buildIdentifier(ctx.target); } // Apply hx-config overrides let configAttr = this.__attributeValue(sourceElement, "hx-config"); if (configAttr) { HCON.merge(configAttr, ctx.request); ctx.request.mode = this.config.mode; // mode is security-sensitive, never allow per-element override } return ctx; } __buildIdentifier(elt) { return `${elt.tagName.toLowerCase()}${elt.id ? '#' + encodeURI(elt.id) : ''}`; } __createCoreHeaders(elt) { let headers = { "HX-Request": "true", "HX-Source": this.__buildIdentifier(elt), "HX-Current-URL": location.href, "Accept": "text/html" }; if (this.__isBoosted(elt)) { headers["HX-Boosted"] = "true" } return headers; } __handleHxHeaders(elt, ctx) { return this.__getAttributeObject(elt, "hx-headers", obj => { for (let key in obj) ctx.request.headers[key] = String(obj[key]); }, {ctx}); } __resolveTarget(elt, selector) { if (selector instanceof Element) { return selector; } else if (selector != null) { return this.__findOrWarn(elt, selector, "hx-target"); } else if (this.__isBoosted(elt)) { return document.body } else { return elt; } } __isBoosted(elt) { return elt?._htmx?.boosted; } async __handleTriggerEvent(ctx) { let elt = ctx.sourceElement let evt = ctx.sourceEvent if (!elt.isConnected) return if (this.__isModifierKeyClick(evt)) return if (this.__shouldCancel(evt)) evt.preventDefault() // determine if request uses query params let usesQueryParams = /GET|DELETE/.test(ctx.request.method); // Only include *enclosing* form info for request types that do not use // query parameters (can still be included explicitly with hx-include) let form = usesQueryParams ? (elt.matches('form') ? elt : null) : (elt.form || elt.closest("form")) // Build request body let body = this.__collectFormData(elt, form, evt.submitter, ctx.request.validate, usesQueryParams) if (!body) return // Validation failed let valsResult = this.__getAttributeObject(elt, "hx-vals", obj => { ctx.vals = obj; // make available for json extensions for (let key in obj) body.set(key, obj[key]); }, {ctx}); if (valsResult) await valsResult; // Only await if it returned a promise if (ctx.values) { for (let k in ctx.values) { body.delete(k); body.append(k, ctx.values[k]); } } // Handle dynamic headers let headersResult = this.__handleHxHeaders(elt, ctx) if (headersResult) await headersResult // Only await if it returned a promise // Setup event-dependent request details Object.assign(ctx.request, { form, submitter: evt.submitter, body }) if (!this.__trigger(elt, "htmx:config:request", {ctx: ctx})) return if (!this.#verbs.includes(ctx.request.method.toLowerCase())) return let javascriptContent = this.__extractJavascriptContent(ctx.request.action); if (javascriptContent != null) { let data = Object.fromEntries(ctx.request.body); await this.__executeJavaScript(ctx.sourceElement, data, javascriptContent, false); return } else if (usesQueryParams) { let url = new URL(ctx.request.action, document.baseURI); for (let key of ctx.request.body.keys()) { url.searchParams.delete(key); } for (let [key, value] of ctx.request.body) { url.searchParams.append(key, value); } // Keep relative if same origin, otherwise use full URL if (url.origin === location.origin) { ctx.request.action = url.pathname + url.search; } else { ctx.request.action = url.href; } ctx.request.body = null; } else if ((this.__attributeValue(elt, "hx-encoding") ?? form?.enctype) !== "multipart/form-data") { ctx.request.body = new URLSearchParams(ctx.request.body); } await this.__issueRequest(ctx); } async __issueRequest(ctx) { let elt = ctx.sourceElement let syncStrategy = this.__determineSyncStrategy(elt); let requestQueue = this.__getRequestQueue(elt); if (!requestQueue.issue(ctx, syncStrategy)) return ctx.status = "issuing" let indicators = []; let disableElements = []; try { // Handle confirmation if (ctx.confirm) { let confirmed = await new Promise(resolve => { let detail = {ctx, issueRequest: () => resolve(true), dropRequest: () => resolve(false)}; if (this.__trigger(elt, "htmx:confirm", detail)) { let js = this.__extractJavascriptContent(ctx.confirm); resolve(js ? this.__executeJavaScript(elt, {ctx}, js, true) : window.confirm(ctx.confirm)); } }); if (!confirmed) return; } // initialize timeout & indicators after confirmation this.__initTimeout(ctx); indicators = this.__showIndicators(elt); disableElements = this.__disableElements(elt); ctx.fetch ||= window.fetch.bind(window) if (!this.__trigger(elt, "htmx:before:request", {ctx})) return; let response = await ctx.fetch(ctx.request.action, ctx.request); ctx.response = { raw: response, status: response.status, headers: response.headers, } this.__extractHxHeaders(ctx); if (!this.__trigger(elt, "htmx:before:response", {ctx})) return; ctx.text = await response.text(); if (!this.__trigger(elt, "htmx:after:request", {ctx})) return; if (ctx.response.status >= 400) { this.__trigger(elt, "htmx:response:error", {ctx}) } if(this.__handleHeadersAndMaybeReturnEarly(ctx)){ ctx.keepIndicators = true; return } if (ctx.status === "issuing") { if (ctx.hx.retarget) ctx.target = ctx.hx.retarget; // HX-Retarget if (ctx.hx.reswap) ctx.swap = ctx.hx.reswap; // HX-Reswap if (ctx.hx.reselect) ctx.select = ctx.hx.reselect; // HX-Reselect ctx.status = "response received"; this.__handleStatusCodes(ctx); await this.swap(ctx); ctx.status = "swapped"; } } catch (error) { ctx.status = "error: " + error; this.__trigger(elt, "htmx:error", {ctx, error}) } finally { clearTimeout(ctx.requestTimeout); this.__trigger(elt, "htmx:finally:request", {ctx}) if (!ctx.keepIndicators) { this.__hideIndicators(indicators); this.__enableElements(disableElements); } requestQueue.finish() if (requestQueue.more()) { // intentionally not awaited — __issueRequest has its own try/catch this.__issueRequest(requestQueue.next()) } } } // Extract HX-* response headers into ctx.hx // Maps: HX-Trigger → ctx.hx.trigger, HX-Push-Url → ctx.hx.pushurl, etc. __extractHxHeaders(ctx) { ctx.hx = {} for (let [k, v] of ctx.response.raw.headers) { if (k.toLowerCase().startsWith('hx-')) { ctx.hx[k.slice(3).toLowerCase().replace(/-/g, '')] = v } } } // Handle response headers that abort normal swap processing. // Returns true if the response was fully handled by a header. __handleHeadersAndMaybeReturnEarly(ctx) { if (ctx.hx.trigger) { // HX-Trigger this.__handleTriggerHeader(ctx.hx.trigger, ctx.sourceElement); } if (ctx.hx.refresh === 'true') { // HX-Refresh location.reload(); return true } if (ctx.hx.redirect) { // HX-Redirect location.href = ctx.hx.redirect; return true } if (ctx.hx.location) { // HX-Location let path = ctx.hx.location, opts = {}; if (path[0] === '{' || /[\s,]/.test(path)) { opts = HCON.parse(path); path = opts.path; delete opts.path; } opts.push ??= 'true'; this.ajax('GET', path, opts); return true } } __initTimeout(ctx) { let timeout = ctx.request.timeout != null ? this.parseInterval(ctx.request.timeout) : this.config.defaultTimeout; if (timeout) { ctx.requestTimeout = setTimeout(() => ctx.request?.abort?.(), timeout); } } __determineSyncStrategy(elt) { let syncValue = this.__attributeValue(elt, "hx-sync"); if (!syncValue) return "queue first"; let strategy = syncValue.split(":").pop().trim(); return /^(drop|abort|replace|queue)/.test(strategy) ? strategy : "queue first"; } __getRequestQueue(elt) { let syncValue = this.__attributeValue(elt, "hx-sync"); let syncElt = elt if (syncValue) { let selector = syncValue.includes(":") ? syncValue.slice(0, syncValue.lastIndexOf(":")).trim() : (/^(drop|abort|replace|queue)/.test(syncValue) ? null : syncValue); if (selector) syncElt = this.__findOrWarn(elt, selector, "hx-sync") || elt; } return this.__htmxState(syncElt).rq ||= new ReqQ() } __isModifierKeyClick(evt) { return evt.type === 'click' && (evt.ctrlKey || evt.metaKey || evt.shiftKey) && !!evt.currentTarget?.closest?.('a[href]') } __shouldCancel(evt) { let elt = evt.currentTarget let isSubmit = evt.type === 'submit' && elt?.tagName === 'FORM' if (isSubmit) return true let isClick = evt.type === 'click' && evt.button === 0 if (!isClick) return false let btn = elt?.closest?.('button, input[type="submit"], input[type="image"]') let form = btn?.form || btn?.closest('form') let isSubmitButton = btn && !btn.disabled && form && (btn.type === 'submit' || btn.type === 'image' || (!btn.type && btn.tagName === 'BUTTON')) if (isSubmitButton) return true let link = elt?.closest?.('a') if (!link || !link.href) return false let href = link.getAttribute('href') let isFragmentOnly = href && href.startsWith('#') && href.length > 1 return !isFragmentOnly } __initializeTriggers(elt, initialHandler = elt._htmx.eventHandler) { let specString = this.__attributeValue(elt, "hx-trigger"); if (!specString) { specString = elt.matches("form") ? "submit" : elt.matches("input:not([type=button]):not([type=submit]),select,textarea") ? "change" : "click"; } this.__onTrigger(elt, specString, initialHandler) } // Wire up event listeners with full modifier support (once, prevent, stop, // delay, throttle, changed, capture, passive, from, filter, etc.) __onTrigger(elt, specString, handler) { let specs = this.__parseTriggerSpecs(specString) this.__htmxProp(elt).triggerSpecs.push(...specs) for (let spec of specs) { spec.listeners = [] let [eventName, filter] = this.__extractFilter(spec.name); // Resolve from: elements (self listens on elt but filters by event.target in guard) let fromElts = [elt]; if (spec.from === 'outside') fromElts = [document]; else if (spec.from && spec.from !== 'self') fromElts = this.__findAllExt(elt, spec.from); // Inner: runs after delay/throttle resolves let inner = (evt) => { if (spec.halt || spec.prevent) evt.preventDefault(); if (spec.halt || spec.stop || spec.consume) evt.stopPropagation(); if (spec.once) { for (let info of spec.listeners) info.fromElt.removeEventListener(info.eventName, info.handler, info); } handler(evt); }; // Wrap inner with delay/throttle if needed let timed = inner; if (spec.delay) { timed = evt => { clearTimeout(spec.timeout); spec.timeout = setTimeout(() => inner(evt), this.parseInterval(spec.delay)); }; } else if (spec.throttle) { timed = evt => { if (spec.throttled) { spec.throttledEvent = evt; } else { spec.throttled = true; inner(evt); spec.throttleTimeout = setTimeout(() => { spec.throttled = false; if (spec.throttledEvent) { let e = spec.throttledEvent; spec.throttledEvent = null; timed(e); } }, this.parseInterval(spec.throttle)); } }; } // Guarded: pre-timing checks that determine if event should proceed spec.handler = (evt) => { if (spec.from === 'self' && evt.target !== elt) return; if (spec.from === 'outside' && elt.contains(evt.target)) return; if (spec.target && !evt.target?.matches?.(spec.target)) return; if (spec.changed) { let values = spec.values ??= new WeakMap(); let changed = false; for (let fromElt of fromElts) { if (values.get(fromElt) !== fromElt.value) { changed = true; values.set(fromElt, fromElt.value); } } if (!changed) return; } if (filter) { if (this.__shouldCancel(evt)) evt.preventDefault(); let evtArgs = {}; for (let k in evt) evtArgs[k] = evt[k]; if (!this.__executeJavaScript(elt, evtArgs, filter, true, false)) return; } timed(evt); }; // Intersect/revealed: set up observer if (eventName === 'intersect' || eventName === 'revealed') { let observerOptions = {rootMargin: spec.rootMargin}; if (spec.root) observerOptions.root = this.__findOrWarn(elt, spec.root); if (spec.threshold) observerOptions.threshold = parseFloat(spec.threshold); let isRevealed = eventName === 'revealed'; spec.observer = new IntersectionObserver((entries) => { for (let i = 0; i < entries.length; i++) { if (entries[i].isIntersecting) { this.trigger(elt, 'intersect', {}, false); if (isRevealed) spec.observer.disconnect(); break; } } }, observerOptions); eventName = 'intersect'; spec.observer.observe(elt); } // Every: set up interval if (eventName === "every") { let interval = Object.keys(spec).find(k => k !== 'name'); spec.interval = setInterval(() => { if (elt.isConnected) this.__trigger(elt, 'every', {}, false); else clearInterval(spec.interval); }, this.parseInterval(interval)); } // Load: fire immediately, no listener needed if (eventName === 'load') { spec.handler(new CustomEvent('load')); continue; } // Register listeners for (let fromElt of fromElts) { let listenerInfo = {fromElt, eventName, handler: spec.handler, capture: !!spec.capture, passive: !!spec.passive}; elt._htmx.listeners.push(listenerInfo); spec.listeners.push(listenerInfo); fromElt.addEventListener(eventName, spec.handler, listenerInfo); } } } __extractFilter(str) { let match = str.match(/^([^\[]*)\[([^\]]*)]/); if (!match) return [str, null]; return [match[1], match[2]]; } __handleTriggerHeader(value, elt) { if (value[0] === '{') { let triggers = HCON.parse(value); for (let name in triggers) { let detail = triggers[name]; let target = elt; if (detail?.target) { target = this.find(detail.target); } this.trigger(target, name, typeof detail === 'object' ? detail : {value: detail}); } } else { value.split(',').forEach(name => this.trigger(elt, name.trim(), {})); } } __apiMethods(thisArg) { let bound = {}; let proto = Object.getPrototypeOf(this); for (let name of Object.getOwnPropertyNames(proto)) { if (name !== 'constructor' && typeof this[name] === 'function') { if (["find", "findAll"].includes(name)) { bound[name] = (arg1, arg2) => { if (arg2 === undefined) { return this[name](thisArg, arg1) } else { return this[name](arg1, arg2) } } } else { bound[name] = this[name].bind(this); } } } return bound; } __executeJavaScript(thisArg, obj, code, expression = true, isAsync = true) { let args = {} Object.assign(args, this.__apiMethods(thisArg)) let scope = {}; this.__triggerExtensions(thisArg, "htmx:scope", { scope }); Object.assign(args, scope); Object.assign(args, obj) let keys = Object.keys(args); let values = Object.values(args); let FunctionConstructor = isAsync ? this.#AsyncFunction : this.#Function; let func = new FunctionConstructor(...keys, expression ? `return (${code})` : code); return func.call(thisArg, ...values); } /** * Initialize htmx attributes on root and all its descendants. When force is true, root * and every powered descendant are first torn down and re-wired from their current * attributes - use this after mutating hx-* attributes on an already-processed element. * @see https://four.htmx.org/reference/methods/htmx-process * @param {Element | ShadowRoot} root * @param {boolean} [force] */ process(root, force) { if (!root?.isConnected) return; if (!(root instanceof Element)) { // ShadowRoot for (let elt of root.children || []) this.process(elt, force); return; } if (force) this.__cleanup(root, true); if (this.__ignore(root)) return; if (!this.__trigger(root, "htmx:before:process")) return let hxOnNodes = [root]; let iter = this.#hxOnQuery.evaluate(root) let node = null while (node = iter.iterateNext()) hxOnNodes.push(node) for (let hxOnNode of hxOnNodes) { if (!this.__ignore(hxOnNode) && this.__trigger(hxOnNode, "htmx:before:on:init", {}, true)) { this.__handleHxOnAttributes(hxOnNode); } } for (let elt of this.__queryEltAndDescendants(root, this.#actionSelector)) { this.__initializeElement(elt); } for (let elt of this.__queryEltAndDescendants(root, this.#boostSelector)) { this.__maybeBoost(elt); } this.__trigger(root, "htmx:after:process"); } __maybeBoost(elt) { let boostValue = this.__attributeValue(elt, "hx-boost"); if (boostValue && boostValue !== "false" && this.__shouldBoost(elt) && this.__trigger(elt, "htmx:before:init", {}, true)) { let htmxProp = this.__htmxProp(elt); htmxProp.initialized = true; htmxProp.eventHandler = this.__createHtmxEventHandler(elt); htmxProp.boosted = boostValue; let eventName = elt.matches('a') ? 'click' : 'submit'; elt._htmx.listeners.push({fromElt: elt, eventName, handler: elt._htmx.eventHandler}); elt.addEventListener(eventName, elt._htmx.eventHandler); this.__trigger(elt, "htmx:after:init", {}, true) } } __shouldBoost(elt) { if (this.__shouldInitialize(elt)) { if (elt.tagName === "A") { if (elt.target === '' || elt.target === '_self') { return !elt.hasAttribute('download') && !elt.getAttribute('href')?.startsWith?.("#") && this.__isSameOrigin(elt.href) } } else if (elt.tagName === "FORM") { return elt.method !== 'dialog' && this.__isSameOrigin(elt.action); } } } __isSameOrigin(url) { try { // URL constructor handles both relative and absolute URLs const parsed = new URL(url, window.location.href); return parsed.origin === window.location.origin; } catch (e) { // If URL parsing fails, assume not same-origin return false; } } __shouldInitialize(elt) { return !elt._htmx?.initialized && !this.__ignore(elt); } /** * Remove listeners, timers, and observers from elt and all its powered descendants. * When force is true, also delete their htmx state so a re-process fully re-initializes them. * @param {Element} elt * @param {boolean} [force] */ __cleanup(elt, force) { let elts = [elt, ...elt.querySelectorAll?.('[data-htmx-powered]') ?? []]; for (let e of elts) { if (!e._htmx) continue; this.__trigger(e, "htmx:before:cleanup") for (let spec of e._htmx.triggerSpecs || []) { if (spec.interval) clearInterval(spec.interval); if (spec.timeout) clearTimeout(spec.timeout); if (spec.throttleTimeout) clearTimeout(spec.throttleTimeout); spec.observer?.disconnect() } for (let info of e._htmx.listeners || []) { info.fromElt.removeEventListener(info.eventName, info.handler, info); } e.removeAttribute('data-htmx-powered'); this.__trigger(e, "htmx:after:cleanup") if (force) delete e._htmx; } } __handlePreservedElements(fragment) { let pantry = document.createElement('div'); pantry.hidden = true; document.body.insertAdjacentElement('afterend', pantry); let newPreservedElts = fragment.querySelectorAll?.(this.__prefixSelector('[hx-preserve]')) || []; for (let preservedElt of newPreservedElts) { let currentElt = document.getElementById(preservedElt.id); if (currentElt) { this.__moveBefore(pantry, currentElt, null); } } return pantry } __restorePreservedElements(pantry) { for (let preservedElt of [...pantry.children]) { let newElt = document.getElementById(preservedElt.id); if (newElt) { this.__moveBefore(newElt.parentNode, preservedElt, newElt); this.__cleanup(newElt) newElt.remove() } } pantry.remove(); } __parseHTML(resp) { let trusted = this.#ttPolicy.createHTML(resp); return Document.parseHTMLUnsafe?.(trusted) || new DOMParser().parseFromString(trusted, 'text/html'); } __makeFragment(text) { // Convert tags (e.g. , ) to