From 240dcf6a4c55c97d025a28aaade63fcd3391bf29 Mon Sep 17 00:00:00 2001 From: Alex Gorischek Date: Mon, 30 Nov 2026 21:53:09 -0800 Subject: [PATCH 1/2] Kit: add useCategories and countFact categoriesOf and useCategories color comparison rows' categories from the categorical palette, ranked over both revisions, and return each category's color, the host legend and (in React) a swatch marked as a categorical color. countFact counts distinct keys on After for the summary bar, with the keys the comparison added and removed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/guides/renderer-kit-components.md | 30 +++- docs/guides/renderer-kit.md | 4 +- docs/reference/renderer-kit.md | 131 ++++++++++++++++++ packages/renderers/kit/src/categories.ts | 65 +++++++++ packages/renderers/kit/src/count-fact.ts | 66 +++++++++ packages/renderers/kit/src/index.ts | 2 + packages/renderers/kit/src/react.ts | 1 + .../renderers/kit/src/react/categories.tsx | 40 ++++++ packages/renderers/kit/styles/layout.css | 13 ++ .../renderers/kit/test/categories.test.mjs | 103 ++++++++++++++ 10 files changed, 452 insertions(+), 3 deletions(-) create mode 100644 packages/renderers/kit/src/categories.ts create mode 100644 packages/renderers/kit/src/count-fact.ts create mode 100644 packages/renderers/kit/src/react/categories.tsx create mode 100644 packages/renderers/kit/test/categories.test.mjs diff --git a/docs/guides/renderer-kit-components.md b/docs/guides/renderer-kit-components.md index 4f12f635..ed0dd5d1 100644 --- a/docs/guides/renderer-kit-components.md +++ b/docs/guides/renderer-kit-components.md @@ -70,7 +70,9 @@ not have to reinvent change emphasis, legends, summary bars, or styling rules: `icon` picks from the SDK vocabulary (`breaking`, `upgraded`, `enforced`), `ids` makes the fact clickable as a filter, `added`/`removed`/`modified` show comparison deltas in change colors (use `summaryChange(was, now)` for a - net measure delta like `39,882 lines of code +2,056`), and `description` + net measure delta like `39,882 lines of code +2,056`, and + `countFact(model.entities, {id, noun, key})` for a count of distinct keys on + After, with the keys the comparison added and removed), and `description` sets the tooltip (for example, the classification rules). The shell appends facts after kind counts and enforces protocol limits—if a fact references too many items, it keeps its count and drops its filter. @@ -311,6 +313,32 @@ accept token scale steps rather than raw lengths or colors—this is how - `Text` renders typography using `size` (`xs`, `sm`, `md`, `lg`, `xl`), `weight`, and `tone` (`default`, `muted`, `subtle`). +## Categories + +For items colored by a category (a language, a tool kind, a team), +`useCategories(rows, key, {title, colorMode})` colors each category from the +kit's categorical palette, ranked over both revisions, so a category keeps its +color and its place in the legend from Before to After and at every progress. +Pass the comparison rows (`model.entities`) and a stable `key(item)` that +returns a category key, a `Category` (`languageCategory(name)` keeps a +language's own color) or `undefined`. Items rank by count over both revisions, +or by `weight(item)`; `distinct` and `pinned` are `categoryPalette`'s options. + +It returns `color(key)` (CSS paint), `legend` (report it with +`useLegend(props.reportLegend, legend)`), `swatch(key)` (a dot in the category's +color, the `Swatch` component) and the `palette` itself. Everything painted with +a category's color carries `data-projections-category`, as `Swatch` does, so the +checks read it as a categorical color rather than a change. `categoriesOf` is +the same without React. + +```tsx +const kindOf = (tool: Entity) => tool.data?.kind as string | undefined +const kinds = useCategories(props.model.entities, kindOf, {title: 'Tool kinds', colorMode: props.colorMode}) +useLegend(props.reportLegend, kinds.legend) +// … +{kinds.swatch(kindOf(tool) ?? 'other')} +``` + ## Data tables When your entities share comparable properties, reach for `DataTable` instead of diff --git a/docs/guides/renderer-kit.md b/docs/guides/renderer-kit.md index 42195f46..ac3ad3f7 100644 --- a/docs/guides/renderer-kit.md +++ b/docs/guides/renderer-kit.md @@ -507,8 +507,8 @@ Build categories with `fileCategory(path)` (Linguist language grouped by parent, falling back to `.ext` or "No extension"), `languageCategory(name)` (for tool-reported language names), or `plainCategory(key)`. Each entry provides `paint` for CSS and `swatch` for the host legend (`{color}` for languages, -`{token}` otherwise), and `paletteLegend(palette, title)` formats the legend for -the host. Your renderer receives `colorMode` in `RendererProps`. +`{token}` otherwise), `paletteLegend` makes the host legend, and +[`useCategories`](renderer-kit-components.md#categories) does both for rows. ## Styles diff --git a/docs/reference/renderer-kit.md b/docs/reference/renderer-kit.md index 5934bb18..1a06d194 100644 --- a/docs/reference/renderer-kit.md +++ b/docs/reference/renderer-kit.md @@ -441,6 +441,62 @@ The narrowest and widest graph card, in card units (the widest grows by an icon' `graphCardWidth`), so a graph of short names packs densely and its layers stay aligned; text longer than the widest card holds is cut short with an ellipsis, and the card's tooltip has it whole. +### `Categories` + +```ts +interface Categories +``` + +What `categoriesOf` returns. + +| Member | Signature | Description | +|---|---|---| +| `color` | `"color": { (key: string): string }` | A category key's color, as CSS paint; the neutral "other" color for a key the items don't have. | +| `legend` | `"legend": RendererLegend` | The host's legend: the categories ranked over both revisions. Report it with `useLegend`. | +| `palette` | `"palette": Palette` | The palette, for anything beyond the color and the legend (`Palette.entry`, `Palette.ranked`). | + +### `categoriesOf` + +```ts +categoriesOf(rows: Iterable, any, any>, key: { (item: T): Category | string | undefined }, options: CategoriesOptions): Categories +``` + +The categories of a set of comparison rows, colored from the kit's categorical palette (`categoryPalette`) and +ranked over both revisions, so a category keeps its color, and its place in the legend, from Before to After and +at every progress. `key` gives an item's category: a key, a `Category` (`languageCategory(name)` for a language's +color) or `undefined` for none. Pass stable functions (defined outside the component, or memoized), so the palette +is computed once per document. + +### `CategoriesOptions` + +```ts +interface CategoriesOptions +``` + +How `categoriesOf` colors and keys its categories. + +| Member | Signature | Description | +|---|---|---| +| `colorMode` | `"colorMode"?: "dark" \| "light"` | The host theme's color mode (`RendererProps.colorMode`), for language colors. | +| `distinct` | `"distinct"?: false \| true` | Choose each color to stand as far as possible from those already used (`PaletteOptions.distinct`). | +| `limit` | `"limit"?: number` | How many categories the legend names before "N other types"; 14 by default. | +| `pinned` | `"pinned"?: ReadonlyMap` | Categories whose color is set, such as a definition's kind colors (`PaletteOptions.pinned`). | +| `title` | `"title": string` | The legend's title, such as `Languages` or `Tools`. | +| `weight` | `"weight"?: { (item: T): number }` | An item's weight, for ranking; 1 by default, so categories rank by how many items they have in both revisions. | + +### `CategorizedRow` + +```ts +interface CategorizedRow +``` + +A comparison row as `categoriesOf` reads it: either revision's item. + +| Member | Signature | Description | +|---|---|---| +| `after` | `"after"?: T \| undefined` | | +| `before` | `"before"?: T \| undefined` | | + ### `Category` ```ts @@ -758,6 +814,48 @@ Which relationships `followContext` follows, by kind: to an item's sources (`inc | `incoming` | `"incoming"?: { (kind: string): false \| true }` | Follow a relationship of this kind from its target back to its source (a dependency to the package that needs it). | | `outgoing` | `"outgoing"?: { (kind: string): false \| true }` | Follow a relationship of this kind from its source to its target (a probe to the hook it attaches to). | +### `CountedRow` + +```ts +interface CountedRow +``` + +A comparison row as `countFact` reads it: its ID and either revision's item. + +| Member | Signature | Description | +|---|---|---| +| `after` | `"after"?: T \| undefined` | | +| `before` | `"before"?: T \| undefined` | | +| `id` | `"id": string` | | + +### `countFact` + +```ts +countFact(rows: Iterable, any, any>, options: CountFactOptions): SummaryFactItem +``` + +A count for the host's summary bar (`SummaryFactItem`), the same at every progress: the distinct keys on After, +with what the comparison added (keys After has and Before hasn't) and removed (the other way round). Its `ids` are +the rows counted on After, so activating the figure filters to them. Pass `model.entities` (or any rows with +`before` and `after`); one extraction has no additions or removals. + +### `CountFactOptions` + +```ts +interface CountFactOptions +``` + +What `countFact` counts and how the summary bar words it. + +| Member | Signature | Description | +|---|---|---| +| `description` | `"description"?: string` | One sentence of context, the figure's tooltip. | +| `icon` | `"icon"?: string` | A theme icon's name, without its `icon-` prefix. | +| `id` | `"id": string` | The fact's stable ID, distinct among the summary's facts. | +| `key` | `"key"?: { (item: T, row: CountedRow): string \| undefined }` | The key an item is counted by, so several items with one key count once (tools by name, say); `undefined` leaves the item out. By default each row counts once, by its ID, in each revision it has. | +| `noun` | `"noun": SummaryNoun` | The figure's words. | +| `tone` | `"tone"?: "added" \| "modified" \| "neutral" \| "removed"` | The figure's color while it counts anything; neutral by default. | + ### `countText` ```ts @@ -3720,6 +3818,21 @@ CardGrid(__0: { "children": Iterable | Promise \| ReactElement \| ReactPortal \| bigint \| false \| null \| number \| string \| true \| undefined> \| ReactElement \| ReactPortal \| bigint \| false \| null \| number \| string \| true \| undefined, any, any> \| Promise \| Promise \| ReactElement \| ReactPortal \| bigint \| false \| null \| number \| string \| true \| undefined, any, any> \| ReactElement \| ReactPortal \| bigint \| false \| null \| number \| string \| true \| undefined> \| Promise \| Promise \| ReactElement \| ReactPortal \| bigint \| false \| null \| number \| string \| true \| undefined> \| ReactElement \| ReactPortal \| bigint \| false \| null \| number \| string \| true \| undefined> \| ReactElement \| ReactPortal \| bigint \| false \| null \| number \| string \| true \| undefined } \| { new (props: any, context: any): Component }> }` | A category's color as a dot (`Swatch`). | + ### `ChangeFooter` ```ts @@ -4467,6 +4580,15 @@ the old value struck through in the removed hue, an arrow, then the new value in the added hue. Pass identifier attributes (the SDK's `identifier`) for code values such as versions. +### `Swatch` + +```ts +Swatch(__0: { "category": string; "color": string; "size"?: "md" | "sm" }): Element +``` + +A category's color as a small dot, marked `data-projections-category` so the renderer checks read it as a +categorical color. `color` is the category's paint (`Categories.color(key)`). + ### `TablePropsSource` ```ts @@ -4505,6 +4627,15 @@ useBorderWidths(ref: RefObject): BorderWidths The border widths in effect on a rendered element, read when it mounts (before its first paint); the defaults until then. +### `useCategories` + +```ts +useCategories(rows: Array>, key: { (item: T): Category | string | undefined }, __2: CategoriesOptions): CategoriesView +``` + +`categoriesOf` (the categories of comparison rows, ranked over both revisions), computed once per document and +option set, with a swatch per category. Report the legend with `useLegend(props.reportLegend, categories.legend)`. + ### `useContentAspect` ```ts diff --git a/packages/renderers/kit/src/categories.ts b/packages/renderers/kit/src/categories.ts new file mode 100644 index 00000000..3653ac55 --- /dev/null +++ b/packages/renderers/kit/src/categories.ts @@ -0,0 +1,65 @@ +// Categorical colors for a renderer's items, ranked over both revisions, with the host legend. +import type {ColorMode, RendererLegend, ThemeTokenName} from '@githubnext/projections-renderer-sdk/protocol' +import {categoryPalette, paletteLegend, plainCategory, type Category, type Palette} from './palette.js' + +/** A comparison row as `categoriesOf` reads it: either revision's item. */ +export interface CategorizedRow { + /** The item in Before, if it has one. */ + before?: T | undefined + /** The item in After, if it has one. */ + after?: T | undefined +} + +/** How `categoriesOf` colors and keys its categories. */ +export interface CategoriesOptions { + /** The host theme's color mode (`RendererProps.colorMode`), for language colors. */ + colorMode?: ColorMode + /** The legend's title, such as `Languages` or `Tools`. */ + title: string + /** How many categories the legend names before "N other types"; 14 by default. */ + limit?: number + /** An item's weight, for ranking; 1 by default, so categories rank by how many items they have in both revisions. */ + weight?: (item: T) => number + /** Choose each color to stand as far as possible from those already used (`PaletteOptions.distinct`). */ + distinct?: boolean + /** Categories whose color is set, such as a definition's kind colors (`PaletteOptions.pinned`). */ + pinned?: ReadonlyMap +} + +/** What `categoriesOf` returns. */ +export interface Categories { + /** The palette, for anything beyond the color and the legend (`Palette.entry`, `Palette.ranked`). */ + palette: Palette + /** A category key's color, as CSS paint; the neutral "other" color for a key the items don't have. */ + color: (key: string) => string + /** The host's legend: the categories ranked over both revisions. Report it with `useLegend`. */ + legend: RendererLegend +} + +/** + * The categories of a set of comparison rows, colored from the kit's categorical palette (`categoryPalette`) and + * ranked over both revisions, so a category keeps its color, and its place in the legend, from Before to After and + * at every progress. `key` gives an item's category: a key, a `Category` (`languageCategory(name)` for a language's + * color) or `undefined` for none. Pass stable functions (defined outside the component, or memoized), so the palette + * is computed once per document. + */ +export function categoriesOf( + rows: Iterable>, + key: (item: T) => string | Category | undefined, + options: CategoriesOptions, +): Categories { + const weighed: {category: Category; weight: number}[] = [] + for (const row of rows) { + for (const item of [row.before, row.after]) { + if (item === undefined) continue + const found = key(item) + if (found === undefined) continue + weighed.push({category: typeof found === 'string' ? plainCategory(found) : found, weight: options.weight?.(item) ?? 1}) + } + } + const palette = categoryPalette(weighed, options.colorMode, { + ...(options.distinct === undefined ? {} : {distinct: options.distinct}), + ...(options.pinned === undefined ? {} : {pinned: options.pinned}), + }) + return {palette, color: palette.paintOf, legend: paletteLegend(palette, options.title, options.limit)} +} diff --git a/packages/renderers/kit/src/count-fact.ts b/packages/renderers/kit/src/count-fact.ts new file mode 100644 index 00000000..2685492b --- /dev/null +++ b/packages/renderers/kit/src/count-fact.ts @@ -0,0 +1,66 @@ +import type {SummaryFactItem, SummaryFactTone, SummaryNoun} from '@githubnext/projections-renderer-sdk/protocol' + +/** A comparison row as `countFact` reads it: its ID and either revision's item. */ +export interface CountedRow { + /** The row's ID, which a figure filters by. */ + id: string + /** The item in Before, if it has one. */ + before?: T | undefined + /** The item in After, if it has one. */ + after?: T | undefined +} + +/** What `countFact` counts and how the summary bar words it. */ +export interface CountFactOptions { + /** The fact's stable ID, distinct among the summary's facts. */ + id: string + /** The figure's words. */ + noun: SummaryNoun + /** + * The key an item is counted by, so several items with one key count once (tools by name, say); `undefined` leaves + * the item out. By default each row counts once, by its ID, in each revision it has. + */ + key?: (item: T, row: CountedRow) => string | undefined + /** One sentence of context, the figure's tooltip. */ + description?: string + /** A theme icon's name, without its `icon-` prefix. */ + icon?: string + /** The figure's color while it counts anything; neutral by default. */ + tone?: SummaryFactTone +} + +/** + * A count for the host's summary bar (`SummaryFactItem`), the same at every progress: the distinct keys on After, + * with what the comparison added (keys After has and Before hasn't) and removed (the other way round). Its `ids` are + * the rows counted on After, so activating the figure filters to them. Pass `model.entities` (or any rows with + * `before` and `after`); one extraction has no additions or removals. + */ +export function countFact(rows: Iterable>, options: CountFactOptions): SummaryFactItem { + const keyOf = options.key ?? ((_item: T, row: CountedRow) => row.id) + const before = new Set() + const after = new Set() + const ids: string[] = [] + for (const row of rows) { + const was = row.before === undefined ? undefined : keyOf(row.before, row) + const now = row.after === undefined ? undefined : keyOf(row.after, row) + if (was !== undefined) before.add(was) + if (now !== undefined) { + after.add(now) + ids.push(row.id) + } + } + const added = [...after].filter(key => !before.has(key)).length + const removed = [...before].filter(key => !after.has(key)).length + return { + type: 'fact', + id: options.id, + count: after.size, + noun: options.noun, + ...(options.icon === undefined ? {} : {icon: options.icon}), + ...(options.tone !== undefined && options.tone !== 'neutral' && after.size > 0 ? {tone: options.tone} : {}), + ...(ids.length ? {ids} : {}), + ...(added ? {added} : {}), + ...(removed ? {removed} : {}), + ...(options.description === undefined ? {} : {description: options.description}), + } +} diff --git a/packages/renderers/kit/src/index.ts b/packages/renderers/kit/src/index.ts index 232d6469..6c63f6ef 100644 --- a/packages/renderers/kit/src/index.ts +++ b/packages/renderers/kit/src/index.ts @@ -51,6 +51,8 @@ export * from './table-controls.js' export * from './fit.js' export * from './zoom.js' export * from './palette.js' +export * from './categories.js' +export * from './count-fact.js' export { variedBeyond, variedBeyondLabel, diff --git a/packages/renderers/kit/src/react.ts b/packages/renderers/kit/src/react.ts index 04c933ba..abcb35c3 100644 --- a/packages/renderers/kit/src/react.ts +++ b/packages/renderers/kit/src/react.ts @@ -18,6 +18,7 @@ export { usePaintHold, } from './react/shell/frame.js' export * from './react/components.js' +export * from './react/categories.js' export * from './react/status-tab.js' export * from './react/generated.js' export * from './react/diff-components.js' diff --git a/packages/renderers/kit/src/react/categories.tsx b/packages/renderers/kit/src/react/categories.tsx new file mode 100644 index 00000000..6ed937e4 --- /dev/null +++ b/packages/renderers/kit/src/react/categories.tsx @@ -0,0 +1,40 @@ +// The kit's categories as a hook, with a swatch for each category's color. +import {useMemo, type ReactElement} from 'react' +import {categoriesOf, type CategorizedRow, type Categories, type CategoriesOptions} from '../categories.js' +import type {Category} from '../palette.js' + +/** What `useCategories` returns: `categoriesOf`'s palette, colors and legend, and a swatch per category. */ +export interface CategoriesView extends Categories { + /** A category's color as a dot (`Swatch`). */ + swatch: (key: string) => ReactElement +} + +/** + * `categoriesOf` (the categories of comparison rows, ranked over both revisions), computed once per document and + * option set, with a swatch per category. Report the legend with `useLegend(props.reportLegend, categories.legend)`. + */ +export function useCategories( + rows: readonly CategorizedRow[], + key: (item: T) => string | Category | undefined, + {colorMode, title, limit, weight, distinct, pinned}: CategoriesOptions, +): CategoriesView { + return useMemo(() => { + const categories = categoriesOf(rows, key, { + title, + ...(colorMode === undefined ? {} : {colorMode}), + ...(limit === undefined ? {} : {limit}), + ...(weight === undefined ? {} : {weight}), + ...(distinct === undefined ? {} : {distinct}), + ...(pinned === undefined ? {} : {pinned}), + }) + return {...categories, swatch: (category: string) => } + }, [rows, key, colorMode, title, limit, weight, distinct, pinned]) +} + +/** + * A category's color as a small dot, marked `data-projections-category` so the renderer checks read it as a + * categorical color. `color` is the category's paint (`Categories.color(key)`). + */ +export function Swatch({category, color, size = 'sm'}: {category: string; color: string; size?: 'sm' | 'md'}) { + return