Skip to content

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

TypeScript

feat(pagination): let the compact variant opt into first/last buttons (#7544)

nynexman4464c68f5e8e5f55
diff --git a/.changeset/pagination-compact-first-last.md b/.changeset/pagination-compact-first-last.md
new file mode 100644
index 0000000000..a1c58fa895
--- /dev/null
+++ b/.changeset/pagination-compact-first-last.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `Pagination`: `variant="compact"` shows first/last buttons around previous/next when `hasFirstLast` is `true` and the page count is known. Compact still omits them by default, and the `input` variant still shows them unless `hasFirstLast` is `false`.
+
+@nynexman4464
diff --git a/apps/storybook/stories/Pagination.stories.tsx b/apps/storybook/stories/Pagination.stories.tsx
index 4caf4d177c..539c182f1a 100644
--- a/apps/storybook/stories/Pagination.stories.tsx
+++ b/apps/storybook/stories/Pagination.stories.tsx
@@ -26,7 +26,8 @@ const meta: Meta<typeof Pagination> = {
},
hasFirstLast: {
control: 'boolean',
- description: 'input variant: show first/last («/») buttons',
+ description:
+ 'input (default on) and compact (default off) variants: show first/last («/») buttons',
},
step: {
control: 'number',
@@ -102,6 +103,14 @@ export const CompactVariant: Story = {
render: () => <PaginationDemo page={1} totalPages={10} variant="compact" />,
};
+export const CompactVariantFirstLast: Story = {
+ name: 'Variant: Compact (first/last)',
+ render: () => (
+ // « ‹ Page X of Y › » — first/last are opt-in for compact.
+ <PaginationDemo page={5} totalPages={10} variant="compact" hasFirstLast />
+ ),
+};
+
export const DotsVariant: Story = {
name: 'Variant: Dots',
render: () => <PaginationDemo page={1} totalPages={8} variant="dots" />,
diff --git a/packages/core/src/Pagination/Pagination.doc.mjs b/packages/core/src/Pagination/Pagination.doc.mjs
index 0bd9f229d9..039b1be846 100644
--- a/packages/core/src/Pagination/Pagination.doc.mjs
+++ b/packages/core/src/Pagination/Pagination.doc.mjs
@@ -137,7 +137,7 @@ export const docs = {
name: 'variant',
type: "'pages' | 'count' | 'compact' | 'dots' | 'input' | 'none'",
description:
- "Visual variant controlling what appears between prev/next buttons. 'pages' shows page number buttons with ellipsis, 'count' shows 'X-Y of Z' text, 'compact' shows 'Page X of Y', 'dots' shows dot indicators, 'input' shows an editable page-number box with a leading label ('Page [ n ] / N') flanked by first/last buttons by default (the box needs a known total to clamp against, so it is disabled in cursor/hasMore mode), 'none' shows just prev/next buttons.",
+ "Visual variant controlling what appears between prev/next buttons. 'pages' shows page number buttons with ellipsis, 'count' shows 'X-Y of Z' text, 'compact' shows 'Page X of Y' (add first/last buttons with hasFirstLast), 'dots' shows dot indicators, 'input' shows an editable page-number box with a leading label ('Page [ n ] / N') flanked by first/last buttons by default (the box needs a known total to clamp against, so it is disabled in cursor/hasMore mode), 'none' shows just prev/next buttons.",
default: "'pages'",
},
{
@@ -150,8 +150,8 @@ export const docs = {
name: 'hasFirstLast',
type: 'boolean',
description:
- "Whether to show first/last («/») double-chevron buttons flanking prev/next. Only applies to the 'input' variant; omitted when the page count is unknown (cursor/hasMore pagination).",
- default: 'true',
+ "Whether to show first/last («/») double-chevron buttons flanking prev/next. Applies to the 'input' variant (shown unless false) and the 'compact' variant (shown only when true); other variants ignore it. Omitted when the page count is unknown (cursor/hasMore pagination).",
+ default: "true for 'input'; false for 'compact'",
},
{
name: 'step',
@@ -288,7 +288,7 @@ export const docsZh = {
name: 'variant',
type: "'pages' | 'count' | 'compact' | 'dots' | 'input' | 'none'",
description:
- "控制上一页/下一页按钮之间显示内容的视觉变体。'pages' 显示带省略号的页码按钮,'count' 显示 'X-Y of Z' 文本,'compact' 显示 'Page X of Y','dots' 显示点指示器,'input' 显示带前置标签的可编辑页码框——'Page [ n ] / N'——默认两侧带首页/末页按钮,'none' 仅显示上一页/下一页按钮。",
+ "控制上一页/下一页按钮之间显示内容的视觉变体。'pages' 显示带省略号的页码按钮,'count' 显示 'X-Y of Z' 文本,'compact' 显示 'Page X of Y'(可通过 hasFirstLast 添加首页/末页按钮),'dots' 显示点指示器,'input' 显示带前置标签的可编辑页码框——'Page [ n ] / N'——默认两侧带首页/末页按钮,'none' 仅显示上一页/下一页按钮。",
default: "'pages'",
},
{
@@ -301,8 +301,8 @@ export const docsZh = {
name: 'hasFirstLast',
type: 'boolean',
description:
- "是否显示首页/末页(«/»)双箭头按钮,位于上一页/下一页两侧。仅适用于 'input' 变体;当页数未知(游标/hasMore 分页)时省略。",
- default: 'true',
+ "是否显示首页/末页(«/»)双箭头按钮,位于上一页/下一页两侧。适用于 'input' 变体(除非设为 false 否则显示)和 'compact' 变体(仅在设为 true 时显示);其他变体忽略此项。当页数未知(游标/hasMore 分页)时省略。",
+ default: "'input' 为 true;'compact' 为 false",
},
{
name: 'step',
@@ -400,7 +400,7 @@ export const docsDense = {
onPageSizeChange: 'Called on page size change. Auto resets to page 1.',
variant: "Display between prev/next. 'input' = 'Page [n] / N' + first/last.",
pageLabel: "Noun before the 'input' box (e.g. 'Page' or 'Row'). Navigation stays page-based. Default localized 'Page'.",
- hasFirstLast: "Show first/last («/») buttons in the 'input' variant. Omitted when total unknown.",
+ hasFirstLast: "Show first/last («/») buttons. 'input' default true; 'compact' default false (opt in). Other variants ignore. Omitted when total unknown.",
step: 'Pages the prev/next buttons advance per click. Clamped to range; < 1 or non-integer falls back to 1.',
siblingCount: "Page buttons each side of current; only variant='pages'.",
size: 'Control size.',
diff --git a/packages/core/src/Pagination/Pagination.spec.md b/packages/core/src/Pagination/Pagination.spec.md
index 0f36865723..9335ae6aba 100644
--- a/packages/core/src/Pagination/Pagination.spec.md
+++ b/packages/core/src/Pagination/Pagination.spec.md
@@ -92,15 +92,15 @@ and usage remain documented in `Pagination.doc.mjs`.
### Representative states
-| State | Required invariant | Allowed variation |
-| ----------------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------- |
-| Numbered, known page count | Page number buttons render; Ellipsis appears only where pages are omitted. | Page count, sibling range, and active page. |
-| Count with known item total | Count readout renders between Previous/next buttons. | Range and total text. |
-| Compact with known page count | Compact readout renders between Previous/next buttons. | Current and total page text. |
-| Dots with known page count | One Dot renders for each page and active state stays on the Dot target. | Dot count and active Dot. |
-| Input with known page count | Page input label, Page input, and Page input total render; First/last may render. | Label text and first/last opt-out. |
-| Input with unknown page count | Page input label and disabled Page input remain; total and First/last are absent. | Cursor-backed current page. |
-| None | Previous/next buttons remain without a presentation-specific part between them. | Enabled state follows current paging availability. |
+| State | Required invariant | Allowed variation |
+| ----------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------- |
+| Numbered, known page count | Page number buttons render; Ellipsis appears only where pages are omitted. | Page count, sibling range, and active page. |
+| Count with known item total | Count readout renders between Previous/next buttons. | Range and total text. |
+| Compact with known page count | Compact readout renders between Previous/next buttons; First/last render only when opted in. | Current and total page text and first/last opt-in. |
+| Dots with known page count | One Dot renders for each page and active state stays on the Dot target. | Dot count and active Dot. |
+| Input with known page count | Page input label, Page input, and Page input total render; First/last may render. | Label text and first/last opt-out. |
+| Input with unknown page count | Page input label and disabled Page input remain; total and First/last are absent. | Cursor-backed current page. |
+| None | Previous/next buttons remain without a presentation-specific part between them. | Enabled state follows current paging availability. |
The optional Page-size selector may precede the paging controls in any current
presentation when page-size options are provided.
diff --git a/packages/core/src/Pagination/Pagination.test.tsx b/packages/core/src/Pagination/Pagination.test.tsx
index e8b027d352..e67075b2bf 100644
--- a/packages/core/src/Pagination/Pagination.test.tsx
+++ b/packages/core/src/Pagination/Pagination.test.tsx
@@ -20,6 +20,7 @@ import {
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {Pagination, generatePageRange} from './Pagination';
+import {InternationalizationProvider} from '../i18n';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
afterEach(() => {
@@ -119,6 +120,28 @@ describe('Pagination', () => {
).toBeInTheDocument();
});
+ it('does not introduce Stack theme targets around navigation controls', () => {
+ const {rerender} = render(
+ <Pagination page={3} onChange={() => {}} totalPages={5} />,
+ );
+ expect(
+ screen.getByRole('navigation').querySelector('.astryx-stack'),
+ ).toBeNull();
+
+ rerender(
+ <Pagination
+ page={3}
+ onChange={() => {}}
+ totalPages={5}
+ variant="compact"
+ hasFirstLast
+ />,
+ );
+ expect(
+ screen.getByRole('navigation').querySelector('.astryx-stack'),
+ ).toBeNull();
+ });
+
it('gives the prev/next carets a hover tooltip matching their accessible name', () => {
// The carets are icon-only, so sighted users need a visible label on
// hover, not just the accessible name. The tooltip reuses the same
@@ -291,6 +314,225 @@ describe('Pagination', () => {
);
expect(screen.getByText('Page 3 of 10')).toBeInTheDocument();
});
+
+ describe('first/last buttons', () => {
+ function navButtonNames(): string[] {
+ return within(screen.getByRole('navigation'))
+ .getAllByRole('button')
+ .map(button => button.getAttribute('aria-label') ?? '');
+ }
+
+ it('omits first/last when hasFirstLast is unset', () => {
+ render(
+ <Pagination
+ page={5}
+ onChange={() => {}}
+ totalPages={10}
+ variant="compact"
+ />,
+ );
+ expect(navButtonNames()).toEqual([
+ 'Go to previous page',
+ 'Go to next page',
+ ]);
+ });
+
+ it('omits first/last when hasFirstLast is false', () => {
+ render(
+ <Pagination
+ page={5}
+ onChange={() => {}}
+ totalPages={10}
+ variant="compact"
+ hasFirstLast={false}
+ />,
+ );
+ expect(navButtonNames()).toEqual([
+ 'Go to previous page',
+ 'Go to next page',
+ ]);
+ });
+
+ it('flanks prev/next with first/last when hasFirstLast is true', () => {
+ render(
+ <Pagination
+ page={5}
+ onChange={() => {}}
+ totalPages={10}
+ variant="compact"
+ hasFirstLast
+ />,
+ );
+ expect(navButtonNames()).toEqual([
+ 'Go to first page',
+ 'Go to previous page',
+ 'Go to next page',
+ 'Go to last page',
+ ]);
+ // The readout stays between prev and next.
+ const readout = within(screen.getByRole('navigation')).getByText(
+ 'Page 5 of 10',
+ );
+ const prev = screen.getByRole('button', {name: 'Go to previous page'});
+ const next = screen.getByRole('button', {name: 'Go to next page'});
+ expect(
+ prev.compareDocumentPosition(readout) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(
+ next.compareDocumentPosition(readout) &
+ Node.DOCUMENT_POSITION_PRECEDING,
+ ).toBeTruthy();
+ // Compact never gains an editable box.
+ expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument();
+ });
+
+ it('jumps to the first and last page through onChange and changeAction', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const changeAction = vi.fn();
+ render(
+ <Pagination
+ page={5}
+ onChange={onChange}
+ changeAction={changeAction}
+ totalItems={95}
+ pageSize={10}
+ variant="compact"
+ hasFirstLast
+ />,
+ );
+ await user.click(
+ screen.getByRole('button', {name: 'Go to first page'}),
+ );
+ expect(onChange).toHaveBeenLastCalledWith(1);
+ expect(changeAction).toHaveBeenLastCalledWith(1);
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('Page 1 of 10');
+ });
+
+ await user.click(screen.getByRole('button', {name: 'Go to last page'}));
+ // 95 items at 10 per page is 10 pages.
+ expect(onChange).toHaveBeenLastCalledWith(10);
+ expect(changeAction).toHaveBeenLastCalledWith(10);
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('Page 10 of 10');
+ });
+ });
+
+ it('disables first on the first page and last on the last page', () => {
+ const {rerender} = render(
+ <Pagination
+ page={1}
+ onChange={() => {}}
+ totalPages={10}
+ variant="compact"
+ hasFirstLast
+ />,
+ );
+ expect(
+ screen.getByRole('button', {name: 'Go to first page'}),
+ ).toBeDisabled();
+ expect(
+ screen.getByRole('button', {name: 'Go to last page'}),
+ ).not.toBeDisabled();
+
+ rerender(
+ <Pagination
+ page={10}
+ onChange={() => {}}
+ totalPages={10}
+ variant="compact"
+ hasFirstLast
+ />,
+ );
+ expect(
+ screen.getByRole('button', {name: 'Go to first page'}),
+ ).not.toBeDisabled();
+ expect(
+ screen.getByRole('button', {name: 'Go to last page'}),
+ ).toBeDisabled();
+ });
+
+ it('omits first/last when the total page count is unknown', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <Pagination
+ page={2}
+ onChange={onChange}
+ hasMore
+ variant="compact"
+ hasFirstLast
+ />,
+ );
+ expect(navButtonNames()).toEqual([
+ 'Go to previous page',
+ 'Go to next page',
+ ]);
+ await user.click(screen.getByRole('button', {name: 'Go to next page'}));
+ expect(onChange).toHaveBeenLastCalledWith(3);
+ });
+
+ it('mirrors the first/last chevrons under RTL like prev/next', () => {
+ render(
+ <InternationalizationProvider locale="en" dir="rtl">
+ <div dir="rtl">
+ <Pagination
+ page={5}
+ onChange={() => {}}
+ totalPages={10}
+ variant="compact"
+ hasFirstLast
+ />
+ </div>
+ </InternationalizationProvider>,
+ );
+ // jsdom applies no CSS transforms, so assert the first/last icons carry
+ // every class the mirrored prev/next icons share (the mirror included).
+ const iconClasses = (name: string) =>
+ new Set(
+ screen
+ .getByRole('button', {name})
+ .querySelector('.astryx-icon')
+ ?.getAttribute('class')
+ ?.split(/\s+/) ?? [],
+ );
+ const prev = iconClasses('Go to previous page');
+ const shared = [...iconClasses('Go to next page')].filter(name =>
+ prev.has(name),
+ );
+ expect(shared.length).toBeGreaterThan(0);
+ for (const name of ['Go to first page', 'Go to last page']) {
+ const classes = iconClasses(name);
+ expect(shared.filter(c => !classes.has(c))).toEqual([]);
+ }
+ });
+ });
+ });
+
+ describe('hasFirstLast on other variants', () => {
+ it.each(['pages', 'count', 'dots', 'none'] as const)(
+ 'does not add first/last to the %s variant',
+ variant => {
+ render(
+ <Pagination
+ page={3}
+ onChange={() => {}}
+ totalItems={50}
+ pageSize={10}
+ variant={variant}
+ hasFirstLast
+ />,
+ );
+ expect(
+ screen.queryByRole('button', {name: 'Go to first page'}),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Go to last page'}),
+ ).not.toBeInTheDocument();
+ },
+ );
});
// ---------------------------------------------------------------------------
diff --git a/packages/core/src/Pagination/Pagination.tsx b/packages/core/src/Pagination/Pagination.tsx
index b089a85c69..b4691f6fd8 100644
--- a/packages/core/src/Pagination/Pagination.tsx
+++ b/packages/core/src/Pagination/Pagination.tsx
@@ -5,9 +5,10 @@
/**
* @file Pagination.tsx
* @input Uses React, StyleX, Button, Icon, Selector, Text; page number buttons delegate to Button.
+ * Compact first/last buttons cancel the inside control gap with logical token margins.
* Prev/next and first/last chevrons mirror under RTL via the shared rtlStyles.mirror
- * (CSS scaleX), not a JS direction read. The input variant uses the chevronsLeft/chevronsRight
- * (first/last) icons.
+ * (CSS scaleX), not a JS direction read. The input and compact variants use the
+ * chevronsLeft/chevronsRight (first/last) icons.
* @output Exports Pagination component, PaginationProps, PaginationVariant, PaginationSize types
* @position Core implementation; consumed by index.ts, tested by Pagination.test.tsx
*
@@ -105,7 +106,8 @@ export interface PaginationProps extends Omit<
* Visual variant controlling what appears between prev/next buttons.
* - pages: Page number buttons with ellipsis (default)
* - count: "X–Y of Z" text
- * - compact: "Page X of Y" text
+ * - compact: "Page X of Y" text. First/last buttons are opt-in (see
+ * hasFirstLast).
* - dots: Dot indicators
* - input: An editable number box rendering "Page [ n ] / N". The leading
* noun is controlled by `pageLabel`. First/last double-chevron buttons
@@ -122,9 +124,11 @@ export interface PaginationProps extends Omit<
pageLabel?: string;
/**
* Whether to show first/last («/») double-chevron buttons flanking
- * prev/next. Only applies to the `input` variant; other variants ignore it.
- * The last button needs a known total — it is omitted when the page count is
- * unknown (cursor/hasMore pagination). @default true
+ * prev/next. Applies to the `input` variant (shown unless false) and the
+ * `compact` variant (shown only when true); other variants ignore it.
+ * The last button needs a known total — both are omitted when the page count
+ * is unknown (cursor/hasMore pagination).
+ * @default true for `input`, false for `compact`
*/
hasFirstLast?: boolean;
/**
@@ -181,6 +185,12 @@ const styles = stylex.create({
alignItems: 'center',
gap: spacingVars['--spacing-1'],
},
+ compactFirst: {
+ marginInlineEnd: `calc(-1 * ${spacingVars['--spacing-1']})`,
+ },
+ compactLast: {
+ marginInlineStart: `calc(-1 * ${spacingVars['--spacing-1']})`,
+ },
ellipsis: {
display: 'inline-flex',
alignItems: 'center',
@@ -369,7 +379,7 @@ export function Pagination({
onPageSizeChange,
variant = 'pages',
pageLabel,
- hasFirstLast = true,
+ hasFirstLast: hasFirstLastProp,
step: stepProp = 1,
siblingCount = 1,
size = 'md',
@@ -572,10 +582,14 @@ export function Pagination({
const buttonSize = size === 'sm' ? 'sm' : 'md';
const isSm = size === 'sm';
- // First/last buttons only exist in the input variant, and only when the page
- // count is known (they'd have no target otherwise).
- const showFirstLast =
- hasFirstLast && variant === 'input' && computedTotalPages != null;
+ // First/last buttons are on by default in the input variant and opt-in for
+ // compact; other variants never render them. They also need a known page
+ // count (the last button would have no target otherwise).
+ const hasFirstLast =
+ variant === 'input'
+ ? (hasFirstLastProp ?? true)
+ : variant === 'compact' && hasFirstLastProp === true;
+ const showFirstLast = hasFirstLast && computedTotalPages != null;
const renderIndicator = () => {
switch (variant) {
@@ -819,6 +833,7 @@ export function Pagination({
onClick={handleFirst}
isDisabled={isDisabled || !hasPrevious}
isIconOnly
+ xstyle={variant === 'compact' && styles.compactFirst}
/>
)}
@@ -874,6 +889,7 @@ export function Pagination({
onClick={handleLast}
isDisabled={isDisabled || !hasNext}
isIconOnly
+ xstyle={variant === 'compact' && styles.compactLast}
/>
)}
</div>