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
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
'use client';

import { Children, RefAttributes, useRef, useState } from 'react';
import { Children, RefAttributes, useState } from 'react';

import { FiltersFormGroupProps } from './FiltersFormGroup.types';

import { OverlayScrollbarsComponentRef } from 'overlayscrollbars-react';

import clsx from 'clsx';

import { useBoolean, useResizeObserver } from '../../../hooks';
import { useBoolean, useScrollPosition } from '../../../hooks';
import { useDefaultProps } from '../../../theming';
import { Link } from '../../Link';
import { OverlayScrollbars } from '../../OverlayScrollbars';
Expand All @@ -24,63 +24,29 @@ export const FiltersFormGroup = ({ ref: inRef, ...inProps }: FiltersFormGroupPro

const [open, toggleOpen] = useBoolean(false);

const [isScrollable, setScrollable] = useState(false);
const [isBeforeScroll, setBeforeScroll] = useState(false);
const [isAfterScroll, setAfterScroll] = useState(true);

const ref = useRef<OverlayScrollbarsComponentRef | null>(null);

// The viewport is published from `onInitialized` rather than read off the ref during render, which
// would have made the observed element depend on a value that cannot trigger a re-render.
const [viewport, setViewport] = useState<HTMLElement | null>(null);

useResizeObserver({ current: viewport }, () => {
if (viewport) {
setScrollable(viewport.scrollHeight > viewport.clientHeight);
}
});
const { isScrollableY, isAtTop, isAtBottom } = useScrollPosition({ current: viewport });

const onInitialized = (instance: NonNullable<ReturnType<OverlayScrollbarsComponentRef['osInstance']>>) => {
const element = instance.elements().viewport;

setViewport(element ?? null);

if (element) {
setScrollable(element.scrollHeight > element.clientHeight);
}
};

const onScroll = () => {
if (!ref.current) {
return;
}

const element = ref.current.osInstance()?.elements().viewport;

if (!element) {
return;
}

const { scrollTop, scrollHeight, clientHeight } = element;
setBeforeScroll(scrollTop > 0);
setAfterScroll(!(scrollTop >= scrollHeight - clientHeight));
setViewport(instance.elements().viewport ?? null);
};

return (
<div ref={inRef} className={clsx('es-filters-form-group', className)} style={style}>
{!!header && <div className="es-filters-form-group__header">{header}</div>}
<OverlayScrollbars
ref={ref}
className={clsx(
'es-filters-form-group__content',
isScrollable && 'es-filters-form-group__content--scrollable',
isBeforeScroll && 'es-filters-form-group__content--scroll-before',
isAfterScroll && 'es-filters-form-group__content--scroll-after'
isScrollableY && 'es-filters-form-group__content--scrollable',
!isAtTop && 'es-filters-form-group__content--scroll-before',
!isAtBottom && 'es-filters-form-group__content--scroll-after'
)}
color="mono-a"
events={{
initialized: onInitialized,
scroll: onScroll,
}}
>
{!!maxLines && !open ? Children.toArray(children).slice(0, maxLines) : children}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
'use client';

import { RefAttributes, useRef, useState } from 'react';
import { RefAttributes, useState } from 'react';

import { SidebarScrollableProps } from './SidebarScrollable.types';

import { OverlayScrollbarsComponentRef } from 'overlayscrollbars-react';

import clsx from 'clsx';

import { useForkRef, useResizeObserver } from '../../../hooks';
import { useScrollPosition } from '../../../hooks';
import { useDefaultProps } from '../../../theming';
import { OverlayScrollbars } from '../..//OverlayScrollbars';

Expand All @@ -24,72 +24,38 @@ export const SidebarScrollable = ({
name: 'ESSidebarScrollable',
});

const [isScrollable, setScrollable] = useState(false);
const [isBeforeScroll, setBeforeScroll] = useState(false);
const [isAfterScroll, setAfterScroll] = useState(true);

const ref = useRef<OverlayScrollbarsComponentRef | null>(null);
const rootRef = useForkRef(ref, inRef);

// The viewport is published from `onInitialized` rather than read off the ref during render, which
// would have made the observed element depend on a value that cannot trigger a re-render.
const [viewport, setViewport] = useState<HTMLElement | null>(null);

useResizeObserver({ current: viewport }, () => {
if (viewport) {
setScrollable(viewport.scrollHeight > viewport.clientHeight);
}
});
const { isScrollableY, isAtTop, isAtBottom } = useScrollPosition({ current: viewport });

const onInitialized = (instance: NonNullable<ReturnType<OverlayScrollbarsComponentRef['osInstance']>>) => {
const element = instance.elements().viewport;

setViewport(element ?? null);

if (element) {
setScrollable(element.scrollHeight > element.clientHeight);
}
};

const onScroll = () => {
if (!ref.current) {
return;
}

const element = ref.current.osInstance()?.elements().viewport;

if (!element) {
return;
}

const { scrollTop, scrollHeight, clientHeight } = element;
setBeforeScroll(scrollTop > 0);
setAfterScroll(!(scrollTop >= scrollHeight - clientHeight));
setViewport(instance.elements().viewport ?? null);
};

return (
<>
{isScrollable && beforeScroll}
{isScrollableY && beforeScroll}
<OverlayScrollbars
ref={rootRef}
ref={inRef}
className={clsx(
'es-sidebar-scrollable',
isScrollable && 'es-sidebar-scrollable--scrollable',
isBeforeScroll && 'es-sidebar-scrollable--scroll-before',
isAfterScroll && 'es-sidebar-scrollable--scroll-after',
isScrollableY && 'es-sidebar-scrollable--scrollable',
!isAtTop && 'es-sidebar-scrollable--scroll-before',
!isAtBottom && 'es-sidebar-scrollable--scroll-after',
className
)}
color="mono-a"
events={{
initialized: onInitialized,
scroll: onScroll,
}}
style={style}
tabIndex={-1}
>
{children}
</OverlayScrollbars>
{isScrollable && afterScroll}
{isScrollableY && afterScroll}
</>
);
};
2 changes: 2 additions & 0 deletions packages/react/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ export { usePreviousValue } from './usePreviousValue';
export { useResizeObserver } from './useResizeObserver';
export { useScrollDirection } from './useScrollDirection';
export { useScrollLock } from './useScrollLock';
export type { UseScrollPositionOptions, UseScrollPositionResult } from './useScrollPosition';
export { useScrollPosition } from './useScrollPosition';
export { useScrollSpy } from './useScrollSpy';
export { useScrollSync } from './useScrollSync';
export { useSessionStorage } from './useSessionStorage';
Expand Down
2 changes: 2 additions & 0 deletions packages/react/src/hooks/useScrollPosition/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export type { UseScrollPositionOptions, UseScrollPositionResult } from './useScrollPosition';
export { useScrollPosition } from './useScrollPosition';
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Meta } from '@storybook/addon-docs/blocks';
import LinkTo from '@storybook/addon-links/react';
import { TableFunction } from '~storybook/components/TableFunction';

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

