Files
once-campfire/app/javascript/helpers/dom_helpers.js
Kevin McConnell df76a227dc Hello world
First open source release of Campfire 🎉
2025-08-21 09:31:59 +01:00

66 lines
1.4 KiB
JavaScript

export function scrollToBottom(container) {
container.scrollTop = container.scrollHeight
}
export function escapeHTML(html) {
const div = document.createElement("div")
div.textContent = html
return div.innerHTML
}
export function parseHTMLFragment(html) {
const template = document.createElement("template")
template.innerHTML = html
return template.content
}
export function insertHTMLFragment(fragment, container, top) {
if (top) {
container.prepend(fragment)
} else {
container.append(fragment)
}
}
export function ignoringBriefDisconnects(element, fn) {
requestAnimationFrame(() => {
if (!element.isConnected) fn()
})
}
export function trimChildren(count, container, top) {
const children = Array.from(container.children)
const elements = top ? children.slice(0, count) : children.slice(-count)
keepScroll(container, top, function() {
for (const element of elements) {
element.remove()
}
})
}
export async function keepScroll(container, top, fn) {
pauseInertiaScroll(container)
const scrollTop = container.scrollTop
const scrollHeight = container.scrollHeight
await fn()
if (top) {
container.scrollTop = scrollTop + (container.scrollHeight - scrollHeight)
} else {
container.scrollTop = scrollTop
}
}
function pauseInertiaScroll(container) {
container.style.overflow = "hidden"
requestAnimationFrame(() => {
container.style.overflow = ""
})
}