| 1 |
var htmx = (() => { |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
const HCON = { |
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 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, |
| 27 |
singleQuotedKey, |
| 28 |
bareKey, |
| 29 |
doubleQuotedValue, |
| 30 |
singleQuotedValue, |
| 31 |
hyperscriptValue, |
| 32 |
bareValue, |
| 33 |
] = match; |
| 34 |
|
| 35 |
|
| 36 |
let key = doubleQuotedKey ?? singleQuotedKey ?? bareKey; |
| 37 |
let value = (doubleQuotedValue ?? singleQuotedValue ?? hyperscriptValue ?? bareValue ?? 'true').trim(); |
| 38 |
|
| 39 |
|
| 40 |
try { value = JSON.parse(value); } catch {} |
| 41 |
|
| 42 |
|
| 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 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
split(string) { |
| 61 |
return string.split(/,(?![^\[]*\])(?![^(]*\))(?![^<]*\/>)(?=(?:[^"']|"[^"]*"|'[^']*')*$)/); |
| 62 |
}, |
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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, |
| 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 []; |
| 339 |
if (/\[[^\]]*$/.test(name)) throw "unterminated:" + name; |
| 340 |
return [{name, ...HCON.parse(rest)}]; |
| 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 |
|
| 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 |
|
| 448 |
let configAttr = this.#attributeValue(sourceElement, "hx-config"); |
| 449 |
if (configAttr) { |
| 450 |
HCON.merge(configAttr, ctx.request); |
| 451 |
ctx.request.mode = this.config.mode; |
| 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 |
|
| 505 |
let usesQueryParams = /GET|DELETE/.test(ctx.request.method); |
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
let form = usesQueryParams |
| 510 |
? (elt.matches('form') ? elt : null) |
| 511 |
: (elt.form || elt.closest("form")) |
| 512 |
|
| 513 |
|
| 514 |
let body = this.#collectFormData(elt, form, evt.submitter, ctx.request.validate, usesQueryParams) |
| 515 |
if (!body) return |
| 516 |
let valsResult = this.#getAttributeObject(elt, "hx-vals", obj => { |
| 517 |
ctx.vals = obj; |
| 518 |
for (let key in obj) body.set(key, obj[key]); |
| 519 |
}, {ctx}); |
| 520 |
if (valsResult) await valsResult; |
| 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 |
|
| 529 |
let headersResult = this.#handleHxHeaders(elt, ctx) |
| 530 |
if (headersResult) await headersResult |
| 531 |
|
| 532 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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; |
| 626 |
if (ctx.hx.reswap) ctx.swap = ctx.hx.reswap; |
| 627 |
if (ctx.hx.reselect) ctx.select = ctx.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 |
ch |
| 648 |
this.#issueRequest(requestQueue.next()) |
| 649 |
} |
| 650 |
} |
| 651 |
} |
| 652 |
|
| 653 |
|
| 654 |
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 |
|
| 665 |
|
| 666 |
#handleHeadersAndMaybeReturnEarly(ctx) { |
| 667 |
if (ctx.hx.trigger) { |
| 668 |
this.#handleTriggerHeader(ctx.hx.trigger, ctx.sourceElement); |
| 669 |
} |
| 670 |
if (ctx.hx.refresh === 'true') { |
| 671 |
location.reload(); |
| 672 |
return true |
| 673 |
} |
| 674 |
if (ctx.hx.redirect) { |
| 675 |
location.href = ctx.hx.redirect; |
| 676 |
return true |
| 677 |
} |
| 678 |
if (ctx.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 |
|
| 757 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 861 |
if (eventName === 'load') { |
| 862 |
spec.handler(new CustomEvent('load')); |
| 863 |
continue; |
| 864 |
} |
| 865 |
|
| 866 |
|
| 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 |
|
| 936 |
|
| 937 |
|
| 938 |
|
| 939 |
|
| 940 |
|
| 941 |
|
| 942 |
process(root, force) { |
| 943 |
if (!root?.isConnected) return; |
| 944 |
if (!(root instanceof Element)) { |
| 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 |
|
| 998 |
const parsed = new URL(url, window.location.href); |
| 999 |
return parsed.origin === window.location.origin; |
| 1000 |
} catch (e) { |
| 1001 |
|
| 1002 |
return false; |
| 1003 |
} |
| 1004 |
} |
| 1005 |
|
| 1006 |
#shouldInitialize(elt) { |
| 1007 |
return !elt._htmx?.initialized && !this.#ignore(elt); |
| 1008 |
} |
| 1009 |
|
| 1010 |
|
| 1011 |
|
| 1012 |
|
| 1013 |
|
| 1014 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1260 |
let oobTasks = this.#processOOB(fragment, ctx.sourceElement, ctx.selectOOB); |
| 1261 |
let partialTasks = this.#processPartials(fragment, ctx); |
| 1262 |
tasks.push(...oobTasks, ...partialTasks); |
| 1263 |
|
| 1264 |
|
| 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 |
|
| 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 |
|
| 1306 |
let swapSpec = this.#parseSwapSpec(ctx.swap || this.config.defaultSwap); |
| 1307 |
|
| 1308 |
if ( |
| 1309 |
swapSpec.style === 'delete' || |
| 1310 |
fragment.childElementCount > 0 || |
| 1311 |
fragment.textContent.trim() || |
| 1312 |
(swapSpec.swapEmpty ?? this.config.defaultSwapEmpty ?? !partialTasks.length) |
| 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 |
se |
| 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 |
|
| 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 |
|
| 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 |
|
| 1486 |
|
| 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 |
|
| 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 |
|
| 1580 |
if (typeof context.source === 'string' && !sourceElt) { |
| 1581 |
return Promise.reject(new Error('Source not found')); |
| 1582 |
} |
| 1583 |
|
| 1584 |
|
| 1585 |
|
| 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 |
|
| 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 |
|
| 1658 |
if (hx?.pushurl || hx?.replaceurl) { |
| 1659 |
push = hx.pushurl; |
| 1660 |
replace = hx.replaceurl; |
| 1661 |
} |
| 1662 |
|
| 1663 |
|
| 1664 |
if (push == null && replace == null && this.#isBoosted(sourceElement)) { |
| 1665 |
push = 'true'; |
| 1666 |
} |
| 1667 |
|
| 1668 |
|
| 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 |
|
| 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 |
|
| 1705 |
|
| 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 |
|
| 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 |
|
| 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]; |
| 1818 |
} else if (['INPUT', 'SELECT', 'TEXTAREA', 'FIELDSET'].includes(tag) || !isGet) { |
| 1819 |
inputs = this.#queryEltAndDescendants(elt, 'input, select, textarea'); |
| 1820 |
} |
| 1821 |
on |
| 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 |
|
| 1830 |
if (input.checked) { |
| 1831 |
formData.append(input.name, input.value); |
| 1832 |
} |
| 1833 |
} else if (type === 'file') { |
| 1834 |
|
| 1835 |
for (let file of input.files) { |
| 1836 |
formData.append(input.name, file); |
| 1837 |
} |
| 1838 |
} else if (type === 'select-multiple') { |
| 1839 |
|
| 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 |
|
| 1856 |
if (javascriptContent.indexOf('{') !== 0) { |
| 1857 |
javascriptContent = '{' + javascriptContent + '}'; |
| 1858 |
} |
| 1859 |
|
| 1860 |
return this.#executeJavaScript(elt, scope, javascriptContent, true).then(obj => { |
| 1861 |
callback(obj); |
| 1862 |
}); |
| 1863 |
} else { |
| 1864 |
|
| 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 |
|
| 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 |
DE |
| 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 |
|
| 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 |
|
| 2101 |
if (oldSet && newSet && [...oldSet].some(id => newSet.has(id))) return cursor; |
| 2102 |
if (!oldSet) { |
| 2103 |
|
| 2104 |
if (scanLimit > 0 && cursor.isEqualNode(node)) return cursor; |
| 2105 |
|
| 2106 |
if (!softMatch) softMatch = cursor; |
| 2107 |
} |
| 2108 |
} |
| 2109 |
|
| 2110 |
displaceMatchCount += oldSet?.size || 0; |
| 2111 |
if (displaceMatchCount > nodeMatchCount) break; |
| 2112 |
|
| 2113 |
if (document.activeElement?.selectionStart != null && cursor.contains(document.activeElement)) break; |
| 2114 |
|
| 2115 |
if (--scanLimit < 1 && nodeMatchCount === 0) break; |
| 2116 |
cursor = cursor.nextSibling; |
| 2117 |
} |
| 2118 |
|
| 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 |
|
| 2128 |
if (oldNode.tagName === 'SCRIPT' && !oldNode.isEqualNode(newNode)) return false; |
| 2129 |
|
| 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 |
|
| 2152 |
} |
| 2153 |
} |
| 2154 |
parentNode.insertBefore(element, after); |
| 2155 |
} |
| 2156 |
|
| 2157 |
#morphNode(oldNode, newNode, ctx) { |
| 2158 |
if (oldNode.nodeType === 3) { |
| 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 |
|
| 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 |
|
| 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 |
|
| 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); |
| 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 |
; |
| 2346 |
(() => { |
| 2347 |
let api; |
| 2348 |
|
| 2349 |
|
| 2350 |
|
| 2351 |
|
| 2352 |
|
| 2353 |
function getConfig(ctx) { |
| 2354 |
let isConnect = api.attributeValue(ctx.sourceElement, 'hx-sse:connect') != null; |
| 2355 |
let defaults = { |
| 2356 |
reconnect: isConnect, |
| 2357 |
reconnectDelay: 500, |
| 2358 |
reconnectMaxDelay: 60000, |
| 2359 |
reconnectMaxAttempts: Infinity, |
| 2360 |
reconnectJitter: 0.3, |
| 2361 |
pauseOnBackground: isConnect |
| 2362 |
}; |
| 2363 |
let global = htmx.config.sse || {}; |
| 2364 |
|
| 2365 |
|
| 2366 |
let perElement = ctx.request.sse || {}; |
| 2367 |
return {...defaults, ...global, ...perElement}; |
| 2368 |
} |
| 2369 |
|
| 2370 |
|
| 2371 |
|
| 2372 |
|
| 2373 |
|
| 2374 |
async function* parseSSE(reader) { |
| 2375 |
let decoder = new TextDecoder(); |
| 2376 |
let buffer = ''; |
| 2377 |
let hasData = false; |
| 2378 |
let message = {data: '', event: '', id: '', retry: null}; |
| 2379 |
let firstChunk = true; |
| 2380 |
|
| 2381 |
try { |
| 2382 |
while (true) { |
| 2383 |
let {done, value} = await reader.read(); |
| 2384 |
if (done) break; |
| 2385 |
|
| 2386 |
let chunk = decoder.decode(value, {stream: true}); |
| 2387 |
|
| 2388 |
if (firstChunk) { |
| 2389 |
if (chunk.charCodeAt(0) === 0xFEFF) chunk = chunk.slice(1); |
| 2390 |
firstChunk = false; |
| 2391 |
} |
| 2392 |
buffer += chunk; |
| 2393 |
|
| 2394 |
|
| 2395 |
let lines = buffer.split(/\r\n|\r|\n/); |
| 2396 |
buffer = lines.pop() || ''; |
| 2397 |
|
| 2398 |
for (let line of lines) { |
| 2399 |
if (!line) { |
| 2400 |
if (hasData) { |
| 2401 |
yield message; |
| 2402 |
hasData = false; |
| 2403 |
message = {data: '', event: '', id: '', retry: null}; |
| 2404 |
} |
| 2405 |
continue; |
| 2406 |
} |
| 2407 |
|
| 2408 |
let colonIndex = line.indexOf(':'); |
| 2409 |
if (colonIndex === 0) continue; |
| 2410 |
|
| 2411 |
let field, value; |
| 2412 |
if (colonIndex < 0) { |
| 2413 |
|
| 2414 |
field = line; |
| 2415 |
value = ''; |
| 2416 |
} else { |
| 2417 |
field = line.slice(0, colonIndex); |
| 2418 |
value = line.slice(colonIndex + 1); |
| 2419 |
if (value[0] === ' ') value = value.slice(1); |
| 2420 |
} |
| 2421 |
|
| 2422 |
if (field === 'data') { |
| 2423 |
message.data += (hasData ? '\n' : '') + value; |
| 2424 |
hasData = true; |
| 2425 |
} else if (field === 'event') { |
| 2426 |
message.event = value; |
| 2427 |
} else if (field === 'id') { |
| 2428 |
if (!value.includes('\0')) message.id = value; |
| 2429 |
} else if (field === 'retry') { |
| 2430 |
let retryValue = parseInt(value, 10); |
| 2431 |
if (!isNaN(retryValue)) message.retry = retryValue; |
| 2432 |
} |
| 2433 |
} |
| 2434 |
} |
| 2435 |
} finally { |
| 2436 |
reader.releaseLock(); |
| 2437 |
} |
| 2438 |
} |
| 2439 |
|
| 2440 |
|
| 2441 |
|
| 2442 |
|
| 2443 |
|
| 2444 |
|
| 2445 |
|
| 2446 |
async function handleSSEResponse(ctx) { |
| 2447 |
let element = ctx.sourceElement; |
| 2448 |
let config = getConfig(ctx); |
| 2449 |
let reconnectRequested = false; |
| 2450 |
|
| 2451 |
let connection = { |
| 2452 |
url: ctx.request.action, |
| 2453 |
config: config, |
| 2454 |
abortController: null, |
| 2455 |
reader: null, |
| 2456 |
lastEventId: null, |
| 2457 |
delayCanceller: null, |
| 2458 |
visibilityHandler: null, |
| 2459 |
attempt: 0, |
| 2460 |
cancelled: false, |
| 2461 |
status: null |
| 2462 |
}; |
| 2463 |
api.htmxProp(element).sse = connection; |
| 2464 |
|
| 2465 |
let reconnect = () => { |
| 2466 |
if (!element.isConnected || reconnectRequested) return; |
| 2467 |
reconnectRequested = true; |
| 2468 |
if (connection.delayCanceller) connection.delayCanceller(); |
| 2469 |
connection.reader?.cancel(); |
| 2470 |
}; |
| 2471 |
|
| 2472 |
let paused = false; |
| 2473 |
let unpauseResolver = null; |
| 2474 |
|
| 2475 |
if (config.pauseOnBackground) { |
| 2476 |
let visibilityHandler = () => { |
| 2477 |
if (document.hidden) { |
| 2478 |
paused = true; |
| 2479 |
connection.reader?.cancel(); |
| 2480 |
} else if (paused) { |
| 2481 |
paused = false; |
| 2482 |
if (unpauseResolver) unpauseResolver(); |
| 2483 |
} |
| 2484 |
}; |
| 2485 |
document.addEventListener('visibilitychange', visibilityHandler); |
| 2486 |
connection.visibilityHandler = visibilityHandler; |
| 2487 |
} |
| 2488 |
|
| 2489 |
connection.cancelled = false; |
| 2490 |
if (!api.triggerHtmxEvent(element, 'htmx:before:sse:connection', {connection}) || connection.cancelled) { |
| 2491 |
cleanup(element, 'cancelled'); |
| 2492 |
return; |
| 2493 |
} |
| 2494 |
|
| 2495 |
connection.status = ctx.response.status; |
| 2496 |
api.triggerHtmxEvent(element, 'htmx:after:sse:connection', {connection}); |
| 2497 |
|
| 2498 |
let currentResponse = ctx.response.raw; |
| 2499 |
|
| 2500 |
try { |
| 2501 |
while (element.isConnected) { |
| 2502 |
e) |
| 2503 |
if (connection.attempt > 0) { |
| 2504 |
|
| 2505 |
if (paused) { |
| 2506 |
await new Promise(r => { unpauseResolver = r; }); |
| 2507 |
unpauseResolver = null; |
| 2508 |
if (!element.isConnected) break; |
| 2509 |
connection.attempt = 1; |
| 2510 |
reconnectRequested = true; |
| 2511 |
} |
| 2512 |
|
| 2513 |
if (!reconnectRequested) { |
| 2514 |
if (!config.reconnect || connection.attempt > config.reconnectMaxAttempts) break; |
| 2515 |
} |
| 2516 |
|
| 2517 |
let baseDelay = htmx.parseInterval(config.reconnectDelay) ?? config.reconnectDelay; |
| 2518 |
let maxDelay = htmx.parseInterval(config.reconnectMaxDelay) ?? config.reconnectMaxDelay; |
| 2519 |
let delay = Math.min( |
| 2520 |
baseDelay * Math.pow(2, connection.attempt - 1), |
| 2521 |
maxDelay |
| 2522 |
); |
| 2523 |
if (config.reconnectJitter > 0) { |
| 2524 |
let jitterRange = delay * config.reconnectJitter; |
| 2525 |
delay = Math.max(0, delay + (Math.random() * 2 - 1) * jitterRange); |
| 2526 |
} |
| 2527 |
|
| 2528 |
connection.cancelled = false; |
| 2529 |
if (!api.triggerHtmxEvent(element, 'htmx:before:sse:connection', {connection}) || connection.cancelled) break; |
| 2530 |
|
| 2531 |
await new Promise(r => { |
| 2532 |
connection.delayCanceller = r; |
| 2533 |
setTimeout(r, delay); |
| 2534 |
}); |
| 2535 |
connection.delayCanceller = null; |
| 2536 |
if (!element.isConnected) break; |
| 2537 |
|
| 2538 |
|
| 2539 |
let ac = new AbortController(); |
| 2540 |
connection.abortController = ac; |
| 2541 |
try { |
| 2542 |
if (connection.lastEventId) ctx.request.headers['Last-Event-ID'] = connection.lastEventId; |
| 2543 |
currentResponse = await fetch(ctx.request.action, { |
| 2544 |
...ctx.request, |
| 2545 |
signal: ac.signal |
| 2546 |
}); |
| 2547 |
} catch (e) { |
| 2548 |
if (ac.signal.aborted) break; |
| 2549 |
api.triggerHtmxEvent(element, 'htmx:sse:error', {error: e, url: ctx.request.action}); |
| 2550 |
reconnectRequested = false; |
| 2551 |
connection.attempt++; |
| 2552 |
continue; |
| 2553 |
} |
| 2554 |
|
| 2555 |
if (!currentResponse.ok) { |
| 2556 |
api.triggerHtmxEvent(element, 'htmx:sse:error', { |
| 2557 |
error: new Error(`SSE reconnect failed with status ${currentResponse.status}`), |
| 2558 |
status: currentResponse.status, |
| 2559 |
url: ctx.request.action |
| 2560 |
}); |
| 2561 |
reconnectRequested = false; |
| 2562 |
connection.attempt++; |
| 2563 |
continue; |
| 2564 |
} |
| 2565 |
|
| 2566 |
connection.status = currentResponse.status; |
| 2567 |
api.triggerHtmxEvent(element, 'htmx:after:sse:connection', {connection}); |
| 2568 |
connection.attempt = 0; |
| 2569 |
} |
| 2570 |
|
| 2571 |
|
| 2572 |
reconnectRequested = false; |
| 2573 |
|
| 2574 |
try { |
| 2575 |
connection.reader = currentResponse.body.getReader(); |
| 2576 |
|
| 2577 |
for await (let msg of parseSSE(connection.reader)) { |
| 2578 |
if (!element.isConnected || reconnectRequested) break; |
| 2579 |
|
| 2580 |
let detail = { |
| 2581 |
message: {data: msg.data, event: msg.event, id: msg.id, cancelled: false} |
| 2582 |
}; |
| 2583 |
if (!api.triggerHtmxEvent(element, 'htmx:before:sse:message', detail) || detail.message.cancelled) continue; |
| 2584 |
|
| 2585 |
if (msg.id) { |
| 2586 |
connection.lastEventId = msg.id; |
| 2587 |
} |
| 2588 |
if (msg.retry != null) config.reconnectDelay = msg.retry; |
| 2589 |
|
| 2590 |
if (detail.message.event) { |
| 2591 |
htmx.trigger(element, detail.message.event, {data: detail.message.data, id: detail.message.id}); |
| 2592 |
delete detail.message.cancelled; |
| 2593 |
api.triggerHtmxEvent(element, 'htmx:after:sse:message', detail); |
| 2594 |
|
| 2595 |
nt |
| 2596 |
let closeEvent = api.attributeValue(element, 'hx-sse:close'); |
| 2597 |
if (closeEvent && detail.message.event === closeEvent) { |
| 2598 |
cleanup(element, 'message'); |
| 2599 |
return; |
| 2600 |
} |
| 2601 |
continue; |
| 2602 |
} |
| 2603 |
|
| 2604 |
|
| 2605 |
ctx.text = detail.message.data; |
| 2606 |
if (!ctx.swap.includes('swapEmpty')) ctx.swap += ' swapEmpty:false'; |
| 2607 |
await htmx.swap(ctx); |
| 2608 |
delete detail.message.cancelled; |
| 2609 |
api.triggerHtmxEvent(element, 'htmx:after:sse:message', detail); |
| 2610 |
} |
| 2611 |
} catch (e) { |
| 2612 |
if (!connection.abortController?.signal?.aborted) { |
| 2613 |
api.triggerHtmxEvent(element, 'htmx:sse:error', {error: e, url: ctx.request.action}); |
| 2614 |
} |
| 2615 |
} |
| 2616 |
|
| 2617 |
connection.reader = null; |
| 2618 |
if (!element.isConnected) break; |
| 2619 |
|
| 2620 |
connection.attempt++; |
| 2621 |
} |
| 2622 |
} finally { |
| 2623 |
cleanup(element, element.isConnected ? 'ended' : 'removed'); |
| 2624 |
} |
| 2625 |
} |
| 2626 |
|
| 2627 |
|
| 2628 |
|
| 2629 |
|
| 2630 |
|
| 2631 |
function processElement(element) { |
| 2632 |
let connectUrl = api.attributeValue(element, 'hx-sse:connect'); |
| 2633 |
if (!connectUrl) return; |
| 2634 |
if (element._htmx?.sse) return; |
| 2635 |
|
| 2636 |
let specString = api.attributeValue(element, 'hx-trigger') || 'load'; |
| 2637 |
api.onTrigger(element, specString, () => { |
| 2638 |
if (element._htmx?.sse) return; |
| 2639 |
htmx.ajax('GET', connectUrl, {source: element}); |
| 2640 |
}); |
| 2641 |
} |
| 2642 |
|
| 2643 |
|
| 2644 |
|
| 2645 |
|
| 2646 |
|
| 2647 |
function cleanup(element, reason) { |
| 2648 |
let connection = element?._htmx?.sse; |
| 2649 |
if (!connection) return; |
| 2650 |
|
| 2651 |
connection.abortController?.abort(); |
| 2652 |
connection.reader?.cancel?.(); |
| 2653 |
if (connection.delayCanceller) connection.delayCanceller(); |
| 2654 |
if (connection.visibilityHandler) { |
| 2655 |
document.removeEventListener('visibilitychange', connection.visibilityHandler); |
| 2656 |
} |
| 2657 |
api.triggerHtmxEvent(element, 'htmx:sse:close', {connection, reason: reason || 'cleanup'}); |
| 2658 |
delete element._htmx.sse; |
| 2659 |
} |
| 2660 |
|
| 2661 |
|
| 2662 |
|
| 2663 |
|
| 2664 |
|
| 2665 |
function checkLegacyAttributes(element) { |
| 2666 |
if (element.hasAttribute('sse-connect')) { |
| 2667 |
console.warn('htmx: [hx-sse] legacy attribute sse-connect is deprecated; use hx-sse:connect instead'); |
| 2668 |
|
| 2669 |
let url = element.getAttribute('sse-connect'); |
| 2670 |
let attr = (htmx.config.prefix || 'hx-') + 'sse' + (htmx.config.metaCharacter || ':') + 'connect'; |
| 2671 |
if (!element.hasAttribute(attr)) { |
| 2672 |
element.setAttribute(attr, url); |
| 2673 |
} |
| 2674 |
} |
| 2675 |
if (element.hasAttribute('sse-swap')) { |
| 2676 |
console.warn('htmx: [hx-sse] sse-swap is removed in htmx 4. Unnamed SSE messages are swapped automatically. Named events are dispatched as DOM events.'); |
| 2677 |
} |
| 2678 |
} |
| 2679 |
|
| 2680 |
|
| 2681 |
|
| 2682 |
|
| 2683 |
|
| 2684 |
htmx.registerExtension('sse', { |
| 2685 |
init: (internalAPI) => { |
| 2686 |
api = internalAPI; |
| 2687 |
}, |
| 2688 |
|
| 2689 |
htmx_config_request: (element, detail) => { |
| 2690 |
detail.ctx.request.headers['Accept'] = 'text/html, text/event-stream'; |
| 2691 |
}, |
| 2692 |
|
| 2693 |
|
| 2694 |
htmx_before_response: (element, detail) => { |
| 2695 |
let ctx = detail.ctx; |
| 2696 |
let contentType = ctx.response.raw.headers.get('Content-Type'); |
| 2697 |
if (!contentType?.includes('text/event-stream')) return; |
| 2698 |
|
| 2699 |
() |
| 2700 |
handleSSEResponse(ctx).catch(e => { |
| 2701 |
api.triggerHtmxEvent(element, 'htmx:sse:error', {error: e, url: ctx.request.action}); |
| 2702 |
cleanup(element); |
| 2703 |
}); |
| 2704 |
return false; |
| 2705 |
}, |
| 2706 |
|
| 2707 |
htmx_after_process: (element) => { |
| 2708 |
checkLegacyAttributes(element); |
| 2709 |
processElement(element); |
| 2710 |
let mc = htmx.config.metaCharacter || ':'; |
| 2711 |
let sseAttr = CSS.escape('hx-sse' + mc + 'connect'); |
| 2712 |
let sseSelector = `[${sseAttr}]`; |
| 2713 |
if (htmx.config.prefix) sseSelector += `,[${CSS.escape(htmx.config.prefix + 'sse' + mc + 'connect')}]`; |
| 2714 |
element.querySelectorAll(`${sseSelector},[sse-connect]`).forEach((el) => { |
| 2715 |
checkLegacyAttributes(el); |
| 2716 |
processElement(el); |
| 2717 |
}); |
| 2718 |
}, |
| 2719 |
|
| 2720 |
htmx_before_cleanup: (element) => { |
| 2721 |
cleanup(element); |
| 2722 |
} |
| 2723 |
}); |
| 2724 |
})(); |
| 2725 |
(() => { |
| 2726 |
let api; |
| 2727 |
|
| 2728 |
|
| 2729 |
function wsSelector(suffix) { |
| 2730 |
let mc = htmx.config.metaCharacter || ':'; |
| 2731 |
let sel = `[${CSS.escape('hx-ws' + mc + suffix)}]`; |
| 2732 |
if (htmx.config.prefix) sel += `,[${CSS.escape(htmx.config.prefix + 'ws' + mc + suffix)}]`; |
| 2733 |
return sel; |
| 2734 |
} |
| 2735 |
|
| 2736 |
|
| 2737 |
|
| 2738 |
|
| 2739 |
|
| 2740 |
|
| 2741 |
function getConfig(element) { |
| 2742 |
const defaults = { |
| 2743 |
reconnect: true, |
| 2744 |
reconnectDelay: 500, |
| 2745 |
reconnectMaxDelay: 60000, |
| 2746 |
reconnectMaxAttempts: Infinity, |
| 2747 |
reconnectJitter: 0.3, |
| 2748 |
pauseOnBackground: true, |
| 2749 |
pendingRequestTTL: 30000 |
| 2750 |
}; |
| 2751 |
let global = htmx.config.ws || {}; |
| 2752 |
let perElement = {}; |
| 2753 |
if (element) { |
| 2754 |
let ctx = api.createRequestContext(element, new CustomEvent('_')); |
| 2755 |
perElement = ctx.request.ws || {}; |
| 2756 |
} |
| 2757 |
let merged = { ...defaults, ...global, ...perElement }; |
| 2758 |
|
| 2759 |
|
| 2760 |
if (typeof merged.reconnectJitter === 'boolean') { |
| 2761 |
merged.reconnectJitter = merged.reconnectJitter ? 0.3 : 0; |
| 2762 |
} |
| 2763 |
|
| 2764 |
return merged; |
| 2765 |
} |
| 2766 |
|
| 2767 |
|
| 2768 |
|
| 2769 |
|
| 2770 |
|
| 2771 |
function normalizeWebSocketUrl(url) { |
| 2772 |
|
| 2773 |
if (url.startsWith('ws://') || url.startsWith('wss://')) { |
| 2774 |
return url; |
| 2775 |
} |
| 2776 |
|
| 2777 |
|
| 2778 |
if (url.startsWith('http://')) { |
| 2779 |
return 'ws://' + url.slice(7); |
| 2780 |
} |
| 2781 |
if (url.startsWith('https://')) { |
| 2782 |
return 'wss://' + url.slice(8); |
| 2783 |
} |
| 2784 |
|
| 2785 |
|
| 2786 |
let protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; |
| 2787 |
let host = window.location.host; |
| 2788 |
|
| 2789 |
if (url.startsWith('//')) { |
| 2790 |
|
| 2791 |
return protocol + url; |
| 2792 |
} |
| 2793 |
|
| 2794 |
if (url.startsWith('/')) { |
| 2795 |
|
| 2796 |
return protocol + '//' + host + url; |
| 2797 |
} |
| 2798 |
|
| 2799 |
|
| 2800 |
let basePath = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1); |
| 2801 |
return protocol + '//' + host + basePath + url; |
| 2802 |
} |
| 2803 |
|
| 2804 |
|
| 2805 |
|
| 2806 |
|
| 2807 |
|
| 2808 |
const connections = new Map(); |
| 2809 |
|
| 2810 |
function getOrCreateConnection(url, element) { |
| 2811 |
let normalizedUrl = normalizeWebSocketUrl(url); |
| 2812 |
|
| 2813 |
if (connections.has(normalizedUrl)) { |
| 2814 |
return connections.get(normalizedUrl); |
| 2815 |
} |
| 2816 |
|
| 2817 |
let connection = { |
| 2818 |
url: normalizedUrl, |
| 2819 |
config: getConfig(element), |
| 2820 |
socket: null, |
| 2821 |
attempt: 0, |
| 2822 |
timer: null, |
| 2823 |
pendingRequests: new Map(), |
| 2824 |
visibilityHandler: null, |
| 2825 |
cancelled: false |
| 2826 |
}; |
| 2827 |
|
| 2828 |
if (!api.triggerHtmxEvent(element, 'htmx:before:ws:connection', {connection}) || connection.cancelled) { |
| 2829 |
api.triggerHtmxEvent(element, 'htmx:ws:close', { |
| 2830 |
connection, reason: 'cancelled', code: null |
| 2831 |
}); |
| 2832 |
return null; |
| 2833 |
} |
| 2834 |
|
| 2835 |
|
| 2836 |
connections.set(normalizedUrl, connection); |
| 2837 |
createWebSocket(normalizedUrl, connection); |
| 2838 |
|
| 2839 |
let config = connection.config; |
| 2840 |
if (config.pauseOnBackground) { |
| 2841 |
connection.visibilityHandler = () => { |
| 2842 |
if (document.hidden) { |
| 2843 |
if (connection.socket && connection.socket.readyState === WebSocket.OPEN) { |
| 2844 |
connection.socket.close(); |
| 2845 |
} |
| 2846 |
} else if (!connection.socket || connection.socket.readyState === WebSocket.CLOSED) { |
| 2847 |
connection.attempt = 0; |
| 2848 |
createWebSocket(normalizedUrl, connection); |
| 2849 |
} |
| 2850 |
}; |
| 2851 |
document.addEventListener('visibilitychange', connection.visibilityHandler); |
| 2852 |
} |
| 2853 |
|
| 2854 |
return connection; |
| 2855 |
} |
| 2856 |
|
| 2857 |
function findConnectedElement(url) { |
| 2858 |
let sel = wsSelector('connect') + ',' + wsSelector('send'); |
| 2859 |
for (let el of document.querySelectorAll(sel)) { |
| 2860 |
if (el._htmx?.ws?.url === url) return el; |
| 2861 |
} |
| 2862 |
return null; |
| 2863 |
} |
| 2864 |
|
| 2865 |
|
| 2866 |
function cleanupOrphanedConnection(url, connection) { |
| 2867 |
if (connection.timer) clearTimeout(connection.timer); |
| 2868 |
if (connection.visibilityHandler) { |
| 2869 |
document.removeEventListener('visibilitychange', connection.visibilityHandler); |
| 2870 |
} |
| 2871 |
if (connection.abortController) { |
| 2872 |
connection.abortController.abort(); |
| 2873 |
} |
| 2874 |
connection.pendingRequests.clear(); |
| 2875 |
if (connection.socket) { |
| 2876 |
try { |
| 2877 |
if (connection.socket.readyState === WebSocket.OPEN || connection.socket.readyState === WebSocket.CONNECTING) { |
| 2878 |
connection.socket.close(); |
| 2879 |
} |
| 2880 |
} catch (e) { |
| 2881 |
|
| 2882 |
} |
| 2883 |
} |
| 2884 |
connections.delete(url); |
| 2885 |
} |
| 2886 |
|
| 2887 |
function createWebSocket(url, connection) { |
| 2888 |
|
| 2889 |
if (connection.abortController) { |
| 2890 |
connection.abortController.abort(); |
| 2891 |
} |
| 2892 |
if (connection.socket) { |
| 2893 |
let oldSocket = connection.socket; |
| 2894 |
connection.socket = null; |
| 2895 |
try { |
| 2896 |
if (oldSocket.readyState === WebSocket.OPEN || oldSocket.readyState === WebSocket.CONNECTING) { |
| 2897 |
oldSocket.close(); |
| 2898 |
} |
| 2899 |
} catch (e) { |
| 2900 |
|
| 2901 |
} |
| 2902 |
} |
| 2903 |
|
| 2904 |
try { |
| 2905 |
connection.socket = new WebSocket(url); |
| 2906 |
let ac = new AbortController(); |
| 2907 |
connection.abortController = ac; |
| 2908 |
let opts = { signal: ac.signal }; |
| 2909 |
|
| 2910 |
connection.socket.addEventListener('open', () => { |
| 2911 |
let elt = findConnectedElement(url); |
| 2912 |
if (elt) { |
| 2913 |
api.triggerHtmxEvent(elt, 'htmx:after:ws:connection', {connection}); |
| 2914 |
} else { |
| 2915 |
et |
| 2916 |
cleanupOrphanedConnection(url, connection); |
| 2917 |
return; |
| 2918 |
} |
| 2919 |
connection.attempt = 0; |
| 2920 |
}, opts); |
| 2921 |
|
| 2922 |
connection.socket.addEventListener('message', (event) => { |
| 2923 |
handleMessage(connection, event); |
| 2924 |
}, opts); |
| 2925 |
|
| 2926 |
connection.socket.addEventListener('close', (event) => { |
| 2927 |
if (event.target !== connection.socket) return; |
| 2928 |
|
| 2929 |
let elt = findConnectedElement(url); |
| 2930 |
if (elt) api.triggerHtmxEvent(elt, 'htmx:ws:close', { |
| 2931 |
connection, reason: 'closed', code: event.code |
| 2932 |
}); |
| 2933 |
|
| 2934 |
if (!connections.has(url)) return; |
| 2935 |
|
| 2936 |
let config = connection.config; |
| 2937 |
if (config.pauseOnBackground && document.hidden) return; |
| 2938 |
|
| 2939 |
if (config.reconnect && findConnectedElement(url)) { |
| 2940 |
scheduleReconnect(url, connection); |
| 2941 |
} else { |
| 2942 |
up |
| 2943 |
cleanupOrphanedConnection(url, connection); |
| 2944 |
} |
| 2945 |
}, opts); |
| 2946 |
|
| 2947 |
connection.socket.addEventListener('error', (error) => { |
| 2948 |
let elt = findConnectedElement(url); |
| 2949 |
if (elt) api.triggerHtmxEvent(elt, 'htmx:ws:error', { url, error }); |
| 2950 |
}, opts); |
| 2951 |
|
| 2952 |
} catch (error) { |
| 2953 |
let elt = findConnectedElement(url); |
| 2954 |
if (elt) api.triggerHtmxEvent(elt, 'htmx:ws:error', { url, error }); |
| 2955 |
} |
| 2956 |
} |
| 2957 |
|
| 2958 |
function scheduleReconnect(url, connection) { |
| 2959 |
let config = connection.config; |
| 2960 |
|
| 2961 |
connection.attempt++; |
| 2962 |
let attempt = connection.attempt; |
| 2963 |
|
| 2964 |
if (!config.reconnect || attempt > config.reconnectMaxAttempts) { |
| 2965 |
cleanupOrphanedConnection(url, connection); |
| 2966 |
return; |
| 2967 |
} |
| 2968 |
|
| 2969 |
let baseDelay = htmx.parseInterval(config.reconnectDelay) ?? config.reconnectDelay; |
| 2970 |
let maxDelay = htmx.parseInterval(config.reconnectMaxDelay) ?? config.reconnectMaxDelay; |
| 2971 |
|
| 2972 |
let delay = Math.min( |
| 2973 |
baseDelay * Math.pow(2, attempt - 1), |
| 2974 |
maxDelay |
| 2975 |
); |
| 2976 |
|
| 2977 |
if (config.reconnectJitter > 0) { |
| 2978 |
let jitterRange = delay * config.reconnectJitter; |
| 2979 |
delay = Math.max(0, delay + (Math.random() * 2 - 1) * jitterRange); |
| 2980 |
} |
| 2981 |
|
| 2982 |
let elt = findConnectedElement(url); |
| 2983 |
if (elt) { |
| 2984 |
connection.cancelled = false; |
| 2985 |
if (!api.triggerHtmxEvent(elt, 'htmx:before:ws:connection', {connection}) || connection.cancelled) { |
| 2986 |
api.triggerHtmxEvent(elt, 'htmx:ws:close', { |
| 2987 |
connection, reason: 'cancelled', code: null |
| 2988 |
}); |
| 2989 |
cleanupOrphanedConnection(url, connection); |
| 2990 |
return; |
| 2991 |
} |
| 2992 |
} else { |
| 2993 |
ct |
| 2994 |
cleanupOrphanedConnection(url, connection); |
| 2995 |
return; |
| 2996 |
} |
| 2997 |
|
| 2998 |
connection.timer = setTimeout(() => { |
| 2999 |
if (findConnectedElement(url)) { |
| 3000 |
createWebSocket(url, connection); |
| 3001 |
} else { |
| 3002 |
cleanupOrphanedConnection(url, connection); |
| 3003 |
} |
| 3004 |
}, delay); |
| 3005 |
} |
| 3006 |
|
| 3007 |
function closeConnection(url, element) { |
| 3008 |
let connection = connections.get(url); |
| 3009 |
if (!connection) return; |
| 3010 |
|
| 3011 |
if (connection.timer) clearTimeout(connection.timer); |
| 3012 |
if (connection.visibilityHandler) { |
| 3013 |
document.removeEventListener('visibilitychange', connection.visibilityHandler); |
| 3014 |
} |
| 3015 |
if (connection.abortController) { |
| 3016 |
connection.abortController.abort(); |
| 3017 |
} |
| 3018 |
connection.pendingRequests.clear(); |
| 3019 |
api.triggerHtmxEvent(element, 'htmx:ws:close', { |
| 3020 |
connection, reason: 'removed', code: null |
| 3021 |
}); |
| 3022 |
if (connection.socket && connection.socket.readyState === WebSocket.OPEN) { |
| 3023 |
connection.socket.close(); |
| 3024 |
} |
| 3025 |
connections.delete(url); |
| 3026 |
} |
| 3027 |
|
| 3028 |
|
| 3029 |
|
| 3030 |
|
| 3031 |
function cleanupExpiredRequests(connection) { |
| 3032 |
let config = connection.config; |
| 3033 |
let now = Date.now(); |
| 3034 |
let timeout = config.pendingRequestTTL || 30000; |
| 3035 |
|
| 3036 |
for (let [requestId, pending] of connection.pendingRequests) { |
| 3037 |
if (now - pending.timestamp > timeout) { |
| 3038 |
connection.pendingRequests.delete(requestId); |
| 3039 |
} |
| 3040 |
} |
| 3041 |
} |
| 3042 |
|
| 3043 |
|
| 3044 |
|
| 3045 |
|
| 3046 |
|
| 3047 |
async function sendRequest(element, event) { |
| 3048 |
|
| 3049 |
let sendAttr = api.attributeValue(element, 'hx-ws:send'); |
| 3050 |
let url = (sendAttr && sendAttr !== 'true') ? sendAttr : null; |
| 3051 |
if (!url) { |
| 3052 |
let ancestor = element.closest(wsSelector('connect')); |
| 3053 |
if (ancestor) { |
| 3054 |
url = api.attributeValue(ancestor, 'hx-ws:connect'); |
| 3055 |
} |
| 3056 |
} |
| 3057 |
|
| 3058 |
if (!url) { |
| 3059 |
api.triggerHtmxEvent(element, 'htmx:ws:error', { |
| 3060 |
url: null, error: 'No WebSocket connection found for element' |
| 3061 |
}); |
| 3062 |
return; |
| 3063 |
} |
| 3064 |
|
| 3065 |
let normalizedUrl = normalizeWebSocketUrl(url); |
| 3066 |
let connection = connections.get(normalizedUrl); |
| 3067 |
|
| 3068 |
|
| 3069 |
if (connection && connection.socket && connection.socket.readyState === WebSocket.CONNECTING) { |
| 3070 |
await new Promise(resolve => { |
| 3071 |
connection.socket.addEventListener('open', resolve, { once: true }); |
| 3072 |
connection.socket.addEventListener('close', resolve, { once: true }); |
| 3073 |
connection.socket.addEventListener('error', resolve, { once: true }); |
| 3074 |
}); |
| 3075 |
} |
| 3076 |
|
| 3077 |
if (!connection || !connection.socket || connection.socket.readyState !== WebSocket.OPEN) { |
| 3078 |
api.triggerHtmxEvent(element, 'htmx:ws:error', { url: normalizedUrl, error: 'Connection not open' }); |
| 3079 |
return; |
| 3080 |
} |
| 3081 |
|
| 3082 |
|
| 3083 |
cleanupExpiredRequests(connection); |
| 3084 |
|
| 3085 |
|
| 3086 |
let ctx = api.createRequestContext(element, event); |
| 3087 |
let headers = {...ctx.request.headers}; |
| 3088 |
delete headers['Accept']; |
| 3089 |
|
| 3090 |
|
| 3091 |
let requestId = crypto.randomUUID(); |
| 3092 |
headers['HX-Request-ID'] = requestId; |
| 3093 |
|
| 3094 |
|
| 3095 |
let form = element.form || element.closest('form'); |
| 3096 |
let formData = api.collectFormData(element, form, event.submitter); |
| 3097 |
|
| 3098 |
|
| 3099 |
let body = {}; |
| 3100 |
for (let [key, value] of formData) { |
| 3101 |
if (key in body) { |
| 3102 |
body[key] = [].concat(body[key], value); |
| 3103 |
} else { |
| 3104 |
body[key] = value; |
| 3105 |
} |
| 3106 |
} |
| 3107 |
|
| 3108 |
|
| 3109 |
let valsResult = api.getAttributeObject(element, 'hx-vals', obj => Object.assign(body, obj)); |
| 3110 |
if (valsResult) await valsResult; |
| 3111 |
|
| 3112 |
let detail = { headers, body }; |
| 3113 |
if (!api.triggerHtmxEvent(element, 'htmx:before:ws:request', detail)) { |
| 3114 |
return; |
| 3115 |
} |
| 3116 |
|
| 3117 |
try { |
| 3118 |
connection.socket.send(JSON.stringify(detail)); |
| 3119 |
|
| 3120 |
|
| 3121 |
connection.pendingRequests.set(requestId, { element, timestamp: Date.now() }); |
| 3122 |
|
| 3123 |
api.triggerHtmxEvent(element, 'htmx:after:ws:request', detail); |
| 3124 |
} catch (error) { |
| 3125 |
api.triggerHtmxEvent(element, 'htmx:ws:error', { url: normalizedUrl, error }); |
| 3126 |
} |
| 3127 |
} |
| 3128 |
|
| 3129 |
|
| 3130 |
|
| 3131 |
|
| 3132 |
|
| 3133 |
function handleMessage(connection, event) { |
| 3134 |
let json = null; |
| 3135 |
try { |
| 3136 |
json = JSON.parse(event.data); |
| 3137 |
} catch (e) { |
| 3138 |
|
| 3139 |
} |
| 3140 |
|
| 3141 |
|
| 3142 |
cleanupExpiredRequests(connection); |
| 3143 |
|
| 3144 |
|
| 3145 |
let connectionElement = null; |
| 3146 |
let requestId = json?.['HX-Request-ID'] || json?.request_id; |
| 3147 |
if (requestId && connection.pendingRequests.has(requestId)) { |
| 3148 |
connectionElement = connection.pendingRequests.get(requestId).element; |
| 3149 |
connection.pendingRequests.delete(requestId); |
| 3150 |
|
| 3151 |
if (!connectionElement.isConnected) { |
| 3152 |
connectionElement = findConnectedElement(connection.url); |
| 3153 |
} |
| 3154 |
} else { |
| 3155 |
connectionElement = findConnectedElement(connection.url); |
| 3156 |
} |
| 3157 |
|
| 3158 |
if (!connectionElement) { |
| 3159 |
up |
| 3160 |
cleanupOrphanedConnection(connection.url, connection); |
| 3161 |
return; |
| 3162 |
} |
| 3163 |
|
| 3164 |
let detail = { |
| 3165 |
message: { text: event.data, json, cancelled: false } |
| 3166 |
}; |
| 3167 |
|
| 3168 |
if (!api.triggerHtmxEvent(connectionElement, 'htmx:before:ws:message', detail) || detail.message.cancelled) { |
| 3169 |
return; |
| 3170 |
} |
| 3171 |
|
| 3172 |
|
| 3173 |
|
| 3174 |
|
| 3175 |
let html; |
| 3176 |
if (detail.message.json) { |
| 3177 |
if (detail.message.json.content !== undefined) { |
| 3178 |
html = detail.message.json.content; |
| 3179 |
} else if (detail.message.json.payload !== undefined) { |
| 3180 |
html = detail.message.json.payload; |
| 3181 |
|
| 3182 |
if (!connection._payloadWarnFired) { |
| 3183 |
console.warn('htmx: [hx-ws] json.payload is deprecated; use json.content instead'); |
| 3184 |
connection._payloadWarnFired = true; |
| 3185 |
} |
| 3186 |
} |
| 3187 |
} else { |
| 3188 |
html = detail.message.text; |
| 3189 |
} |
| 3190 |
if (html != null) { |
| 3191 |
let target = detail.message.json?.target || api.attributeValue(connectionElement, 'hx-target'); |
| 3192 |
let swap = detail.message.json?.swap || api.attributeValue(connectionElement, 'hx-swap'); |
| 3193 |
|
| 3194 |
htmx.swap({ |
| 3195 |
sourceElement: connectionElement, |
| 3196 |
target: target || connectionElement, |
| 3197 |
swap: swap || (target ? htmx.config.defaultSwap : 'none'), |
| 3198 |
text: html, |
| 3199 |
transition: false |
| 3200 |
}); |
| 3201 |
} |
| 3202 |
|
| 3203 |
delete detail.message.cancelled; |
| 3204 |
api.triggerHtmxEvent(connectionElement, 'htmx:after:ws:message', detail); |
| 3205 |
} |
| 3206 |
|
| 3207 |
|
| 3208 |
|
| 3209 |
|
| 3210 |
|
| 3211 |
function initializeElement(element) { |
| 3212 |
api.htmxProp(element).ws ??= {}; |
| 3213 |
if (element._htmx.ws.initialized) return; |
| 3214 |
|
| 3215 |
let connectUrl = api.attributeValue(element, 'hx-ws:connect'); |
| 3216 |
if (!connectUrl) return; |
| 3217 |
|
| 3218 |
let specString = api.attributeValue(element, 'hx-trigger') || 'load'; |
| 3219 |
api.onTrigger(element, specString, () => { |
| 3220 |
if (element._htmx?.ws?.url) return; |
| 3221 |
let connection = getOrCreateConnection(connectUrl, element); |
| 3222 |
if (connection) { |
| 3223 |
element._htmx.ws.url = connection.url; |
| 3224 |
} |
| 3225 |
}); |
| 3226 |
element._htmx.ws.initialized = true; |
| 3227 |
} |
| 3228 |
|
| 3229 |
function initializeSendElement(element) { |
| 3230 |
api.htmxProp(element).ws ??= {}; |
| 3231 |
if (element._htmx.ws.sendInitialized) return; |
| 3232 |
|
| 3233 |
let sendAttr = api.attributeValue(element, 'hx-ws:send'); |
| 3234 |
let sendUrl = (sendAttr && sendAttr !== 'true') ? sendAttr : null; |
| 3235 |
let specString = api.attributeValue(element, 'hx-trigger'); |
| 3236 |
if (!specString) { |
| 3237 |
specString = element.matches('form') ? 'submit' : |
| 3238 |
element.matches('input:not([type=button]),select,textarea') ? 'change' : |
| 3239 |
'click'; |
| 3240 |
} |
| 3241 |
|
| 3242 |
api.onTrigger(element, specString, async (evt) => { |
| 3243 |
if (element.matches('form') && evt.type === 'submit') { |
| 3244 |
evt.preventDefault(); |
| 3245 |
} |
| 3246 |
if (sendUrl && !element._htmx?.ws?.url) { |
| 3247 |
let connection = getOrCreateConnection(sendUrl, element); |
| 3248 |
if (connection) { |
| 3249 |
element._htmx.ws.url = connection.url; |
| 3250 |
} |
| 3251 |
} |
| 3252 |
await sendRequest(element, evt); |
| 3253 |
}); |
| 3254 |
element._htmx.ws.sendInitialized = true; |
| 3255 |
} |
| 3256 |
|
| 3257 |
function cleanupElement(element) { |
| 3258 |
let url = element._htmx?.ws?.url; |
| 3259 |
if (!url || !connections.has(url)) return; |
| 3260 |
element._htmx.ws.url = null; |
| 3261 |
if (!findConnectedElement(url)) { |
| 3262 |
closeConnection(url, element); |
| 3263 |
} |
| 3264 |
} |
| 3265 |
|
| 3266 |
|
| 3267 |
|
| 3268 |
|
| 3269 |
|
| 3270 |
function checkLegacyAttributes(element) { |
| 3271 |
if (element.hasAttribute('ws-connect') || element.hasAttribute('ws-send')) { |
| 3272 |
console.warn('htmx: [hx-ws] legacy attributes ws-connect and ws-send are deprecated; use hx-ws:connect and hx-ws:send instead'); |
| 3273 |
|
| 3274 |
if (element.hasAttribute('ws-connect')) { |
| 3275 |
let url = element.getAttribute('ws-connect'); |
| 3276 |
let mc = htmx.config.metaCharacter || ':'; |
| 3277 |
let attr = (htmx.config.prefix || 'hx-') + 'ws' + mc + 'connect'; |
| 3278 |
if (!element.hasAttribute(attr)) { |
| 3279 |
element.setAttribute(attr, url); |
| 3280 |
} |
| 3281 |
} |
| 3282 |
|
| 3283 |
if (element.hasAttribute('ws-send')) { |
| 3284 |
let mc = htmx.config.metaCharacter || ':'; |
| 3285 |
let attr = (htmx.config.prefix || 'hx-') + 'ws' + mc + 'send'; |
| 3286 |
if (!element.hasAttribute(attr)) { |
| 3287 |
element.setAttribute(attr, ''); |
| 3288 |
} |
| 3289 |
} |
| 3290 |
} |
| 3291 |
} |
| 3292 |
|
| 3293 |
|
| 3294 |
|
| 3295 |
|
| 3296 |
|
| 3297 |
htmx.registerExtension('ws', { |
| 3298 |
init: (internalAPI) => { |
| 3299 |
api = internalAPI; |
| 3300 |
|
| 3301 |
|
| 3302 |
if (!htmx.config.ws) { |
| 3303 |
htmx.config.ws = {}; |
| 3304 |
} |
| 3305 |
}, |
| 3306 |
|
| 3307 |
htmx_after_process: (element) => { |
| 3308 |
const processNode = (node) => { |
| 3309 |
checkLegacyAttributes(node); |
| 3310 |
|
| 3311 |
if (api.attributeValue(node, 'hx-ws:connect') != null) { |
| 3312 |
initializeElement(node); |
| 3313 |
} |
| 3314 |
|
| 3315 |
if (api.attributeValue(node, 'hx-ws:send') != null) { |
| 3316 |
initializeSendElement(node); |
| 3317 |
} |
| 3318 |
}; |
| 3319 |
|
| 3320 |
processNode(element); |
| 3321 |
|
| 3322 |
let sel = wsSelector('connect') + ',' + wsSelector('send') + ',[ws-connect],[ws-send]'; |
| 3323 |
element.querySelectorAll(sel).forEach(processNode); |
| 3324 |
}, |
| 3325 |
|
| 3326 |
htmx_before_cleanup: (element) => { |
| 3327 |
cleanupElement(element); |
| 3328 |
} |
| 3329 |
}); |
| 3330 |
|
| 3331 |
|
| 3332 |
if (typeof window !== 'undefined' && window.htmx) { |
| 3333 |
|
| 3334 |
window.addEventListener('pagehide', () => { |
| 3335 |
connections.forEach((connection) => { |
| 3336 |
if (connection.socket) { |
| 3337 |
connection.socket.close(1001, 'page navigating away'); |
| 3338 |
} |
| 3339 |
}); |
| 3340 |
}); |
| 3341 |
|
| 3342 |
window.htmx.ext = window.htmx.ext || {}; |
| 3343 |
window.htmx.ext.ws = { |
| 3344 |
getRegistry: () => ({ |
| 3345 |
clear: () => { |
| 3346 |
let activeConnections = Array.from(connections.values()); |
| 3347 |
connections.clear(); |
| 3348 |
|
| 3349 |
activeConnections.forEach(connection => { |
| 3350 |
if (connection.timer) { |
| 3351 |
clearTimeout(connection.timer); |
| 3352 |
} |
| 3353 |
if (connection.visibilityHandler) { |
| 3354 |
document.removeEventListener('visibilitychange', connection.visibilityHandler); |
| 3355 |
} |
| 3356 |
if (connection.abortController) { |
| 3357 |
connection.abortController.abort(); |
| 3358 |
} |
| 3359 |
if (connection.socket) { |
| 3360 |
connection.socket.close(); |
| 3361 |
} |
| 3362 |
connection.pendingRequests.clear(); |
| 3363 |
}); |
| 3364 |
}, |
| 3365 |
get: (key) => connections.get(normalizeWebSocketUrl(key)), |
| 3366 |
has: (key) => connections.has(normalizeWebSocketUrl(key)), |
| 3367 |
get size() { return connections.size; } |
| 3368 |
}) |
| 3369 |
}; |
| 3370 |
} |
| 3371 |
})(); |
| 3372 |
(()=>{ |
| 3373 |
let api; |
| 3374 |
|
| 3375 |
function initializePreload(elt) { |
| 3376 |
let preloadSpec = api.attributeValue(elt, "hx-preload"); |
| 3377 |
if (preloadSpec == undefined && !elt._htmx?.boosted) return; |
| 3378 |
|
| 3379 |
let preloadEvents = [] |
| 3380 |
let timeout = 5000; |
| 3381 |
if (preloadSpec) { |
| 3382 |
let specs = api.parseTriggerSpecs(preloadSpec); |
| 3383 |
if (specs.length === 0) return; |
| 3384 |
for (const spec of specs) { |
| 3385 |
preloadEvents.push(spec.name) |
| 3386 |
if (spec.timeout) { |
| 3387 |
timeout = htmx.parseInterval(spec.timeout) |
| 3388 |
} |
| 3389 |
} |
| 3390 |
} else { |
| 3391 |
let isBoostedAnchor = elt._htmx?.boosted && elt.tagName === "A"; |
| 3392 |
let isHxGet = api.attributeValue(elt, "hx-get") != null; |
| 3393 |
if (!isBoostedAnchor && !isHxGet) return; |
| 3394 |
if (isBoostedAnchor && htmx.config?.preload?.autoBoost === false) return; |
| 3395 |
if (htmx.config?.preload?.boostTimeout) { |
| 3396 |
timeout = htmx.parseInterval(htmx.config.preload.boostTimeout) |
| 3397 |
} |
| 3398 |
preloadEvents.push(htmx.config?.preload?.boostEvent || "mousedown"); |
| 3399 |
preloadEvents.push("touchstart"); |
| 3400 |
} |
| 3401 |
|
| 3402 |
let preloadListener = async (evt) => { |
| 3403 |
let {method} = api.determineMethodAndAction(elt, evt); |
| 3404 |
if (method !== 'GET') return; |
| 3405 |
|
| 3406 |
if (elt._htmx?.preload) return; |
| 3407 |
|
| 3408 |
let ctx = api.createRequestContext(elt, evt); |
| 3409 |
let form = elt.form || elt.closest("form"); |
| 3410 |
let body = api.collectFormData(elt, form, evt.submitter); |
| 3411 |
let valsResult = api.getAttributeObject(elt, 'hx-vals', obj => { |
| 3412 |
for (let key in obj) body.set(key, obj[key]); |
| 3413 |
}); |
| 3414 |
if (valsResult) await valsResult; |
| 3415 |
|
| 3416 |
let action = ctx.request.action.replace?.(/#.*$/, ''); |
| 3417 |
|
| 3418 |
let params = new URLSearchParams(body); |
| 3419 |
if (params.size) action += (/\?/.test(action) ? "&" : "?") + params; |
| 3420 |
|
| 3421 |
elt._htmx.preload = { |
| 3422 |
prefetch: fetch(action, ctx.request), |
| 3423 |
action: action, |
| 3424 |
expiresAt: Date.now() + timeout |
| 3425 |
}; |
| 3426 |
|
| 3427 |
try { |
| 3428 |
await elt._htmx.preload.prefetch; |
| 3429 |
} catch (error) { |
| 3430 |
delete elt._htmx.preload; |
| 3431 |
} |
| 3432 |
}; |
| 3433 |
for (let eventName of preloadEvents) { |
| 3434 |
elt.addEventListener(eventName, preloadListener, { passive: true }); |
| 3435 |
} |
| 3436 |
elt._htmx.preloadListener = preloadListener; |
| 3437 |
elt._htmx.preloadEvents = preloadEvents; |
| 3438 |
} |
| 3439 |
|
| 3440 |
htmx.registerExtension('preload', { |
| 3441 |
init: (internalAPI) => { |
| 3442 |
api = internalAPI; |
| 3443 |
}, |
| 3444 |
|
| 3445 |
htmx_after_init: (elt) => { |
| 3446 |
initializePreload(elt); |
| 3447 |
}, |
| 3448 |
|
| 3449 |
htmx_before_request: (elt, detail) => { |
| 3450 |
let {ctx} = detail; |
| 3451 |
if (elt._htmx?.preload && |
| 3452 |
elt._htmx.preload.action === ctx.request.action && |
| 3453 |
Date.now() < elt._htmx.preload.expiresAt) { |
| 3454 |
let prefetch = elt._htmx.preload.prefetch; |
| 3455 |
ctx.fetch = () => prefetch; |
| 3456 |
delete elt._htmx.preload; |
| 3457 |
} else { |
| 3458 |
if (elt._htmx) delete elt._htmx.preload; |
| 3459 |
} |
| 3460 |
}, |
| 3461 |
|
| 3462 |
htmx_before_cleanup: (elt) => { |
| 3463 |
if (elt._htmx?.preloadListener) { |
| 3464 |
for (let eventName of elt._htmx.preloadEvents) { |
| 3465 |
elt.removeEventListener(eventName, elt._htmx.preloadListener); |
| 3466 |
} |
| 3467 |
} |
| 3468 |
} |
| 3469 |
}); |
| 3470 |
})(); |
| 3471 |
(() => { |
| 3472 |
|
| 3473 |
if (typeof navigation === 'undefined') return; |
| 3474 |
|
| 3475 |
let api; |
| 3476 |
let activeCount = 0; |
| 3477 |
let activeAborts = new Set(); |
| 3478 |
|
| 3479 |
|
| 3480 |
|
| 3481 |
|
| 3482 |
ly |
| 3483 |
|
| 3484 |
|
| 3485 |
|
| 3486 |
|
| 3487 |
|
| 3488 |
let cleanupNavigation = null; |
| 3489 |
|
| 3490 |
function shouldShowIndicator(elt) { |
| 3491 |
if (api.attributeValue(elt, 'hx-browser-indicator') === 'true') return true; |
| 3492 |
if (htmx.config.boostBrowserIndicator && elt._htmx?.boosted) return true; |
| 3493 |
return false; |
| 3494 |
} |
| 3495 |
|
| 3496 |
function listenForNavigate() { |
| 3497 |
navigation.addEventListener('navigate', (event) => { |
| 3498 |
|
| 3499 |
|
| 3500 |
if (!event.canIntercept) return; |
| 3501 |
|
| 3502 |
|
| 3503 |
|
| 3504 |
|
| 3505 |
|
| 3506 |
t. |
| 3507 |
|
| 3508 |
let savedState = history.state; |
| 3509 |
|
| 3510 |
let hideBrowserIndicator; |
| 3511 |
event.intercept({ |
| 3512 |
handler: () => new Promise(r => { hideBrowserIndicator = r }), |
| 3513 |
scroll: 'manual', |
| 3514 |
focusReset: 'manual' |
| 3515 |
}); |
| 3516 |
|
| 3517 |
let abortHandler = () => { |
| 3518 |
h. |
| 3519 |
|
| 3520 |
|
| 3521 |
|
| 3522 |
|
| 3523 |
|
| 3524 |
if (activeCount > 0) { |
| 3525 |
activeAborts.forEach(abort => abort()); |
| 3526 |
activeAborts.clear(); |
| 3527 |
activeCount = 0; |
| 3528 |
} |
| 3529 |
|
| 3530 |
|
| 3531 |
cleanupNavigation = null; |
| 3532 |
}; |
| 3533 |
event.signal.addEventListener('abort', abortHandler); |
| 3534 |
|
| 3535 |
cleanupNavigation = () => { |
| 3536 |
hideBrowserIndicator(); |
| 3537 |
|
| 3538 |
|
| 3539 |
|
| 3540 |
er |
| 3541 |
|
| 3542 |
|
| 3543 |
history.replaceState(savedState, ''); |
| 3544 |
}; |
| 3545 |
}, {once: true}); |
| 3546 |
} |
| 3547 |
|
| 3548 |
function startIndicator() { |
| 3549 |
listenForNavigate(); |
| 3550 |
navigation.navigate(location.href, { history: 'replace' }); |
| 3551 |
} |
| 3552 |
|
| 3553 |
function stopIndicator() { |
| 3554 |
if (cleanupNavigation) { |
| 3555 |
cleanupNavigation(); |
| 3556 |
cleanupNavigation = null; |
| 3557 |
} |
| 3558 |
} |
| 3559 |
|
| 3560 |
htmx.registerExtension('browser-indicator', { |
| 3561 |
init: (internalAPI) => { |
| 3562 |
api = internalAPI; |
| 3563 |
}, |
| 3564 |
|
| 3565 |
htmx_before_history_update: () => { |
| 3566 |
|
| 3567 |
|
| 3568 |
|
| 3569 |
|
| 3570 |
|
| 3571 |
|
| 3572 |
ly |
| 3573 |
|
| 3574 |
|
| 3575 |
|
| 3576 |
stopIndicator(); |
| 3577 |
}, |
| 3578 |
|
| 3579 |
ng |
| 3580 |
|
| 3581 |
|
| 3582 |
htmx_before_request: (elt, detail) => { |
| 3583 |
if (!shouldShowIndicator(elt)) return; |
| 3584 |
detail.ctx._browserIndicator = true; |
| 3585 |
activeCount++; |
| 3586 |
if (activeCount === 1) startIndicator(); |
| 3587 |
|
| 3588 |
|
| 3589 |
|
| 3590 |
|
| 3591 |
d. |
| 3592 |
|
| 3593 |
|
| 3594 |
if (detail.ctx.request?.abort) activeAborts.add(detail.ctx.request.abort); |
| 3595 |
}, |
| 3596 |
|
| 3597 |
htmx_finally_request: (elt, detail) => { |
| 3598 |
if (!detail.ctx._browserIndicator) return; |
| 3599 |
if (detail.ctx.request?.abort) activeAborts.delete(detail.ctx.request.abort); |
| 3600 |
if (activeCount === 0) return; |
| 3601 |
activeCount--; |
| 3602 |
if (activeCount === 0) stopIndicator(); |
| 3603 |
} |
| 3604 |
}); |
| 3605 |
})(); |
| 3606 |
|
| 3607 |
|
| 3608 |
|
| 3609 |
|
| 3610 |
|
| 3611 |
|
| 3612 |
|
| 3613 |
|
| 3614 |
|
| 3615 |
|
| 3616 |
|
| 3617 |
|
| 3618 |
|
| 3619 |
|
| 3620 |
|
| 3621 |
|
| 3622 |
|
| 3623 |
|
| 3624 |
|
| 3625 |
|
| 3626 |
|
| 3627 |
|
| 3628 |
(() => { |
| 3629 |
let api; |
| 3630 |
|
| 3631 |
htmx.registerExtension('download', { |
| 3632 |
init: (internalAPI) => { |
| 3633 |
api = internalAPI; |
| 3634 |
}, |
| 3635 |
htmx_before_response: (elt, {ctx}) => { |
| 3636 |
let downloadUrl = ctx.response.headers.get('HX-Download'); |
| 3637 |
if (downloadUrl) { |
| 3638 |
(async () => streamDownload(ctx.sourceElement, await fetch(downloadUrl), downloadUrl))(); |
| 3639 |
return; |
| 3640 |
} |
| 3641 |
let cd = ctx.response.headers.get('Content-Disposition'); |
| 3642 |
if (ctx.swap !== 'download' && !cd?.includes('attachment')) return; |
| 3643 |
streamDownload(ctx.sourceElement, ctx.response.raw, ctx.request.action); |
| 3644 |
return false; |
| 3645 |
} |
| 3646 |
}); |
| 3647 |
|
| 3648 |
function streamDownload(sourceElement, response, url) { |
| 3649 |
(async () => { |
| 3650 |
let total = +response.headers.get('Content-Length') || null; |
| 3651 |
api.triggerHtmxEvent(sourceElement, 'htmx:download:start', {total}); |
| 3652 |
let reader = response.body.getReader(); |
| 3653 |
let chunks = [], loaded = 0; |
| 3654 |
while (true) { |
| 3655 |
let {done, value} = await reader.read(); |
| 3656 |
if (done) break; |
| 3657 |
chunks.push(value); |
| 3658 |
loaded += value.length; |
| 3659 |
api.triggerHtmxEvent(sourceElement, 'htmx:download:progress', { |
| 3660 |
loaded, total, |
| 3661 |
percent: total ? Math.round(loaded / total * 100) : null |
| 3662 |
}); |
| 3663 |
} |
| 3664 |
let blob = new Blob(chunks, { |
| 3665 |
type: response.headers.get('Content-Type') || 'application/octet-stream' |
| 3666 |
}); |
| 3667 |
let filename = parseFilename(response.headers, url); |
| 3668 |
let blobUrl = URL.createObjectURL(blob); |
| 3669 |
Object.assign(document.createElement('a'), {href: blobUrl, download: filename}).click(); |
| 3670 |
URL.revokeObjectURL(blobUrl); |
| 3671 |
api.triggerHtmxEvent(sourceElement, 'htmx:download:complete', {filename, size: blob.size}); |
| 3672 |
})(); |
| 3673 |
} |
| 3674 |
|
| 3675 |
function parseFilename(headers, url) { |
| 3676 |
let cd = headers.get('Content-Disposition'); |
| 3677 |
if (cd) { |
| 3678 |
let match = cd.match(/filename\*?=['"]?(?:UTF-8'')?([^'";]+)/i); |
| 3679 |
if (match) return decodeURIComponent(match[1]); |
| 3680 |
} |
| 3681 |
return url.split('/').pop().split('?')[0] || 'download'; |
| 3682 |
} |
| 3683 |
})(); |
| 3684 |
(() =>{ |
| 3685 |
|
| 3686 |
function normalizeSwapStyle(style) { |
| 3687 |
return style === 'before' ? 'beforebegin' : |
| 3688 |
style === 'after' ? 'afterend' : |
| 3689 |
style === 'prepend' ? 'afterbegin' : |
| 3690 |
style === 'append' ? 'beforeend' : style; |
| 3691 |
} |
| 3692 |
|
| 3693 |
let api; |
| 3694 |
|
| 3695 |
function insertOptimisticContent(ctx) { |
| 3696 |
ctx.optimistic = api.attributeValue(ctx.sourceElement, "hx-optimistic"); |
| 3697 |
if (!ctx.optimistic) { |
| 3698 |
return |
| 3699 |
} |
| 3700 |
|
| 3701 |
let sourceElt = document.querySelector(ctx.optimistic); |
| 3702 |
if (!sourceElt) return; |
| 3703 |
|
| 3704 |
let target = ctx.target; |
| 3705 |
|
| 3706 |
if (typeof target === 'string') { |
| 3707 |
target = document.querySelector(target); |
| 3708 |
} |
| 3709 |
if (!target) return; |
| 3710 |
|
| 3711 |
|
| 3712 |
let optimisticDiv = document.createElement('div'); |
| 3713 |
optimisticDiv.style.cssText = 'all: initial'; |
| 3714 |
optimisticDiv.classList.add('hx-optimistic'); |
| 3715 |
optimisticDiv.innerHTML = sourceElt.innerHTML; |
| 3716 |
|
| 3717 |
|
| 3718 |
if (ctx.optimisticBody) { |
| 3719 |
let keys = new Set(ctx.optimisticBody.keys()); |
| 3720 |
for (let k of keys) { |
| 3721 |
let values = ctx.optimisticBody.getAll(k).filter(v => typeof v === 'string'); |
| 3722 |
if (!values.length) continue; |
| 3723 |
let val = values.length === 1 ? values[0] : JSON.stringify(values); |
| 3724 |
try { |
| 3725 |
optimisticDiv.dataset[k] = val; |
| 3726 |
} catch (e) { |
| 3727 |
try { |
| 3728 |
optimisticDiv.setAttribute('data-' + k, val); |
| 3729 |
} catch (e2) { } |
| 3730 |
} |
| 3731 |
} |
| 3732 |
} |
| 3733 |
|
| 3734 |
let swapStyle = normalizeSwapStyle(ctx.swap); |
| 3735 |
ctx.optHidden = []; |
| 3736 |
|
| 3737 |
if (swapStyle === 'innerHTML') { |
| 3738 |
|
| 3739 |
for (let child of target.children) { |
| 3740 |
child.style.display = 'none'; |
| 3741 |
ctx.optHidden.push(child); |
| 3742 |
} |
| 3743 |
target.appendChild(optimisticDiv); |
| 3744 |
} else if (['beforebegin', 'afterbegin', 'beforeend', 'afterend'].includes(swapStyle)) { |
| 3745 |
target.insertAdjacentElement(swapStyle, optimisticDiv); |
| 3746 |
} else { |
| 3747 |
|
| 3748 |
target.style.display = 'none'; |
| 3749 |
ctx.optHidden.push(target); |
| 3750 |
target.after(optimisticDiv); |
| 3751 |
} |
| 3752 |
ctx.optimisticDiv = optimisticDiv; |
| 3753 |
htmx.process(optimisticDiv); |
| 3754 |
} |
| 3755 |
|
| 3756 |
function removeOptimisticContent(ctx) { |
| 3757 |
if (!ctx.optimisticDiv) return; |
| 3758 |
|
| 3759 |
|
| 3760 |
ctx.optimisticDiv.remove(); |
| 3761 |
|
| 3762 |
|
| 3763 |
for (let elt of ctx.optHidden) { |
| 3764 |
elt.style.display = ''; |
| 3765 |
} |
| 3766 |
} |
| 3767 |
|
| 3768 |
htmx.registerExtension('hx-optimistic', { |
| 3769 |
init: (internalAPI) => { api = internalAPI; }, |
| 3770 |
htmx_config_request: (elt, detail) => { |
| 3771 |
let body = detail.ctx.request.body; |
| 3772 |
if (body?.entries) detail.ctx.optimisticBody = body; |
| 3773 |
}, |
| 3774 |
htmx_before_request: (elt, detail) => { |
| 3775 |
insertOptimisticContent(detail.ctx); |
| 3776 |
}, |
| 3777 |
htmx_error : (elt, detail) => { |
| 3778 |
removeOptimisticContent(detail.ctx) |
| 3779 |
}, |
| 3780 |
htmx_before_swap : (elt, detail) => { |
| 3781 |
removeOptimisticContent(detail.ctx) |
| 3782 |
} |
| 3783 |
}); |
| 3784 |
})(); |
| 3785 |
|
| 3786 |
|
| 3787 |
|
| 3788 |
|
| 3789 |
|
| 3790 |
|
| 3791 |
|
| 3792 |
|
| 3793 |
|
| 3794 |
|
| 3795 |
|
| 3796 |
|
| 3797 |
(() => { |
| 3798 |
let api; |
| 3799 |
|
| 3800 |
htmx.registerExtension('hx-targets', { |
| 3801 |
init: (internalAPI) => { |
| 3802 |
api = internalAPI; |
| 3803 |
}, |
| 3804 |
htmx_before_swap: (elt, detail) => { |
| 3805 |
let {ctx, tasks} = detail; |
| 3806 |
let selector = api.attributeValue(ctx.sourceElement, 'hx-targets'); |
| 3807 |
if (!selector) return; |
| 3808 |
|
| 3809 |
let targets = htmx.findAll(ctx.sourceElement, selector); |
| 3810 |
if (!targets.length) { |
| 3811 |
console.warn(`htmx: '${selector}' on hx-targets did not match any elements`, { selector }); |
| 3812 |
return; |
| 3813 |
} |
| 3814 |
|
| 3815 |
|
| 3816 |
let mainIndex = tasks.findIndex(t => t.type === 'main'); |
| 3817 |
if (mainIndex === -1) return; |
| 3818 |
|
| 3819 |
let mainTask = tasks[mainIndex]; |
| 3820 |
let newTasks = Array.from(targets).map(target => ({ |
| 3821 |
...mainTask, |
| 3822 |
fragment: mainTask.fragment.cloneNode(true), |
| 3823 |
target |
| 3824 |
})); |
| 3825 |
|
| 3826 |
tasks.splice(mainIndex, 1, ...newTasks); |
| 3827 |
} |
| 3828 |
}); |
| 3829 |
})(); |
| 3830 |
|
| 3831 |
|
| 3832 |
|
| 3833 |
|
| 3834 |
|
| 3835 |
|
| 3836 |
(() => { |
| 3837 |
let api; |
| 3838 |
let fns = new Set(); |
| 3839 |
let pending = false; |
| 3840 |
let dbSym = Symbol(); |
| 3841 |
let observer = null; |
| 3842 |
let recomputeBound = null; |
| 3843 |
let swaps = 0; |
| 3844 |
let i = 0; |
| 3845 |
let start = 0; |
| 3846 |
let warned = false; |
| 3847 |
|
| 3848 |
const OBSERVE_OPTIONS = { childList: true, subtree: true, attributes: true, characterData: true }; |
| 3849 |
|
| 3850 |
function ensureActive() { |
| 3851 |
if (observer) return; |
| 3852 |
recomputeBound = () => schedule(); |
| 3853 |
document.addEventListener('input', recomputeBound, true); |
| 3854 |
document.addEventListener('change', recomputeBound, true); |
| 3855 |
observer = new MutationObserver(recomputeBound); |
| 3856 |
observer.observe(document.documentElement, OBSERVE_OPTIONS); |
| 3857 |
} |
| 3858 |
|
| 3859 |
function deactivate() { |
| 3860 |
if (!observer) return; |
| 3861 |
document.removeEventListener('input', recomputeBound, true); |
| 3862 |
document.removeEventListener('change', recomputeBound, true); |
| 3863 |
observer.disconnect(); |
| 3864 |
observer = null; |
| 3865 |
recomputeBound = null; |
| 3866 |
} |
| 3867 |
|
| 3868 |
function schedule() { |
| 3869 |
if (pending) return; |
| 3870 |
if (swaps > 0) return; |
| 3871 |
let now = Date.now(); |
| 3872 |
if (now - start > 1000) { |
| 3873 |
start = now; |
| 3874 |
i = 0; |
| 3875 |
warned = false; |
| 3876 |
} |
| 3877 |
if (++i > 50 && !warned) { |
| 3878 |
console.warn('htmx: hx-live recompute exceeded 50/sec.'); |
| 3879 |
warned = true; |
| 3880 |
} |
| 3881 |
pending = true; |
| 3882 |
queueMicrotask(() => { |
| 3883 |
|
| 3884 |
observer?.disconnect(); |
| 3885 |
fns.forEach(f => f()); |
| 3886 |
if (fns.size === 0) { |
| 3887 |
deactivate(); |
| 3888 |
} else { |
| 3889 |
observer.observe(document.documentElement, OBSERVE_OPTIONS); |
| 3890 |
} |
| 3891 |
pending = false; |
| 3892 |
}); |
| 3893 |
} |
| 3894 |
|
| 3895 |
let BOOLEAN_ATTRS = new Set([ |
| 3896 |
'disabled','hidden','required','readonly','open','inert', |
| 3897 |
'multiple','autofocus','novalidate','default','reversed', |
| 3898 |
'loop','muted','controls','autoplay','playsinline', |
| 3899 |
'formnovalidate','async','defer','ismap','typemustmatch', |
| 3900 |
'allowfullscreen','itemscope','nomodule' |
| 3901 |
]); |
| 3902 |
let PROPERTY_ATTRS = new Set(['checked','value','selected']); |
| 3903 |
let STRINGY_BOOLEAN_ATTRS = new Set(['contenteditable','draggable','spellcheck']); |
| 3904 |
|
| 3905 |
|
| 3906 |
|
| 3907 |
|
| 3908 |
|
| 3909 |
|
| 3910 |
|
| 3911 |
|
| 3912 |
|
| 3913 |
|
| 3914 |
|
| 3915 |
|
| 3916 |
|
| 3917 |
|
| 3918 |
|
| 3919 |
|
| 3920 |
|
| 3921 |
|
| 3922 |
|
| 3923 |
|
| 3924 |
|
| 3925 |
function applyAttr(elts, name, ...rest) { |
| 3926 |
let isClass = name.startsWith('.'); |
| 3927 |
let isMultiClass = name === 'class'; |
| 3928 |
let isAria = name.startsWith('aria-'); |
| 3929 |
let isPropAttr = PROPERTY_ATTRS.has(name); |
| 3930 |
|
| 3931 |
if (rest.length === 0) { |
| 3932 |
let e = elts[0]; |
| 3933 |
if (!e) return undefined; |
| 3934 |
if (isClass) return e.classList.contains(name.slice(1)); |
| 3935 |
if (isMultiClass) return e.getAttribute('class'); |
| 3936 |
if (isAria) return e.getAttribute(name) === 'true'; |
| 3937 |
if (BOOLEAN_ATTRS.has(name)) return e.hasAttribute(name); |
| 3938 |
if (isPropAttr) return e[name]; |
| 3939 |
return e.getAttribute(name); |
| 3940 |
} |
| 3941 |
|
| 3942 |
let value = rest[0]; |
| 3943 |
for (let e of elts) { |
| 3944 |
if (isClass) { |
| 3945 |
e.classList.toggle(name.slice(1), !!value); |
| 3946 |
if (e.classList.length === 0) e.removeAttribute('class'); |
| 3947 |
} else if (isMultiClass) { |
| 3948 |
applyMultiClass(e, value); |
| 3949 |
} else if (isAria) { |
| 3950 |
|
| 3951 |
|
| 3952 |
|
| 3953 |
let attrVal = (typeof value === 'string' || typeof value === 'number') |
| 3954 |
? String(value) |
| 3955 |
: (value ? 'true' : 'false'); |
| 3956 |
e.setAttribute(name, attrVal); |
| 3957 |
} else if (isPropAttr) { |
| 3958 |
if (value === false || value == null) { |
| 3959 |
e[name] = (typeof e[name] === 'boolean') ? false : ''; |
| 3960 |
e.removeAttribute(name); |
| 3961 |
} else if (value === true) { |
| 3962 |
e[name] = true; |
| 3963 |
e.setAttribute(name, ''); |
| 3964 |
} else { |
| 3965 |
e[name] = value; |
| 3966 |
e.setAttribute(name, String(value)); |
| 3967 |
} |
| 3968 |
} else if (BOOLEAN_ATTRS.has(name)) { |
| 3969 |
if (value) e.setAttribute(name, ''); |
| 3970 |
else e.removeAttribute(name); |
| 3971 |
} else if (STRINGY_BOOLEAN_ATTRS.has(name)) { |
| 3972 |
if (value === null || value === undefined) e.removeAttribute(name); |
| 3973 |
else if (value === true) e.setAttribute(name, 'true'); |
| 3974 |
else if (value === false) e.setAttribute(name, 'false'); |
| 3975 |
else e.setAttribute(name, String(value)); |
| 3976 |
} else { |
| 3977 |
if (value === null || value === undefined || value === false) e.removeAttribute(name); |
| 3978 |
else e.setAttribute(name, value === true ? '' : String(value)); |
| 3979 |
} |
| 3980 |
} |
| 3981 |
} |
| 3982 |
|
| 3983 |
function applyStyleBinding(elt, value) { |
| 3984 |
let prop = api.htmxProp(elt); |
| 3985 |
let oldManaged = prop.liveStyles || new Set(); |
| 3986 |
let newManaged = new Set(); |
| 3987 |
|
| 3988 |
if (typeof value === 'string') { |
| 3989 |
for (let decl of value.split(';')) { |
| 3990 |
let idx = decl.indexOf(':'); |
| 3991 |
if (idx < 0) continue; |
| 3992 |
let k = decl.slice(0, idx).trim(); |
| 3993 |
let v = decl.slice(idx + 1).trim(); |
| 3994 |
if (k) { |
| 3995 |
newManaged.add(k); |
| 3996 |
elt.style.setProperty(k, v); |
| 3997 |
} |
| 3998 |
} |
| 3999 |
} else if (value && typeof value === 'object') { |
| 4000 |
for (let [k, v] of Object.entries(value)) { |
| 4001 |
let cssProp = camelToKebab(k); |
| 4002 |
newManaged.add(cssProp); |
| 4003 |
if (v == null || v === '') elt.style.removeProperty(cssProp); |
| 4004 |
else elt.style.setProperty(cssProp, String(v)); |
| 4005 |
} |
| 4006 |
} |
| 4007 |
for (let k of oldManaged) if (!newManaged.has(k)) elt.style.removeProperty(k); |
| 4008 |
if (elt.style.length === 0) elt.removeAttribute('style'); |
| 4009 |
prop.liveStyles = newManaged; |
| 4010 |
} |
| 4011 |
|
| 4012 |
function camelToKebab(s) { |
| 4013 |
return s.replace(/[A-Z]/g, m => '-' + m.toLowerCase()); |
| 4014 |
} |
| 4015 |
|
| 4016 |
|
| 4017 |
|
| 4018 |
|
| 4019 |
function makeDataProxy(elt) { |
| 4020 |
return new Proxy({}, { |
| 4021 |
get: (_, prop) => { |
| 4022 |
if (typeof prop !== 'string') return undefined; |
| 4023 |
let kebab = camelToKebab(prop); |
| 4024 |
let ancestor = elt.closest('[data-' + kebab + ']'); |
| 4025 |
if (!ancestor) return undefined; |
| 4026 |
let raw = ancestor.dataset[prop]; |
| 4027 |
try { return JSON.parse(raw); } catch { return raw; } |
| 4028 |
}, |
| 4029 |
set: (_, prop, val) => { |
| 4030 |
if (typeof prop !== 'string') return false; |
| 4031 |
let kebab = camelToKebab(prop); |
| 4032 |
let target = elt.closest('[data-' + kebab + ']') || elt; |
| 4033 |
target.dataset[prop] = typeof val === 'string' ? val : JSON.stringify(val); |
| 4034 |
return true; |
| 4035 |
}, |
| 4036 |
has: (_, prop) => { |
| 4037 |
if (typeof prop !== 'string') return false; |
| 4038 |
let kebab = camelToKebab(prop); |
| 4039 |
return !!elt.closest('[data-' + kebab + ']'); |
| 4040 |
}, |
| 4041 |
ownKeys: () => { |
| 4042 |
let result = []; |
| 4043 |
let seen = new Set(); |
| 4044 |
for (let node = elt; node; node = node.parentElement) { |
| 4045 |
for (let key of Object.keys(node.dataset)) { |
| 4046 |
if (key !== 'htmxPowered' && !seen.has(key)) { |
| 4047 |
seen.add(key); |
| 4048 |
result.push(key); |
| 4049 |
} |
| 4050 |
} |
| 4051 |
} |
| 4052 |
return result; |
| 4053 |
}, |
| 4054 |
getOwnPropertyDescriptor: (_, prop) => { |
| 4055 |
if (typeof prop !== 'string' || prop === 'htmxPowered') return; |
| 4056 |
let kebab = camelToKebab(prop); |
| 4057 |
if (elt.closest('[data-' + kebab + ']')) return { enumerable: true, configurable: true }; |
| 4058 |
} |
| 4059 |
}); |
| 4060 |
} |
| 4061 |
|
| 4062 |
function applyMultiClass(elt, value) { |
| 4063 |
let prop = api.htmxProp(elt); |
| 4064 |
let oldManaged = prop.liveClasses || new Set(); |
| 4065 |
let newManaged = new Set(); |
| 4066 |
|
| 4067 |
if (typeof value === 'string') { |
| 4068 |
for (let c of value.trim().split(/\s+/).filter(Boolean)) { |
| 4069 |
newManaged.add(c); |
| 4070 |
elt.classList.add(c); |
| 4071 |
} |
| 4072 |
} else if (value && typeof value === 'object') { |
| 4073 |
for (let [key, cond] of Object.entries(value)) { |
| 4074 |
for (let c of key.trim().split(/\s+/).filter(Boolean)) { |
| 4075 |
newManaged.add(c); |
| 4076 |
elt.classList.toggle(c, !!cond); |
| 4077 |
} |
| 4078 |
} |
| 4079 |
} |
| 4080 |
for (let c of oldManaged) if (!newManaged.has(c)) elt.classList.remove(c); |
| 4081 |
if (elt.classList.length === 0) elt.removeAttribute('class'); |
| 4082 |
prop.liveClasses = newManaged; |
| 4083 |
} |
| 4084 |
|
| 4085 |
function applyTake(targets, name, scope) { |
| 4086 |
let isClass = name.startsWith('.'); |
| 4087 |
let key = isClass ? name.slice(1) : name; |
| 4088 |
let isAria = name.startsWith('aria-'); |
| 4089 |
let auto = isClass ? '.' + key : '[' + name + ']'; |
| 4090 |
let root = scope == null ? targets[0]?.parentElement |
| 4091 |
: scope.nodeType ? scope : null; |
| 4092 |
let sources = root |
| 4093 |
? [root, ...root.querySelectorAll(auto)] |
| 4094 |
: document.querySelectorAll(typeof scope === 'string' ? scope : scope?.from || auto); |
| 4095 |
let targetSet = new Set(targets); |
| 4096 |
for (let s of sources) { |
| 4097 |
if (targetSet.has(s)) continue; |
| 4098 |
if (isClass) { |
| 4099 |
s.classList?.remove(key); |
| 4100 |
if (s.classList?.length === 0) s.removeAttribute('class'); |
| 4101 |
} else if (isAria) { |
| 4102 |
s.setAttribute(name, 'false'); |
| 4103 |
} else { |
| 4104 |
s.removeAttribute(name); |
| 4105 |
} |
| 4106 |
} |
| 4107 |
for (let t of targets) { |
| 4108 |
if (isClass) t.classList?.add(key); |
| 4109 |
else if (isAria) t.setAttribute(name, 'true'); |
| 4110 |
else t.setAttribute(name, ''); |
| 4111 |
} |
| 4112 |
} |
| 4113 |
|
| 4114 |
function forEvent(elt, ...args) { |
| 4115 |
let target = elt || document; |
| 4116 |
for (let a of args) if (a?.nodeType) target = a; |
| 4117 |
return new Promise(resolve => { |
| 4118 |
let cleanups = [], done = false; |
| 4119 |
let fire = v => { if (done) return; done = true; for (let c of cleanups) c(); resolve(v); }; |
| 4120 |
for (let a of args) { |
| 4121 |
if (a == null || a?.nodeType) continue; |
| 4122 |
let ms = typeof a === 'number' ? a |
| 4123 |
: (typeof a === 'string' ? htmx.parseInterval(a) : undefined); |
| 4124 |
if (ms !== undefined && ms > 0) { |
| 4125 |
let id = setTimeout(() => fire(a), ms); |
| 4126 |
cleanups.push(() => clearTimeout(id)); |
| 4127 |
} else if (typeof a === 'string') { |
| 4128 |
let h = evt => fire(evt); |
| 4129 |
target.addEventListener(a, h, { once: true }); |
| 4130 |
cleanups.push(() => target.removeEventListener(a, h)); |
| 4131 |
} |
| 4132 |
} |
| 4133 |
}); |
| 4134 |
} |
| 4135 |
|
| 4136 |
|
| 4137 |
|
| 4138 |
|
| 4139 |
|
| 4140 |
|
| 4141 |
|
| 4142 |
|
| 4143 |
|
| 4144 |
|
| 4145 |
e" |
| 4146 |
|
| 4147 |
|
| 4148 |
|
| 4149 |
ot |
| 4150 |
|
| 4151 |
function applyToggle(name, values, element) { |
| 4152 |
let isClass = name.startsWith('.'); |
| 4153 |
let key = isClass ? name.slice(1) : name; |
| 4154 |
let isAria = name.startsWith('aria-'); |
| 4155 |
let asArray = values && (typeof values === 'string' |
| 4156 |
? values.split('|').map(v => v.trim()) |
| 4157 |
: values); |
| 4158 |
|
| 4159 |
if (!asArray) { |
| 4160 |
if (isClass) element.classList.toggle(key); |
| 4161 |
else if (isAria) { |
| 4162 |
let cur = element.getAttribute(name); |
| 4163 |
element.setAttribute(name, cur === 'true' ? 'false' : 'true'); |
| 4164 |
} else { |
| 4165 |
element.toggleAttribute(name); |
| 4166 |
} |
| 4167 |
return; |
| 4168 |
} |
| 4169 |
if (isClass) { |
| 4170 |
let cur = asArray.findIndex(v => v && element.classList.contains(v)); |
| 4171 |
if (cur >= 0) element.classList.remove(asArray[cur]); |
| 4172 |
let next = asArray[(cur + 1) % asArray.length]; |
| 4173 |
if (next) element.classList.add(next); |
| 4174 |
} else { |
| 4175 |
let curVal = element.getAttribute(name) ?? ''; |
| 4176 |
let cur = asArray.indexOf(curVal); |
| 4177 |
let next = asArray[(cur + 1) % asArray.length]; |
| 4178 |
if (next === '') element.removeAttribute(name); |
| 4179 |
else element.setAttribute(name, next); |
| 4180 |
} |
| 4181 |
} |
| 4182 |
|
| 4183 |
function makeDebounce() { |
| 4184 |
|
| 4185 |
let channels = new Map(); |
| 4186 |
let chan = key => channels.get(key) || (channels.set(key, { last: 0, reject: null }), channels.get(key)); |
| 4187 |
return (ms, fn) => { |
| 4188 |
let ch = chan(fn ? fn.toString() : null); |
| 4189 |
ch.reject?.(dbSym); |
| 4190 |
ch.reject = null; |
| 4191 |
let id = ++ch.last; |
| 4192 |
if (fn) { |
| 4193 |
setTimeout(() => id === ch.last && fn(), ms); |
| 4194 |
return; |
| 4195 |
} |
| 4196 |
return new Promise((res, rej) => { |
| 4197 |
ch.reject = rej; |
| 4198 |
setTimeout(() => { |
| 4199 |
if (id !== ch.last) return; |
| 4200 |
ch.reject = null; |
| 4201 |
res(); |
| 4202 |
}, ms); |
| 4203 |
}); |
| 4204 |
}; |
| 4205 |
} |
| 4206 |
|
| 4207 |
function getDebounce(elt) { |
| 4208 |
let prop = api.htmxProp(elt); |
| 4209 |
return prop.debounce || (prop.debounce = makeDebounce()); |
| 4210 |
} |
| 4211 |
|
| 4212 |
function makeQ(ctx, defaultRoot = document) { |
| 4213 |
return selectorOrElt => { |
| 4214 |
if (typeof selectorOrElt !== 'string') { |
| 4215 |
return qProxy( |
| 4216 |
selectorOrElt?.nodeType ? [selectorOrElt] : [...(selectorOrElt || [])] |
| 4217 |
); |
| 4218 |
} |
| 4219 |
let sel = selectorOrElt; |
| 4220 |
let inMatch = sel.match(/^(.+)\s+in\s+(.+)$/); |
| 4221 |
let roots = [defaultRoot]; |
| 4222 |
if (inMatch) { |
| 4223 |
sel = inMatch[1]; |
| 4224 |
if (inMatch[2] === 'this' || inMatch[2] === 'me') { |
| 4225 |
roots = [ctx]; |
| 4226 |
} else { |
| 4227 |
roots = [...document.querySelectorAll(inMatch[2])]; |
| 4228 |
} |
| 4229 |
} |
| 4230 |
if (!roots.length) return qProxy([]); |
| 4231 |
let qsa = s => { |
| 4232 |
if (roots.length === 1) return [...roots[0].querySelectorAll(s)]; |
| 4233 |
let out = [], seen = new Set(); |
| 4234 |
for (let r of roots) for (let e of r.querySelectorAll(s)) { |
| 4235 |
if (!seen.has(e)) { seen.add(e); out.push(e); } |
| 4236 |
} |
| 4237 |
return out.sort((a, b) => a.compareDocumentPosition(b) & 4 ? -1 : 1); |
| 4238 |
}; |
| 4239 |
let dirMatch = sel.match(/^(next|previous|closest|first|last)\s+(.+)$/); |
| 4240 |
let elts; |
| 4241 |
if (dirMatch) { |
| 4242 |
let [, dir, s] = dirMatch; |
| 4243 |
let cdp = e => ctx.compareDocumentPosition(e); |
| 4244 |
if (dir === 'closest') { |
| 4245 |
let c = ctx.closest?.(s); |
| 4246 |
elts = c ? [c] : []; |
| 4247 |
} else { |
| 4248 |
let all = qsa(s); |
| 4249 |
if (dir === 'first') elts = all.slice(0, 1); |
| 4250 |
else if (dir === 'last') elts = all.slice(-1); |
| 4251 |
else if (dir === 'next') { |
| 4252 |
let n = all.find(e => cdp(e) & 4); |
| 4253 |
elts = n ? [n] : []; |
| 4254 |
} else { |
| 4255 |
let p = all.reverse().find(e => cdp(e) & 2); |
| 4256 |
elts = p ? [p] : []; |
| 4257 |
} |
| 4258 |
} |
| 4259 |
} else { |
| 4260 |
elts = qsa(sel); |
| 4261 |
} |
| 4262 |
return qProxy(elts); |
| 4263 |
}; |
| 4264 |
} |
| 4265 |
|
| 4266 |
let arrayMethods = new Set(['map', 'filter', 'reduce', 'reduceRight', 'forEach', 'some', 'every', |
| 4267 |
'find', 'findIndex', 'findLast', 'findLastIndex', 'flatMap', 'flat', |
| 4268 |
'slice', 'indexOf', 'lastIndexOf', 'includes', 'join', 'at']); |
| 4269 |
|
| 4270 |
let positions = { before: 'beforebegin', after: 'afterend', start: 'afterbegin', end: 'beforeend' }; |
| 4271 |
|
| 4272 |
function qProxy(elts) { |
| 4273 |
let proxy = new Proxy({}, { |
| 4274 |
get: (_, p) => { |
| 4275 |
if (p === 'count') return elts.length; |
| 4276 |
if (p === 'arr') return () => elts.slice(); |
| 4277 |
if (p === Symbol.iterator) return () => elts.values(); |
| 4278 |
if (p === 'q') return s => { |
| 4279 |
let out = new Set(); |
| 4280 |
for (let e of elts) for (let r of makeQ(e, e)(s).arr()) out.add(r); |
| 4281 |
return qProxy([...out]); |
| 4282 |
}; |
| 4283 |
if (p === 'trigger') return (t, d, b) => { elts.forEach(e => htmx.trigger(e, t, d, b)); return proxy; }; |
| 4284 |
if (p === 'insert') return (pos, s) => { elts.forEach(e => e.insertAdjacentHTML(positions[pos], s)); return proxy; }; |
| 4285 |
if (p === 'take') return (name, scope) => { applyTake(elts, name, scope); return proxy; }; |
| 4286 |
if (p === 'toggle') return (name, values) => { elts.forEach(e => applyToggle(name, values, e)); return proxy; }; |
| 4287 |
if (p === 'attr') return (name, ...rest) => { |
| 4288 |
if (rest.length === 0) return applyAttr(elts, name); |
| 4289 |
applyAttr(elts, name, ...rest); |
| 4290 |
return proxy; |
| 4291 |
}; |
| 4292 |
if (p === 'data') return elts[0] ? makeDataProxy(elts[0]) : undefined; |
| 4293 |
if (arrayMethods.has(p)) return elts[p].bind(elts); |
| 4294 |
let v = elts[0]?.[p]; |
| 4295 |
if (typeof v === 'function') return (...a) => elts.map(e => e[p](...a))[0]; |
| 4296 |
if (v && typeof v === 'object') return qProxy(elts.map(e => e[p])); |
| 4297 |
return v; |
| 4298 |
}, |
| 4299 |
set: (_, p, v) => { |
| 4300 |
elts.forEach(e => e[p] = v); |
| 4301 |
schedule(); |
| 4302 |
return true; |
| 4303 |
} |
| 4304 |
}); |
| 4305 |
return proxy; |
| 4306 |
} |
| 4307 |
|
| 4308 |
let liveQuery, bindPrefixes, bodyAttrs; |
| 4309 |
|
| 4310 |
function buildLiveQuery() { |
| 4311 |
let mc = htmx.config.metaCharacter || ':'; |
| 4312 |
let p = htmx.config.prefix; |
| 4313 |
bindPrefixes = ['hx-live' + mc]; |
| 4314 |
if (p) bindPrefixes.push(p + 'live' + mc); |
| 4315 |
let extra = htmx.config.live?.bindPrefix; |
| 4316 |
if (extra === undefined) { |
| 4317 |
if (window.Alpine) { |
| 4318 |
extra = ''; |
| 4319 |
console.warn('hx-live: Alpine.js detected — ":" short-form bindings disabled. Set htmx.config.live.bindPrefix to configure.'); |
| 4320 |
} else { |
| 4321 |
extra = ':'; |
| 4322 |
} |
| 4323 |
} |
| 4324 |
if (extra) bindPrefixes.push(extra); |
| 4325 |
bodyAttrs = ['hx-live']; |
| 4326 |
if (p) bodyAttrs.push(p + 'live'); |
| 4327 |
let bind = bindPrefixes.map(bp => `starts-with(name(), "${bp}")`).join(' or '); |
| 4328 |
let body = bodyAttrs.map(n => `@${n}`).join(' or '); |
| 4329 |
liveQuery = new XPathEvaluator().createExpression(`.//*[@*[${bind}] or ${body}]`); |
| 4330 |
} |
| 4331 |
|
| 4332 |
function extractBindingName(attrName) { |
| 4333 |
for (let p of bindPrefixes) { |
| 4334 |
if (attrName.startsWith(p) && attrName.length > p.length) return attrName.slice(p.length); |
| 4335 |
} |
| 4336 |
} |
| 4337 |
|
| 4338 |
function cleanupLive(elt) { |
| 4339 |
let prop = elt._htmx; |
| 4340 |
if (!prop?.liveRuns) return; |
| 4341 |
for (let run of prop.liveRuns) fns.delete(run); |
| 4342 |
delete prop.liveRuns; |
| 4343 |
delete prop.liveRegistered; |
| 4344 |
delete prop.liveAttrs; |
| 4345 |
} |
| 4346 |
|
| 4347 |
function processElement(elt) { |
| 4348 |
if (elt.closest('[hx-ignore]')) return; |
| 4349 |
let prop = api.htmxProp(elt); |
| 4350 |
if (!prop.liveRegistered) { |
| 4351 |
let bodyAttr = bodyAttrs.find(n => elt.hasAttribute(n)); |
| 4352 |
if (bodyAttr) { |
| 4353 |
prop.liveRegistered = true; |
| 4354 |
ensureActive(); |
| 4355 |
let code = elt.getAttribute(bodyAttr) |
| 4356 |
let debounce = getDebounce(elt); |
| 4357 |
let run = async () => { |
| 4358 |
if (!elt.isConnected) { |
| 4359 |
fns.delete(run); |
| 4360 |
return; |
| 4361 |
} |
| 4362 |
try { |
| 4363 |
await api.executeJavaScript(elt, { debounce }, code, false); |
| 4364 |
} catch (e) { |
| 4365 |
if (e !== dbSym) console.error('htmx: hx-live expression threw', e, { elt }); |
| 4366 |
} |
| 4367 |
}; |
| 4368 |
fns.add(run); |
| 4369 |
prop.liveRuns = prop.liveRuns || new Set(); |
| 4370 |
prop.liveRuns.add(run); |
| 4371 |
run(); |
| 4372 |
} |
| 4373 |
} |
| 4374 |
prop.liveAttrs ||= new Set(); |
| 4375 |
for (let a of elt.attributes) { |
| 4376 |
let name = extractBindingName(a.name); |
| 4377 |
if (!name || prop.liveAttrs.has(name)) continue; |
| 4378 |
prop.liveAttrs.add(name); |
| 4379 |
registerSimpleLive(elt, name, a.value); |
| 4380 |
} |
| 4381 |
} |
| 4382 |
|
| 4383 |
function processLive(root) { |
| 4384 |
if (!liveQuery) buildLiveQuery(); |
| 4385 |
if (root.nodeType === 1) processElement(root); |
| 4386 |
let iter = liveQuery.evaluate(root), node, nodes = []; |
| 4387 |
while (node = iter.iterateNext()) nodes.push(node); |
| 4388 |
for (node of nodes) processElement(node); |
| 4389 |
} |
| 4390 |
|
| 4391 |
function registerSimpleLive(elt, attrName, code) { |
| 4392 |
ensureActive(); |
| 4393 |
let debounce = getDebounce(elt); |
| 4394 |
let isAsync = /\bawait\b/.test(code); |
| 4395 |
let run = isAsync ? async () => { |
| 4396 |
if (!elt.isConnected) { |
| 4397 |
fns.delete(run); |
| 4398 |
return; |
| 4399 |
} |
| 4400 |
try { |
| 4401 |
let value = await api.executeJavaScript(elt, { debounce }, code, true); |
| 4402 |
writeAttrBinding(elt, attrName, value); |
| 4403 |
observer?.takeRecords(); |
| 4404 |
} catch (e) { |
| 4405 |
if (e !== dbSym) console.error('htmx: hx-live expression threw', e, { elt, attr: attrName }); |
| 4406 |
} |
| 4407 |
} : () => { |
| 4408 |
if (!elt.isConnected) { |
| 4409 |
fns.delete(run); |
| 4410 |
return; |
| 4411 |
} |
| 4412 |
try { |
| 4413 |
let value = api.executeJavaScript(elt, { debounce }, code, true, false); |
| 4414 |
writeAttrBinding(elt, attrName, value); |
| 4415 |
} catch (e) { |
| 4416 |
if (e !== dbSym) console.error('htmx: hx-live expression threw', e, { elt, attr: attrName }); |
| 4417 |
} |
| 4418 |
}; |
| 4419 |
fns.add(run); |
| 4420 |
let prop = api.htmxProp(elt); |
| 4421 |
prop.liveRuns = prop.liveRuns || new Set(); |
| 4422 |
prop.liveRuns.add(run); |
| 4423 |
run(); |
| 4424 |
} |
| 4425 |
|
| 4426 |
function writeAttrBinding(elt, attrName, value) { |
| 4427 |
if (attrName === 'text') { elt.textContent = value == null ? '' : String(value); return; } |
| 4428 |
if (attrName === 'html') { elt.innerHTML = value == null ? '' : String(value); return; } |
| 4429 |
if (attrName === 'style') { applyStyleBinding(elt, value); return; } |
| 4430 |
r. |
| 4431 |
applyAttr([elt], attrName, value); |
| 4432 |
} |
| 4433 |
|
| 4434 |
let asTargets = t => t == null ? [] |
| 4435 |
: typeof t === 'string' ? document.querySelectorAll(t) |
| 4436 |
: t.nodeType ? [t] |
| 4437 |
: t; |
| 4438 |
|
| 4439 |
htmx.live = { |
| 4440 |
q: s => makeQ(document.documentElement)(s), |
| 4441 |
debounce: makeDebounce(), |
| 4442 |
refresh: () => schedule(), |
| 4443 |
take: (target, name, scope) => applyTake([...asTargets(target)], name, scope), |
| 4444 |
toggle: (target, name, values) => [...asTargets(target)].forEach(e => applyToggle(name, values, e)), |
| 4445 |
attr: (target, name, ...rest) => applyAttr([...asTargets(target)], name, ...rest), |
| 4446 |
forEvent: (...args) => forEvent(null, ...args), |
| 4447 |
nextFrame: () => new Promise(r => requestAnimationFrame(r)) |
| 4448 |
}; |
| 4449 |
|
| 4450 |
htmx.registerExtension('hx-live', { |
| 4451 |
init: (internalAPI) => { |
| 4452 |
api = internalAPI; |
| 4453 |
}, |
| 4454 |
htmx_before_cleanup: (elt) => { |
| 4455 |
cleanupLive(elt); |
| 4456 |
}, |
| 4457 |
htmx_before_morph_attr: (elt, detail) => { |
| 4458 |
if (bindPrefixes.some(p => detail.attrName.startsWith(p))) cleanupLive(elt); |
| 4459 |
}, |
| 4460 |
htmx_after_process: (elt) => { |
| 4461 |
processLive(elt); |
| 4462 |
}, |
| 4463 |
htmx_before_swap: () => { |
| 4464 |
swaps++; |
| 4465 |
}, |
| 4466 |
htmx_swap_finally: () => { |
| 4467 |
if (--swaps === 0 && fns.size > 0) schedule(); |
| 4468 |
}, |
| 4469 |
htmx_scope: (elt, detail) => { |
| 4470 |
Object.assign(detail.scope, { |
| 4471 |
q: makeQ(elt), |
| 4472 |
forEvent: (...args) => forEvent(elt, ...args), |
| 4473 |
nextFrame: () => new Promise(r => requestAnimationFrame(r)), |
| 4474 |
trigger: (type, detail, bubbles) => htmx.trigger(elt, type, detail, bubbles), |
| 4475 |
debounce: getDebounce(elt), |
| 4476 |
take: (name, scope) => applyTake([elt], name, scope), |
| 4477 |
toggle: (name, values) => applyToggle(name, values, elt), |
| 4478 |
attr: (name, ...rest) => applyAttr([elt], name, ...rest), |
| 4479 |
insert: (pos, html) => elt.insertAdjacentHTML(positions[pos], html), |
| 4480 |
matches: (sel) => elt.matches(sel), |
| 4481 |
style: elt.style, |
| 4482 |
classList: elt.classList, |
| 4483 |
data: makeDataProxy(elt) |
| 4484 |
}); |
| 4485 |
} |
| 4486 |
}); |
| 4487 |
})(); |