# useScrollPosition API

```js
import { useScrollPosition } from '@esfront/react';
```

<TableFunction name="useScrollPosition" />

<br />

<br />

## Demos

<ul>
<li>
<LinkTo kind="hooks-useScrollPosition" story="demo">
<code>useScrollPosition</code>
</LinkTo>
</li>
</ul>
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { CSSProperties, useRef, useState } from 'react';

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

import { useScrollPosition } from './useScrollPosition';

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

type Args = { threshold?: number };

const meta: Meta = {
tags: ['autodocs'],
title: 'Hooks/useScrollPosition',
parameters: {
references: ['useScrollPosition'],
},
argTypes: {
threshold: {
control: {
type: 'number',
},
},
},
};

export default meta;

type Story = StoryObj<Args>;

const SHADOW_SIZE = 24;

const getShadow = (direction: string, isVisible: boolean): CSSProperties => ({
position: 'absolute',
inset: 0,
pointerEvents: 'none',
opacity: isVisible ? 1 : 0,
transition: 'opacity 150ms',
background: `linear-gradient(to ${direction}, var(--es-mono-a-a150), transparent ${SHADOW_SIZE}px)`,
});

export const Demo: Story = {
render: function Render(args) {
const ref = useRef<HTMLDivElement | null>(null);
const [rows, setRows] = useState(8);

const { isScrollableX, isScrollableY, isAtLeft, isAtRight, isAtTop, isAtBottom } = useScrollPosition(ref, {
threshold: args.threshold,
});

return (
<div className="flex flex-col gap-16" style={{ maxWidth: '400px' }}>
<div style={{ position: 'relative' }}>
<div
ref={ref}
style={{
height: '200px',
overflow: 'auto',
border: '1px solid var(--es-mono-a-a150)',
borderRadius: '4px',
}}
>
{Array.from({ length: rows }, (_, index) => (
<div key={index} className="body100" style={{ padding: '8px 16px', whiteSpace: 'nowrap' }}>
Row {index + 1} — scroll both axes to see the flags change
</div>
))}
</div>
<div style={getShadow('bottom', isScrollableY && !isAtTop)} />
<div style={getShadow('top', isScrollableY && !isAtBottom)} />
<div style={getShadow('right', isScrollableX && !isAtLeft)} />
<div style={getShadow('left', isScrollableX && !isAtRight)} />
</div>
<div className="body100">
<div>isScrollableX: {isScrollableX.toString()}</div>
<div>isScrollableY: {isScrollableY.toString()}</div>
<div>isAtLeft: {isAtLeft.toString()}</div>
<div>isAtRight: {isAtRight.toString()}</div>
<div>isAtTop: {isAtTop.toString()}</div>
<div>isAtBottom: {isAtBottom.toString()}</div>
</div>
<div className="flex gap-8">
<Button onClick={() => setRows((value) => value + 4)}>Add rows</Button>
<Button variant="outlined" onClick={() => setRows(1)}>
Reset rows
</Button>
</div>
</div>
);
},
};
Loading
Loading