Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

docs(useScrollOverflow): add a filter strip edge fade example block (#9616)

Parman Mohammadalizadeh9d1405aca842
diff --git a/.changeset/use-scroll-overflow-filter-strip-example.md b/.changeset/use-scroll-overflow-filter-strip-example.md
new file mode 100644
index 0000000000..1e5b5d5992
--- /dev/null
+++ b/.changeset/use-scroll-overflow-filter-strip-example.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] A new `useScrollOverflow — Filter Strip Edge Fades` example block shows a row of active filters that scrolls sideways and fades only the edge where `useScrollOverflow` reports hidden filters. Adding or removing a filter updates the fades, and a right-to-left switch moves the start edge to the right. Copy it with `astryx template useScrollOverflowHookUsage <path>`.
+
+@MannXo
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index d8a339bd7c..1914120a28 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -807,6 +807,7 @@
"/templates/useOutlineFromMarkdownHookUsage/",
"/templates/useOverflowHookUsage/",
"/templates/usePressFeedbackHookUsage/",
+ "/templates/useScrollOverflowHookUsage/",
"/templates/useScrollableAreaHookUsage/",
"/templates/useStreamingTextHookUsage/",
"/templates/useThemeHookUsage/",
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index ec7f3c10e2..7c60cf109f 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -3791,6 +3791,11 @@
"path": "examples/use-press-feedback/pressable-card",
"aliases": []
},
+ {
+ "name": "example-use-scroll-overflow-filter-strip-edge-fades",
+ "path": "examples/use-scroll-overflow/filter-strip-edge-fades",
+ "aliases": []
+ },
{
"name": "example-use-scrollable-area-activity-log-panel",
"path": "examples/use-scrollable-area/activity-log-panel",
diff --git a/packages/cli/api/template/use-scroll-overflow-hook-usage.test.tsx b/packages/cli/api/template/use-scroll-overflow-hook-usage.test.tsx
new file mode 100644
index 0000000000..42e54e5474
--- /dev/null
+++ b/packages/cli/api/template/use-scroll-overflow-hook-usage.test.tsx
@@ -0,0 +1,166 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * The useScrollOverflow example fades the edge of its filter strip only on
+ * the side where filters are hidden, and updates the fade as the strip
+ * scrolls and as filters are added. The side follows the strip's own
+ * direction (the Right to left switch), not the page's.
+ */
+
+import {act} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import UseScrollOverflowHookUsage from '../../assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage';
+
+// The node project does not compile StyleX. Each style compiles to its key as
+// the class name, so the test can read which fade the strip has.
+vi.mock('@stylexjs/stylex', () => ({
+ create: (styles: Record<string, unknown>) =>
+ Object.fromEntries(
+ Object.keys(styles).map(key => [key, {$$css: true, [key]: key}]),
+ ),
+ props: (...styles: unknown[]) => ({
+ className: styles
+ .filter(style => typeof style === 'object' && style != null)
+ .flatMap(style => Object.keys(style as object))
+ .filter(key => key !== '$$css')
+ .join(' '),
+ }),
+}));
+
+(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const STRIP_WIDTH = 320;
+const FILTER_WIDTH = 120;
+
+let root: Root | null = null;
+let container: HTMLElement;
+let scrollLeft = 0;
+
+function strip(): HTMLElement {
+ const element = container.querySelector<HTMLElement>(
+ '[aria-label="Active filters"]',
+ );
+ if (element == null) {
+ throw new Error('no filter strip rendered');
+ }
+ return element;
+}
+
+function fade(): string {
+ return (
+ strip()
+ .className.split(' ')
+ .find(name => name.startsWith('fade')) ?? 'none'
+ );
+}
+
+function setRightToLeft(): void {
+ const toggle = container.querySelector<HTMLInputElement>('[role="switch"]');
+ act(() => {
+ toggle?.click();
+ });
+}
+
+function scrollTo(offset: number): void {
+ scrollLeft = offset;
+ act(() => {
+ strip().dispatchEvent(new Event('scroll'));
+ });
+}
+
+async function addFilter(): Promise<void> {
+ const button = Array.from(container.querySelectorAll('button')).find(
+ candidate => candidate.textContent === 'Add filter',
+ );
+ await act(async () => {
+ button?.click();
+ });
+}
+
+beforeEach(() => {
+ scrollLeft = 0;
+ // jsdom has no layout. The strip is as wide as its filters.
+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(
+ function (this: HTMLElement) {
+ return this.getAttribute('aria-label') === 'Active filters'
+ ? STRIP_WIDTH
+ : 0;
+ },
+ );
+ vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockImplementation(
+ function (this: HTMLElement) {
+ return this.children.length * FILTER_WIDTH;
+ },
+ );
+ vi.spyOn(HTMLElement.prototype, 'scrollLeft', 'get').mockImplementation(
+ () => scrollLeft,
+ );
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ act(() => {
+ root = createRoot(container);
+ root.render(<UseScrollOverflowHookUsage />);
+ });
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+ document.documentElement.removeAttribute('dir');
+ vi.restoreAllMocks();
+});
+
+describe('useScrollOverflow example', () => {
+ it('shows no fade while every filter fits', () => {
+ expect(strip().children).toHaveLength(2);
+ expect(fade()).toBe('none');
+ });
+
+ it('fades the end once an added filter overflows the strip', async () => {
+ await addFilter();
+ await addFilter();
+ expect(strip().children).toHaveLength(4);
+ expect(fade()).toBe('fadeRight');
+ });
+
+ it('fades the side where filters are hidden as the strip scrolls', async () => {
+ await addFilter();
+ await addFilter();
+ const maxScroll = 4 * FILTER_WIDTH - STRIP_WIDTH;
+
+ scrollTo(maxScroll / 2);
+ expect(fade()).toBe('fadeBoth');
+
+ scrollTo(maxScroll);
+ expect(fade()).toBe('fadeLeft');
+
+ scrollTo(0);
+ expect(fade()).toBe('fadeRight');
+ });
+
+ it('fades the right edge first when the strip is right to left', async () => {
+ setRightToLeft();
+ await addFilter();
+ await addFilter();
+ const maxScroll = 4 * FILTER_WIDTH - STRIP_WIDTH;
+ expect(fade()).toBe('fadeLeft');
+
+ scrollTo(-maxScroll);
+ expect(fade()).toBe('fadeRight');
+ });
+
+ it('follows the strip, not the page, inside a right-to-left page', async () => {
+ document.documentElement.setAttribute('dir', 'rtl');
+ await addFilter();
+ await addFilter();
+ const maxScroll = 4 * FILTER_WIDTH - STRIP_WIDTH;
+ expect(fade()).toBe('fadeRight');
+
+ scrollTo(maxScroll);
+ expect(fade()).toBe('fadeLeft');
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.doc.mjs
new file mode 100644
index 0000000000..7b167338ee
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'useScrollOverflow',
+ name: 'useScrollOverflow — Filter Strip Edge Fades',
+ displayName: 'useScrollOverflow — Filter Strip Edge Fades',
+ description:
+ 'A row of active filters that scrolls sideways. useScrollOverflow reports which edge has hidden filters, and the strip fades only that edge: none while every filter fits, the end at the start, both mid-scroll and the start at the end. Adding or removing a filter updates the fades, and in a right-to-left layout the start edge is on the right.',
+ isReady: true,
+ aspectRatio: 4 / 3,
+ componentsUsed: ['Token', 'Button', 'Switch', 'Layout'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.tsx
new file mode 100644
index 0000000000..d440bdd88a
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useScrollOverflowHookUsage.tsx
@@ -0,0 +1,94 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Button} from '@astryxdesign/core/Button';
+import {useScrollOverflow} from '@astryxdesign/core/hooks';
+import {HStack, VStack} from '@astryxdesign/core/Layout';
+import {Switch} from '@astryxdesign/core/Switch';
+import {Token} from '@astryxdesign/core/Token';
+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
+
+const FADE = spacingVars['--spacing-8'];
+const FADE_FROM_LEFT = `linear-gradient(to right, transparent, black ${FADE})`;
+const FADE_FROM_RIGHT = `linear-gradient(to left, transparent, black ${FADE})`;
+
+const styles = stylex.create({
+ strip: {
+ display: 'flex',
+ gap: spacingVars['--spacing-2'],
+ overflowX: 'auto',
+ },
+ filter: {
+ flexShrink: 0,
+ },
+ fadeLeft: {
+ maskImage: FADE_FROM_LEFT,
+ },
+ fadeRight: {
+ maskImage: FADE_FROM_RIGHT,
+ },
+ fadeBoth: {
+ maskImage: `linear-gradient(to right, transparent, black ${FADE}, black calc(100% - ${FADE}), transparent)`,
+ },
+});
+
+const FILTERS = [
+ 'Open now',
+ 'Free delivery',
+ 'Vegetarian',
+ 'Under $15',
+ 'Top rated',
+ 'Outdoor seating',
+ 'Pet friendly',
+];
+
+export default function UseScrollOverflowHookUsage() {
+ const [filters, setFilters] = useState(FILTERS.slice(0, 2));
+ const [isRtl, setIsRtl] = useState(false);
+ const {scrollRef, overflowStart, overflowEnd} = useScrollOverflow();
+ const nextFilter = FILTERS.find(filter => !filters.includes(filter));
+ const fadeStart = isRtl ? styles.fadeRight : styles.fadeLeft;
+ const fadeEnd = isRtl ? styles.fadeLeft : styles.fadeRight;
+
+ return (
+ <VStack gap={3} width={320}>
+ <div dir={isRtl ? 'rtl' : 'ltr'}>
+ <div
+ ref={scrollRef}
+ role="group"
+ aria-label="Active filters"
+ {...stylex.props(
+ styles.strip,
+ overflowStart && overflowEnd
+ ? styles.fadeBoth
+ : overflowStart
+ ? fadeStart
+ : overflowEnd && fadeEnd,
+ )}>
+ {filters.map(filter => (
+ <Token
+ key={filter}
+ label={filter}
+ xstyle={styles.filter}
+ onRemove={() =>
+ setFilters(current => current.filter(item => item !== filter))
+ }
+ />
+ ))}
+ </div>
+ </div>
+ <HStack gap={3} vAlign="center">
+ <Button
+ label="Add filter"
+ variant="secondary"
+ isDisabled={nextFilter == null}
+ onClick={() => nextFilter && setFilters([...filters, nextFilter])}
+ />
+ <Switch label="Right to left" value={isRtl} onChange={setIsRtl} />
+ </HStack>
+ </VStack>
+ );
+}