Skip to content

Instantly share code, notes, and snippets.

@trusktr
Created September 7, 2024 04:12
Show Gist options
  • Save trusktr/50df9726639cddb9e400a47dd105865a to your computer and use it in GitHub Desktop.
Save trusktr/50df9726639cddb9e400a47dd105865a to your computer and use it in GitHub Desktop.
DOM signals
import {createMemo} from 'solid-js'
import {elementMutations} from './elementMutations.js'
import {createArrayMemo} from './createArrayMemo.js'
export function childElements(element: Element | (() => Element | undefined | null)) {
const records = elementMutations(element, {childList: true})
const elMemo = createMemo(() => (typeof element === 'function' ? element() : element))
const elements = createArrayMemo(() => {
const el = elMemo()
if (!el) return [] as Element[]
records()
return Array.from(el.children)
})
return elements
}
import {createEffect, createMemo, createSignal, onCleanup} from 'solid-js'
export function elementMutations(element: Element | (() => Element | undefined | null), options: MutationObserverInit) {
const [records, setRecords] = createSignal<MutationRecord[]>([])
const elMemo = createMemo(() => (typeof element === 'function' ? element() : element))
createEffect(() => {
const el = elMemo()
if (!el) return
const observer = new MutationObserver(setRecords)
observer.observe(el, options)
onCleanup(() => observer.disconnect())
})
return records
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment