Skip to content

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

TypeScript

docs(useScrollableArea): add an activity log panel example block (#9618)

Parman Mohammadalizadeh4934ffcf92e3
diff --git a/.changeset/use-scrollable-area-activity-log-example.md b/.changeset/use-scrollable-area-activity-log-example.md
new file mode 100644
index 0000000000..493af6aef8
--- /dev/null
+++ b/.changeset/use-scrollable-area-activity-log-example.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] A new `useScrollableArea — Activity Log Panel` example block shows a fixed-height Activity log whose entries scroll. `useScrollableArea` makes the panel a keyboard tab stop only when its entries overflow, shows a top or bottom edge shadow only where entries are hidden, and stops a scroll at the end from scrolling the page. Add entry flips it from not scrollable to scrollable. Copy it with `astryx template useScrollableAreaHookUsage <path>`.
+
+@MannXo
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index 40a51cca8b..ddccff9248 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -794,6 +794,7 @@
"/templates/useOutlineFromMarkdownHookUsage/",
"/templates/useOverflowHookUsage/",
"/templates/usePressFeedbackHookUsage/",
+ "/templates/useScrollableAreaHookUsage/",
"/templates/useStreamingTextHookUsage/",
"/templates/useThemeHookUsage/",
"/templates/useToastHookUsage/",
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index 45dbdc8b56..0a270aa984 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -3726,6 +3726,11 @@
"path": "examples/use-press-feedback/pressable-card",
"aliases": []
},
+ {
+ "name": "example-use-scrollable-area-activity-log-panel",
+ "path": "examples/use-scrollable-area/activity-log-panel",
+ "aliases": []
+ },
{
"name": "example-use-streaming-text-streaming-response",
"path": "examples/use-streaming-text/streaming-response",
diff --git a/packages/cli/api/template/use-scrollable-area-hook-usage.test.tsx b/packages/cli/api/template/use-scrollable-area-hook-usage.test.tsx
new file mode 100644
index 0000000000..f219467d1d
--- /dev/null
+++ b/packages/cli/api/template/use-scrollable-area-hook-usage.test.tsx
@@ -0,0 +1,168 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * The useScrollableArea example is an Activity log panel that becomes a
+ * keyboard tab stop only when its entries overflow, shades only the edges
+ * with hidden entries, and keeps its scroll from chaining to the page.
+ */
+
+import {act} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import UseScrollableAreaHookUsage from '../../assets/templates/blocks/components/Hooks/useScrollableAreaHookUsage';
+
+// The node project does not compile StyleX. Each style renders as its key in
+// the class name, so the test can read which edge shadow the panel has.
+vi.mock('@stylexjs/stylex', () => ({
+ create: (styles: Record<string, unknown>) =>
+ Object.fromEntries(Object.keys(styles).map(key => [key, key])),
+ props: (...styles: unknown[]) => ({
+ className: styles.filter(style => typeof style === 'string').join(' '),
+ }),
+}));
+
+(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const PANEL_HEIGHT = 160;
+const ENTRY_HEIGHT = 40;
+
+let root: Root | null = null;
+let container: HTMLElement;
+let scrollTop = 0;
+
+function isPanel(element: Element): boolean {
+ return element.getAttribute('aria-label') === 'Activity log';
+}
+
+function panel(): HTMLElement {
+ const element = container.querySelector<HTMLElement>(
+ '[aria-label="Activity log"]',
+ );
+ if (element == null) {
+ throw new Error('no Activity log panel rendered');
+ }
+ return element;
+}
+
+function entryCount(element: Element): number {
+ return element.querySelector('[data-scroll-content]')?.children.length ?? 0;
+}
+
+function shadow(): string {
+ return (
+ panel()
+ .className.split(' ')
+ .find(name => name.startsWith('shadow')) ?? 'none'
+ );
+}
+
+async function nextFrame(): Promise<void> {
+ await act(
+ () => new Promise<void>(resolve => requestAnimationFrame(() => resolve())),
+ );
+}
+
+async function addEntries(count: number): Promise<void> {
+ const button = Array.from(container.querySelectorAll('button')).find(
+ candidate => candidate.textContent === 'Add entry',
+ );
+ for (let i = 0; i < count; i++) {
+ act(() => button?.click());
+ await nextFrame();
+ }
+}
+
+function scrollTo(offset: number): void {
+ scrollTop = offset;
+ act(() => {
+ panel().dispatchEvent(new Event('scroll'));
+ });
+}
+
+beforeEach(() => {
+ scrollTop = 0;
+ // jsdom has no layout. The panel is 160px tall, and each entry is 40px.
+ const getComputedStyle = window.getComputedStyle.bind(window);
+ vi.spyOn(window, 'getComputedStyle').mockImplementation(element => {
+ const style = getComputedStyle(element);
+ if (!isPanel(element)) {
+ return style;
+ }
+ return new Proxy(style, {
+ get: (target, property) =>
+ property === 'overflowY'
+ ? 'auto'
+ : (target[property as keyof CSSStyleDeclaration] as unknown),
+ });
+ });
+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(
+ function (this: HTMLElement) {
+ return isPanel(this) ? 300 : 0;
+ },
+ );
+ vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockImplementation(
+ function (this: HTMLElement) {
+ return isPanel(this) ? 300 : 0;
+ },
+ );
+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(
+ function (this: HTMLElement) {
+ return isPanel(this) ? PANEL_HEIGHT : 0;
+ },
+ );
+ vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(
+ function (this: HTMLElement) {
+ return isPanel(this)
+ ? Math.max(PANEL_HEIGHT, entryCount(this) * ENTRY_HEIGHT)
+ : 0;
+ },
+ );
+ vi.spyOn(HTMLElement.prototype, 'scrollTop', 'get').mockImplementation(
+ () => scrollTop,
+ );
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ act(() => {
+ root = createRoot(container);
+ root.render(<UseScrollableAreaHookUsage />);
+ });
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+ vi.restoreAllMocks();
+});
+
+describe('useScrollableArea example', () => {
+ it('is not a tab stop and has no shadow while every entry fits', () => {
+ expect(entryCount(panel())).toBe(3);
+ expect(panel().hasAttribute('tabindex')).toBe(false);
+ expect(shadow()).toBe('none');
+ });
+
+ it('becomes a tab stop that does not scroll the page once entries overflow', async () => {
+ await addEntries(2);
+ expect(entryCount(panel())).toBe(5);
+ expect(panel().tabIndex).toBe(0);
+ expect(panel().style.overscrollBehaviorY).toBe('contain');
+ expect(shadow()).toBe('shadowBottom');
+ });
+
+ it('shades only the edges with hidden entries as the panel scrolls', async () => {
+ await addEntries(3);
+ const maxScroll = 6 * ENTRY_HEIGHT - PANEL_HEIGHT;
+
+ scrollTo(maxScroll / 2);
+ expect(shadow()).toBe('shadowBoth');
+
+ scrollTo(maxScroll);
+ expect(shadow()).toBe('shadowTop');
+
+ scrollTo(0);
+ expect(shadow()).toBe('shadowBottom');
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useScrollableAreaHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useScrollableAreaHookUsage.doc.mjs
new file mode 100644
index 0000000000..9ec82c3bd4
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useScrollableAreaHookUsage.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: 'useScrollableArea',
+ name: 'useScrollableArea — Activity Log Panel',
+ displayName: 'useScrollableArea — Activity Log Panel',
+ description:
+ 'A fixed-height Activity log panel whose entries scroll up and down. useScrollableArea makes the panel a keyboard tab stop only when its entries overflow, reports which edges have more entries so a top or bottom shadow shows only there, and keeps a scroll that reaches the end from scrolling the page. Add entry flips the panel from not scrollable to scrollable.',
+ isReady: true,
+ aspectRatio: 4 / 3,
+ componentsUsed: ['Card', 'Button', 'Text', 'Layout'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useScrollableAreaHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/useScrollableAreaHookUsage.tsx
new file mode 100644
index 0000000000..c191b470e4
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useScrollableAreaHookUsage.tsx
@@ -0,0 +1,90 @@
+// 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 {Card} from '@astryxdesign/core/Card';
+import {useScrollableArea} from '@astryxdesign/core/hooks';
+import {HStack, VStack} from '@astryxdesign/core/Layout';
+import {Heading, Text} from '@astryxdesign/core/Text';
+import {colorVars} from '@astryxdesign/core/theme/tokens.stylex';
+
+const TOP_SHADOW = `inset 0 12px 8px -8px ${colorVars['--color-shadow']}`;
+const BOTTOM_SHADOW = `inset 0 -12px 8px -8px ${colorVars['--color-shadow']}`;
+
+const styles = stylex.create({
+ viewport: {
+ height: 160,
+ },
+ shadowTop: {
+ boxShadow: TOP_SHADOW,
+ },
+ shadowBottom: {
+ boxShadow: BOTTOM_SHADOW,
+ },
+ shadowBoth: {
+ boxShadow: `${TOP_SHADOW}, ${BOTTOM_SHADOW}`,
+ },
+});
+
+const ACTIVITY = [
+ 'Maya created the Checkout project',
+ 'Sam invited Lee',
+ 'Build 318 passed',
+ 'Lee opened "Card total rounds down"',
+ 'Maya deployed 1.4.2 to staging',
+ 'Build 319 failed',
+ 'Sam fixed the rounding test',
+ 'Build 320 passed',
+ 'Maya deployed 1.4.3 to production',
+ 'Lee closed "Card total rounds down"',
+];
+
+export default function UseScrollableAreaHookUsage() {
+ const [count, setCount] = useState(3);
+ const {getViewportProps, getContentProps, state} = useScrollableArea({
+ axis: 'block',
+ keyboardAccess: {owner: 'viewport', label: 'Activity log'},
+ overscroll: 'contain',
+ });
+ const {isScrollable, atStart, atEnd} = state.block;
+ const hiddenAbove = isScrollable && !atStart;
+ const hiddenBelow = isScrollable && !atEnd;
+
+ return (
+ <Card width={320} padding={4}>
+ <VStack gap={3}>
+ <HStack justify="between" vAlign="center">
+ <Heading level={4}>Activity log</Heading>
+ <Button
+ label="Add entry"
+ variant="secondary"
+ isDisabled={count === ACTIVITY.length}
+ onClick={() => setCount(count + 1)}
+ />
+ </HStack>
+ <div
+ {...getViewportProps(
+ stylex.props(
+ styles.viewport,
+ hiddenAbove && hiddenBelow
+ ? styles.shadowBoth
+ : hiddenAbove
+ ? styles.shadowTop
+ : hiddenBelow && styles.shadowBottom,
+ ),
+ )}>
+ <VStack {...getContentProps()} gap={2}>
+ {ACTIVITY.slice(0, count).map(entry => (
+ <Text key={entry} type="body">
+ {entry}
+ </Text>
+ ))}
+ </VStack>
+ </div>
+ </VStack>
+ </Card>
+ );
+}