@fefade/svelte
Version:
Reusable Svelte UI components powered by the FEFADE core system.
57 lines (56 loc) • 1.69 kB
JavaScript
const data = $state({
sections: [],
currentReference: ""
});
export default function scrollSectionState() {
return {
set(sections) {
data.sections = sections;
},
setCurrentReference(reference) {
data.currentReference = reference;
},
register(node, reference) {
if (this.getByReference(reference))
return;
this.set([...data.sections, { node, reference }]);
},
getAll() {
return data.sections;
},
getCurrentReference() {
return data.currentReference;
},
getByReference(reference) {
return data.sections.find((s) => s.reference === reference);
},
scrollTo(reference) {
const section = this.getByReference(reference);
if (section?.node) {
section.node.scrollIntoView({
behavior: "smooth"
});
this.setCurrentReference(reference);
}
},
getSections() {
return data.sections.map(({ node, reference }) => ({
node,
reference,
onClick: () => this.scrollTo(reference),
isActive: data.currentReference === reference
}));
},
clear() {
this.set([]);
this.setCurrentReference("");
},
unregister(reference) {
this.set(data.sections.filter((s) => s.reference !== reference));
}
};
}
export function getSections() {
const scrollSection = scrollSectionState();
return scrollSection.getSections();
}