Created
September 7, 2024 04:12
-
-
Save trusktr/50df9726639cddb9e400a47dd105865a to your computer and use it in GitHub Desktop.
DOM signals
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
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 | |
} |
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
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