Created
February 22, 2023 14:18
-
-
Save alexbezhan/2d3515e1a5b2a2029e3b32e8c2916480 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```js | |
htmx.onLoad(function (content) { | |
const attr = 'lr-post'; | |
const httpMethod = 'POST'; | |
const controlElts = content.querySelectorAll(`[${attr}]`); | |
for (const controlElt of controlElts) { | |
const link = controlElt.getAttribute && controlElt.getAttribute(attr); | |
if (link === undefined) { | |
continue | |
} | |
controlElt.addEventListener('click', async function onClick(elt) { | |
const paramsValue = controlElt.getAttribute && controlElt.getAttribute('lr-params'); | |
const paramsValueArr = paramsValue.split(','); | |
const params = new URLSearchParams() | |
for (const name of paramsValueArr) { | |
const nameClean = name.trim(); | |
const paramElt = document.getElementsByName(nameClean)[0]; | |
let shouldInclude = false; | |
if (paramElt.type === 'checkbox' || paramElt.type === 'radio') { | |
shouldInclude = paramElt.checked; | |
} | |
if (shouldInclude) { | |
params.append(name, paramElt.value); | |
} | |
} | |
const request = new Request(link, { | |
method: httpMethod, | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded', | |
}, | |
body: params, | |
}); | |
const response = await fetch(request); | |
const responseText = await response.text(); | |
if (!response.ok) { | |
throw new Error(responseText); | |
} | |
let parser = new DOMParser(); | |
let responseDoc = parser.parseFromString(`<body><template>${responseText}</template></body>`, 'text/html'); | |
let responseFragment = responseDoc.body.firstChild.content; | |
for (let i = 0; i < responseFragment.children.length; i++) { | |
const responseElt = responseFragment.children[i]; | |
const swapOobAttr = responseElt.getAttribute && responseElt.getAttribute('hx-swap-oob'); | |
if (swapOobAttr === undefined || swapOobAttr === null || swapOobAttr.length === 0) { | |
continue; | |
} | |
const [swapStrategy, destSelector] = swapOobAttr.split(':'); | |
if (swapStrategy === 'outerHTML') { | |
let existingElt | |
if (destSelector.at(0) === '#') { | |
existingElt = document.getElementById(destSelector.slice(1)); | |
} else { | |
console.error(`Unsupported selector: ${destSelector}`); | |
continue | |
} | |
Idiomorph.morph(existingElt, responseElt.cloneNode(true)); | |
} | |
} | |
}); | |
} | |
}) | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment