| 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 |
; |