Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/react/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export { usePreviousValue } from './usePreviousValue';
export { useResizeObserver } from './useResizeObserver';
export { useScrollDirection } from './useScrollDirection';
export { useScrollLock } from './useScrollLock';
export { useScrollSpy } from './useScrollSpy';
export { useScrollSync } from './useScrollSync';
export { useSessionStorage } from './useSessionStorage';
export { useSticky } from './useSticky';
Expand Down
1 change: 1 addition & 0 deletions packages/react/src/hooks/useScrollSpy/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useScrollSpy } from './useScrollSpy';
26 changes: 26 additions & 0 deletions packages/react/src/hooks/useScrollSpy/useScrollSpy.api.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Meta } from '@storybook/addon-docs';
import LinkTo from '@storybook/addon-links/react';
import { TableFunction } from '~storybook/components/TableFunction';

<Meta title="Hooks API/useScrollSpy" />

# useScrollSpy API

```js
import { useScrollSpy } from '@elonkit/react';
```

<TableFunction name="useScrollSpy" />

<br />
<br />

## Demos

<ul>
<li>
<LinkTo kind="hooks-useScrollSpy" story="demo">
<code>useScrollSpy</code>
</LinkTo>
</li>
</ul>
74 changes: 74 additions & 0 deletions packages/react/src/hooks/useScrollSpy/useScrollSpy.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { useRef } from 'react';

import { Meta, StoryObj } from '@storybook/react';

import { useScrollSpy } from './useScrollSpy';

import { Button } from '../../components';

const sections = ['1', '2', '3', '4', '5'];

const meta: Meta = {
tags: ['autodocs'],
title: 'Hooks/useScrollSpy',
parameters: {
references: ['useScrollSpy'],
},
};

export default meta;

type Story = StoryObj;

export const Demo: Story = {
render: function Render() {
const containerRef = useRef<HTMLDivElement | null>(null);

const isDocsPage = window.location.href.includes('docs');

const activeId = useScrollSpy(sections, {
...(containerRef.current ? { root: containerRef.current } : {}),
});

return (
<div
className="flex flex-col"
style={{
maxHeight: isDocsPage ? '40dvh' : undefined,
margin: '-1rem',
}}
>
<div
className="flex flex-row"
style={{ position: 'sticky', top: 0, backgroundColor: 'var(--es-surface-50)', zIndex: 2 }}
>
{sections.map((section) => (
<Button
key={section}
color={activeId === section ? 'primary' : 'tertiary'}
style={{ borderRadius: 0 }}
variant="contained"
>
{section}
</Button>
))}
</div>
<div ref={containerRef}>
{sections.map((section, index) => (
<section
key={section}
className="px-16 py-16"
id={section}
style={{
height: '101vh',
backgroundColor: index % 2 === 0 ? 'var(--es-mono-a-a100)' : 'var(--es-mono-a-a50)',
}}
>
{section}
</section>
))}
</div>
</div>
);
},
};
38 changes: 38 additions & 0 deletions packages/react/src/hooks/useScrollSpy/useScrollSpy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { useEffect, useState } from 'react';

import { useCallbackThrottle } from '../useCallbackThrottle';
import { useEvent } from '../useEvent';

/**
* The hook that observes the intersection of elements with an ancestor or viewport and determines the active one.
* @param items An array of ids of elements to be observed.
* @param options An options object allowing you to set options for the observation.
* @param throttleDelay The time in milliseconds used to throttle the observation.
*/
export const useScrollSpy = (items: string[], options?: IntersectionObserverInit, throttleDelay = 0): string => {
const [activeElementId, setActiveElementId] = useState('');

const callback = useEvent(
useCallbackThrottle((entries: IntersectionObserverEntry[]) => {
entries.forEach((e) => e.isIntersecting && setActiveElementId(e.target.id));
}, throttleDelay)
);

useEffect(() => {
const observer = new IntersectionObserver(callback, options);

items.forEach((id) => {
const element = document.getElementById(id);

if (element) {
observer.observe(element);
}
});

return () => {
observer.disconnect();
};
}, [items]);

return activeElementId;
};
Loading