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
61 changes: 31 additions & 30 deletions README.md

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions fixtures/consumer/check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ assert.match(
/width="12"/,
"Icon renders on the server",
);
assert.match(
renderToString(createElement(variants.Badge, { variant: "success" }, "Live")),
/data-slot="badge"/,
"Badge renders on the server from the variants entry",
);

// A built-in theme from the shipped TOML, through the shipped resolver.
const toml = readFileSync(require.resolve("@tryatlas/design/themes/dracula.toml"), "utf8");
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@tryatlas/design",
"version": "0.1.2",
"version": "0.1.3",
"private": false,
"description": "Atlas's design system: primitives, tokens, themes and the ratchet, shared by desktop, web and docs.",
"license": "Apache-2.0",
Expand Down
116 changes: 116 additions & 0 deletions src/components/patterns/data-table.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { useState } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";

import { type Column, DataTable, type DataTableSort } from "./data-table.tsx";

afterEach(cleanup);

type Row = { id: string; name: string; seats: number };

const ROWS: Row[] = [
{ id: "a", name: "Beta", seats: 5 },
{ id: "b", name: "Alpha", seats: 12 },
{ id: "c", name: "Gamma", seats: 1 },
];

const COLUMNS: Column<Row>[] = [
{ id: "name", header: "Name", cell: (r) => r.name, sortValue: (r) => r.name },
{ id: "seats", header: "Seats", cell: (r) => r.seats, sortable: true },
];

const names = () =>
screen
.getAllByRole("row")
.slice(1)
.map((row) => row.querySelector("td")?.textContent);

describe("DataTable sorting", () => {
it("sorts locally by default: asc, desc, then the order given", () => {
render(<DataTable rows={ROWS} columns={COLUMNS} rowId={(r) => r.id} />);
const header = screen.getByRole("columnheader", { name: "Name" });
expect(names()).toEqual(["Beta", "Alpha", "Gamma"]);
fireEvent.click(header);
expect(names()).toEqual(["Alpha", "Beta", "Gamma"]);
expect(header.getAttribute("aria-sort")).toBe("ascending");
fireEvent.click(header);
expect(names()).toEqual(["Gamma", "Beta", "Alpha"]);
fireEvent.click(header);
expect(names()).toEqual(["Beta", "Alpha", "Gamma"]);
expect(header.getAttribute("aria-sort")).toBeNull();
});

it("does not offer a sort on a column it cannot sort locally", () => {
render(<DataTable rows={ROWS} columns={COLUMNS} rowId={(r) => r.id} />);
const seats = screen.getByRole("columnheader", { name: "Seats" });
fireEvent.click(seats);
expect(seats.getAttribute("aria-sort")).toBeNull();
expect(names()).toEqual(["Beta", "Alpha", "Gamma"]);
});

it("reports the next sort to onSortChange, and still sorts locally when uncontrolled", () => {
const onSortChange = vi.fn();
render(
<DataTable rows={ROWS} columns={COLUMNS} rowId={(r) => r.id} onSortChange={onSortChange} />,
);
fireEvent.click(screen.getByRole("columnheader", { name: "Name" }));
expect(onSortChange).toHaveBeenLastCalledWith({ id: "name", dir: "asc" });
expect(names()).toEqual(["Alpha", "Beta", "Gamma"]);
});

it("controlled: draws the sort it is given and asks for the next one", () => {
const onSortChange = vi.fn();
render(
<DataTable
rows={ROWS}
columns={COLUMNS}
rowId={(r) => r.id}
sort={{ id: "name", dir: "desc" }}
onSortChange={onSortChange}
/>,
);
const header = screen.getByRole("columnheader", { name: "Name" });
expect(header.getAttribute("aria-sort")).toBe("descending");
expect(names()).toEqual(["Gamma", "Beta", "Alpha"]);
fireEvent.click(header);
expect(onSortChange).toHaveBeenLastCalledWith(null);
// The parent did not change `sort`, so neither does the table.
expect(header.getAttribute("aria-sort")).toBe("descending");
expect(names()).toEqual(["Gamma", "Beta", "Alpha"]);
});

it("manualSorting: keeps the rows in the order given, sorted elsewhere", () => {
function ServerSorted() {
const [sort, setSort] = useState<DataTableSort>(null);
// Stand-in for the server: the parent sorts and hands the rows back.
const rows =
sort?.id === "seats"
? [...ROWS].sort((a, b) => (sort.dir === "asc" ? a.seats - b.seats : b.seats - a.seats))
: ROWS;
return (
<DataTable
rows={rows}
columns={COLUMNS}
rowId={(r) => r.id}
sort={sort}
onSortChange={setSort}
manualSorting
/>
);
}
render(<ServerSorted />);
const seats = screen.getByRole("columnheader", { name: "Seats" });
fireEvent.click(seats);
expect(seats.getAttribute("aria-sort")).toBe("ascending");
expect(names()).toEqual(["Gamma", "Beta", "Alpha"]);
fireEvent.click(seats);
expect(names()).toEqual(["Alpha", "Beta", "Gamma"]);

// A column with a sortValue is not re-sorted locally under manualSorting.
const name = screen.getByRole("columnheader", { name: "Name" });
fireEvent.click(name);
expect(name.getAttribute("aria-sort")).toBe("ascending");
expect(names()).toEqual(["Beta", "Alpha", "Gamma"]);
});
});
45 changes: 37 additions & 8 deletions src/components/patterns/data-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ import { ScrollFade, useScrollEdges } from "../../ui/scroll-fade.tsx";
* `border-subtle` hairlines; and a footer band. Rows highlight on hover and
* take the `element-selected` wash when chosen. Right-aligned cells are
* tabular. The body fades at an edge only while there is more past it.
*
* Sorting is local by default: a header click sorts `rows` by the column's
* `sortValue`. A table whose data is sorted on the server controls it
* instead: pass `sort` and `onSortChange` to own the state, and
* `manualSorting` so the table draws `rows` in the order given. Under
* `manualSorting`, a column with no `sortValue` opts in with `sortable`.
*/

