UNPKG

@eslamdevui/ui

Version:

A UI Library for Modern Web Apps, powered by Vue & Tailwind CSS.

39 lines (38 loc) 1.08 kB
import { ref, watch, onBeforeMount, onBeforeUnmount } from "vue"; export function useScrollspy() { const observer = ref(null); const visibleHeadings = ref([]); const activeHeadings = ref([]); function observerCallback(entries) { entries.forEach((entry) => { const id = entry.target.id; if (!id) return; if (entry.isIntersecting) { if (!visibleHeadings.value.includes(id)) { visibleHeadings.value = [...visibleHeadings.value, id]; } } else { visibleHeadings.value = visibleHeadings.value.filter((h) => h !== id); } }); } function updateHeadings(headings) { headings.forEach((heading) => { observer.value?.observe(heading); }); } watch(visibleHeadings, (val, oldVal) => { activeHeadings.value = val.length === 0 ? oldVal : val; }); onBeforeMount(() => { observer.value = new IntersectionObserver(observerCallback); }); onBeforeUnmount(() => { observer.value?.disconnect(); }); return { visibleHeadings, activeHeadings, updateHeadings }; }