diff --git a/README.md b/README.md
index 9376fc3..52e5323 100644
--- a/README.md
+++ b/README.md
@@ -33,7 +33,7 @@ An unofficial add-on for the Next.js App Router. It draws slide transitions betw
- Scroll offset restored per history entry (`preserveScroll`).
- Document scrolling by default (`window.scrollTo`, `window.scrollY` keep working); an independent scroll container also works (`scrollTarget`).
- Only the scrollbar changes, never the scroller: the document still scrolls, so `window.scrollTo`, `window.scrollY`, `scrollTop` and `scroll` events behave as without the package. The browser's own scrollbar is hidden on `` and `
`, and the drawn scrollbar replaces it.
-- A vertical scrollbar drawn with [OverlayScrollbars](https://github.com/KingSora/OverlayScrollbars): its track stays between fixed headers, footers and tab bars, follows whichever scroller is moving, and can be dragged or clicked.
+- A vertical scrollbar drawn with [OverlayScrollbars](https://github.com/KingSora/OverlayScrollbars): its track stays between fixed headers, footers and tab bars, follows whichever scroller is moving, and can be dragged or clicked. A horizontal bar appears along the bottom of the track only when the page overflows sideways. `scrollbar={{ autoHide, autoHideDelay, autoHideSuspend }}` sets when it hides.
- `edgeBounce`: optional touch bounce at scroll boundaries on non-Apple touch devices.
- `skipSlideQueryKeys`: skip the page slide when only a popup query parameter changes.
- `fixedTargets` keeps chosen elements still during the slide.
@@ -54,7 +54,6 @@ An unofficial add-on for the Next.js App Router. It draws slide transitions betw
- Next.js below 16.4.6 and React below 19.3.1 are untested.
- No benchmarks against other libraries.
- No physics or spring animation. Motion is CSS and the Web Animations API.
-- No horizontal custom scrollbar. Horizontal overflow keeps native scrolling without a drawn bar.
- The drawn scrollbar no longer shrinks during elastic overscroll; `edgeBounce` still compresses it.
## Where it stands
diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md
index a2d9ec2..8e56028 100644
--- a/docs/REFERENCE.md
+++ b/docs/REFERENCE.md
@@ -266,6 +266,21 @@ the scrollbar follows that element while it scrolls and switches to the
document when document scrolling takes over. The scrollbar appears while the
pointer moves or the page scrolls and hides 0.8 seconds later. Drag the handle
or click the track to scroll; keyboard, wheel and touch scrolling stay native.
+When the page or the scroll area overflows sideways, a horizontal bar appears
+along the bottom of the track; otherwise it stays hidden.
+
+Set `scrollbar` to change when the drawn scrollbar hides. Scrolling itself is
+not affected.
+
+```tsx
+
+```
+
+| Option | Default | Meaning |
+| --- | --- | --- |
+| `autoHide` | `'move'` | `'move'`: shown while the pointer moves or the page scrolls. `'scroll'`: only while scrolling. `'leave'`: hidden when the pointer leaves the page. `'never'`: always shown. |
+| `autoHideDelay` | `800` | Milliseconds before hiding. |
+| `autoHideSuspend` | `true` | Stay hidden until the first scroll. |
```tsx
diff --git a/src/next/index.tsx b/src/next/index.tsx
index bbf0bed..89ca0e7 100644
--- a/src/next/index.tsx
+++ b/src/next/index.tsx
@@ -4,13 +4,14 @@ import Link, { type LinkProps } from 'next/link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { NavigationEngine, safeHref, type RouteTransition, type SlideDirection } from './engine.js';
import { attachSwipeBack } from './swipe.js';
-import { attachScrollViewport, attachWindowScroll } from './scroll.js';
+import { attachScrollViewport, attachWindowScroll, createOverlayScrollbarFactory, type ScrollbarOptions } from './scroll.js';
import type { FixedTarget } from './fixed-targets.js';
import { createSkeletonRouteMatcher, type SkeletonRoute } from './skeleton-routes.js';
import { loadingMessage } from './loading-message.js';
export type { FixedTarget } from './fixed-targets.js';
export type { RouteTransition } from './engine.js';
export type { SkeletonRoute } from './skeleton-routes.js';
+export type { ScrollbarOptions } from './scroll.js';
export { StackMotion, type StackMotionPreset, type StackMotionProps } from './motion.js';
const Context = createContext(undefined);
@@ -48,6 +49,8 @@ export interface StackflowProviderProps {
scrollTarget?: string;
/** Add touch-only bounce where Apple-style native rubber-banding is unavailable. */
edgeBounce?: boolean;
+ /** When the drawn scrollbar hides itself. Scrolling itself is unaffected. */
+ scrollbar?: ScrollbarOptions;
/** CSS selectors for shared elements inside the page that should not slide. */
fixedTargets?: FixedTarget | readonly FixedTarget[];
/** Pathnames presented as full-height modal pages. */
@@ -72,7 +75,7 @@ export interface StackflowProviderProps {
className?: string;
style?: CSSProperties;
}
-export function StackflowProvider({children,header,footer,persistent,animation='ios',preserveScroll=true,scrollMode='window',scrollTarget,edgeBounce=false,fixedTargets,modalRoutes,transitionRoutes,skipSlideQueryKeys,transitionTarget,swipeBack=false,maxEntries=32,navigationTimeout=4000,waitForPage=false,skeletonRoutes,loading,locale,className='',style}: StackflowProviderProps) {
+export function StackflowProvider({children,header,footer,persistent,animation='ios',preserveScroll=true,scrollMode='window',scrollTarget,edgeBounce=false,scrollbar: scrollbarOptions,fixedTargets,modalRoutes,transitionRoutes,skipSlideQueryKeys,transitionTarget,swipeBack=false,maxEntries=32,navigationTimeout=4000,waitForPage=false,skeletonRoutes,loading,locale,className='',style}: StackflowProviderProps) {
const viewport=useRef(null);
const scrollbar = useRef(null);
const fixed = useRef([]);
@@ -100,6 +103,8 @@ export function StackflowProvider({children,header,footer,persistent,animation='
console.warn('[StackflowProvider] Remove transitionTarget to use the full-page transition. Use fixedTargets to keep selected elements still.');
}
}, [transitionTarget]);
+ const {autoHide, autoHideDelay, autoHideSuspend} = scrollbarOptions ?? {};
+ const createScrollbar = useMemo(() => createOverlayScrollbarFactory({autoHide, autoHideDelay, autoHideSuspend}), [autoHide, autoHideDelay, autoHideSuspend]);
useLayoutEffect(()=>{
const content = viewport.current;
const thumb = scrollbar.current;
@@ -109,15 +114,15 @@ export function StackflowProvider({children,header,footer,persistent,animation='
// Let the initial route hydrate before marking a descendant scroll target.
const frame = window.requestAnimationFrame(() => {
scroll.current = scrollMode === 'window'
- ? attachWindowScroll(content, scrollTarget, capture, thumb, fixedSelectors, edgeBounce)
- : attachScrollViewport(content, scrollTarget, capture, element => engineRef.current?.restoreScroll(element), thumb, fixedSelectors, edgeBounce);
+ ? attachWindowScroll(content, scrollTarget, capture, thumb, fixedSelectors, edgeBounce, createScrollbar)
+ : attachScrollViewport(content, scrollTarget, capture, element => engineRef.current?.restoreScroll(element), thumb, fixedSelectors, edgeBounce, createScrollbar);
});
return () => {
window.cancelAnimationFrame(frame);
scroll.current?.dispose();
scroll.current = null;
};
- },[scrollTarget,scrollMode,fixedTargets,edgeBounce]);
+ },[scrollTarget,scrollMode,fixedTargets,edgeBounce,createScrollbar]);
useLayoutEffect(()=>{
if(!Number.isInteger(maxEntries)||maxEntries<1) throw new RangeError('maxEntries must be positive');
if(!Number.isFinite(navigationTimeout)||navigationTimeout<=0) throw new RangeError('navigationTimeout must be positive');
diff --git a/src/next/scroll.ts b/src/next/scroll.ts
index 33f7759..5d2ac90 100644
--- a/src/next/scroll.ts
+++ b/src/next/scroll.ts
@@ -17,40 +17,65 @@ export type OverlayScrollbar = { setActive(active: boolean): void; dispose(): vo
*/
export type OverlayScrollbarFactory = (scroller: HTMLElement, root: boolean, slot: HTMLElement) => OverlayScrollbar | undefined;
-// Shown while the pointer moves or the page scrolls, so a mouse can grab it.
-// Nothing shows before the first scroll (OverlayScrollbars' accessible default).
-const overlayOptions = {
- scrollbars: {
- theme: 'os-theme-stackflow', autoHide: 'move', autoHideDelay: 800, autoHideSuspend: true,
- dragScroll: true, clickScroll: true,
- },
-} as const;
+/** When the drawn scrollbar hides itself. */
+export type ScrollbarOptions = {
+ /**
+ * 'move' (default): shown while the pointer moves or the page scrolls.
+ * 'scroll': shown only while scrolling. 'leave': hidden when the pointer
+ * leaves the page. 'never': always shown.
+ */
+ autoHide?: 'never' | 'scroll' | 'leave' | 'move';
+ /** Milliseconds before hiding. Defaults to 800. */
+ autoHideDelay?: number;
+ /** Keep it hidden until the first scroll. Defaults to true. */
+ autoHideSuspend?: boolean;
+};
+
+export function overlayScrollbarOptions(options: ScrollbarOptions = {}) {
+ const autoHideDelay = options.autoHideDelay;
+ return {
+ scrollbars: {
+ theme: 'os-theme-stackflow',
+ autoHide: options.autoHide ?? 'move',
+ autoHideDelay: typeof autoHideDelay === 'number' && Number.isFinite(autoHideDelay) && autoHideDelay >= 0 ? autoHideDelay : 800,
+ autoHideSuspend: options.autoHideSuspend ?? true,
+ dragScroll: true,
+ clickScroll: true,
+ },
+ } as const;
+}
let clickScrollRegistered = false;
/**
* OverlayScrollbars keeps native scrolling (window.scrollTo, keyboard, touch
- * momentum) and draws a draggable, clickable scrollbar whose handle follows a
+ * momentum) and draws draggable, clickable scrollbars whose handles follow a
* ScrollTimeline where supported. The scroller's DOM is not wrapped: the
* document uses as its viewport, and an element is its own viewport.
+ * The horizontal bar appears only when that axis actually overflows.
*/
-export const createOverlayScrollbar: OverlayScrollbarFactory = (scroller, root, slot) => {
- try {
- if (!clickScrollRegistered) {
- OverlayScrollbars.plugin(ClickScrollPlugin);
- clickScrollRegistered = true;
+export function createOverlayScrollbarFactory(options?: ScrollbarOptions): OverlayScrollbarFactory {
+ const overlayOptions = overlayScrollbarOptions(options);
+ return (scroller, root, slot) => {
+ try {
+ if (!clickScrollRegistered) {
+ OverlayScrollbars.plugin(ClickScrollPlugin);
+ clickScrollRegistered = true;
+ }
+ const instance = OverlayScrollbars(root
+ ? { target: scroller.ownerDocument.body, scrollbars: { slot }, cancel: { body: null } }
+ : { target: scroller, elements: { viewport: scroller }, scrollbars: { slot } }, overlayOptions);
+ if (!OverlayScrollbars.valid(instance)) return;
+ return {
+ setActive(active) { instance.options({ scrollbars: { visibility: active ? 'auto' : 'hidden' } }); },
+ dispose() { instance.destroy(); },
+ };
+ } catch {
+ return;
}
- const instance = OverlayScrollbars(root
- ? { target: scroller.ownerDocument.body, scrollbars: { slot }, cancel: { body: null } }
- : { target: scroller, elements: { viewport: scroller }, scrollbars: { slot } }, overlayOptions);
- if (!OverlayScrollbars.valid(instance)) return;
- return {
- setActive(active) { instance.options({ scrollbars: { visibility: active ? 'auto' : 'hidden' } }); },
- dispose() { instance.destroy(); },
- };
- } catch {
- return;
- }
-};
+ };
+}
+
+export const createOverlayScrollbar: OverlayScrollbarFactory = createOverlayScrollbarFactory();
function overlays(slot: HTMLElement, factory: OverlayScrollbarFactory) {
const created = new Map();
@@ -124,9 +149,11 @@ export function previewScrollElement(content: HTMLElement) {
* Returns true when the slot's containing block moves with the document,
* which means the track must be placed again after each document scroll.
*/
-function placeTrack(slot: HTMLElement, track: ScrollBounds, scrollRange: number, origin: ScrollbarOrigin) {
+function placeTrack(slot: HTMLElement, track: ScrollBounds, origin: ScrollbarOrigin) {
const trackHeight = track.bottom - track.top;
- slot.hidden = trackHeight <= 0 || track.right <= track.left || scrollRange <= 0;
+ // Each drawn bar hides itself when its axis does not overflow, so the slot
+ // only hides when the track has no area.
+ slot.hidden = trackHeight <= 0 || track.right <= track.left;
if (slot.hidden) return false;
const fixed = 'viewportRight' in origin;
@@ -143,6 +170,8 @@ function placeTrack(slot: HTMLElement, track: ScrollBounds, scrollRange: number,
// the slot's effective zoom, including when inherited from an ancestor.
const zoom = slot.currentCSSZoom || 1;
slot.style.height = `${trackHeight / zoom}px`;
+ // The horizontal bar runs along the bottom of the track, leftward from its right edge.
+ slot.style.setProperty('--stackflow-track-width', `${(track.right - track.left) / zoom}px`);
slot.style.right = `${(originRight - track.right) / zoom}px`;
slot.style.transform = `translateY(${(track.top - originTop) / zoom}px)`;
return !!parent;
@@ -198,7 +227,7 @@ function placeElementTrack(slot: HTMLElement, element: HTMLElement,
if (target === element) fitTrack(track, contentBox(element, scrollport, false), 0, 0);
else if (target) fitTrack(track, contentBox(target, target.getBoundingClientRect(), true), offset, range);
excludeChrome?.(track);
- return placeTrack(slot, track, range, origin);
+ return placeTrack(slot, track, origin);
}
function visualBounds(content: HTMLElement): ScrollBounds {
@@ -383,7 +412,7 @@ export function attachWindowScroll(content: HTMLElement, selector: string | unde
viewportBounds.right = Math.min(viewportBounds.right, region.right);
}
chrome.exclude(viewportBounds);
- followsDocument = placeTrack(slot, viewportBounds, range, { viewportRight });
+ followsDocument = placeTrack(slot, viewportBounds, { viewportRight });
}
function schedule() { if (!frame) frame = win.requestAnimationFrame(paint); }
diff --git a/src/next/style.css b/src/next/style.css
index 7d45ed9..e9b8682 100644
--- a/src/next/style.css
+++ b/src/next/style.css
@@ -14,8 +14,17 @@ html[data-stackflow-animating] .stackflow-next-content:not([data-stackflow-slide
.stackflow-next-content[data-stackflow-scroll-delegated]{overflow:clip}
/* The slot is the track box. OverlayScrollbars draws the handle inside it. */
.stackflow-next-scrollbar{position:absolute;top:0;right:0;width:10px;z-index:3;pointer-events:none}
-.stackflow-next-scrollbar > .os-scrollbar-vertical{top:0;right:0;bottom:0;height:auto}
-.stackflow-next-scrollbar > .os-scrollbar-horizontal{display:none}
+.stackflow-next-scrollbar > .os-scrollbar.os-scrollbar-vertical{top:0;right:0;bottom:0;height:auto}
+.stackflow-next-scrollbar > .os-scrollbar.os-scrollbar-vertical:not(.os-scrollbar-cornerless){bottom:var(--os-size)}
+/* The horizontal bar shows only when that axis overflows. It runs along the
+ bottom of the track, from the track's right edge across its width. */
+.stackflow-next-scrollbar > .os-scrollbar.os-scrollbar-horizontal,
+.stackflow-next-scrollbar > .os-scrollbar.os-scrollbar-horizontal.os-scrollbar-cornerless{
+ top:auto;right:0;bottom:0;left:auto;width:var(--stackflow-track-width,100%)
+}
+.stackflow-next-scrollbar > .os-scrollbar.os-scrollbar-horizontal:not(.os-scrollbar-cornerless){
+ right:var(--os-size);width:calc(var(--stackflow-track-width,100%) - var(--os-size))
+}
.os-theme-stackflow{
box-sizing:border-box;
--os-size:10px;--os-padding-perpendicular:3px;--os-padding-axis:0px;
diff --git a/test/next/scroll.test.ts b/test/next/scroll.test.ts
index b909da8..d8e69b0 100644
--- a/test/next/scroll.test.ts
+++ b/test/next/scroll.test.ts
@@ -1,7 +1,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { Window } from 'happy-dom';
-import { attachScrollViewport, attachWindowScroll, type OverlayScrollbarFactory } from '../../src/next/scroll.ts';
+import { attachScrollViewport, attachWindowScroll, overlayScrollbarOptions, type OverlayScrollbarFactory } from '../../src/next/scroll.ts';
// Records how the provider drives the drawn scrollbars without loading OverlayScrollbars.
function recordScrollbars() {
@@ -266,3 +266,45 @@ for (const mode of ['window', 'container']) {
assert.equal(created[0].disposed, true);
});
}
+
+test('scrollbar options default to move, 800 ms and hidden until the first scroll', () => {
+ assert.deepEqual(overlayScrollbarOptions().scrollbars, {
+ theme: 'os-theme-stackflow', autoHide: 'move', autoHideDelay: 800, autoHideSuspend: true,
+ dragScroll: true, clickScroll: true,
+ });
+ const custom = overlayScrollbarOptions({ autoHide: 'never', autoHideDelay: 0, autoHideSuspend: false }).scrollbars;
+ assert.equal(custom.autoHide, 'never');
+ assert.equal(custom.autoHideDelay, 0);
+ assert.equal(custom.autoHideSuspend, false);
+ for (const invalid of [-1, Number.NaN, Number.POSITIVE_INFINITY]) {
+ assert.equal(overlayScrollbarOptions({ autoHideDelay: invalid }).scrollbars.autoHideDelay, 800);
+ }
+});
+
+test('the track stays available for a horizontal-only overflow and exposes its width', t => {
+ const win = new Window();
+ const root = win.document.documentElement;
+ // No vertical overflow: the drawn bars decide per axis whether to show.
+ Object.defineProperties(root, {
+ clientHeight: { value: 700 }, clientWidth: { value: 400 }, scrollHeight: { value: 700 },
+ });
+ Object.defineProperty(win, 'visualViewport', { value: undefined });
+ Object.defineProperty(win, 'scrollY', { get: () => 0 });
+ let paint: FrameRequestCallback;
+ t.mock.method(win, 'requestAnimationFrame', (callback: FrameRequestCallback) => { paint = callback; return 1; });
+ win.document.body.innerHTML = `
+ `;
+ const content = win.document.querySelector('.stackflow-next-content')! as unknown as HTMLElement;
+ const slot = content.nextElementSibling as HTMLElement;
+ t.mock.method(content, 'getBoundingClientRect', () => new win.DOMRect(10, 0, 380, 700));
+ const { factory } = recordScrollbars();
+ const controller = attachWindowScroll(content, undefined, () => {}, slot, [], false, factory);
+ try {
+ paint!(0);
+ assert.equal(slot.hidden, false);
+ assert.equal(slot.style.getPropertyValue('--stackflow-track-width'), '380px');
+ assert.equal(slot.style.right, '10px');
+ } finally {
+ controller.dispose();
+ }
+});