export type Column<T> = {
Expand All @@ -25,11 +31,21 @@ export type Column<T> = {
cell: (row: T) => React.ReactNode;
/** Enables the sort toggle. Return a comparable value. */
sortValue?: (row: T) => string | number;
/** Enables the sort toggle without a `sortValue`. Only under
* `manualSorting`, where the rows arrive sorted. */
sortable?: boolean;
align?: "left" | "right";
className?: string;
};

type Sort = { id: string; dir: "asc" | "desc" } | null;
/** The column a table is sorted by, or `null` for the order given. */
export type DataTableSort = { id: string; dir: "asc" | "desc" } | null;

/** A header click: ascending, then descending, then unsorted. */
function nextSort(current: DataTableSort, id: string): DataTableSort {
if (current?.id !== id) return { id, dir: "asc" };
return current.dir === "asc" ? { id, dir: "desc" } : null;
}

function DataTable<T>({
rows,
Expand All @@ -40,6 +56,9 @@ function DataTable<T>({
toolbar,
footer,
empty,
sort: sortProp,
onSortChange,
manualSorting = false,
className,
}: {
rows: Array<T>;
Expand All @@ -52,14 +71,21 @@ function DataTable<T>({
/** What the body says when there are no rows (a filter that matched
* nothing, a period with no sessions). Without it the body is blank. */
empty?: React.ReactNode;
/** The sort, controlled. Leave it out and the table keeps its own. */
sort?: DataTableSort;
/** Called with the next sort on a header click, controlled or not. */
onSortChange?: (next: DataTableSort) => void;
/** `rows` arrive already sorted (on the server): draw them as given. */
manualSorting?: boolean;
className?: string;
}) {
const [sort, setSort] = useState<Sort>(null);
const [localSort, setLocalSort] = useState<DataTableSort>(null);
const sort = sortProp !== undefined ? sortProp : localSort;
const scroller = useRef<HTMLDivElement>(null);
const edges = useScrollEdges(scroller, [rows]);

const sorted = useMemo(() => {
if (!sort) return rows;
if (!sort || manualSorting) return rows;
const col = columns.find((c) => c.id === sort.id);
if (!col?.sortValue) return rows;
const get = col.sortValue;
Expand All @@ -69,12 +95,12 @@ function DataTable<T>({
const r = av < bv ? -1 : av > bv ? 1 : 0;
return sort.dir === "asc" ? r : -r;
});
}, [rows, columns, sort]);
}, [rows, columns, sort, manualSorting]);

function toggle(id: string) {
setSort((s) =>
s?.id === id ? (s.dir === "asc" ? { id, dir: "desc" } : null) : { id, dir: "asc" },
);
const next = nextSort(sort, id);
if (sortProp === undefined) setLocalSort(next);
onSortChange?.(next);
}

return (
Expand Down Expand Up @@ -104,7 +130,10 @@ function DataTable<T>({
<tr>
{columns.map((col) => {
const active = sort?.id === col.id;
const sortable = !!col.sortValue;
// Sorted here, a column needs a `sortValue`; sorted elsewhere,
// `sortable` is enough. Otherwise the arrow would claim a
// sort the rows don't show.
const sortable = !!col.sortValue || (manualSorting && !!col.sortable);
return (
<th
key={col.id}
Expand Down
20 changes: 19 additions & 1 deletion src/components/shell/sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,29 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "../../ui/tooltip.tsx";
* backgrounds. The `railId` comes from `useId` at the rail level so every
* row agrees on it.
*
* 2. WIDTH IS A SPRING. `motion.aside` animates between `14rem` and
* 2. WIDTH IS A SPRING. `motion.nav` animates between `14rem` and
* `3.25rem` — rem strings, so the rail follows the interface scale with
* no JS multiplication. Labels fade on their own, faster curve so text is
* gone before the rail is narrow enough to clip it.
*
* This is a layout animation on purpose; the composited alternatives were
* tried on paper and each one shows. The page beside the rail is a
* bordered, rounded card whose left edge has to follow the rail's right
* edge every frame, and only a width change moves one edge of a box:
* - `scaleX` on the rail stretches its glyphs, its text and the panel's
* rounded border mid-flight.
* - Snapping the rail's layout width and revealing it with `clip-path`
* loses the panel's right border for the whole motion, and the glyph
* column jumps between its expanded and centred positions.
* - Resizing the page once and sliding it with `translateX` either opens
* a strip of bare canvas at the page's right edge (expanding) or pushes
* its right-aligned controls off-screen (collapsing), then text reflows
* in one step at the end.
* The cost is bounded: the spring is critically damped, so it settles
* without oscillating past the target, and it plays only when the user
* toggles the rail. Revisit if a profile shows dropped frames
* on a large page.
*
* 3. CHILDREN HANG OFF A RAIL. A parent with children is a disclosure, not
* a destination; its children fade in on a hairline with L-connectors,
* and the connector turns to ink on the active one.
Expand Down
12 changes: 10 additions & 2 deletions src/components/ui/upload-icon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ import { ICON_STROKE_WIDTH } from "../../ui/icon.tsx";
/**
* A tray with an arrow that springs up out of it — "share" / "send out".
*
* The arrow rides a critically damped spring (damping at, or rounded just
* over, 2·√stiffness), as the mailbox's flag does: it rises and stops, with no overshoot, since a
* hover throws nothing. Both directions name their spring; motion's default
* for `y` is under-damped and would bounce on the way back.
*
* Animates on hover by itself, or through a ref (`startAnimation` /
* `stopAnimation`) so a whole button can drive it. `currentColor`, at the
* system's icon stroke so it sits beside Lucide glyphs.
Expand All @@ -21,10 +26,13 @@ export type UploadIconHandle = {
};

const ARROW: Variants = {
normal: { y: 0 },
normal: {
y: 0,
transition: { type: "spring", stiffness: 300, damping: 35 },
},
animate: {
y: -2,
transition: { type: "spring", stiffness: 200, damping: 10, mass: 1 },
transition: { type: "spring", stiffness: 280, damping: 34, mass: 1 },
},
};

Expand Down
5 changes: 3 additions & 2 deletions src/ui/badge.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
"use client";

import * as React from "react";
import type { VariantProps } from "class-variance-authority";
import { cn } from "../lib/utils.ts";
Expand All @@ -15,6 +13,9 @@ import { badgeVariants } from "./badge-variants.ts";
*
* A badge is not a control, so it is not on the control-height scale: it sizes
* itself to its text. Reach for `Kbd` instead when the content is a keystroke.
*
* No `"use client"`: it is a plain `<span>` with no hooks, so a React Server
* Component can render it. Import it from `@tryatlas/design/variants` there.
*/
export interface BadgeProps
extends React.ComponentProps<"span">, VariantProps<typeof badgeVariants> {}
Expand Down
Loading
Loading