From 5caa771997bea7cc9b3580789892eef6f1c6eafc Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:42:21 +0000 Subject: [PATCH 1/9] Kit: fold mass removals into one summary card (work in progress) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- docs/guides/renderer-kit-components.md | 8 +- docs/guides/renderer-kit-graphs.md | 18 ++ .../renderers/graph/browser/graph.spec.ts | 35 +- .../graph/fixtures/mass-removal-after.json | 49 +++ .../graph/fixtures/mass-removal-before.json | 299 ++++++++++++++++++ packages/renderers/graph/scenarios.json | 8 + .../renderers/kit/browser/card-grid-page.ts | 58 ++++ .../renderers/kit/browser/card-grid.spec.ts | 74 +++++ packages/renderers/kit/src/index.ts | 1 + packages/renderers/kit/src/mass-fold.ts | 275 ++++++++++++++++ packages/renderers/kit/src/react/fold.tsx | 2 +- .../kit/src/react/graph-canvas/canvas.tsx | 14 +- .../src/react/graph-canvas/entity-card.tsx | 6 +- .../kit/src/react/graph-canvas/mass-folds.ts | 107 +++++++ .../renderers/kit/src/react/grid-folds.tsx | 171 ++++++++++ .../renderers/kit/src/react/kind-nouns.ts | 14 + .../kit/src/react/layout-components.tsx | 30 +- .../kit/src/react/shell/kit-renderer.tsx | 77 +++-- packages/renderers/kit/src/summary.ts | 16 +- packages/renderers/kit/styles/diff.css | 4 + packages/renderers/kit/styles/layout.css | 14 + .../renderers/kit/test/mass-fold.test.mjs | 131 ++++++++ packages/renderers/testing/README.md | 5 +- .../renderers/testing/src/checks/catalog.ts | 2 +- .../testing/src/checks/comparison/diff.ts | 28 +- .../testing/src/checks/comparison/steps.ts | 12 +- .../renderers/testing/src/measure/entities.ts | 11 + packages/renderers/testing/src/types.ts | 2 + .../renderers/testing/test/helpers.test.mjs | 52 +++ 29 files changed, 1467 insertions(+), 56 deletions(-) create mode 100644 packages/renderers/graph/fixtures/mass-removal-after.json create mode 100644 packages/renderers/graph/fixtures/mass-removal-before.json create mode 100644 packages/renderers/kit/browser/card-grid-page.ts create mode 100644 packages/renderers/kit/browser/card-grid.spec.ts create mode 100644 packages/renderers/kit/src/mass-fold.ts create mode 100644 packages/renderers/kit/src/react/graph-canvas/mass-folds.ts create mode 100644 packages/renderers/kit/src/react/grid-folds.tsx create mode 100644 packages/renderers/kit/src/react/kind-nouns.ts create mode 100644 packages/renderers/kit/test/mass-fold.test.mjs diff --git a/docs/guides/renderer-kit-components.md b/docs/guides/renderer-kit-components.md index efc41642f..e658cf754 100644 --- a/docs/guides/renderer-kit-components.md +++ b/docs/guides/renderer-kit-components.md @@ -315,7 +315,13 @@ accept token scale steps rather than raw lengths or colors—this is how inset, so it lines up with the title. Tables stay unpadded, so their rows run edge to edge. - `CardGrid` lays cards out in as many columns as fit, collapsing to one column - on phones. + on phones. In a comparison, a dozen or more of its `EntityCard`s + (`massFoldMinimum`) removed together, of one kind, fold into one card in the + removed style that counts them with the definition's noun ("14 jobs removed"); + additions fold the same way. The card takes the place of the first, opens them + in place ("Hide 14 removed jobs") and, while closed, lists them in + `data-entity-aliases`, so the host's selection, hover and filter of one find + it. A card reports its status and kind from its `change` row. - `EntityCard` renders a single entity as a ring unit with `data-entity-id`, a select button, `label`, `identifier`, `children`, and worded change status. In progress modes, its leading edge picks up the change hue as `emphasis` rises diff --git a/docs/guides/renderer-kit-graphs.md b/docs/guides/renderer-kit-graphs.md index 52debc974..b8697d628 100644 --- a/docs/guides/renderer-kit-graphs.md +++ b/docs/guides/renderer-kit-graphs.md @@ -94,6 +94,24 @@ subgraphs share layers, and cards within a layer align along the edge where their incoming relationships arrive (top or left) so each layer forms a clean baseline. +**Mass changes.** In a comparison, a dozen or more sibling cards +(`massFoldMinimum`, twice `blockMinimum`) removed together fold into one card +(`foldMassChanges`): cards of one kind with the same status in the same +container, or at the top level, whose container stays. The card takes their kind +and status, so it is drawn in the removed style, and counts them with the +definition's noun (`presentation.kinds..noun`, else the renderer's +`nouns`, else the host's words): "48 tables removed". It stands for the cards, +the parts they contain and their relationships: a relationship to a card that +stays is drawn once from the fold for each other end, kind and direction, and +the fold and its links join the first step that changes any of them. Additions +fold the same way. The card keeps a `data-entity-id` of its own (`pk-mass:…`) +and lists everything it stands for in `data-entity-aliases`, so the host's +selection, hover, filter and annotations of a folded item find it; the canvas +moves a selection, focus request (`--entity`) or `focus` of a folded item onto +the card. Activating the card, or one of its links, opens its cards in place; +the card stays, labeled "Hide 48 removed tables", as the way to fold them again, +until the document changes. + **Sibling blocks.** When six or more cards (`blockMinimum`) share every relationship, they wrap into a block instead of stretching their layer into one long row. Sharing every relationship means having the same sources and targets, diff --git a/packages/renderers/graph/browser/graph.spec.ts b/packages/renderers/graph/browser/graph.spec.ts index a01b14690..7987a08e2 100644 --- a/packages/renderers/graph/browser/graph.spec.ts +++ b/packages/renderers/graph/browser/graph.spec.ts @@ -1,5 +1,6 @@ import {expect, test} from '@playwright/test' -import {openRenderer} from '@githubnext/projections-renderer-harness/playwright' +import {harnessInspector, openRenderer} from '@githubnext/projections-renderer-harness/playwright' +import {openStage} from '@githubnext/projections-renderer-testing/playwright' import {featureFlags, fileReflow, layeredWaves, wideFanOut} from '../../kit/browser/fixtures.js' import {scrubSuite, selectionSuite} from '../../kit/browser/suite.js' import {paneStatusSuite, statusSuite} from '../../kit/browser/status.js' @@ -281,3 +282,35 @@ test('a wide fan-out wraps into a block whose relationships enter and leave its expect(into.every(link => link.toBlock !== undefined) && out.every(link => link.fromBlock !== undefined)).toBe(true) } }) + +test('16 reports removed together fold into one card that presents them to the host and opens in place', async ({page}) => { + const fold = 'pk-mass:removed:report:' + for (const comparisonMode of ['animated', 'diff'] as const) { + const renderer = await openStage(page, harnessInspector(), {scenario: 'graph/mass-removal', comparisonMode, progress: 0}) + const card = renderer.frame.locator(`.graph-node[data-entity-id="${fold}"]`) + await expect(card).toHaveCount(1) + await expect(card).toHaveAttribute('aria-label', 'Show 16 reports removed') + await expect(card).toHaveAttribute('aria-expanded', 'false') + await expect(renderer.frame.locator('.graph-node[data-entity-id^="report:"]')).toHaveCount(0) + const aliases: unknown = JSON.parse((await card.getAttribute('data-entity-aliases')) ?? '[]') + expect(aliases).toEqual(expect.arrayContaining(['report:refunds', 'report:refunds->postgres', 'reporting->report:refunds'])) + // The host's selection and hover of a folded report find the card. + await renderer.select('report:refunds') + await expect(card).toHaveClass(/\bselected\b/u) + await expect(card).toHaveAttribute('data-projections-ring-selected', /.*/u) + await renderer.select(null) + await renderer.hover('report:refunds') + await expect(card).toHaveAttribute('data-projections-ring-hover', /.*/u) + await renderer.hover(null) + // Activating it opens the reports in place and selects nothing; again folds them. + await card.click() + await expect(renderer.frame.locator('.graph-node[data-entity-id^="report:"]')).toHaveCount(16) + await expect(card).toHaveAttribute('aria-expanded', 'true') + expect((await renderer.state()).selections).toEqual([]) + await card.click() + await expect(renderer.frame.locator('.graph-node[data-entity-id^="report:"]')).toHaveCount(0) + } + // `--entity` on a folded report opens on its card. + const focused = await openStage(page, harnessInspector(), {scenario: 'graph/mass-removal', progress: 0, focus: {id: 'report:refunds'}}) + await expect(focused.frame.locator(`.graph-node[data-entity-id="${fold}"]`)).toBeInViewport() +}) diff --git a/packages/renderers/graph/fixtures/mass-removal-after.json b/packages/renderers/graph/fixtures/mass-removal-after.json new file mode 100644 index 000000000..c60afee08 --- /dev/null +++ b/packages/renderers/graph/fixtures/mass-removal-after.json @@ -0,0 +1,49 @@ +{ + "protocolVersion": 0, + "schema": "graph/v0", + "entities": [ + { "id": "gateway", "kind": "service", "label": "gateway" }, + { "id": "orders", "kind": "service", "label": "orders" }, + { "id": "catalog", "kind": "service", "label": "catalog" }, + { "id": "postgres", "kind": "database", "label": "postgres" }, + { "id": "analytics", "kind": "service", "label": "analytics" } + ], + "relationships": [ + { + "id": "gateway->orders", + "kind": "calls", + "from": "gateway", + "to": "orders" + }, + { + "id": "gateway->catalog", + "kind": "calls", + "from": "gateway", + "to": "catalog" + }, + { + "id": "orders->postgres", + "kind": "reads", + "from": "orders", + "to": "postgres" + }, + { + "id": "catalog->postgres", + "kind": "reads", + "from": "catalog", + "to": "postgres" + }, + { + "id": "gateway->analytics", + "kind": "calls", + "from": "gateway", + "to": "analytics" + }, + { + "id": "analytics->postgres", + "kind": "reads", + "from": "analytics", + "to": "postgres" + } + ] +} diff --git a/packages/renderers/graph/fixtures/mass-removal-before.json b/packages/renderers/graph/fixtures/mass-removal-before.json new file mode 100644 index 000000000..17c7b3efb --- /dev/null +++ b/packages/renderers/graph/fixtures/mass-removal-before.json @@ -0,0 +1,299 @@ +{ + "protocolVersion": 0, + "schema": "graph/v0", + "entities": [ + { "id": "gateway", "kind": "service", "label": "gateway" }, + { "id": "orders", "kind": "service", "label": "orders" }, + { "id": "catalog", "kind": "service", "label": "catalog" }, + { "id": "postgres", "kind": "database", "label": "postgres" }, + { "id": "reporting", "kind": "service", "label": "reporting" }, + { + "id": "report:daily-orders", + "kind": "report", + "label": "report:daily-orders" + }, + { + "id": "report:weekly-orders", + "kind": "report", + "label": "report:weekly-orders" + }, + { + "id": "report:monthly-orders", + "kind": "report", + "label": "report:monthly-orders" + }, + { "id": "report:refunds", "kind": "report", "label": "report:refunds" }, + { + "id": "report:chargebacks", + "kind": "report", + "label": "report:chargebacks" + }, + { + "id": "report:inventory-levels", + "kind": "report", + "label": "report:inventory-levels" + }, + { "id": "report:stockouts", "kind": "report", "label": "report:stockouts" }, + { + "id": "report:top-products", + "kind": "report", + "label": "report:top-products" + }, + { + "id": "report:slow-movers", + "kind": "report", + "label": "report:slow-movers" + }, + { + "id": "report:customer-churn", + "kind": "report", + "label": "report:customer-churn" + }, + { + "id": "report:new-customers", + "kind": "report", + "label": "report:new-customers" + }, + { "id": "report:cohorts", "kind": "report", "label": "report:cohorts" }, + { + "id": "report:revenue-by-region", + "kind": "report", + "label": "report:revenue-by-region" + }, + { + "id": "report:tax-summary", + "kind": "report", + "label": "report:tax-summary" + }, + { "id": "report:payouts", "kind": "report", "label": "report:payouts" }, + { + "id": "report:fraud-review", + "kind": "report", + "label": "report:fraud-review" + } + ], + "relationships": [ + { + "id": "gateway->orders", + "kind": "calls", + "from": "gateway", + "to": "orders" + }, + { + "id": "gateway->catalog", + "kind": "calls", + "from": "gateway", + "to": "catalog" + }, + { + "id": "orders->postgres", + "kind": "reads", + "from": "orders", + "to": "postgres" + }, + { + "id": "catalog->postgres", + "kind": "reads", + "from": "catalog", + "to": "postgres" + }, + { + "id": "gateway->reporting", + "kind": "calls", + "from": "gateway", + "to": "reporting" + }, + { + "id": "reporting->report:daily-orders", + "kind": "runs", + "from": "reporting", + "to": "report:daily-orders" + }, + { + "id": "reporting->report:weekly-orders", + "kind": "runs", + "from": "reporting", + "to": "report:weekly-orders" + }, + { + "id": "reporting->report:monthly-orders", + "kind": "runs", + "from": "reporting", + "to": "report:monthly-orders" + }, + { + "id": "reporting->report:refunds", + "kind": "runs", + "from": "reporting", + "to": "report:refunds" + }, + { + "id": "reporting->report:chargebacks", + "kind": "runs", + "from": "reporting", + "to": "report:chargebacks" + }, + { + "id": "reporting->report:inventory-levels", + "kind": "runs", + "from": "reporting", + "to": "report:inventory-levels" + }, + { + "id": "reporting->report:stockouts", + "kind": "runs", + "from": "reporting", + "to": "report:stockouts" + }, + { + "id": "reporting->report:top-products", + "kind": "runs", + "from": "reporting", + "to": "report:top-products" + }, + { + "id": "reporting->report:slow-movers", + "kind": "runs", + "from": "reporting", + "to": "report:slow-movers" + }, + { + "id": "reporting->report:customer-churn", + "kind": "runs", + "from": "reporting", + "to": "report:customer-churn" + }, + { + "id": "reporting->report:new-customers", + "kind": "runs", + "from": "reporting", + "to": "report:new-customers" + }, + { + "id": "reporting->report:cohorts", + "kind": "runs", + "from": "reporting", + "to": "report:cohorts" + }, + { + "id": "reporting->report:revenue-by-region", + "kind": "runs", + "from": "reporting", + "to": "report:revenue-by-region" + }, + { + "id": "reporting->report:tax-summary", + "kind": "runs", + "from": "reporting", + "to": "report:tax-summary" + }, + { + "id": "reporting->report:payouts", + "kind": "runs", + "from": "reporting", + "to": "report:payouts" + }, + { + "id": "reporting->report:fraud-review", + "kind": "runs", + "from": "reporting", + "to": "report:fraud-review" + }, + { + "id": "report:daily-orders->postgres", + "kind": "reads", + "from": "report:daily-orders", + "to": "postgres" + }, + { + "id": "report:weekly-orders->postgres", + "kind": "reads", + "from": "report:weekly-orders", + "to": "postgres" + }, + { + "id": "report:monthly-orders->postgres", + "kind": "reads", + "from": "report:monthly-orders", + "to": "postgres" + }, + { + "id": "report:refunds->postgres", + "kind": "reads", + "from": "report:refunds", + "to": "postgres" + }, + { + "id": "report:chargebacks->postgres", + "kind": "reads", + "from": "report:chargebacks", + "to": "postgres" + }, + { + "id": "report:inventory-levels->postgres", + "kind": "reads", + "from": "report:inventory-levels", + "to": "postgres" + }, + { + "id": "report:stockouts->postgres", + "kind": "reads", + "from": "report:stockouts", + "to": "postgres" + }, + { + "id": "report:top-products->postgres", + "kind": "reads", + "from": "report:top-products", + "to": "postgres" + }, + { + "id": "report:slow-movers->postgres", + "kind": "reads", + "from": "report:slow-movers", + "to": "postgres" + }, + { + "id": "report:customer-churn->postgres", + "kind": "reads", + "from": "report:customer-churn", + "to": "postgres" + }, + { + "id": "report:new-customers->postgres", + "kind": "reads", + "from": "report:new-customers", + "to": "postgres" + }, + { + "id": "report:cohorts->postgres", + "kind": "reads", + "from": "report:cohorts", + "to": "postgres" + }, + { + "id": "report:revenue-by-region->postgres", + "kind": "reads", + "from": "report:revenue-by-region", + "to": "postgres" + }, + { + "id": "report:tax-summary->postgres", + "kind": "reads", + "from": "report:tax-summary", + "to": "postgres" + }, + { + "id": "report:payouts->postgres", + "kind": "reads", + "from": "report:payouts", + "to": "postgres" + }, + { + "id": "report:fraud-review->postgres", + "kind": "reads", + "from": "report:fraud-review", + "to": "postgres" + } + ] +} diff --git a/packages/renderers/graph/scenarios.json b/packages/renderers/graph/scenarios.json index e35ad12b8..4722b5184 100644 --- a/packages/renderers/graph/scenarios.json +++ b/packages/renderers/graph/scenarios.json @@ -25,6 +25,14 @@ } } }, + { + "id": "mass-removal", + "title": "Reporting retired, 16 reports with it", + "description": "The reporting service leaves with the 16 reports it ran: a dozen or more siblings removed together fold into one card, 16 reports removed, which opens in place. An analytics service arrives.", + "renderer": "graph", + "before": "fixtures/mass-removal-before.json", + "after": "fixtures/mass-removal-after.json" + }, { "id": "test-timings", "title": "Test timings with volatile durations", diff --git a/packages/renderers/kit/browser/card-grid-page.ts b/packages/renderers/kit/browser/card-grid-page.ts new file mode 100644 index 000000000..f848c848e --- /dev/null +++ b/packages/renderers/kit/browser/card-grid-page.ts @@ -0,0 +1,58 @@ +// The card grid page's script (card-grid.spec.ts bundles it): a `CardGrid` of job cards in a `Group`, a workflow that +// drops 14 jobs and keeps 2, in the mode asked for. +import {createElement as h} from 'react' +import {flushSync} from 'react-dom' +import {createRoot} from 'react-dom/client' +import {CardGrid, ContentView, EntityCard, Group} from '../src/react/layout-components.js' +import '../react.css' + +export interface GridMode { + diff: boolean + emphasis: number +} + +declare global { + var showGrid: (mode: GridMode) => void + var selected: string[] +} + +const job = (id: string) => ({id, kind: 'job', label: id}) +const rows = [ + ...['build', 'test'].map(id => ({id, before: job(id), after: job(id), status: 'unchanged' as const})), + ...Array.from({length: 14}, (_, index) => `legacy-${String(index + 1).padStart(2, '0')}`).map(id => ({ + id, + before: job(id), + status: 'removed' as const, + })), +] + +const container = document.getElementById('root') +if (!container) throw new Error('The page has no #root') +const root = createRoot(container) +globalThis.selected = [] +globalThis.showGrid = ({diff, emphasis}) => { + const cards = rows.map(row => + h(EntityCard, { + key: row.id, + id: row.id, + label: row.id, + kind: 'Job', + selected: false, + onSelect: (id: string) => { + globalThis.selected.push(id) + }, + change: row, + emphasis, + ...(diff && row.status !== 'unchanged' ? {mark: row} : {}), + }), + ) + flushSync(() => { + root.render( + h( + 'div', + {className: 'pk'}, + h(ContentView, {children: h(Group, {title: 'Jobs', children: h(CardGrid, {label: 'Jobs', children: cards})})}), + ), + ) + }) +} diff --git a/packages/renderers/kit/browser/card-grid.spec.ts b/packages/renderers/kit/browser/card-grid.spec.ts new file mode 100644 index 000000000..c737d3d64 --- /dev/null +++ b/packages/renderers/kit/browser/card-grid.spec.ts @@ -0,0 +1,74 @@ +import {expect, test} from '@playwright/test' +import {build} from 'vite' +import {fileURLToPath} from 'node:url' +import {defaultThemeTokens} from '@githubnext/projections-renderer-sdk/protocol' +import type {GridMode} from './card-grid-page.js' + +/** + * A `CardGrid` folds a dozen or more of its cards removed together into one card in their removed style, which presents + * them to the host and opens them in place. + */ +const kit = fileURLToPath(new URL('../', import.meta.url)) + +let page: Promise | undefined +/** The card grid page: the kit's styles and the default light theme's tokens, and `card-grid-page.ts` bundled. */ +function gridPage() { + page ??= (async () => { + const built = await build({ + root: kit, + configFile: false, + logLevel: 'warn', + define: {'process.env.NODE_ENV': '"production"'}, + build: { + write: false, + minify: true, + cssCodeSplit: false, + lib: {entry: 'browser/card-grid-page.ts', formats: ['iife'], name: 'cardGridPage', fileName: () => 'grid.js'}, + }, + }) + const chunks = (Array.isArray(built) ? built : [built]).flatMap(result => ('output' in result ? result.output : [])) + const script = chunks.flatMap(chunk => (chunk.type === 'chunk' ? [chunk.code] : [])).join('\n') + const css = chunks + .flatMap(chunk => (chunk.type === 'asset' && chunk.fileName.endsWith('.css') ? [String(chunk.source)] : [])) + .join('\n') + const variables = Object.entries(defaultThemeTokens('light')) + .map(([name, value]) => `--projections-${name}: ${value};`) + .join('\n') + return `
` + })() + return page +} + +const legacy = Array.from({length: 14}, (_, index) => `legacy-${String(index + 1).padStart(2, '0')}`) + +for (const mode of [ + {diff: true, emphasis: 1}, + {diff: false, emphasis: 1}, +] satisfies GridMode[]) { + test(`a card grid folds 14 removed jobs into one card that opens in place (${mode.diff ? 'diff' : 'transition'})`, async ({ + page: target, + }) => { + await target.setContent(await gridPage()) + await target.evaluate(shown => globalThis.showGrid(shown), mode) + const fold = target.locator('.pk-mass-fold') + await expect(fold).toHaveCount(1) + await expect(fold).toHaveText(/14 jobs removed/u) + await expect(fold).toHaveAttribute('data-fold', 'closed') + // Closed, the fold presents every job it folds, so the host's selection of one finds it, and they take no room. + expect(JSON.parse((await fold.getAttribute('data-entity-aliases')) ?? '[]')).toEqual(legacy) + await expect(target.locator('[data-entity-id^="legacy-"]')).toHaveCount(0) + await expect(target.locator('[data-entity-id="build"]')).toBeVisible() + // It is drawn in the removed style its jobs share. + if (mode.diff) await expect(fold).toHaveAttribute('data-change', 'removed') + else await expect(fold).toHaveAttribute('data-status', 'removed') + // Opening it draws the jobs after it, and selects nothing; the fold stays, as the way to fold them again. + await fold.getByRole('button').click() + await expect(target.locator('[data-entity-id^="legacy-"]')).toHaveCount(14) + await expect(fold).toHaveText(/Hide 14 removed jobs/u) + await expect(fold.getByRole('button')).toHaveAttribute('aria-expanded', 'true') + expect(await fold.getAttribute('data-entity-aliases')).toBeNull() + expect(await target.evaluate(() => globalThis.selected)).toEqual([]) + await fold.getByRole('button').click() + await expect(target.locator('[data-entity-id^="legacy-"]')).toHaveCount(0) + }) +} diff --git a/packages/renderers/kit/src/index.ts b/packages/renderers/kit/src/index.ts index b958b3306..6d79fb155 100644 --- a/packages/renderers/kit/src/index.ts +++ b/packages/renderers/kit/src/index.ts @@ -37,6 +37,7 @@ export * from './legend.js' export * from './identifiers.js' export {focusedIds, placedAttribute} from './focus.js' export {changesScope, foldList, foldPrefix, isFold, scopedModel} from './scope.js' +export * from './mass-fold.js' export {followContext} from './scope-context.js' export {layoutFilter, partOwners} from './scope-filter.js' export type {ContextPaths} from './scope-context.js' diff --git a/packages/renderers/kit/src/mass-fold.ts b/packages/renderers/kit/src/mass-fold.ts new file mode 100644 index 000000000..d3b47212e --- /dev/null +++ b/packages/renderers/kit/src/mass-fold.ts @@ -0,0 +1,275 @@ +// Mass changes: a dozen or more sibling items removed (or added) together, folded into one card that counts them +// ("48 tables removed") and opens in place, so a comparison that drops a whole schema stays one readable frame. +import {humanizeKind, isContainment} from '@githubnext/projections-renderer-sdk/presentation' +import type {SummaryNoun} from '@githubnext/projections-renderer-sdk/protocol' +import type {Extraction} from '@githubnext/projections-schemas' +import type {ComparisonModel, ModelStep} from './model.js' +import {sides, type Side} from './scope-parts.js' + +/** + * The fewest sibling items removed (or added) together that fold into one card: twice a sibling block's + * `blockMinimum`, two full lines of its tray, past which more cards add height without saying more than their count. + * It is also where a stack of removed database tables alone outgrows a frame: on one schema, 48 removed tables drew a + * frame 81,546 px tall, about 1,700 px a table, so a dozen pass the 20,000 px most hosts render. + */ +export const massFoldMinimum = 12 + +/** The ID prefix of the cards and links `foldMassChanges` adds. */ +export const massFoldPrefix = 'pk-mass:' + +/** Whether an item is a card or link `foldMassChanges` adds. */ +export const isMassFold = (id: string) => id.startsWith(massFoldPrefix) + +/** The statuses that fold: items that only one revision has. */ +export type MassStatus = 'removed' | 'added' + +/** One fold of sibling items removed or added together. */ +export interface MassFold { + /** The fold card's row ID (`massFoldPrefix`). */ + id: string + status: MassStatus + /** The folded items' kind, which the card takes. */ + kind: string + /** The sibling entity rows it folds, in the model's order. */ + items: readonly string[] + /** + * Every row the card presents while closed: the siblings, the parts they contain and the relationships among them + * or to them, for the card's `data-entity-aliases`. + */ + presents: readonly string[] + /** Whether it is open: its items drawn on their own, and the card the way to fold them again. */ + open: boolean + /** The card's label: `48 tables removed`, or open, `Hide 48 removed tables`. */ + label: string +} + +/** A model with its mass changes folded (`foldMassChanges`), and what each fold stands for. */ +export interface MassFolded { + model: ComparisonModel + /** Each fold, by its card's ID; empty when nothing folds (and `model` is the one passed). */ + folds: ReadonlyMap + /** Each row a closed fold hides (entity or relationship), and the card or link drawn for it. */ + folded: ReadonlyMap + /** Each card and link a fold adds, and the rows it stands for: their step and emphasis are its. */ + stands: ReadonlyMap +} + +/** How `foldMassChanges` folds. */ +export interface MassFoldOptions { + /** Folds the person opened, by card ID: their items are drawn, and the card stays as the way to fold them again. */ + open?: ReadonlySet + /** The fewest siblings that fold (`massFoldMinimum` by default). */ + minimum?: number + /** A kind's words (the definition's noun); `humanizeKind` by default. */ + noun?: (kind: string) => SummaryNoun | undefined + /** BCP 47 locale for the count (`en-US` by default). */ + locale?: string +} + +/** The side that has an item of this status. */ +const sideOf = (status: MassStatus): Side => (status === 'removed' ? 'before' : 'after') + +/** A fold's card label: `48 tables removed`; open, `Hide 48 removed tables`. */ +export function massFoldLabel(count: number, status: MassStatus, noun: SummaryNoun, open = false, locale = 'en-US'): string { + const words = count === 1 ? noun.singular : noun.plural + const number = count.toLocaleString(locale) + return open ? `Hide ${number} ${status} ${words}` : `${number} ${words} ${status}` +} + +/** + * Folds every run of `minimum` or more sibling items removed together, or added together, into one card: items of + * one kind with the same status in the same container (or at the top level, outside any) when the container itself + * stays. The card takes their kind and status, so it is drawn in the removed (or added) style, and counts them with the + * definition's noun (`48 tables removed`). It stands for the items, the parts they contain and the relationships among + * them; a relationship from one of them to an item that stays is drawn once from the card, for each item, kind and + * direction. Steps place the card and its links in the first step that changes what they stand for. A fold in `open` + * draws its items, and its card stays, labeled `Hide 48 removed tables`, as the way to fold them again. A model with no + * such run is returned as it is. + */ +export function foldMassChanges(model: ComparisonModel, options: MassFoldOptions = {}): MassFolded { + const none: MassFolded = {model, folds: new Map(), folded: new Map(), stands: new Map()} + if (model.mode !== 'comparison') return none + const minimum = Math.max(2, options.minimum ?? massFoldMinimum) + const open = options.open ?? new Set() + const rows = new Map(model.entities.map(row => [row.id, row])) + // Each side's containment: what holds each entity row, and what each holds. + const parentOf = {before: new Map(), after: new Map()} + const childrenOf = {before: new Map(), after: new Map()} + for (const side of sides) { + const contains = isContainment(model[side]) + const rowOf = model.entityRow[side] + for (const relationship of model[side].relationships) { + if (!contains(relationship)) continue + const parent = rowOf.get(relationship.from) + const child = rowOf.get(relationship.to) + if (parent === undefined || child === undefined || parent === child || parentOf[side].has(child)) continue + parentOf[side].set(child, parent) + childrenOf[side].set(parent, [...(childrenOf[side].get(parent) ?? []), child]) + } + } + // Siblings that only one revision has, by status, container and kind. + const groups = new Map() + for (const row of model.entities) { + if (row.status !== 'removed' && row.status !== 'added') continue + const status = row.status + const side = sideOf(status) + const entity = row[side] + if (!entity) continue + const parent = parentOf[side].get(row.id) + // A part of an item leaving (or arriving) with it goes with it. + if (parent !== undefined && rows.get(parent)?.status === status) continue + const key = `${status}\n${parent ?? ''}\n${entity.kind}` + const group = groups.get(key) ?? {status, parent, kind: entity.kind, items: []} + group.items.push(row.id) + groups.set(key, group) + } + const folds = new Map & {presents: string[]}>() + const hidden = new Map() + const addedRows: ComparisonModel['entities'] = [] + const addedLinks: ComparisonModel['relationships'] = [] + const stands = new Map() + // Each fold's container and the link that puts the card in it, which stands for the container holding each item. + const holders = new Map() + for (const {status, parent, kind, items} of groups.values()) { + if (items.length < minimum) continue + const side = sideOf(status) + const id = `${massFoldPrefix}${status}:${kind}:${parent ?? ''}` + const opened = open.has(id) + // The items and every part they hold that leaves (or arrives) with them. + const members: string[] = [] + const stack = items.toReversed() + for (let item = stack.pop(); item !== undefined; item = stack.pop()) { + members.push(item) + for (const child of (childrenOf[side].get(item) ?? []).toReversed()) if (rows.get(child)?.status === status) stack.push(child) + } + if (!opened) for (const member of members) hidden.set(member, id) + const noun = options.noun?.(kind) ?? humanizeKind(kind) + const label = massFoldLabel(items.length, status, noun, opened, options.locale) + folds.set(id, {id, status, kind, items, presents: members, open: opened, label}) + stands.set(id, items) + const entity: X['entities'][number] = {id, kind, label, data: {count: items.length, ...(opened ? {open: true} : {})}} + addedRows.push({id, [side]: entity, status, correspondence: 'exact'}) + const holder = parent === undefined ? undefined : rows.get(parent)?.[side] + if (parent !== undefined && holder) { + const link = `${id}:contains` + const contains: X['relationships'][number] = {id: link, kind: 'contains', from: holder.id, to: id} + addedLinks.push({id: link, [side]: contains, status, correspondence: 'exact'}) + stands.set(link, items) + holders.set(id, {parent, link}) + } + } + if (!folds.size) return none + // Relationships to a hidden item: among one fold's items, the card presents them; to an item that stays, one link + // from the card for each other end, kind and direction stands for them all. + const kept: ComparisonModel['relationships'] = [] + const merged = new Map< + string, + {sides: Set; rows: string[]; ends: Partial>} + >() + const containment = {before: isContainment(model.before), after: isContainment(model.after)} + const hiddenEntities = new Map(hidden) + const present = (fold: string, row: string) => { + const presents = folds.get(fold)?.presents + if (presents && !presents.includes(row)) presents.push(row) + } + for (const row of model.relationships) { + const touched = sides.flatMap(side => { + const item = row[side] + return item && [item.from, item.to].some(end => hiddenEntities.has(model.entityRow[side].get(end) ?? '')) ? [{side, item}] : [] + }) + if (!touched.length) { + kept.push(row) + continue + } + for (const {side, item} of touched) { + const fromRow = model.entityRow[side].get(item.from) ?? '' + const toRow = model.entityRow[side].get(item.to) ?? '' + const from = hiddenEntities.get(fromRow) + const to = hiddenEntities.get(toRow) + if (from !== undefined && from === to) { + hidden.set(row.id, from) + present(from, row.id) + continue + } + const holder = to === undefined ? undefined : holders.get(to) + if (to !== undefined && holder && from === undefined && fromRow === holder.parent && containment[side](item)) { + hidden.set(row.id, holder.link) + present(to, row.id) + continue + } + const fromEnd = from ?? item.from + const toEnd = to ?? item.to + const id = `${massFoldPrefix}link:${item.kind}:${fromEnd}->${toEnd}` + const link = merged.get(id) ?? {sides: new Set(), rows: [], ends: {}} + link.sides.add(side) + if (!link.rows.includes(row.id)) link.rows.push(row.id) + link.ends[side] = {kind: item.kind, from: fromEnd, to: toEnd} + merged.set(id, link) + hidden.set(row.id, id) + present(from ?? to ?? '', row.id) + } + } + for (const [id, link] of merged) { + const both = link.sides.size === 2 + const status = both ? 'modified' : link.sides.has('before') ? 'removed' : 'added' + const ends = Object.fromEntries(Object.entries(link.ends).map(([side, end]) => [side, {id, ...end}])) + addedLinks.push({id, ...ends, status, correspondence: 'exact'}) + stands.set(id, link.rows) + } + const entities = [...model.entities.filter(row => !hidden.has(row.id)), ...addedRows] + const relationships = [...kept, ...addedLinks] + const extraction = (side: Side): X => { + const items = (list: readonly Partial>[]) => list.flatMap(row => (row[side] ? [row[side]] : [])) + return {...model[side], entities: items(entities), relationships: items(relationships)} + } + const entityRow = (side: Side) => + new Map([ + ...[...model.entityRow[side]].filter(([, row]) => !hidden.has(row)), + ...addedRows.filter(row => row[side]).map(row => [row.id, row.id] as const), + ]) + const result = { + ...model, + before: extraction('before'), + after: extraction('after'), + entities, + relationships, + entityRow: {before: entityRow('before'), after: entityRow('after')}, + } + const folding = {folds, folded: hidden, stands} + return { + model: { + ...result, + steps: foldMassSteps(model.steps, folding), + ...(model.reverseSteps ? {reverseSteps: foldMassSteps(model.reverseSteps, folding)} : {}), + }, + ...folding, + } +} + +/** + * Steps (a model's, or a schedule) with a fold's cards and links in place of what they stand for: each in the first + * step that changes any of it, and in no other. A step left with nothing keeps its place, so timing doesn't move. + */ +export function foldMassSteps(steps: readonly S[], folding: Pick): S[] { + if (!folding.stands.size) return [...steps] + const placed = new Set() + const standsFor = new Map() + for (const [id, rows] of folding.stands) for (const row of rows) standsFor.set(row, [...(standsFor.get(row) ?? []), id]) + const isEntity = (id: string) => folding.folds.has(id) + return steps.map(step => { + const added: string[] = [] + for (const id of [...step.entities, ...step.relationships]) { + for (const fold of standsFor.get(id) ?? []) { + if (placed.has(fold)) continue + placed.add(fold) + added.push(fold) + } + } + const keep = (id: string) => !folding.folded.has(id) + return { + ...step, + entities: [...step.entities.filter(keep), ...added.filter(isEntity)], + relationships: [...step.relationships.filter(keep), ...added.filter(id => !isEntity(id))], + } + }) +} diff --git a/packages/renderers/kit/src/react/fold.tsx b/packages/renderers/kit/src/react/fold.tsx index 9009989d1..f98807f1f 100644 --- a/packages/renderers/kit/src/react/fold.tsx +++ b/packages/renderers/kit/src/react/fold.tsx @@ -78,7 +78,7 @@ export function Fold({ * The fold's glyph: chevrons pointing apart (Lucide's `chevrons-up-down`), the run opens both ways; open, chevrons * pointing together (`chevrons-down-up`). */ -function FoldGlyph({open}: {open: boolean}) { +export function FoldGlyph({open}: {open: boolean}) { return ( ): number { - const expands = props.synthetic?.(row.id) && props.syntheticAction?.((row.after ?? row.before)!)?.expanded !== undefined + const expands = + ((props.synthetic?.(row.id) ?? false) || isMassFold(row.id)) && + props.syntheticAction?.((row.after ?? row.before)!)?.expanded !== undefined return expands ? expanderMetrics.size + 4 : 0 } @@ -61,9 +65,15 @@ interface Laid { * ELK layouts per comparison step (laid out off the main thread before the * first paint), identity-stable cards, spline relationships that morph on the * same clock as their cards, stable framing across the whole transition, and - * host-driven change emphasis. + * host-driven change emphasis. A dozen or more sibling cards removed (or added) + * together fold into one card that counts them and opens in place + * (`foldMassChanges`). */ export function GraphCanvas(props: GraphCanvasProps) { + return +} + +function Canvas(props: GraphCanvasProps) { const {model, schedule, comparing, visibleIds} = props // Under the Changes scope the model is a view of the whole one, which a renderer's own `source` (its input model) is // in All: Changes and All are views of one document, so the drawing stays while the other is laid out, and moves to it. diff --git a/packages/renderers/kit/src/react/graph-canvas/entity-card.tsx b/packages/renderers/kit/src/react/graph-canvas/entity-card.tsx index 1fe093cb6..82288aaa7 100644 --- a/packages/renderers/kit/src/react/graph-canvas/entity-card.tsx +++ b/packages/renderers/kit/src/react/graph-canvas/entity-card.tsx @@ -12,6 +12,7 @@ import {CardSubtitle} from './subtitle.js' import {CardIcon} from './card-icon.js' import {SvgIcon} from '../icons.js' import {entityAliasesAttribute} from '@githubnext/projections-renderer-sdk/interactions' +import {isMassFold} from '../../mass-fold.js' /** The expander a card that opens or closes a group draws in its top-right corner: its size and inset. */ export const expanderMetrics = {size: 14, inset: 10} @@ -25,7 +26,9 @@ export function EntityCard({node, drawing}: {node: TransitionNode; drawing: Draw const card = props.cards?.get(node.id) const synthetic = props.synthetic?.(node.id) ?? false const aliases = synthetic ? undefined : props.aliases?.(node.id) - const action = synthetic ? (props.syntheticAction?.(entity) ?? {label: `Show ${entity.label}`}) : undefined + // A fold of mass changes presents its items to the host, as an entity element, and opens them, as a synthetic card. + const opens = synthetic || isMassFold(node.id) + const action = opens ? (props.syntheticAction?.(entity) ?? {label: `Show ${entity.label}`}) : undefined const expander = action?.expanded !== undefined const text = cardLinesLayout(node, entity, drawing, Boolean(card), expander ? expanderMetrics.size + 4 : 0) const {fileNode, top, labelY, whole} = text @@ -36,6 +39,7 @@ export function EntityCard({node, drawing}: {node: TransitionNode; drawing: Draw 0 ? {[entityAliasesAttribute]: JSON.stringify(aliases)} : {})} + {...(opens && !synthetic ? {'data-fold': action?.expanded === true ? 'open' : 'closed'} : {})} transform={`translate(${node.x} ${node.y}) scale(${0.9 + node.opacity * 0.1})`} {...mark(node, emphasis)} opacity={node.opacity} diff --git a/packages/renderers/kit/src/react/graph-canvas/mass-folds.ts b/packages/renderers/kit/src/react/graph-canvas/mass-folds.ts new file mode 100644 index 000000000..e20f5a2fe --- /dev/null +++ b/packages/renderers/kit/src/react/graph-canvas/mass-folds.ts @@ -0,0 +1,107 @@ +// The graph canvas's folds of mass changes: a dozen or more sibling cards removed (or added) together drawn as one card +// that counts them and opens in place (`foldMassChanges`). +import {useCallback, useMemo, useState} from 'react' +import type {Entity} from '@githubnext/projections-schemas' +import type {RendererFocus} from '@githubnext/projections-renderer-sdk/protocol' +import {foldMassChanges, foldMassSteps, isMassFold} from '../../mass-fold.js' +import type {EmphasisOf} from '../../emphasis.js' +import {useKindNoun} from '../kind-nouns.js' +import type {GraphCanvasProps} from './props.js' + +const none: ReadonlySet = new Set() + +/** + * The canvas's props with mass changes folded: the model and schedule with each fold's card and links in place of + * what they stand for, a fold's card presenting its items (`aliases`, so the host's selection, hover and filter of one + * find the card), and the host's selection and focus of a folded item moved onto its card. Activating a fold's card, or + * a link drawn for it, opens or closes it; what the person opened stays open until the document changes. The props + * pass through unchanged when nothing folds. + */ +export function useMassFolds(props: GraphCanvasProps): GraphCanvasProps { + const noun = useKindNoun() + const {model, comparing, locale} = props + // Folds stay open while the same document is shown, the Changes scope's views of it included. + const document = props.scope?.all ?? props.source ?? model + const [opened, setOpened] = useState<{document: unknown; ids: ReadonlySet}>({document, ids: none}) + const open = opened.document === document ? opened.ids : none + const folding = useMemo( + () => (comparing ? foldMassChanges(model, {open, noun, locale}) : undefined), + [comparing, model, open, noun, locale], + ) + const toggle = useCallback( + (id: string) => + setOpened(previous => { + const ids = new Set(previous.document === document ? previous.ids : none) + if (ids.has(id)) ids.delete(id) + else ids.add(id) + return {document, ids} + }), + [document], + ) + const folds = folding !== undefined && folding.folds.size > 0 ? folding : undefined + // What the canvas lays out and frames keeps its identity while the folds and the renderer's props do. + const onCard = useCallback((id: string) => folds?.folded.get(id) ?? id, [folds]) + const schedule = useMemo(() => (folds ? foldMassSteps(props.schedule, folds) : props.schedule), [folds, props.schedule]) + const request = props.focusRequest + const focusRequest = useMemo( + () => (request?.id === undefined ? request : {...request, id: onCard(request.id)}), + [request, onCard], + ) + const focus = useMemo(() => props.focus && {...props.focus, ids: new Set([...props.focus.ids].map(onCard))}, [props.focus, onCard]) + const visibleIds = useMemo(() => props.visibleIds && new Set([...props.visibleIds].map(onCard)), [props.visibleIds, onCard]) + // The fold a card or link opens: a link drawn for folded relationships opens the fold at its end. + const foldOf = useMemo(() => { + const found = new Map() + if (!folds) return found + for (const row of folds.model.relationships) { + if (!isMassFold(row.id)) continue + const item = row.before ?? row.after + if (!item) continue + const fold = [item.from, item.to].find(end => folds.folds.has(end)) + if (fold !== undefined) found.set(row.id, fold) + } + for (const id of folds.folds.keys()) found.set(id, id) + return found + }, [folds]) + const rows = useMemo( + () => new Map[0]>([...model.entities, ...model.relationships].map(row => [row.id, row])), + [model], + ) + if (!folds) return props + const {onSelect, synthetic, syntheticAction, aliases, prose} = props + const emphasis: EmphasisOf = (change, id = change.id) => { + const standing = id === undefined ? undefined : folds.stands.get(id) + if (!standing) return props.emphasis(change, id) + return Math.max(0, ...standing.map(row => props.emphasis(rows.get(row) ?? change, row))) + } + return { + ...props, + model: folds.model, + schedule, + emphasis, + source: document, + selectedId: props.selectedId === null ? null : onCard(props.selectedId), + focusRequest, + ...(props.focus === undefined ? {} : {focus}), + ...(visibleIds ? {visibleIds} : {}), + onSelect: (id: string | null) => { + const fold = id === null ? undefined : foldOf.get(id) + if (fold === undefined) onSelect(id) + else toggle(fold) + }, + // A fold's links stand for relationships the card presents: drawn, and opening the fold, but no item of the host's. + synthetic: (id: string) => (isMassFold(id) && !folds.folds.has(id)) || (synthetic?.(id) ?? false), + syntheticAction: (entity: Entity) => { + const fold = folds.folds.get(entity.id) + if (!fold) return syntheticAction?.(entity) + return {label: fold.open ? fold.label : `Show ${fold.label}`, expanded: fold.open} + }, + aliases: (id: string) => { + const fold = folds.folds.get(id) + if (!fold) return aliases?.(id) + if (fold.open) return undefined + return [...fold.presents, ...fold.presents.flatMap(member => aliases?.(member) ?? [])] + }, + prose: (entity: Entity) => folds.folds.has(entity.id) || (prose?.(entity) ?? false), + } +} diff --git a/packages/renderers/kit/src/react/grid-folds.tsx b/packages/renderers/kit/src/react/grid-folds.tsx new file mode 100644 index 000000000..08e31ac47 --- /dev/null +++ b/packages/renderers/kit/src/react/grid-folds.tsx @@ -0,0 +1,171 @@ +// A card grid's folds of mass changes: a dozen or more of its cards removed (or added) together, of one kind, drawn as +// one card that counts them and opens in place, as a graph canvas folds them (`foldMassChanges`). +import {createContext, use, useCallback, useLayoutEffect, useMemo, useState} from 'react' +import {entityAliasesAttribute} from '@githubnext/projections-renderer-sdk/interactions' +import {massFoldLabel, massFoldMinimum, massFoldPrefix, type MassStatus} from '../mass-fold.js' +import {changeMark} from '../diff/model.js' +import {ChangeFooter} from './components.js' +import {FoldGlyph} from './fold.js' +import {useKindNoun} from './kind-nouns.js' + +/** What a card tells its grid: whether it is removed or added, and its kind. */ +interface GridCard { + status: MassStatus + kind: string +} + +/** One fold of a grid's cards. */ +export interface GridFold { + /** The fold card's `data-entity-id`: `massFoldPrefix`, the status, the kind and its first card's ID. */ + id: string + status: MassStatus + /** The cards it folds, in the grid's order: their IDs are the card's `data-entity-aliases` while it is closed. */ + members: readonly string[] + label: string + open: boolean +} + +interface GridFolds { + report: (id: string, card: GridCard | undefined) => void + foldOf: (id: string) => GridFold | undefined + toggle: (fold: string) => void +} + +const GridFoldsContext = createContext(undefined) + +/** Provides a grid's folds to its cards: they report themselves, and it folds the runs. */ +export const GridFoldsProvider = GridFoldsContext + +/** + * A grid's folds: each card reports its status and kind (`useGridFold`), and a dozen or more cards of one kind removed + * (or added) fold into one card in the place of the first. What the person opened stays open. + */ +export function useGridFolds(): GridFolds { + const noun = useKindNoun() + const [cards, setCards] = useState>(() => new Map()) + const [open, setOpen] = useState>(() => new Set()) + const report = useCallback( + (id: string, card: GridCard | undefined) => + setCards(previous => { + const known = previous.get(id) + if (known?.status === card?.status && known?.kind === card?.kind) return previous + const next = new Map(previous) + if (card) next.set(id, card) + else next.delete(id) + return next + }), + [], + ) + const toggle = useCallback( + (fold: string) => + setOpen(previous => { + const next = new Set(previous) + if (next.has(fold)) next.delete(fold) + else next.add(fold) + return next + }), + [], + ) + const folds = useMemo(() => { + const groups = new Map() + for (const [id, card] of cards) { + const key = `${card.status}\n${card.kind}` + const group = groups.get(key) ?? {card, members: []} + group.members.push(id) + groups.set(key, group) + } + const byCard = new Map() + for (const {card, members} of groups.values()) { + const [first] = members + if (first === undefined || members.length < massFoldMinimum) continue + const id = `${massFoldPrefix}${card.status}:${card.kind}:${first}` + const opened = open.has(id) + const fold = { + id, + status: card.status, + members, + open: opened, + label: massFoldLabel(members.length, card.status, noun(card.kind), opened), + } + for (const member of members) byCard.set(member, fold) + } + return byCard + }, [cards, open, noun]) + const foldOf = useCallback((id: string) => folds.get(id), [folds]) + return useMemo(() => ({report, foldOf, toggle}), [report, foldOf, toggle]) +} + +/** + * A card's fold in its grid, once it has said whether it is removed or added and its kind: undefined outside a grid, + * and for a card no fold takes. `row` is the card's change (its `before` or `after` entity gives the kind). + */ +export function useGridFold( + id: string, + row: {status?: string; before?: {kind?: unknown}; after?: {kind?: unknown}} | undefined, +): {fold: GridFold; toggle: () => void} | undefined { + const grid = use(GridFoldsContext) + const status = row?.status === 'removed' || row?.status === 'added' ? row.status : undefined + const kind = (status === 'removed' ? row?.before?.kind : row?.after?.kind) ?? undefined + const report = grid?.report + // Reported before the first paint, so a folded grid never draws its cards first. + useLayoutEffect(() => { + if (!report) return undefined + report(id, status && typeof kind === 'string' ? {status, kind} : undefined) + return () => report(id, undefined) + }, [report, id, status, kind]) + const fold = grid?.foldOf(id) + return fold && grid ? {fold, toggle: () => grid.toggle(fold.id)} : undefined +} + +/** + * The card a fold draws in the place of its first card: `48 jobs removed`, in the removed (or added) style its cards + * share, a button that opens them in place; open, `Hide 48 removed jobs` before them, which folds them again. Closed, + * it presents its cards to the host (`data-entity-aliases`), so selecting, hovering or finding one finds it. + */ +export function GridFoldCard({ + fold, + onToggle, + emphasis, + mark, + presence, +}: { + fold: GridFold + onToggle: () => void + emphasis: number + mark: Parameters[0] | undefined + presence: number +}) { + const style = { + '--emphasis': emphasis, + ...(presence < 1 ? {opacity: presence, visibility: presence > 0 ? ('visible' as const) : ('hidden' as const)} : {}), + } + const change = {status: fold.status} + return ( +
  • 0 ? fold.status : undefined} + {...(mark !== undefined ? changeMark(mark) : {})} + style={style} + > + +
    + +
    +
  • + ) +} diff --git a/packages/renderers/kit/src/react/kind-nouns.ts b/packages/renderers/kit/src/react/kind-nouns.ts new file mode 100644 index 000000000..14579827b --- /dev/null +++ b/packages/renderers/kit/src/react/kind-nouns.ts @@ -0,0 +1,14 @@ +import {createContext, use} from 'react' +import type {SummaryNoun} from '@githubnext/projections-renderer-sdk/protocol' +import {kindNoun} from '../summary.js' + +/** + * A kind's words in this frame (`kindNoun`): the definition's noun, else the renderer's, else the host's. Outside a kit + * renderer, the host's words. + */ +export const KindNouns = createContext<(kind: string) => SummaryNoun>(kind => kindNoun(kind)) + +/** A kind's words in this frame, as the summary bar words it (see `KindNouns`). */ +export function useKindNoun(): (kind: string) => SummaryNoun { + return use(KindNouns) +} diff --git a/packages/renderers/kit/src/react/layout-components.tsx b/packages/renderers/kit/src/react/layout-components.tsx index 8332687dc..be710180a 100644 --- a/packages/renderers/kit/src/react/layout-components.tsx +++ b/packages/renderers/kit/src/react/layout-components.tsx @@ -14,6 +14,7 @@ import {Icon} from './icons.js' import {useSelectable} from './shell/frame.js' import {useSelectControl} from './select-control.js' import {mixedChange, type ChangeClassification} from '../emphasis.js' +import {GridFoldCard, GridFoldsProvider, useGridFold, useGridFolds} from './grid-folds.js' interface StatusChange { status: Status @@ -157,12 +158,18 @@ export function Group({ ) } -/** Cards in a responsive grid: as many columns as fit, one on a phone. */ +/** + * Cards in a responsive grid: as many columns as fit, one on a phone. A dozen or more of its `EntityCard`s removed + * (or added) together, of one kind, fold into one card that counts them and opens in place (`GridFoldCard`). + */ export function CardGrid({children, label}: {children: ReactNode; label?: string}) { + const folds = useGridFolds() return ( -
      - {children} -
    + +
      + {children} +
    +
    ) } @@ -227,6 +234,7 @@ export function EntityCard({ children, }: EntityCardProps) { const selectControl = useSelectControl() + const folding = useGridFold(id, change ?? (typeof mark === 'object' ? mark : undefined)) const style = {'--emphasis': emphasis, ...(presence < 1 ? {opacity: presence, visibility: presence > 0 ? 'visible' : 'hidden'} : {})} const name = ( @@ -238,7 +246,10 @@ export function EntityCard({ ) - return ( + // A card a closed fold takes is drawn by the fold, in the place of its first card. + if (folding && !folding.fold.open && folding.fold.members[0] !== id) return null + const leads = folding?.fold.members[0] === id ? folding : undefined + const card = (
  • ) + // The fold keeps its place whether open or closed, so its button stays the same element. + return leads ? ( + <> + + {leads.fold.open && card} + + ) : ( + card + ) } /** A card's relationships, one selectable row each (`RelationshipItem`). */ diff --git a/packages/renderers/kit/src/react/shell/kit-renderer.tsx b/packages/renderers/kit/src/react/shell/kit-renderer.tsx index d5764ae8f..1a9f4c11d 100644 --- a/packages/renderers/kit/src/react/shell/kit-renderer.tsx +++ b/packages/renderers/kit/src/react/shell/kit-renderer.tsx @@ -3,6 +3,8 @@ import {interactionCapabilities} from '@githubnext/projections-renderer-sdk/inte import {useRenderer} from '@githubnext/projections-renderer-sdk/react' import {RendererBoundary} from '../components.js' import {LegendContext} from '../legend-context.js' +import {KindNouns} from '../kind-nouns.js' +import {kindNoun} from '../../summary.js' import {useDocumentModel, useTimeline} from './document.js' import { ContentAspect, @@ -94,6 +96,9 @@ export function KitRenderer({component: Renderer, options}: {component: Componen controls, }) const pane = renderer.environment ? renderer.environment.pane : init?.pane + // A kind's words for the renderer's own text (a fold's `48 tables removed`), as the summary bar words its count. + const definitionKinds = init?.projection.kinds + const nouns = useCallback((kind: string) => kindNoun(kind, definitionKinds, options.nouns), [definitionKinds, options.nouns]) const environment = useMemo(() => { const source = renderer.environment ?? init if (!source) return undefined @@ -151,41 +156,43 @@ export function KitRenderer({component: Renderer, options}: {component: Componen - + + + diff --git a/packages/renderers/kit/src/summary.ts b/packages/renderers/kit/src/summary.ts index df7d2b3e0..d2545a099 100644 --- a/packages/renderers/kit/src/summary.ts +++ b/packages/renderers/kit/src/summary.ts @@ -1,4 +1,4 @@ -import {summaryItems, type SummaryNouns} from '@githubnext/projections-renderer-sdk/presentation' +import {humanizeKind, summaryItems, type SummaryNouns} from '@githubnext/projections-renderer-sdk/presentation' import { rendererLimits, type ControlValue, @@ -7,6 +7,7 @@ import { type RendererSummary, type SummaryItem, type SummaryFactItem, + type SummaryNoun, } from '@githubnext/projections-renderer-sdk/protocol' import type {ComparisonModel} from './model.js' import {boundaryKinds, moduleGroups} from './layout/groups.js' @@ -59,6 +60,19 @@ function withoutIds({ids: _ids, ...fact}: SummaryFactItem): SummaryFactItem { return fact } +/** + * A kind's words, as the summary bar words its count: the definition's noun (`presentation.kinds..noun`), else + * the renderer's (`SummaryNouns`), else the host's (`humanizeKind`). + */ +export function kindNoun(kind: string, kinds?: RendererProjection['kinds'], nouns?: SummaryNouns): SummaryNoun { + const defined = kinds !== undefined && Object.hasOwn(kinds, kind) ? kinds[kind]?.noun : undefined + if (defined !== undefined) return {singular: defined.singular, plural: defined.plural} + const entry = + typeof nouns === 'function' ? nouns(kind, 'entities') : nouns !== undefined && Object.hasOwn(nouns, kind) ? nouns[kind] : undefined + const words = typeof entry === 'object' ? ('distinct' in entry ? entry.noun : entry) : undefined + return words ? {singular: words.singular, plural: words.plural} : humanizeKind(kind) +} + /** * Count figures worded with the definition's nouns (`presentation.kinds..noun`, sent as * `init.projection.kinds`) where it gives one: a definition names its own kinds, so its words win over the diff --git a/packages/renderers/kit/styles/diff.css b/packages/renderers/kit/styles/diff.css index 769be6acf..e35dd426b 100644 --- a/packages/renderers/kit/styles/diff.css +++ b/packages/renderers/kit/styles/diff.css @@ -17,6 +17,10 @@ fill: var(--muted); text-decoration: line-through; } +/* A fold of removed cards says so in words ("16 reports removed"): its count isn't struck as a removed name is. */ +.pk .graph-node[data-fold][data-change='removed'] .pk-diff-text { + text-decoration: none; +} /* Replace is neutral, neither added nor removed: its badge is gray beside any status word. */ .pk [data-icon='replace'] { diff --git a/packages/renderers/kit/styles/layout.css b/packages/renderers/kit/styles/layout.css index a129d8926..6ba7e1343 100644 --- a/packages/renderers/kit/styles/layout.css +++ b/packages/renderers/kit/styles/layout.css @@ -209,6 +209,20 @@ .pk .pk-entity-card:is([data-status='renamed'], [data-status='moved'], [data-status='unchanged']) { --change: var(--violet); } +/* + * A fold of a dozen or more cards removed (or added) together (`GridFoldCard`): a card in their style whose button, + * the fold's glyph beside its count, opens them in place. + */ +.pk .pk-mass-fold .pk-mass-fold-button { + align-self: stretch; + padding-bottom: var(--projections-space-2); +} +.pk .pk-mass-fold .pk-entity-card-top { + align-items: center; +} +.pk .pk-mass-fold .pk-fold-icon { + color: var(--muted); +} /* Hover, keyboard focus and selection rings are the renderer SDK's, on the card's own element. */ .pk .pk-entity-card-select { display: flex; diff --git a/packages/renderers/kit/test/mass-fold.test.mjs b/packages/renderers/kit/test/mass-fold.test.mjs new file mode 100644 index 000000000..60bc901eb --- /dev/null +++ b/packages/renderers/kit/test/mass-fold.test.mjs @@ -0,0 +1,131 @@ +import {test} from 'node:test' +import assert from 'node:assert/strict' +import {comparisonModel, extractionModel, foldMassChanges, foldMassSteps, kindNoun, massFoldMinimum} from '../dist/index.js' + +// A schema in a database: `users` stays; `legacy` and its 14 tables (each with a column and a key to `users`) go. +const db = (entities, relationships) => ({protocolVersion: 0, schema: 'database/v0', entities, relationships}) +const item = (id, kind) => ({id, kind, label: id}) +const contains = (from, to) => ({id: `${from}>${to}`, kind: 'contains', from, to}) +const legacy = Array.from({length: 14}, (_, index) => `legacy.t${String(index).padStart(2, '0')}`) +const before = db( + [ + item('app', 'schema'), + item('users', 'table'), + item('legacy', 'schema'), + ...legacy.flatMap(table => [item(table, 'table'), item(`${table}.id`, 'column')]), + ], + [ + contains('app', 'users'), + ...legacy.flatMap(table => [ + contains('legacy', table), + contains(table, `${table}.id`), + {id: `${table}->users`, kind: 'foreign-key', from: table, to: 'users'}, + ]), + // Two of the removed tables refer to each other. + {id: 'pair', kind: 'foreign-key', from: legacy[0], to: legacy[1]}, + ], +) +const after = db([item('app', 'schema'), item('users', 'table'), item('legacy', 'schema')], [contains('app', 'users')]) +const removed = (id, collection) => ({id, collection, before: [id], after: [], status: 'removed', correspondence: 'none'}) +const removedRelationships = before.relationships.filter(row => row.id !== 'app>users') +const comparison = { + protocolVersion: 0, + changes: [ + ...before.entities.filter(row => row.id.startsWith('legacy.')).map(row => removed(row.id, 'entities')), + ...removedRelationships.map(row => removed(row.id, 'relationships')), + ], + // The tables go in two steps; the fold goes with the first. + steps: [ + {changes: [...legacy.slice(0, 7), ...legacy.slice(0, 7).map(table => `${table}.id`)]}, + { + changes: [...legacy.slice(7), ...legacy.slice(7).map(table => `${table}.id`), ...removedRelationships.map(row => row.id)], + }, + ], +} +const model = comparisonModel(before, after, comparison) +const fold = 'pk-mass:removed:table:legacy' + +test('a dozen or more sibling items removed together fold into one card in their container, in the removed style', () => { + assert.equal(massFoldMinimum, 12) + const {model: folded, folds, folded: hidden} = foldMassChanges(model) + assert.deepEqual([...folds.keys()], [fold]) + const card = folded.entities.find(row => row.id === fold) + assert.equal(card.status, 'removed') + assert.equal(card.after, undefined) + assert.equal(card.before.kind, 'table') + assert.equal(card.before.label, '14 tables removed') + // The tables and their columns are gone from the model; the schemas and `users` stay. + assert.deepEqual(folded.entities.map(row => row.id).toSorted(), ['app', 'legacy', 'users', fold].toSorted()) + assert.equal(hidden.get('legacy.t03.id'), fold) + // The card sits in the schema the tables were in. + const holder = folded.relationships.find(row => row.id === `${fold}:contains`) + assert.deepEqual([holder.before.from, holder.before.to], ['legacy', fold]) + // Its keys to `users` are drawn once, from the card; the key between two folded tables is the card's own. + const links = folded.relationships.filter(row => row.id.startsWith('pk-mass:link:')) + assert.equal(links.length, 1) + assert.deepEqual([links[0].before.from, links[0].before.to, links[0].status], [fold, 'users', 'removed']) + assert.equal(hidden.get('pair'), fold) + assert.equal(folded.entityRow.before.get(fold), fold) + assert.equal(folded.entityRow.before.has('legacy.t03'), false) + assert.equal( + folded.before.entities.some(entity => entity.id === 'legacy.t03'), + false, + ) +}) + +test("the card presents every item it folds, so the host's selection and focus of one find it", () => { + const {folds} = foldMassChanges(model) + const presents = new Set(folds.get(fold).presents) + for (const table of legacy) { + assert.ok(presents.has(table), table) + assert.ok(presents.has(`${table}.id`), `${table}.id`) + assert.ok(presents.has(`${table}->users`), `${table}->users`) + } + assert.ok(presents.has('pair')) + assert.deepEqual(folds.get(fold).items, legacy) +}) + +test('the card and its links take the first step that changes what they stand for, and no other', () => { + const {model: folded} = foldMassChanges(model) + const [first, second] = folded.steps + assert.deepEqual(first.entities, [fold]) + assert.ok(first.relationships.includes(`${fold}:contains`)) + assert.deepEqual(second.entities, []) + assert.ok(second.relationships.includes('pk-mass:link:foreign-key:pk-mass:removed:table:legacy->users')) + // A reversed schedule places them in its own first step. + const reversed = foldMassSteps(model.steps.toReversed(), foldMassChanges(model)) + assert.ok(reversed[0].entities.includes(fold)) + assert.deepEqual(reversed[1].entities, []) +}) + +test('an open fold draws its items, and its card stays as the way to fold them again', () => { + const {model: folded, folds, folded: hidden} = foldMassChanges(model, {open: new Set([fold])}) + assert.equal(folds.get(fold).open, true) + assert.equal(hidden.size, 0) + assert.equal(folded.entities.find(row => row.id === fold).before.label, 'Hide 14 removed tables') + assert.ok(folded.entities.some(row => row.id === 'legacy.t03')) + assert.ok(folded.relationships.some(row => row.id === 'legacy.t03->users')) +}) + +test("fewer than a dozen don't fold, nor does a single revision; additions fold as removals do", () => { + assert.equal(foldMassChanges(model, {minimum: 15}).model, model) + assert.equal(foldMassChanges(extractionModel(before)).folds.size, 0) + const reversed = comparisonModel(after, before, { + ...comparison, + changes: comparison.changes.map(change => ({...change, before: change.after, after: change.before, status: 'added'})), + }) + const {folds, model: folded} = foldMassChanges(reversed) + const added = folded.entities.find(row => row.id === 'pk-mass:added:table:legacy') + assert.equal(folds.size, 1) + assert.equal(added.status, 'added') + assert.equal(added.after.label, '14 tables added') +}) + +test("a fold counts in the definition's noun, else the renderer's, else the host's", () => { + const {model: folded} = foldMassChanges(model, { + noun: kind => kindNoun(kind, {table: {noun: {singular: 'relation', plural: 'relations'}}}), + }) + assert.equal(folded.entities.find(row => row.id === fold).before.label, '14 relations removed') + assert.deepEqual(kindNoun('table', undefined, {table: {singular: 'model', plural: 'models'}}), {singular: 'model', plural: 'models'}) + assert.deepEqual(kindNoun('table'), {singular: 'table', plural: 'tables'}) +}) diff --git a/packages/renderers/testing/README.md b/packages/renderers/testing/README.md index cfd92b922..00f17a504 100644 --- a/packages/renderers/testing/README.md +++ b/packages/renderers/testing/README.md @@ -52,8 +52,9 @@ Build the bundle before the tests. The checks: fades or repaints. - `highlight-scope`: After each step, only entities that step or an earlier one changed (or a unit's changed parts) are emphasized. -- `diff-changes`: In diff mode every changed entity is drawn, and drawn - differently from how an unchanged comparison of its revision draws it. +- `diff-changes`: In diff mode every changed entity is drawn (as its own element + or on a card that lists it in `data-entity-aliases`), and drawn differently + from how an unchanged comparison of its revision draws it. - `diff-neutral`: In diff mode, entities no change touches are painted exactly as in an unchanged comparison. - `diff-clipping`: In diff mode, at full and phone width, no element cuts off diff --git a/packages/renderers/testing/src/checks/catalog.ts b/packages/renderers/testing/src/checks/catalog.ts index 652c5196e..c3f486229 100644 --- a/packages/renderers/testing/src/checks/catalog.ts +++ b/packages/renderers/testing/src/checks/catalog.ts @@ -107,7 +107,7 @@ export const checkDescriptions: Record = { 'highlight-scope': 'After each step, only entities that step or an earlier one changed are emphasized; no step pre-tints later changes, and items that varied only within tolerance are never emphasized.', 'diff-changes': - 'In diff mode every changed entity is drawn, and drawn differently from how an unchanged comparison of its revision draws it.', + 'In diff mode every changed entity is drawn, by its own element or by a card that presents it in data-entity-aliases, and drawn differently from how an unchanged comparison of its revision draws it.', 'diff-neutral': 'In diff mode, entities no change touches, including those that varied only within tolerance, are painted exactly as in an unchanged comparison of the after revision.', 'diff-clipping': diff --git a/packages/renderers/testing/src/checks/comparison/diff.ts b/packages/renderers/testing/src/checks/comparison/diff.ts index 6dcd28cbc..e33f5e421 100644 --- a/packages/renderers/testing/src/checks/comparison/diff.ts +++ b/packages/renderers/testing/src/checks/comparison/diff.ts @@ -38,16 +38,27 @@ export const diffChecks: Pick ids.has(sample.id)) + // Drawn by its own element, or by a card that presents it (`data-entity-aliases`). + const drawn = shown.filter(sample => ids.has(sample.id) || (sample.aliases ?? []).some(alias => ids.has(alias))) const describe = `${change.status}${change.before.join(',') !== change.after.join(',') && change.before.length && change.after.length ? ' (renamed)' : ''} "${change.id}"` if (!drawn.length) { failures.push( - `The ${describe} change isn't drawn: no visible element has data-entity-id ${[...ids].map(id => `"${id}"`).join(' or ')}.`, + `The ${describe} change isn't drawn: no visible element has data-entity-id ${[...ids].map(id => `"${id}"`).join(' or ')}, or presents it in data-entity-aliases.`, ) } else { const side = change.after.length ? references.after : references.before - const reference = [...side.values()].find(sample => (change.after.length ? change.after : change.before).includes(sample.id)) - if (reference && drawn.every(sample => looks(sample) === looks(reference))) { + const own = change.after.length ? change.after : change.before + // Each drawing compared with how an unchanged comparison draws the same element: its own, or for a card that + // presents it, that card, which may present nothing there. + const neutral = (sample: EntitySample) => + ids.has(sample.id) + ? [...side.values()].find(reference => own.includes(reference.id)) + : (side.get(sample.key) ?? [...side.values()].find(reference => reference.id === sample.id)) + const compared = drawn.flatMap(sample => { + const reference = neutral(sample) + return reference ? [{sample, reference}] : [] + }) + if (compared.length && compared.every(({sample, reference}) => looks(sample) === looks(reference))) { failures.push(`The ${describe} change is drawn exactly as an unchanged comparison draws it, so nothing marks it as changed.`) } } @@ -68,7 +79,14 @@ export const diffChecks: Pick touches.has(part))) continue + // A card presenting a changed item (`data-entity-aliases`) is touched by its change. + if ( + touches.has(sample.id) || + sample.parts.some(part => touches.has(part)) || + (sample.aliases ?? []).some(alias => touches.has(alias)) + ) { + continue + } const neutral = reference.get(key) if (!neutral) continue compared++ diff --git a/packages/renderers/testing/src/checks/comparison/steps.ts b/packages/renderers/testing/src/checks/comparison/steps.ts index 92d170d98..02b368464 100644 --- a/packages/renderers/testing/src/checks/comparison/steps.ts +++ b/packages/renderers/testing/src/checks/comparison/steps.ts @@ -72,7 +72,17 @@ export const stepChecks: Pick = { for (const [key, sample] of on) { const neutral = off.get(key) // A unit may show its parts' emphasis (a card tinting the zone of a changed part). - if (!neutral || looks(neutral) === looks(sample) || allowed.has(sample.id) || sample.parts.some(part => allowed.has(part))) continue + // A card presenting a changed item (`data-entity-aliases`) may show its emphasis too. + const presents = (sample.aliases ?? []).some(alias => allowed.has(alias)) + if ( + !neutral || + looks(neutral) === looks(sample) || + allowed.has(sample.id) || + sample.parts.some(part => allowed.has(part)) || + presents + ) { + continue + } const step = stepOf(sample.id) failures.push( `After step ${index + 1} of ${ordered.length}, "${key}" is emphasized, but ${step < 0 ? (varied.has(sample.id) ? 'it varied only within tolerance, so it is unchanged' : 'no step changes it') : `step ${step + 1} changes it`}.`, diff --git a/packages/renderers/testing/src/measure/entities.ts b/packages/renderers/testing/src/measure/entities.ts index d53c6b932..fe254eb32 100644 --- a/packages/renderers/testing/src/measure/entities.ts +++ b/packages/renderers/testing/src/measure/entities.ts @@ -20,11 +20,22 @@ export function entitySamples(root: Element = document.body): EntitySample[] { opacity: Math.round(effectiveOpacity(element) * 100) / 100, ...paintOf(element), parts: [...new Set([...element.querySelectorAll('[data-entity-id]')].map(part => part.getAttribute('data-entity-id')!))], + aliases: aliasesOf(element), }) } return samples } +/** An element's `data-entity-aliases`, the SDK's JSON array of IDs; none when absent or unreadable. */ +function aliasesOf(element: Element): string[] { + try { + const aliases: unknown = JSON.parse(element.getAttribute('data-entity-aliases') ?? '[]') + return Array.isArray(aliases) ? aliases.filter((alias): alias is string => typeof alias === 'string') : [] + } catch { + return [] + } +} + /** IDs of visible entities: nested ones (parts) first, then units. */ export function visibleEntities(root: Element = document.body): string[] { const all = [...root.querySelectorAll('[data-entity-id]')].filter(visible) diff --git a/packages/renderers/testing/src/types.ts b/packages/renderers/testing/src/types.ts index e9ce4b23d..d982d4d93 100644 --- a/packages/renderers/testing/src/types.ts +++ b/packages/renderers/testing/src/types.ts @@ -171,6 +171,8 @@ export interface EntitySample { text: string /** IDs of entity elements nested inside it (a unit's parts), whose emphasis it may show. */ parts: string[] + /** The other items it presents (`data-entity-aliases`), such as a project drawn on its target framework's card. */ + aliases?: string[] /** * Categorical colours it paints, by category key: parts marked * `data-projections-category`. Their fill and background read as diff --git a/packages/renderers/testing/test/helpers.test.mjs b/packages/renderers/testing/test/helpers.test.mjs index 7695f9574..a35bbd869 100644 --- a/packages/renderers/testing/test/helpers.test.mjs +++ b/packages/renderers/testing/test/helpers.test.mjs @@ -163,6 +163,58 @@ test('stable-layout compares two diffs once each frame has the height its render assert.equal(result.status, 'pass', result.details.join('\n')) }) +test('a card that presents a changed item in data-entity-aliases draws its change, and may show it', async () => { + // A package folded into the card of the package that brought it: no element of its own. Only the comparison's card + // presents it; an unchanged comparison draws the same card plain and presenting nothing. + const card = (paint, aliases) => ({ + key: 'b', + id: 'b', + box: [0, 0, 10, 10], + opacity: 1, + paint, + text: 'b', + parts: [], + categories: {}, + aliases, + }) + const check = async (id, aliases, marked = true) => { + const {driver, loads} = fakeDriver(['diff']) + driver.measure = async call => { + if (call !== 'samples') return [] + const unchanged = loads.at(-1).subject.comparison?.changes.length === 0 + return [unchanged ? card('plain', []) : card(marked ? 'tinted' : 'plain', aliases)] + } + const [result] = await runChecks(driver, subject, {checks: [id]}) + return result + } + assert.equal((await check('diff-changes', ['a'])).status, 'pass') + const missing = await check('diff-changes', []) + assert.equal(missing.status, 'fail') + assert.match(missing.details[0], /presents it in data-entity-aliases/u) + // Presented, but drawn as an unchanged comparison draws the same card: nothing marks the change. + const unmarked = await check('diff-changes', ['a'], false) + assert.equal(unmarked.status, 'fail') + assert.match(unmarked.details[0], /drawn exactly as an unchanged comparison draws it/u) + // The card's emphasis is the change's, not an unchanged item's. + assert.notEqual((await check('diff-neutral', ['a'])).status, 'fail') + assert.equal((await check('diff-neutral', [])).status, 'fail') + // After the step that changes it, highlighting may tint the card that presents it. + const highlighted = async aliases => { + const {driver, loads} = fakeDriver(['animated']) + const load = driver.load.bind(driver) + driver.load = async (loaded, options) => ({...(await load(loaded, options)), steps: [0, 0.5, 1]}) + driver.seek = async (progress, options = {}) => { + const {subject: loaded, ...rest} = loads.at(-1) + return driver.load(loaded, {...rest, ...options, progress}) + } + driver.measure = async call => (call === 'samples' ? [card(loads.at(-1).highlighting === 1 ? 'tinted' : 'plain', aliases)] : []) + const [result] = await runChecks(driver, subject, {checks: ['highlight-scope']}) + return result + } + assert.equal((await highlighted(['a'])).status, 'pass') + assert.equal((await highlighted([])).status, 'fail') +}) + test('checks run per declared comparison mode', async () => { const status = results => Object.fromEntries(results.map(result => [result.id, result.status])) const diffOnly = fakeDriver(['diff']) From 6b145495670f495697a73d9ccb9522b2094e5187 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:50:59 +0000 Subject: [PATCH 2/9] Kit: fold runs of unchanged cards into bands in CardGrid (work in progress) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- docs/guides/renderer-kit-components.md | 8 +- .../cli/browser/starter-repository.spec.ts | 2 +- packages/cli/browser/starter.spec.ts | 24 +++ .../cli/templates/renderer/scenarios.json | 57 +++++ .../renderers/kit/browser/card-grid-page.ts | 26 +-- .../renderers/kit/browser/card-grid.spec.ts | 30 ++- packages/renderers/kit/src/react/fold.tsx | 20 +- .../renderers/kit/src/react/grid-folds.tsx | 198 ++++++++++++------ .../kit/src/react/layout-components.tsx | 35 ++-- .../renderers/kit/src/react/shell/focus.ts | 16 +- packages/renderers/kit/styles/diff.css | 2 +- packages/renderers/kit/styles/layout.css | 7 + 12 files changed, 329 insertions(+), 96 deletions(-) diff --git a/docs/guides/renderer-kit-components.md b/docs/guides/renderer-kit-components.md index e658cf754..b1ea36ee7 100644 --- a/docs/guides/renderer-kit-components.md +++ b/docs/guides/renderer-kit-components.md @@ -321,7 +321,13 @@ accept token scale steps rather than raw lengths or colors—this is how additions fold the same way. The card takes the place of the first, opens them in place ("Hide 14 removed jobs") and, while closed, lists them in `data-entity-aliases`, so the host's selection, hover and filter of one find - it. A card reports its status and kind from its `change` row. + it. A run of a dozen or more unchanged cards with nothing between them folds + the same way into a `Fold` band across the grid ("14 unchanged services"), + except under the Changes scope, which shows its unchanged cards as context. A + single revision folds nothing. A card reports its status and kind from its + `change` row, and keeps its place in the grid, hidden, while a fold takes it. + `Fold` takes an `id` and the IDs it `presents` for a fold that stands for + items the host can select. - `EntityCard` renders a single entity as a ring unit with `data-entity-id`, a select button, `label`, `identifier`, `children`, and worded change status. In progress modes, its leading edge picks up the change hue as `emphasis` rises diff --git a/packages/cli/browser/starter-repository.spec.ts b/packages/cli/browser/starter-repository.spec.ts index 079773f69..426e2b5fc 100644 --- a/packages/cli/browser/starter-repository.spec.ts +++ b/packages/cli/browser/starter-repository.spec.ts @@ -27,7 +27,7 @@ test('the repository Inspector presents the renderer package scenarios beside th await page.goto(harness.url) // The Explorer's Compare section lists them as "Renderer scenarios", beside the Before → After pair. const scenarios = page.getByRole('list', {name: 'Renderer scenarios'}) - await expect(scenarios.getByRole('button')).toHaveCount(2) + await expect(scenarios.getByRole('button')).toHaveCount(3) await expect(scenarios.getByRole('button', {name: /^Checkout splits out payments/u})).toHaveAttribute('aria-pressed', 'false') await scenarios.getByRole('button', {name: /^Checkout splits out payments/u}).click() await expect(scenarios.getByRole('button', {name: /^Checkout splits out payments/u})).toHaveAttribute('aria-pressed', 'true') diff --git a/packages/cli/browser/starter.spec.ts b/packages/cli/browser/starter.spec.ts index 3bd3de9a4..b32a402cd 100644 --- a/packages/cli/browser/starter.spec.ts +++ b/packages/cli/browser/starter.spec.ts @@ -43,3 +43,27 @@ test('the starter renderer lays out only what the Changes scope shows', async ({ await stage.filter({query: '', changesOnly: false, ids: null, scope: null}) await expect(card('service:orders')).toBeVisible() }) + +test('the starter renderer folds a run of unchanged cards into a band in All, which opens in place', async ({page, inspector}) => { + const stage = await openStage(page, inspector, { + scenario: 'renderer/catalog', + comparisonMode: 'diff', + filter: {query: '', changesOnly: false, ids: null, scope: null}, + }) + const band = stage.frame.locator('.pk-grid-band') + await expect(band).toHaveCount(1) + await expect(band).toHaveText(/14 unchanged services/u) + await expect(stage.frame.locator('[data-entity-id="service:search"]')).toHaveCount(0) + await expect(stage.frame.locator('[data-entity-id="service:payments"]')).toBeVisible() + // The host's selection of a folded service finds the band. + await stage.select('service:search') + await expect(band).toHaveAttribute('data-projections-ring-selected', /.*/u) + await stage.select(null) + await band.getByRole('button').click() + await expect(stage.frame.locator('[data-entity-id="service:search"]')).toBeVisible() + await expect(band).toHaveText(/Hide 14 unchanged services/u) + // The Changes scope shows only the changes and their context: nothing to fold. + await stage.filter({query: '', changesOnly: true, ids: null, scope: ['service:checkout', 'service:payments', 'calls:checkout->payments']}) + await expect(stage.frame.locator('.pk-grid-band')).toHaveCount(0) + await expect(stage.frame.locator('[data-entity-id="service:payments"]')).toBeVisible() +}) diff --git a/packages/cli/templates/renderer/scenarios.json b/packages/cli/templates/renderer/scenarios.json index cd0c79b07..3f2e2b3e0 100644 --- a/packages/cli/templates/renderer/scenarios.json +++ b/packages/cli/templates/renderer/scenarios.json @@ -37,6 +37,63 @@ ] } }, + { + "id": "catalog", + "title": "Payments joins fourteen unchanged services", + "description": "In All, the run of fourteen unchanged services folds into one band across the grid, which opens in place; the Changes scope shows only the changes and their context.", + "before": { + "protocolVersion": 0, + "schema": "graph/v0", + "entities": [ + {"id": "service:checkout", "kind": "service", "label": "Checkout", "data": {"owner": "web"}}, + {"id": "service:accounts", "kind": "service", "label": "Accounts"}, + {"id": "service:analytics", "kind": "service", "label": "Analytics"}, + {"id": "service:audit", "kind": "service", "label": "Audit"}, + {"id": "service:catalog", "kind": "service", "label": "Catalog"}, + {"id": "service:email", "kind": "service", "label": "Email"}, + {"id": "service:inventory", "kind": "service", "label": "Inventory"}, + {"id": "service:invoices", "kind": "service", "label": "Invoices"}, + {"id": "service:ledger", "kind": "service", "label": "Ledger"}, + {"id": "service:notifications", "kind": "service", "label": "Notifications"}, + {"id": "service:pricing", "kind": "service", "label": "Pricing"}, + {"id": "service:profiles", "kind": "service", "label": "Profiles"}, + {"id": "service:reviews", "kind": "service", "label": "Reviews"}, + {"id": "service:search", "kind": "service", "label": "Search"}, + {"id": "service:shipping", "kind": "service", "label": "Shipping"} + ], + "relationships": [ + {"id": "calls:checkout->pricing", "kind": "calls", "from": "service:checkout", "to": "service:pricing"}, + {"id": "calls:checkout->inventory", "kind": "calls", "from": "service:checkout", "to": "service:inventory"} + ] + }, + "after": { + "protocolVersion": 0, + "schema": "graph/v0", + "entities": [ + {"id": "service:checkout", "kind": "service", "label": "Checkout", "data": {"owner": "payments"}}, + {"id": "service:accounts", "kind": "service", "label": "Accounts"}, + {"id": "service:analytics", "kind": "service", "label": "Analytics"}, + {"id": "service:audit", "kind": "service", "label": "Audit"}, + {"id": "service:catalog", "kind": "service", "label": "Catalog"}, + {"id": "service:email", "kind": "service", "label": "Email"}, + {"id": "service:inventory", "kind": "service", "label": "Inventory"}, + {"id": "service:invoices", "kind": "service", "label": "Invoices"}, + {"id": "service:ledger", "kind": "service", "label": "Ledger"}, + {"id": "service:notifications", "kind": "service", "label": "Notifications"}, + {"id": "service:pricing", "kind": "service", "label": "Pricing"}, + {"id": "service:profiles", "kind": "service", "label": "Profiles"}, + {"id": "service:reviews", "kind": "service", "label": "Reviews"}, + {"id": "service:search", "kind": "service", "label": "Search"}, + {"id": "service:shipping", "kind": "service", "label": "Shipping"}, + {"id": "service:payments", "kind": "service", "label": "Payments"} + ], + "relationships": [ + {"id": "calls:checkout->pricing", "kind": "calls", "from": "service:checkout", "to": "service:pricing"}, + {"id": "calls:checkout->inventory", "kind": "calls", "from": "service:checkout", "to": "service:inventory"}, + {"id": "calls:checkout->payments", "kind": "calls", "from": "service:checkout", "to": "service:payments"} + ] + } + }, { "id": "single", "title": "One revision", diff --git a/packages/renderers/kit/browser/card-grid-page.ts b/packages/renderers/kit/browser/card-grid-page.ts index f848c848e..17fb5d23b 100644 --- a/packages/renderers/kit/browser/card-grid-page.ts +++ b/packages/renderers/kit/browser/card-grid-page.ts @@ -1,5 +1,5 @@ // The card grid page's script (card-grid.spec.ts bundles it): a `CardGrid` of job cards in a `Group`, a workflow that -// drops 14 jobs and keeps 2, in the mode asked for. +// drops 14 jobs and keeps 2, or keeps 14 and adds 1, in the mode asked for, under the Changes scope or not. import {createElement as h} from 'react' import {flushSync} from 'react-dom' import {createRoot} from 'react-dom/client' @@ -9,6 +9,10 @@ import '../react.css' export interface GridMode { diff: boolean emphasis: number + /** `removed`: 14 jobs dropped, 2 kept; `unchanged`: 14 kept, then 1 added. */ + rows: 'removed' | 'unchanged' + /** Under the Changes scope (`data-scope="changes"` on the kit's root). */ + scoped?: boolean } declare global { @@ -17,21 +21,19 @@ declare global { } const job = (id: string) => ({id, kind: 'job', label: id}) -const rows = [ - ...['build', 'test'].map(id => ({id, before: job(id), after: job(id), status: 'unchanged' as const})), - ...Array.from({length: 14}, (_, index) => `legacy-${String(index + 1).padStart(2, '0')}`).map(id => ({ - id, - before: job(id), - status: 'removed' as const, - })), -] +const numbered = (prefix: string) => Array.from({length: 14}, (_, index) => `${prefix}-${String(index + 1).padStart(2, '0')}`) +const kept = (id: string) => ({id, before: job(id), after: job(id), status: 'unchanged' as const}) +const sets = { + removed: [...['build', 'test'].map(kept), ...numbered('legacy').map(id => ({id, before: job(id), status: 'removed' as const}))], + unchanged: [...numbered('step').map(kept), {id: 'deploy', after: job('deploy'), status: 'added' as const}], +} const container = document.getElementById('root') if (!container) throw new Error('The page has no #root') const root = createRoot(container) globalThis.selected = [] -globalThis.showGrid = ({diff, emphasis}) => { - const cards = rows.map(row => +globalThis.showGrid = ({diff, emphasis, rows, scoped = false}) => { + const cards = sets[rows].map(row => h(EntityCard, { key: row.id, id: row.id, @@ -50,7 +52,7 @@ globalThis.showGrid = ({diff, emphasis}) => { root.render( h( 'div', - {className: 'pk'}, + {className: 'pk', 'data-mode': 'comparison', ...(scoped ? {'data-scope': 'changes'} : {})}, h(ContentView, {children: h(Group, {title: 'Jobs', children: h(CardGrid, {label: 'Jobs', children: cards})})}), ), ) diff --git a/packages/renderers/kit/browser/card-grid.spec.ts b/packages/renderers/kit/browser/card-grid.spec.ts index c737d3d64..d5143d135 100644 --- a/packages/renderers/kit/browser/card-grid.spec.ts +++ b/packages/renderers/kit/browser/card-grid.spec.ts @@ -5,8 +5,8 @@ import {defaultThemeTokens} from '@githubnext/projections-renderer-sdk/protocol' import type {GridMode} from './card-grid-page.js' /** - * A `CardGrid` folds a dozen or more of its cards removed together into one card in their removed style, which presents - * them to the host and opens them in place. + * A `CardGrid` folds a dozen or more of its cards removed together into one card in their removed style, and a run of a + * dozen or more unchanged ones into a band across it; each presents its cards to the host and opens them in place. */ const kit = fileURLToPath(new URL('../', import.meta.url)) @@ -42,8 +42,8 @@ function gridPage() { const legacy = Array.from({length: 14}, (_, index) => `legacy-${String(index + 1).padStart(2, '0')}`) for (const mode of [ - {diff: true, emphasis: 1}, - {diff: false, emphasis: 1}, + {diff: true, emphasis: 1, rows: 'removed'}, + {diff: false, emphasis: 1, rows: 'removed'}, ] satisfies GridMode[]) { test(`a card grid folds 14 removed jobs into one card that opens in place (${mode.diff ? 'diff' : 'transition'})`, async ({ page: target, @@ -72,3 +72,25 @@ for (const mode of [ await expect(target.locator('[data-entity-id^="legacy-"]')).toHaveCount(0) }) } + +test('a card grid folds a run of 14 unchanged jobs into a band across it, but not under the Changes scope', async ({page: target}) => { + await target.setContent(await gridPage()) + await target.evaluate(shown => globalThis.showGrid(shown), {diff: true, emphasis: 1, rows: 'unchanged'} satisfies GridMode) + const band = target.locator('.pk-grid-band') + await expect(band).toHaveCount(1) + await expect(band).toHaveText(/14 unchanged jobs/u) + await expect(band).toHaveAttribute('data-fold', 'closed') + expect(JSON.parse((await band.getAttribute('data-entity-aliases')) ?? '[]')).toHaveLength(14) + await expect(target.locator('[data-entity-id^="step-"]')).toHaveCount(0) + await expect(target.locator('[data-entity-id="deploy"]')).toBeVisible() + // The band spans the grid. + const [grid, drawn] = await Promise.all([target.locator('.pk-card-grid').boundingBox(), band.boundingBox()]) + expect(Math.abs((drawn?.width ?? 0) - (grid?.width ?? 0))).toBeLessThan(1) + await band.getByRole('button').click() + await expect(target.locator('[data-entity-id^="step-"]')).toHaveCount(14) + await expect(band).toHaveText(/Hide 14 unchanged jobs/u) + // The Changes scope shows its unchanged cards as context: no band. + await target.evaluate(shown => globalThis.showGrid(shown), {diff: true, emphasis: 1, rows: 'unchanged', scoped: true} satisfies GridMode) + await expect(target.locator('.pk-grid-band')).toHaveCount(0) + await expect(target.locator('[data-entity-id^="step-"]')).toHaveCount(14) +}) diff --git a/packages/renderers/kit/src/react/fold.tsx b/packages/renderers/kit/src/react/fold.tsx index f98807f1f..454d8319f 100644 --- a/packages/renderers/kit/src/react/fold.tsx +++ b/packages/renderers/kit/src/react/fold.tsx @@ -3,6 +3,7 @@ import {useCallback, useState, createElement, type ElementType} from 'react' import {ChevronsDownUp, ChevronsUpDown} from 'lucide' import {foldList, type ChangesScope, type Folded} from '../scope.js' import {keyed} from '@githubnext/projections-renderer-sdk/presentation' +import {entityAliasesAttribute} from '@githubnext/projections-renderer-sdk/interactions' /** * Folds a list for the Changes scope (`foldList`) and keeps which folds the person expanded, until the scope's shown @@ -35,7 +36,9 @@ export function useFolds( /** * A fold: "12 unchanged declarations", a button that opens the run in place; `open`, "Hide 12 unchanged declarations" * above the opened run, which folds it again. `as` sets its element (`div` by default, `tr` or `li` in tables and lists; - * a `tr` puts the button in one cell spanning `columns`). + * a `tr` puts the button in one cell spanning `columns`). Given an `id`, the fold is an item the host sees, and while + * closed it presents the items it folds (`presents`, in `data-entity-aliases`), so the host's selection, hover and + * filter of one find it. */ export function Fold({ count, @@ -45,6 +48,8 @@ export function Fold({ as: Element = 'div', columns, className, + id, + presents, }: { count: number /** @@ -58,6 +63,10 @@ export function Fold({ as?: ElementType columns?: number className?: string + /** The fold's own `data-entity-id`, when it presents the items it folds to the host. */ + id?: string | undefined + /** The IDs of the items it folds, presented while it is closed (with `id`). */ + presents?: readonly string[] | undefined }) { warnUnchangedNoun(noun) const label = `${open ? 'Hide ' : ''}${count.toLocaleString()} unchanged ${noun}` @@ -68,7 +77,14 @@ export function Fold({ ) return ( - + {Element === 'tr' ? {button} : button} ) diff --git a/packages/renderers/kit/src/react/grid-folds.tsx b/packages/renderers/kit/src/react/grid-folds.tsx index 08e31ac47..bf691fb50 100644 --- a/packages/renderers/kit/src/react/grid-folds.tsx +++ b/packages/renderers/kit/src/react/grid-folds.tsx @@ -1,61 +1,93 @@ -// A card grid's folds of mass changes: a dozen or more of its cards removed (or added) together, of one kind, drawn as -// one card that counts them and opens in place, as a graph canvas folds them (`foldMassChanges`). -import {createContext, use, useCallback, useLayoutEffect, useMemo, useState} from 'react' +// A card grid's folds: a dozen or more of its cards removed (or added) together, of one kind, drawn as one card that +// counts them and opens in place, as a graph canvas folds them (`foldMassChanges`); and a run of a dozen or more +// unchanged cards drawn as one band across the grid, the Changes scope's `Fold`. +import {createContext, use, useCallback, useMemo, useState} from 'react' import {entityAliasesAttribute} from '@githubnext/projections-renderer-sdk/interactions' import {massFoldLabel, massFoldMinimum, massFoldPrefix, type MassStatus} from '../mass-fold.js' +import {foldPrefix} from '../scope-parts.js' import {changeMark} from '../diff/model.js' import {ChangeFooter} from './components.js' -import {FoldGlyph} from './fold.js' +import {Fold, FoldGlyph} from './fold.js' import {useKindNoun} from './kind-nouns.js' -/** What a card tells its grid: whether it is removed or added, and its kind. */ -interface GridCard { - status: MassStatus - kind: string -} +/** A card's slot in its grid (`gridSlot`): its ID, status and kind, kept in place (hidden) while a fold takes it. */ +const slotAttribute = 'data-pk-grid-card' +const statusAttribute = 'data-pk-grid-status' +const kindAttribute = 'data-pk-grid-kind' +/** The grid's own folds, which stand in a run rather than break it. */ +const ownFolds = '.pk-mass-fold, .pk-grid-band' + +/** One of a grid's children in order: a card's slot, or anything else (a Changes scope fold, a note), which breaks a run. */ +type GridEntry = {id: string; status: string; kind: string} | null /** One fold of a grid's cards. */ export interface GridFold { - /** The fold card's `data-entity-id`: `massFoldPrefix`, the status, the kind and its first card's ID. */ + /** + * Its own `data-entity-id`: for a fold of removed or added cards, `massFoldPrefix`, the status, the kind and its + * first card's ID; for a band of unchanged ones, `foldPrefix`, `grid:` and its first card's ID. + */ id: string - status: MassStatus - /** The cards it folds, in the grid's order: their IDs are the card's `data-entity-aliases` while it is closed. */ + /** `mass`: cards removed (or added) together, in their style; `unchanged`: a run of unchanged cards, as a band. */ + type: 'mass' | 'unchanged' + status: MassStatus | 'unchanged' + /** The cards it folds, in the grid's order: their IDs are its `data-entity-aliases` while it is closed. */ members: readonly string[] + /** A mass fold's label (`48 jobs removed`); a band's plural noun (`jobs`), which `Fold` counts as unchanged. */ label: string open: boolean } interface GridFolds { - report: (id: string, card: GridCard | undefined) => void foldOf: (id: string) => GridFold | undefined toggle: (fold: string) => void } const GridFoldsContext = createContext(undefined) -/** Provides a grid's folds to its cards: they report themselves, and it folds the runs. */ +/** Provides a grid's folds to its cards. */ export const GridFoldsProvider = GridFoldsContext /** - * A grid's folds: each card reports its status and kind (`useGridFold`), and a dozen or more cards of one kind removed - * (or added) fold into one card in the place of the first. What the person opened stays open. + * What a grid's children say, in order (`GridEntry`), and whether the Changes scope is shown. A single revision (the + * kit shell's `data-mode`) folds nothing: its cards have no change, however a renderer passes its rows. + */ +function readGrid(element: Element): {key: string; entries: readonly GridEntry[]; scoped: boolean} { + const scoped = element.closest('[data-scope="changes"]') !== null + const mode = element.closest('[data-mode]')?.getAttribute('data-mode') + const children = mode === undefined || mode === 'comparison' ? [...element.children] : [] + const entries = children.flatMap((child): GridEntry[] => { + if (child.matches(ownFolds)) return [] + const id = child.getAttribute(slotAttribute) + return [id === null ? null : {id, status: child.getAttribute(statusAttribute) ?? '', kind: child.getAttribute(kindAttribute) ?? ''}] + }) + return {key: JSON.stringify([scoped, entries]), entries, scoped} +} + +/** + * A grid's folds, read from its children in order as they are drawn (`attach` is the grid element's `ref`): a dozen or + * more cards of one kind removed (or added) fold into one card in the place of the first (`GridFoldCard`); a run of a + * dozen or more unchanged cards, nothing else between them, folds into a band across the grid (`GridBand`), except + * under the Changes scope, which shows its unchanged cards as context. What the person opened stays open. */ -export function useGridFolds(): GridFolds { +export function useGridFolds(): {folds: GridFolds; attach: (element: HTMLElement | null) => (() => void) | undefined} { const noun = useKindNoun() - const [cards, setCards] = useState>(() => new Map()) + const [read, setRead] = useState<{key: string; entries: readonly GridEntry[]; scoped: boolean}>({key: '', entries: [], scoped: false}) const [open, setOpen] = useState>(() => new Set()) - const report = useCallback( - (id: string, card: GridCard | undefined) => - setCards(previous => { - const known = previous.get(id) - if (known?.status === card?.status && known?.kind === card?.kind) return previous - const next = new Map(previous) - if (card) next.set(id, card) - else next.delete(id) - return next - }), - [], - ) + // The cards as drawn, read once the grid is attached and again whenever its cards change, before the next paint: a + // folded grid never draws its cards first. + const attach = useCallback((element: HTMLElement | null) => { + if (!element) return undefined + const update = () => { + const next = readGrid(element) + setRead(previous => (previous.key === next.key ? previous : next)) + } + update() + const observer = new MutationObserver(update) + observer.observe(element, {childList: true, subtree: true, attributeFilter: [slotAttribute, statusAttribute, kindAttribute]}) + const root = element.closest('.pk') + if (root) observer.observe(root, {attributeFilter: ['data-scope', 'data-mode']}) + return () => observer.disconnect() + }, []) const toggle = useCallback( (fold: string) => setOpen(previous => { @@ -66,55 +98,101 @@ export function useGridFolds(): GridFolds { }), [], ) - const folds = useMemo(() => { - const groups = new Map() - for (const [id, card] of cards) { - const key = `${card.status}\n${card.kind}` - const group = groups.get(key) ?? {card, members: []} - group.members.push(id) + const byId = useMemo(() => { + const byCard = new Map() + const groups = new Map() + for (const entry of read.entries) { + if (entry?.status !== 'removed' && entry?.status !== 'added') continue + const key = `${entry.status}\n${entry.kind}` + const group = groups.get(key) ?? {status: entry.status, kind: entry.kind, members: []} + group.members.push(entry.id) groups.set(key, group) } - const byCard = new Map() - for (const {card, members} of groups.values()) { + for (const {status, kind, members} of groups.values()) { const [first] = members if (first === undefined || members.length < massFoldMinimum) continue - const id = `${massFoldPrefix}${card.status}:${card.kind}:${first}` + const id = `${massFoldPrefix}${status}:${kind}:${first}` const opened = open.has(id) - const fold = { + const fold: GridFold = { id, - status: card.status, + type: 'mass', + status, members, open: opened, - label: massFoldLabel(members.length, card.status, noun(card.kind), opened), + label: massFoldLabel(members.length, status, noun(kind), opened), } for (const member of members) byCard.set(member, fold) } + if (!read.scoped) { + let run: {id: string; kind: string}[] = [] + const flush = () => { + const [first] = run + if (first !== undefined && run.length >= massFoldMinimum) { + const id = `${foldPrefix}grid:${first.id}` + const kinds = new Set(run.map(card => card.kind)) + const label = kinds.size === 1 ? noun(first.kind).plural : 'items' + const fold: GridFold = {id, type: 'unchanged', status: 'unchanged', members: run.map(card => card.id), open: open.has(id), label} + for (const card of run) byCard.set(card.id, fold) + } + run = [] + } + for (const entry of read.entries) { + if (entry?.status === 'unchanged') run.push(entry) + else flush() + } + flush() + } return byCard - }, [cards, open, noun]) - const foldOf = useCallback((id: string) => folds.get(id), [folds]) - return useMemo(() => ({report, foldOf, toggle}), [report, foldOf, toggle]) + }, [read, open, noun]) + const foldOf = useCallback((id: string) => byId.get(id), [byId]) + const folds = useMemo(() => ({foldOf, toggle}), [foldOf, toggle]) + return {folds, attach} +} + +/** A card's place in its grid: the attributes of its slot, and the fold that takes it, if any. */ +export interface GridSlot { + /** Attributes for the card's element, or the hidden one that keeps its place while a fold takes it. */ + slot: Record + fold: GridFold | undefined + /** Whether it is the fold's first card, which draws the fold. */ + leads: boolean + toggle: () => void } /** - * A card's fold in its grid, once it has said whether it is removed or added and its kind: undefined outside a grid, - * and for a card no fold takes. `row` is the card's change (its `before` or `after` entity gives the kind). + * A card's place in its grid (undefined outside one): `row` is the card's change, its `before` or `after` entity giving + * the kind; a card with no change (one revision) has no status, and no fold takes it. */ -export function useGridFold( +export function useGridSlot( id: string, row: {status?: string; before?: {kind?: unknown}; after?: {kind?: unknown}} | undefined, -): {fold: GridFold; toggle: () => void} | undefined { +): GridSlot | undefined { const grid = use(GridFoldsContext) - const status = row?.status === 'removed' || row?.status === 'added' ? row.status : undefined - const kind = (status === 'removed' ? row?.before?.kind : row?.after?.kind) ?? undefined - const report = grid?.report - // Reported before the first paint, so a folded grid never draws its cards first. - useLayoutEffect(() => { - if (!report) return undefined - report(id, status && typeof kind === 'string' ? {status, kind} : undefined) - return () => report(id, undefined) - }, [report, id, status, kind]) - const fold = grid?.foldOf(id) - return fold && grid ? {fold, toggle: () => grid.toggle(fold.id)} : undefined + if (!grid) return undefined + const entity = row?.status === 'removed' ? row.before : (row?.after ?? row?.before) + const kind = typeof entity?.kind === 'string' ? entity.kind : '' + const slot = {[slotAttribute]: id, [statusAttribute]: row?.status ?? '', [kindAttribute]: kind} + const fold = grid.foldOf(id) + const toggle = () => { + if (fold) grid.toggle(fold.id) + } + return {slot, fold, leads: fold?.members[0] === id, toggle} +} + +/** A band across the grid for a run of unchanged cards: `Fold`, presenting them to the host while closed. */ +export function GridBand({fold, onToggle}: {fold: GridFold; onToggle: () => void}) { + return ( + + ) } /** diff --git a/packages/renderers/kit/src/react/layout-components.tsx b/packages/renderers/kit/src/react/layout-components.tsx index be710180a..6ba7838bb 100644 --- a/packages/renderers/kit/src/react/layout-components.tsx +++ b/packages/renderers/kit/src/react/layout-components.tsx @@ -14,7 +14,7 @@ import {Icon} from './icons.js' import {useSelectable} from './shell/frame.js' import {useSelectControl} from './select-control.js' import {mixedChange, type ChangeClassification} from '../emphasis.js' -import {GridFoldCard, GridFoldsProvider, useGridFold, useGridFolds} from './grid-folds.js' +import {GridBand, GridFoldCard, GridFoldsProvider, useGridFolds, useGridSlot} from './grid-folds.js' interface StatusChange { status: Status @@ -159,14 +159,16 @@ export function Group({ } /** - * Cards in a responsive grid: as many columns as fit, one on a phone. A dozen or more of its `EntityCard`s removed - * (or added) together, of one kind, fold into one card that counts them and opens in place (`GridFoldCard`). + * Cards in a responsive grid: as many columns as fit, one on a phone. In a comparison, a dozen or more of its + * `EntityCard`s removed (or added) together, of one kind, fold into one card that counts them and opens in place + * (`GridFoldCard`), and a run of a dozen or more unchanged ones folds into a band across the grid (`GridBand`), except + * under the Changes scope. */ export function CardGrid({children, label}: {children: ReactNode; label?: string}) { - const folds = useGridFolds() + const {folds, attach} = useGridFolds() return ( -
      +
        {children}
      @@ -234,7 +236,7 @@ export function EntityCard({ children, }: EntityCardProps) { const selectControl = useSelectControl() - const folding = useGridFold(id, change ?? (typeof mark === 'object' ? mark : undefined)) + const place = useGridSlot(id, change ?? (typeof mark === 'object' ? mark : undefined)) const style = {'--emphasis': emphasis, ...(presence < 1 ? {opacity: presence, visibility: presence > 0 ? 'visible' : 'hidden'} : {})} const name = ( @@ -246,9 +248,10 @@ export function EntityCard({ ) - // A card a closed fold takes is drawn by the fold, in the place of its first card. - if (folding && !folding.fold.open && folding.fold.members[0] !== id) return null - const leads = folding?.fold.members[0] === id ? folding : undefined + const fold = place?.fold + // A card a closed fold takes keeps its place, hidden; the fold is drawn in the place of its first card. + const hidden =
    • 0 ? (change.renamed ? 'renamed' : change.status) : undefined} {...(mark !== undefined ? changeMark(mark) : {})} style={style as CSSProperties} @@ -285,14 +289,17 @@ export function EntityCard({ )}
    • ) + if (!fold || !place.leads) return card // The fold keeps its place whether open or closed, so its button stays the same element. - return leads ? ( + return ( <> - - {leads.fold.open && card} + {fold.type === 'mass' ? ( + + ) : ( + + )} + {fold.open ? card : hidden} - ) : ( - card ) } diff --git a/packages/renderers/kit/src/react/shell/focus.ts b/packages/renderers/kit/src/react/shell/focus.ts index 3be5a61c2..132701a17 100644 --- a/packages/renderers/kit/src/react/shell/focus.ts +++ b/packages/renderers/kit/src/react/shell/focus.ts @@ -2,6 +2,7 @@ import {useEffect, useMemo, useState, type RefObject} from 'react' import type {FilterPayload} from '@githubnext/projections-renderer-sdk/protocol' import {afterPaint} from '@githubnext/projections-renderer-sdk/client' +import {entityAliasesAttribute} from '@githubnext/projections-renderer-sdk/interactions' import {placedAttribute} from '../../focus.js' import {layoutFilter} from '../../scope-filter.js' @@ -33,14 +34,27 @@ export function useOpeningReveal(root: RefObject, ids: Reado if (!element || !wanted) return undefined const focused = new Set(wanted.split('\n')) return afterPaint(() => { + // An item a fold presents (`data-entity-aliases`) is found on the fold. const target = [...element.querySelectorAll('[data-entity-id]')].find( - item => focused.has(item.getAttribute('data-entity-id') ?? '') && !item.closest(`[${placedAttribute}]`), + item => + (focused.has(item.getAttribute('data-entity-id') ?? '') || aliasesOf(item).some(alias => focused.has(alias))) && + !item.closest(`[${placedAttribute}]`), ) if (target) scrollOpen(target) }) }, [root, wanted, key]) } +/** An element's `data-entity-aliases`: the other items it presents. */ +function aliasesOf(element: Element): string[] { + try { + const parsed: unknown = JSON.parse(element.getAttribute(entityAliasesAttribute) ?? '[]') + return Array.isArray(parsed) ? parsed.filter((alias): alias is string => typeof alias === 'string') : [] + } catch { + return [] + } +} + /** Scrolls each container that hides `target` so it sits a fifth of the way down (and in view across). */ function scrollOpen(target: Element): void { const document = target.ownerDocument diff --git a/packages/renderers/kit/styles/diff.css b/packages/renderers/kit/styles/diff.css index e35dd426b..442d2b7dd 100644 --- a/packages/renderers/kit/styles/diff.css +++ b/packages/renderers/kit/styles/diff.css @@ -18,7 +18,7 @@ text-decoration: line-through; } /* A fold of removed cards says so in words ("16 reports removed"): its count isn't struck as a removed name is. */ -.pk .graph-node[data-fold][data-change='removed'] .pk-diff-text { +.pk .graph-node[data-fold] .pk-diff-text { text-decoration: none; } diff --git a/packages/renderers/kit/styles/layout.css b/packages/renderers/kit/styles/layout.css index 6ba7e1343..6879954c4 100644 --- a/packages/renderers/kit/styles/layout.css +++ b/packages/renderers/kit/styles/layout.css @@ -223,6 +223,13 @@ .pk .pk-mass-fold .pk-fold-icon { color: var(--muted); } +/* A run of unchanged cards folded into a band across the grid (`GridBand`); a card a fold takes keeps its place, hidden. */ +.pk .pk-card-grid > .pk-grid-band { + grid-column: 1 / -1; +} +.pk .pk-card-grid > [hidden] { + display: none; +} /* Hover, keyboard focus and selection rings are the renderer SDK's, on the card's own element. */ .pk .pk-entity-card-select { display: flex; From 15a2dae71444db53e6d17e72b86480cb9dfe8b17 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:12:49 +0000 Subject: [PATCH 3/9] Kit: fold controls are their own action; scrub and check coverage for folds Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../renderers/graph/browser/graph.spec.ts | 3 +- .../renderers/kit/browser/card-grid.spec.ts | 11 +++++-- packages/renderers/kit/browser/fixtures.ts | 30 +++++++++++++++++++ .../renderers/kit/browser/invariants/frame.ts | 18 ++++++++++- packages/renderers/kit/browser/suite.ts | 20 ++++++++++--- packages/renderers/kit/src/react/fold.tsx | 2 +- .../src/react/graph-canvas/entity-card.tsx | 2 +- .../renderers/kit/src/react/grid-folds.tsx | 1 + packages/renderers/testing/README.md | 3 +- .../renderers/testing/src/checks/catalog.ts | 2 +- .../testing/src/checks/interaction.ts | 3 +- .../renderers/testing/src/measure/entities.ts | 11 +++++-- packages/renderers/testing/src/probe.ts | 1 + packages/renderers/testing/src/types.ts | 1 + 14 files changed, 91 insertions(+), 17 deletions(-) diff --git a/packages/renderers/graph/browser/graph.spec.ts b/packages/renderers/graph/browser/graph.spec.ts index 7987a08e2..ca8139754 100644 --- a/packages/renderers/graph/browser/graph.spec.ts +++ b/packages/renderers/graph/browser/graph.spec.ts @@ -1,7 +1,7 @@ import {expect, test} from '@playwright/test' import {harnessInspector, openRenderer} from '@githubnext/projections-renderer-harness/playwright' import {openStage} from '@githubnext/projections-renderer-testing/playwright' -import {featureFlags, fileReflow, layeredWaves, wideFanOut} from '../../kit/browser/fixtures.js' +import {featureFlags, fileReflow, layeredWaves, massRemoval, wideFanOut} from '../../kit/browser/fixtures.js' import {scrubSuite, selectionSuite} from '../../kit/browser/suite.js' import {paneStatusSuite, statusSuite} from '../../kit/browser/status.js' @@ -12,6 +12,7 @@ scrubSuite([ featureFlags(), wideFanOut(), wideFanOut('graph-horizontal'), + massRemoval(), ]) selectionSuite(fileReflow('graph'), 'file:src/api.ts') statusSuite(fileReflow('graph')) diff --git a/packages/renderers/kit/browser/card-grid.spec.ts b/packages/renderers/kit/browser/card-grid.spec.ts index d5143d135..4d2d28924 100644 --- a/packages/renderers/kit/browser/card-grid.spec.ts +++ b/packages/renderers/kit/browser/card-grid.spec.ts @@ -83,9 +83,14 @@ test('a card grid folds a run of 14 unchanged jobs into a band across it, but no expect(JSON.parse((await band.getAttribute('data-entity-aliases')) ?? '[]')).toHaveLength(14) await expect(target.locator('[data-entity-id^="step-"]')).toHaveCount(0) await expect(target.locator('[data-entity-id="deploy"]')).toBeVisible() - // The band spans the grid. - const [grid, drawn] = await Promise.all([target.locator('.pk-card-grid').boundingBox(), band.boundingBox()]) - expect(Math.abs((drawn?.width ?? 0) - (grid?.width ?? 0))).toBeLessThan(1) + // The band spans the grid's columns. + const spans = await band.evaluate(element => { + const grid = element.parentElement ?? element + const style = getComputedStyle(grid) + const content = grid.clientWidth - Number.parseFloat(style.paddingLeft) - Number.parseFloat(style.paddingRight) + return Math.abs(element.getBoundingClientRect().width - content) + }) + expect(spans).toBeLessThan(1) await band.getByRole('button').click() await expect(target.locator('[data-entity-id^="step-"]')).toHaveCount(14) await expect(band).toHaveText(/Hide 14 unchanged jobs/u) diff --git a/packages/renderers/kit/browser/fixtures.ts b/packages/renderers/kit/browser/fixtures.ts index 06c1889eb..765e30b38 100644 --- a/packages/renderers/kit/browser/fixtures.ts +++ b/packages/renderers/kit/browser/fixtures.ts @@ -288,3 +288,33 @@ export const graphFamilyFixtures = (): FixturePair[] => [ architectureModules(), weightedFiles(), ] + +/** + * A reporting service retires with the 16 reports it ran, and an analytics service arrives: the reports fold into one + * card, `16 reports removed`, whose links stand for theirs (the `graph/mass-removal` scenario's pair). + */ +export function massRemoval(renderer = 'graph'): FixturePair { + const reports = Array.from({length: 16}, (_, index) => `report:r${String(index + 1).padStart(2, '0')}`) + const kept = [entity('gateway', 'service'), entity('orders', 'service'), entity('postgres', 'database')] + const keptLinks = [link('gateway', 'orders', 'calls'), link('orders', 'postgres', 'reads')] + return { + name: 'mass removal', + renderer, + before: { + protocolVersion: 0, + schema: 'graph/v0', + entities: [...kept, entity('reporting', 'service'), ...reports.map(id => entity(id, 'report'))], + relationships: [ + ...keptLinks, + link('gateway', 'reporting', 'calls'), + ...reports.flatMap(id => [link('reporting', id, 'runs'), link(id, 'postgres', 'reads')]), + ], + }, + after: { + protocolVersion: 0, + schema: 'graph/v0', + entities: [...kept, entity('analytics', 'service')], + relationships: [...keptLinks, link('gateway', 'analytics', 'calls'), link('analytics', 'postgres', 'reads')], + }, + } +} diff --git a/packages/renderers/kit/browser/invariants/frame.ts b/packages/renderers/kit/browser/invariants/frame.ts index 0c09892cb..a7ef01692 100644 --- a/packages/renderers/kit/browser/invariants/frame.ts +++ b/packages/renderers/kit/browser/invariants/frame.ts @@ -9,7 +9,13 @@ export interface FrameMeasurement { /** The diagram's `viewBox`, or undefined for HTML layouts. */ viewBox: string | undefined /** Visible cards (opacity above 0.01) in CSS pixels from the diagram's corner (so scrolling never moves them), and their opacity. */ - cards: {id: string; opacity: number; box: {left: number; top: number; right: number; bottom: number}}[] + cards: { + id: string + opacity: number + box: {left: number; top: number; right: number; bottom: number} + /** The other items it presents (`data-entity-aliases`), such as the cards a fold stands for. */ + presents: string[] + }[] /** Fully visible compound boundaries (architecture modules). */ groups: string[] /** Change decoration still drawn: emphasis overlays, status marks and badges, change marks and was/now text colors. */ @@ -30,12 +36,22 @@ export function measureFrame(root: Element): FrameMeasurement { } // A view opened above its fit scrolls; positions are taken from the diagram's corner so scrolling never moves them. const origin = svg?.getBoundingClientRect() ?? {left: 0, top: 0} + // An element's `data-entity-aliases`: the other items it presents (defined here, as the page runs this alone). + const aliasesOf = (element: Element): string[] => { + try { + const parsed: unknown = JSON.parse(element.getAttribute('data-entity-aliases') ?? '[]') + return Array.isArray(parsed) ? parsed.filter((alias): alias is string => typeof alias === 'string') : [] + } catch { + return [] + } + } const cards = [...root.querySelectorAll('.graph-node:not(.graph-group), .hierarchy-row, .fp-node')] .map(node => { const surface = node.querySelector('.node-surface, .fp-surface') ?? node const rect = surface.getBoundingClientRect() return { id: node.dataset.entityId ?? '', + presents: aliasesOf(node), opacity: opacityOf(node), box: {left: rect.left - origin.left, top: rect.top - origin.top, right: rect.right - origin.left, bottom: rect.bottom - origin.top}, } diff --git a/packages/renderers/kit/browser/suite.ts b/packages/renderers/kit/browser/suite.ts index 1a72fc02f..4aba13768 100644 --- a/packages/renderers/kit/browser/suite.ts +++ b/packages/renderers/kit/browser/suite.ts @@ -5,8 +5,19 @@ import {arrowContacts, contactIssues} from './invariants/contacts.js' import {measureFrame, type FrameMeasurement} from './invariants/frame.js' import {scrubFailures} from './invariants/scrub.js' -const ids = (frame: FrameMeasurement) => - [...new Set([...frame.cards.filter(card => card.opacity > 0.999).map(card => card.id), ...frame.groups])].toSorted() +/** + * The items a frame draws in full: its cards and groups, and the items a card presents (`data-entity-aliases`) among + * `items`, such as the cards a fold of mass changes stands for, which is no item itself. + */ +const ids = (frame: FrameMeasurement, items: ReadonlySet = new Set()) => + [ + ...new Set([ + ...frame.cards.flatMap(card => + card.opacity > 0.999 ? [card.id, ...card.presents.filter(id => items.has(id))].filter(id => !id.startsWith('pk-mass:')) : [], + ), + ...frame.groups, + ]), + ].toSorted() /** * Dense-scrub suite for staged graph-family renderers in the real host frame: @@ -55,8 +66,9 @@ export function scrubSuite(pairs: readonly FixturePair[]) { .map(entity => (side === 'before' ? (renamed.get(entity.id) ?? entity.id) : entity.id)) .filter(id => !undrawn.has(id)) .toSorted() - expect(ids(at(0))).toEqual(changedIds('before')) - expect(ids(at(1))).toEqual(changedIds('after')) + const items = new Set([...changedIds('before'), ...changedIds('after')]) + expect(ids(at(0), items)).toEqual(changedIds('before')) + expect(ids(at(1), items)).toEqual(changedIds('after')) expect( frames.some(frame => frame.decorated.length > 0), 'changes are emphasized mid-transition', diff --git a/packages/renderers/kit/src/react/fold.tsx b/packages/renderers/kit/src/react/fold.tsx index 454d8319f..adbd0abe1 100644 --- a/packages/renderers/kit/src/react/fold.tsx +++ b/packages/renderers/kit/src/react/fold.tsx @@ -80,7 +80,7 @@ export function Fold({ 0 ? {[entityAliasesAttribute]: JSON.stringify(aliases)} : {})} - {...(opens && !synthetic ? {'data-fold': action?.expanded === true ? 'open' : 'closed'} : {})} + {...(opens && !synthetic ? {'data-fold': action?.expanded === true ? 'open' : 'closed', 'data-projections-action': ''} : {})} transform={`translate(${node.x} ${node.y}) scale(${0.9 + node.opacity * 0.1})`} {...mark(node, emphasis)} opacity={node.opacity} diff --git a/packages/renderers/kit/src/react/grid-folds.tsx b/packages/renderers/kit/src/react/grid-folds.tsx index bf691fb50..9dcff3052 100644 --- a/packages/renderers/kit/src/react/grid-folds.tsx +++ b/packages/renderers/kit/src/react/grid-folds.tsx @@ -225,6 +225,7 @@ export function GridFoldCard({ {...(fold.open ? {} : {[entityAliasesAttribute]: JSON.stringify(fold.members)})} data-projections-unit="" data-fold={fold.open ? 'open' : 'closed'} + data-projections-action="" data-status={mark === undefined && emphasis > 0 ? fold.status : undefined} {...(mark !== undefined ? changeMark(mark) : {})} style={style} diff --git a/packages/renderers/testing/README.md b/packages/renderers/testing/README.md index 00f17a504..2111291a8 100644 --- a/packages/renderers/testing/README.md +++ b/packages/renderers/testing/README.md @@ -84,7 +84,8 @@ Build the bundle before the tests. The checks: - `phone-overflow`: At 390 px the document never scrolls sideways (at progress 0, 0.5 and 1). - `selection`: Clicking an entity reports it; the host's selection is shown and - can be cleared. + can be cleared. An entity element that is its own action + (`data-projections-action`, such as a fold) is passed by. - `stable-layout`: Change status appears in reserved space: at 0, 0.25, 0.5, 0.75 and 1 (animated; the endpoints for two-pane modes) and in the diff, every entity has the same box with highlighting on and off. diff --git a/packages/renderers/testing/src/checks/catalog.ts b/packages/renderers/testing/src/checks/catalog.ts index c3f486229..ddf1aa4af 100644 --- a/packages/renderers/testing/src/checks/catalog.ts +++ b/packages/renderers/testing/src/checks/catalog.ts @@ -122,7 +122,7 @@ export const checkDescriptions: Record = { "When the renderer sends a summary for the host's summary bar, each count figure's count (and, in a comparison, its added, removed and modified counts) is the documents' own for its kind: the extraction's items, or the after revision's and the comparison's changes. A fact figure's count is the renderer's, but every item ID it filters to exists, one extraction's facts have no changes, and what a fact counts as added or modified is part of its count. The summary describes the whole document, so it is the same at every progress.", 'phone-overflow': 'At phone width the renderer document never scrolls sideways.', selection: - "Clicking an entity reports it to the host; clicking it again, or the renderer's background, clears the selection; and the host's selection (and clearing it) is shown.", + "Clicking an entity reports it to the host; clicking it again, or the renderer's background, clears the selection; and the host's selection (and clearing it) is shown. An entity element that is its own action (data-projections-action, such as a fold) is passed by.", 'read-only': "In a view where nothing can be selected (`RendererEnvironment.selectable: false`, a read-only embed or a picture), hovering or tapping an item changes nothing it paints (no ring, tint or underline, apart from controls in it that still act, such as a fold), and no control that selects an item stays in the tab order: nothing with `aria-pressed`, marked `data-projections-select`, or an item's own button. The kit's `useSelectControl` takes a control out of the tab order there and marks it unavailable; a control that is its own action, such as a toggle, carries `data-projections-action`. Checked in the default mode and the diff.", 'stable-layout': diff --git a/packages/renderers/testing/src/checks/interaction.ts b/packages/renderers/testing/src/checks/interaction.ts index 678cd40f7..bb5126b74 100644 --- a/packages/renderers/testing/src/checks/interaction.ts +++ b/packages/renderers/testing/src/checks/interaction.ts @@ -84,7 +84,8 @@ export const interactionChecks: Pick('entities')).toReversed() + // An item that is its own action (a fold that opens) reports no selection. + const ids = (await driver.measure('selectable')).toReversed() if (!ids.length) throw new Skip('The renderer draws no entities (elements with data-entity-id).') const id = ids[0]! const reports = async () => (await driver.state()).selections diff --git a/packages/renderers/testing/src/measure/entities.ts b/packages/renderers/testing/src/measure/entities.ts index fe254eb32..8e17df541 100644 --- a/packages/renderers/testing/src/measure/entities.ts +++ b/packages/renderers/testing/src/measure/entities.ts @@ -36,9 +36,14 @@ function aliasesOf(element: Element): string[] { } } -/** IDs of visible entities: nested ones (parts) first, then units. */ -export function visibleEntities(root: Element = document.body): string[] { - const all = [...root.querySelectorAll('[data-entity-id]')].filter(visible) +/** + * IDs of visible entities: nested ones (parts) first, then units. `selectable` leaves out those that are their own + * action (`data-projections-action`), such as a fold that presents the items it folds and opens them when activated. + */ +export function visibleEntities(root: Element = document.body, selectable = false): string[] { + const all = [...root.querySelectorAll('[data-entity-id]')].filter( + element => visible(element) && !(selectable && element.closest('[data-projections-action]')), + ) const nested = all.filter(element => element.parentElement?.closest('[data-entity-id]')) return [...new Set([...nested, ...all].map(element => element.getAttribute('data-entity-id')!))] } diff --git a/packages/renderers/testing/src/probe.ts b/packages/renderers/testing/src/probe.ts index 55b33b235..8c5c7c994 100644 --- a/packages/renderers/testing/src/probe.ts +++ b/packages/renderers/testing/src/probe.ts @@ -45,6 +45,7 @@ import type {ProbeCall} from './types.js' const calls: Record unknown> = { samples: () => entitySamples(), entities: () => visibleEntities(), + selectable: () => visibleEntities(document.body, true), affordances: () => affordanceFailures(document.body), overflow: () => horizontalOverflow(), legends: () => legends(), diff --git a/packages/renderers/testing/src/types.ts b/packages/renderers/testing/src/types.ts index d982d4d93..a4fa2d0e4 100644 --- a/packages/renderers/testing/src/types.ts +++ b/packages/renderers/testing/src/types.ts @@ -128,6 +128,7 @@ export interface StageState { export type ProbeCall = | 'samples' | 'entities' + | 'selectable' | 'affordances' | 'overflow' | 'legends' From e2484e799ed3f7ebc3a05dcdd72c907e20078171 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:28:52 +0000 Subject: [PATCH 4/9] Starter: a catalog scenario whose unchanged services fold into a band Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- packages/cli/browser/starter.spec.ts | 6 ++--- .../cli/templates/renderer/scenarios.json | 24 +++++++++---------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/packages/cli/browser/starter.spec.ts b/packages/cli/browser/starter.spec.ts index b32a402cd..f9ddfea38 100644 --- a/packages/cli/browser/starter.spec.ts +++ b/packages/cli/browser/starter.spec.ts @@ -54,7 +54,7 @@ test('the starter renderer folds a run of unchanged cards into a band in All, wh await expect(band).toHaveCount(1) await expect(band).toHaveText(/14 unchanged services/u) await expect(stage.frame.locator('[data-entity-id="service:search"]')).toHaveCount(0) - await expect(stage.frame.locator('[data-entity-id="service:payments"]')).toBeVisible() + await expect(stage.frame.locator('[data-entity-id="service:wallet"]')).toBeVisible() // The host's selection of a folded service finds the band. await stage.select('service:search') await expect(band).toHaveAttribute('data-projections-ring-selected', /.*/u) @@ -63,7 +63,7 @@ test('the starter renderer folds a run of unchanged cards into a band in All, wh await expect(stage.frame.locator('[data-entity-id="service:search"]')).toBeVisible() await expect(band).toHaveText(/Hide 14 unchanged services/u) // The Changes scope shows only the changes and their context: nothing to fold. - await stage.filter({query: '', changesOnly: true, ids: null, scope: ['service:checkout', 'service:payments', 'calls:checkout->payments']}) + await stage.filter({query: '', changesOnly: true, ids: null, scope: ['service:accounts', 'service:wallet', 'calls:accounts->wallet']}) await expect(stage.frame.locator('.pk-grid-band')).toHaveCount(0) - await expect(stage.frame.locator('[data-entity-id="service:payments"]')).toBeVisible() + await expect(stage.frame.locator('[data-entity-id="service:wallet"]')).toBeVisible() }) diff --git a/packages/cli/templates/renderer/scenarios.json b/packages/cli/templates/renderer/scenarios.json index 3f2e2b3e0..b81131ed3 100644 --- a/packages/cli/templates/renderer/scenarios.json +++ b/packages/cli/templates/renderer/scenarios.json @@ -39,14 +39,13 @@ }, { "id": "catalog", - "title": "Payments joins fourteen unchanged services", + "title": "Wallet joins fourteen unchanged services", "description": "In All, the run of fourteen unchanged services folds into one band across the grid, which opens in place; the Changes scope shows only the changes and their context.", "before": { "protocolVersion": 0, "schema": "graph/v0", "entities": [ - {"id": "service:checkout", "kind": "service", "label": "Checkout", "data": {"owner": "web"}}, - {"id": "service:accounts", "kind": "service", "label": "Accounts"}, + {"id": "service:accounts", "kind": "service", "label": "Accounts", "data": {"owner": "web"}}, {"id": "service:analytics", "kind": "service", "label": "Analytics"}, {"id": "service:audit", "kind": "service", "label": "Audit"}, {"id": "service:catalog", "kind": "service", "label": "Catalog"}, @@ -59,19 +58,19 @@ {"id": "service:profiles", "kind": "service", "label": "Profiles"}, {"id": "service:reviews", "kind": "service", "label": "Reviews"}, {"id": "service:search", "kind": "service", "label": "Search"}, - {"id": "service:shipping", "kind": "service", "label": "Shipping"} + {"id": "service:shipping", "kind": "service", "label": "Shipping"}, + {"id": "service:tax", "kind": "service", "label": "Tax"} ], "relationships": [ - {"id": "calls:checkout->pricing", "kind": "calls", "from": "service:checkout", "to": "service:pricing"}, - {"id": "calls:checkout->inventory", "kind": "calls", "from": "service:checkout", "to": "service:inventory"} + {"id": "calls:accounts->profiles", "kind": "calls", "from": "service:accounts", "to": "service:profiles"}, + {"id": "calls:accounts->ledger", "kind": "calls", "from": "service:accounts", "to": "service:ledger"} ] }, "after": { "protocolVersion": 0, "schema": "graph/v0", "entities": [ - {"id": "service:checkout", "kind": "service", "label": "Checkout", "data": {"owner": "payments"}}, - {"id": "service:accounts", "kind": "service", "label": "Accounts"}, + {"id": "service:accounts", "kind": "service", "label": "Accounts", "data": {"owner": "identity"}}, {"id": "service:analytics", "kind": "service", "label": "Analytics"}, {"id": "service:audit", "kind": "service", "label": "Audit"}, {"id": "service:catalog", "kind": "service", "label": "Catalog"}, @@ -85,12 +84,13 @@ {"id": "service:reviews", "kind": "service", "label": "Reviews"}, {"id": "service:search", "kind": "service", "label": "Search"}, {"id": "service:shipping", "kind": "service", "label": "Shipping"}, - {"id": "service:payments", "kind": "service", "label": "Payments"} + {"id": "service:tax", "kind": "service", "label": "Tax"}, + {"id": "service:wallet", "kind": "service", "label": "Wallet"} ], "relationships": [ - {"id": "calls:checkout->pricing", "kind": "calls", "from": "service:checkout", "to": "service:pricing"}, - {"id": "calls:checkout->inventory", "kind": "calls", "from": "service:checkout", "to": "service:inventory"}, - {"id": "calls:checkout->payments", "kind": "calls", "from": "service:checkout", "to": "service:payments"} + {"id": "calls:accounts->profiles", "kind": "calls", "from": "service:accounts", "to": "service:profiles"}, + {"id": "calls:accounts->ledger", "kind": "calls", "from": "service:accounts", "to": "service:ledger"}, + {"id": "calls:accounts->wallet", "kind": "calls", "from": "service:accounts", "to": "service:wallet"} ] } }, From 723a57786a5a344aa7adba6f33ae94f5ef9dbc7e Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:37:43 +0000 Subject: [PATCH 5/9] Kit: split mass folds into a module directory; keep guides within limits Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- docs/guides/renderer-kit-components.md | 14 +- docs/guides/renderer-kit-graphs.md | 8 +- .../renderers/kit/browser/invariants/frame.ts | 15 +- packages/renderers/kit/src/mass-fold.ts | 240 ++---------------- .../renderers/kit/src/mass-fold/groups.ts | 108 ++++++++ packages/renderers/kit/src/mass-fold/links.ts | 60 +++++ packages/renderers/kit/src/mass-fold/model.ts | 75 ++++++ 7 files changed, 280 insertions(+), 240 deletions(-) create mode 100644 packages/renderers/kit/src/mass-fold/groups.ts create mode 100644 packages/renderers/kit/src/mass-fold/links.ts create mode 100644 packages/renderers/kit/src/mass-fold/model.ts diff --git a/docs/guides/renderer-kit-components.md b/docs/guides/renderer-kit-components.md index b1ea36ee7..d7ccfb9a2 100644 --- a/docs/guides/renderer-kit-components.md +++ b/docs/guides/renderer-kit-components.md @@ -315,19 +315,7 @@ accept token scale steps rather than raw lengths or colors—this is how inset, so it lines up with the title. Tables stay unpadded, so their rows run edge to edge. - `CardGrid` lays cards out in as many columns as fit, collapsing to one column - on phones. In a comparison, a dozen or more of its `EntityCard`s - (`massFoldMinimum`) removed together, of one kind, fold into one card in the - removed style that counts them with the definition's noun ("14 jobs removed"); - additions fold the same way. The card takes the place of the first, opens them - in place ("Hide 14 removed jobs") and, while closed, lists them in - `data-entity-aliases`, so the host's selection, hover and filter of one find - it. A run of a dozen or more unchanged cards with nothing between them folds - the same way into a `Fold` band across the grid ("14 unchanged services"), - except under the Changes scope, which shows its unchanged cards as context. A - single revision folds nothing. A card reports its status and kind from its - `change` row, and keeps its place in the grid, hidden, while a fold takes it. - `Fold` takes an `id` and the IDs it `presents` for a fold that stands for - items the host can select. + on phones, folding [mass changes](renderer-kit-graphs.md). - `EntityCard` renders a single entity as a ring unit with `data-entity-id`, a select button, `label`, `identifier`, `children`, and worded change status. In progress modes, its leading edge picks up the change hue as `emphasis` rises diff --git a/docs/guides/renderer-kit-graphs.md b/docs/guides/renderer-kit-graphs.md index b8697d628..115971ab1 100644 --- a/docs/guides/renderer-kit-graphs.md +++ b/docs/guides/renderer-kit-graphs.md @@ -110,7 +110,13 @@ selection, hover, filter and annotations of a folded item find it; the canvas moves a selection, focus request (`--entity`) or `focus` of a folded item onto the card. Activating the card, or one of its links, opens its cards in place; the card stays, labeled "Hide 48 removed tables", as the way to fold them again, -until the document changes. +until the document changes. `CardGrid` folds its `EntityCard`s the same way, and +folds a run of a dozen or more unchanged cards with nothing between them into a +`Fold` band across the grid ("14 unchanged services"), except under the Changes +scope, which shows its unchanged cards as context. A grid reads each card's +status and kind from its `change` row, and a card a fold takes keeps its place, +hidden. A single revision folds nothing. `Fold` takes an `id` and the IDs it +`presents` for a fold the host can find its items on. **Sibling blocks.** When six or more cards (`blockMinimum`) share every relationship, they wrap into a block instead of stretching their layer into one diff --git a/packages/renderers/kit/browser/invariants/frame.ts b/packages/renderers/kit/browser/invariants/frame.ts index a7ef01692..1975d3ae2 100644 --- a/packages/renderers/kit/browser/invariants/frame.ts +++ b/packages/renderers/kit/browser/invariants/frame.ts @@ -36,22 +36,17 @@ export function measureFrame(root: Element): FrameMeasurement { } // A view opened above its fit scrolls; positions are taken from the diagram's corner so scrolling never moves them. const origin = svg?.getBoundingClientRect() ?? {left: 0, top: 0} - // An element's `data-entity-aliases`: the other items it presents (defined here, as the page runs this alone). - const aliasesOf = (element: Element): string[] => { - try { - const parsed: unknown = JSON.parse(element.getAttribute('data-entity-aliases') ?? '[]') - return Array.isArray(parsed) ? parsed.filter((alias): alias is string => typeof alias === 'string') : [] - } catch { - return [] - } - } const cards = [...root.querySelectorAll('.graph-node:not(.graph-group), .hierarchy-row, .fp-node')] .map(node => { const surface = node.querySelector('.node-surface, .fp-surface') ?? node const rect = surface.getBoundingClientRect() return { id: node.dataset.entityId ?? '', - presents: aliasesOf(node), + // The other items it presents: the IDs in `data-entity-aliases`, a JSON array of strings without quotes ("null" + // when absent, which holds none). + presents: String(node.getAttribute('data-entity-aliases')) + .split(/"(?:,")?/u) + .slice(1, -1), opacity: opacityOf(node), box: {left: rect.left - origin.left, top: rect.top - origin.top, right: rect.right - origin.left, bottom: rect.bottom - origin.top}, } diff --git a/packages/renderers/kit/src/mass-fold.ts b/packages/renderers/kit/src/mass-fold.ts index d3b47212e..2b509ce78 100644 --- a/packages/renderers/kit/src/mass-fold.ts +++ b/packages/renderers/kit/src/mass-fold.ts @@ -1,80 +1,14 @@ // Mass changes: a dozen or more sibling items removed (or added) together, folded into one card that counts them // ("48 tables removed") and opens in place, so a comparison that drops a whole schema stays one readable frame. -import {humanizeKind, isContainment} from '@githubnext/projections-renderer-sdk/presentation' -import type {SummaryNoun} from '@githubnext/projections-renderer-sdk/protocol' import type {Extraction} from '@githubnext/projections-schemas' import type {ComparisonModel, ModelStep} from './model.js' -import {sides, type Side} from './scope-parts.js' +import type {Side} from './scope-parts.js' +import {containmentOf, foldGroups, siblingGroups} from './mass-fold/groups.js' +import {foldRelationships} from './mass-fold/links.js' +import type {MassFolded, MassFoldOptions} from './mass-fold/model.js' -/** - * The fewest sibling items removed (or added) together that fold into one card: twice a sibling block's - * `blockMinimum`, two full lines of its tray, past which more cards add height without saying more than their count. - * It is also where a stack of removed database tables alone outgrows a frame: on one schema, 48 removed tables drew a - * frame 81,546 px tall, about 1,700 px a table, so a dozen pass the 20,000 px most hosts render. - */ -export const massFoldMinimum = 12 - -/** The ID prefix of the cards and links `foldMassChanges` adds. */ -export const massFoldPrefix = 'pk-mass:' - -/** Whether an item is a card or link `foldMassChanges` adds. */ -export const isMassFold = (id: string) => id.startsWith(massFoldPrefix) - -/** The statuses that fold: items that only one revision has. */ -export type MassStatus = 'removed' | 'added' - -/** One fold of sibling items removed or added together. */ -export interface MassFold { - /** The fold card's row ID (`massFoldPrefix`). */ - id: string - status: MassStatus - /** The folded items' kind, which the card takes. */ - kind: string - /** The sibling entity rows it folds, in the model's order. */ - items: readonly string[] - /** - * Every row the card presents while closed: the siblings, the parts they contain and the relationships among them - * or to them, for the card's `data-entity-aliases`. - */ - presents: readonly string[] - /** Whether it is open: its items drawn on their own, and the card the way to fold them again. */ - open: boolean - /** The card's label: `48 tables removed`, or open, `Hide 48 removed tables`. */ - label: string -} - -/** A model with its mass changes folded (`foldMassChanges`), and what each fold stands for. */ -export interface MassFolded { - model: ComparisonModel - /** Each fold, by its card's ID; empty when nothing folds (and `model` is the one passed). */ - folds: ReadonlyMap - /** Each row a closed fold hides (entity or relationship), and the card or link drawn for it. */ - folded: ReadonlyMap - /** Each card and link a fold adds, and the rows it stands for: their step and emphasis are its. */ - stands: ReadonlyMap -} - -/** How `foldMassChanges` folds. */ -export interface MassFoldOptions { - /** Folds the person opened, by card ID: their items are drawn, and the card stays as the way to fold them again. */ - open?: ReadonlySet - /** The fewest siblings that fold (`massFoldMinimum` by default). */ - minimum?: number - /** A kind's words (the definition's noun); `humanizeKind` by default. */ - noun?: (kind: string) => SummaryNoun | undefined - /** BCP 47 locale for the count (`en-US` by default). */ - locale?: string -} - -/** The side that has an item of this status. */ -const sideOf = (status: MassStatus): Side => (status === 'removed' ? 'before' : 'after') - -/** A fold's card label: `48 tables removed`; open, `Hide 48 removed tables`. */ -export function massFoldLabel(count: number, status: MassStatus, noun: SummaryNoun, open = false, locale = 'en-US'): string { - const words = count === 1 ? noun.singular : noun.plural - const number = count.toLocaleString(locale) - return open ? `Hide ${number} ${status} ${words}` : `${number} ${words} ${status}` -} +export {isMassFold, massFoldLabel, massFoldMinimum, massFoldPrefix} from './mass-fold/model.js' +export type {MassFold, MassFolded, MassFoldOptions, MassStatus} from './mass-fold/model.js' /** * Folds every run of `minimum` or more sibling items removed together, or added together, into one card: items of @@ -89,160 +23,34 @@ export function massFoldLabel(count: number, status: MassStatus, noun: SummaryNo export function foldMassChanges(model: ComparisonModel, options: MassFoldOptions = {}): MassFolded { const none: MassFolded = {model, folds: new Map(), folded: new Map(), stands: new Map()} if (model.mode !== 'comparison') return none - const minimum = Math.max(2, options.minimum ?? massFoldMinimum) - const open = options.open ?? new Set() - const rows = new Map(model.entities.map(row => [row.id, row])) - // Each side's containment: what holds each entity row, and what each holds. - const parentOf = {before: new Map(), after: new Map()} - const childrenOf = {before: new Map(), after: new Map()} - for (const side of sides) { - const contains = isContainment(model[side]) - const rowOf = model.entityRow[side] - for (const relationship of model[side].relationships) { - if (!contains(relationship)) continue - const parent = rowOf.get(relationship.from) - const child = rowOf.get(relationship.to) - if (parent === undefined || child === undefined || parent === child || parentOf[side].has(child)) continue - parentOf[side].set(child, parent) - childrenOf[side].set(parent, [...(childrenOf[side].get(parent) ?? []), child]) - } - } - // Siblings that only one revision has, by status, container and kind. - const groups = new Map() - for (const row of model.entities) { - if (row.status !== 'removed' && row.status !== 'added') continue - const status = row.status - const side = sideOf(status) - const entity = row[side] - if (!entity) continue - const parent = parentOf[side].get(row.id) - // A part of an item leaving (or arriving) with it goes with it. - if (parent !== undefined && rows.get(parent)?.status === status) continue - const key = `${status}\n${parent ?? ''}\n${entity.kind}` - const group = groups.get(key) ?? {status, parent, kind: entity.kind, items: []} - group.items.push(row.id) - groups.set(key, group) - } - const folds = new Map & {presents: string[]}>() - const hidden = new Map() - const addedRows: ComparisonModel['entities'] = [] - const addedLinks: ComparisonModel['relationships'] = [] - const stands = new Map() - // Each fold's container and the link that puts the card in it, which stands for the container holding each item. - const holders = new Map() - for (const {status, parent, kind, items} of groups.values()) { - if (items.length < minimum) continue - const side = sideOf(status) - const id = `${massFoldPrefix}${status}:${kind}:${parent ?? ''}` - const opened = open.has(id) - // The items and every part they hold that leaves (or arrives) with them. - const members: string[] = [] - const stack = items.toReversed() - for (let item = stack.pop(); item !== undefined; item = stack.pop()) { - members.push(item) - for (const child of (childrenOf[side].get(item) ?? []).toReversed()) if (rows.get(child)?.status === status) stack.push(child) - } - if (!opened) for (const member of members) hidden.set(member, id) - const noun = options.noun?.(kind) ?? humanizeKind(kind) - const label = massFoldLabel(items.length, status, noun, opened, options.locale) - folds.set(id, {id, status, kind, items, presents: members, open: opened, label}) - stands.set(id, items) - const entity: X['entities'][number] = {id, kind, label, data: {count: items.length, ...(opened ? {open: true} : {})}} - addedRows.push({id, [side]: entity, status, correspondence: 'exact'}) - const holder = parent === undefined ? undefined : rows.get(parent)?.[side] - if (parent !== undefined && holder) { - const link = `${id}:contains` - const contains: X['relationships'][number] = {id: link, kind: 'contains', from: holder.id, to: id} - addedLinks.push({id: link, [side]: contains, status, correspondence: 'exact'}) - stands.set(link, items) - holders.set(id, {parent, link}) - } - } - if (!folds.size) return none - // Relationships to a hidden item: among one fold's items, the card presents them; to an item that stays, one link - // from the card for each other end, kind and direction stands for them all. - const kept: ComparisonModel['relationships'] = [] - const merged = new Map< - string, - {sides: Set; rows: string[]; ends: Partial>} - >() - const containment = {before: isContainment(model.before), after: isContainment(model.after)} - const hiddenEntities = new Map(hidden) - const present = (fold: string, row: string) => { - const presents = folds.get(fold)?.presents - if (presents && !presents.includes(row)) presents.push(row) - } - for (const row of model.relationships) { - const touched = sides.flatMap(side => { - const item = row[side] - return item && [item.from, item.to].some(end => hiddenEntities.has(model.entityRow[side].get(end) ?? '')) ? [{side, item}] : [] - }) - if (!touched.length) { - kept.push(row) - continue - } - for (const {side, item} of touched) { - const fromRow = model.entityRow[side].get(item.from) ?? '' - const toRow = model.entityRow[side].get(item.to) ?? '' - const from = hiddenEntities.get(fromRow) - const to = hiddenEntities.get(toRow) - if (from !== undefined && from === to) { - hidden.set(row.id, from) - present(from, row.id) - continue - } - const holder = to === undefined ? undefined : holders.get(to) - if (to !== undefined && holder && from === undefined && fromRow === holder.parent && containment[side](item)) { - hidden.set(row.id, holder.link) - present(to, row.id) - continue - } - const fromEnd = from ?? item.from - const toEnd = to ?? item.to - const id = `${massFoldPrefix}link:${item.kind}:${fromEnd}->${toEnd}` - const link = merged.get(id) ?? {sides: new Set(), rows: [], ends: {}} - link.sides.add(side) - if (!link.rows.includes(row.id)) link.rows.push(row.id) - link.ends[side] = {kind: item.kind, from: fromEnd, to: toEnd} - merged.set(id, link) - hidden.set(row.id, id) - present(from ?? to ?? '', row.id) - } - } - for (const [id, link] of merged) { - const both = link.sides.size === 2 - const status = both ? 'modified' : link.sides.has('before') ? 'removed' : 'added' - const ends = Object.fromEntries(Object.entries(link.ends).map(([side, end]) => [side, {id, ...end}])) - addedLinks.push({id, ...ends, status, correspondence: 'exact'}) - stands.set(id, link.rows) - } - const entities = [...model.entities.filter(row => !hidden.has(row.id)), ...addedRows] - const relationships = [...kept, ...addedLinks] + const tree = containmentOf(model) + const folding = foldGroups(model, tree, siblingGroups(model, tree), options) + if (!folding.folds.size) return none + const kept = foldRelationships(model, folding) + const entities = [...model.entities.filter(row => !folding.hidden.has(row.id)), ...folding.rows] + const relationships = [...kept, ...folding.links] const extraction = (side: Side): X => { const items = (list: readonly Partial>[]) => list.flatMap(row => (row[side] ? [row[side]] : [])) return {...model[side], entities: items(entities), relationships: items(relationships)} } const entityRow = (side: Side) => new Map([ - ...[...model.entityRow[side]].filter(([, row]) => !hidden.has(row)), - ...addedRows.filter(row => row[side]).map(row => [row.id, row.id] as const), + ...[...model.entityRow[side]].filter(([, row]) => !folding.hidden.has(row)), + ...folding.rows.filter(row => row[side]).map(row => [row.id, row.id] as const), ]) - const result = { - ...model, - before: extraction('before'), - after: extraction('after'), - entities, - relationships, - entityRow: {before: entityRow('before'), after: entityRow('after')}, - } - const folding = {folds, folded: hidden, stands} + const folded = {folds: folding.folds, folded: folding.hidden, stands: folding.stands} return { model: { - ...result, - steps: foldMassSteps(model.steps, folding), - ...(model.reverseSteps ? {reverseSteps: foldMassSteps(model.reverseSteps, folding)} : {}), + ...model, + before: extraction('before'), + after: extraction('after'), + entities, + relationships, + entityRow: {before: entityRow('before'), after: entityRow('after')}, + steps: foldMassSteps(model.steps, folded), + ...(model.reverseSteps ? {reverseSteps: foldMassSteps(model.reverseSteps, folded)} : {}), }, - ...folding, + ...folded, } } diff --git a/packages/renderers/kit/src/mass-fold/groups.ts b/packages/renderers/kit/src/mass-fold/groups.ts new file mode 100644 index 000000000..57257aa0e --- /dev/null +++ b/packages/renderers/kit/src/mass-fold/groups.ts @@ -0,0 +1,108 @@ +// Folding mass changes: the siblings that fold, and the cards that stand for them. +import {humanizeKind, isContainment} from '@githubnext/projections-renderer-sdk/presentation' +import type {Extraction} from '@githubnext/projections-schemas' +import type {ComparisonModel} from '../model.js' +import {sides, type Side} from '../scope-parts.js' +import {massFoldLabel, massFoldMinimum, massFoldPrefix, sideOf, type MassFold, type MassFoldOptions, type MassStatus} from './model.js' + +/** Each side's containment: what holds each entity row, and what each holds. */ +export interface Containment { + parentOf: Record> + childrenOf: Record> +} + +export function containmentOf(model: ComparisonModel): Containment { + const tree: Containment = {parentOf: {before: new Map(), after: new Map()}, childrenOf: {before: new Map(), after: new Map()}} + for (const side of sides) { + const contains = isContainment(model[side]) + const rowOf = model.entityRow[side] + for (const relationship of model[side].relationships) { + if (!contains(relationship)) continue + const parent = rowOf.get(relationship.from) + const child = rowOf.get(relationship.to) + if (parent === undefined || child === undefined || parent === child || tree.parentOf[side].has(child)) continue + tree.parentOf[side].set(child, parent) + tree.childrenOf[side].set(parent, [...(tree.childrenOf[side].get(parent) ?? []), child]) + } + } + return tree +} + +/** Siblings that only one revision has. */ +export interface SiblingGroup { + status: MassStatus + parent: string | undefined + kind: string + items: string[] +} + +/** Entity rows only one revision has, by status, container and kind; a part leaving (or arriving) with its container goes with it. */ +export function siblingGroups(model: ComparisonModel, tree: Containment): SiblingGroup[] { + const statusOf = new Map(model.entities.map(row => [row.id, row.status])) + const groups = new Map() + for (const row of model.entities) { + if (row.status !== 'removed' && row.status !== 'added') continue + const status = row.status + const side = sideOf(status) + const entity = row[side] + const parent = tree.parentOf[side].get(row.id) + if (!entity || (parent !== undefined && statusOf.get(parent) === status)) continue + const key = `${status}\n${parent ?? ''}\n${entity.kind}` + const group = groups.get(key) ?? {status, parent, kind: entity.kind, items: []} + group.items.push(row.id) + groups.set(key, group) + } + return [...groups.values()] +} + +/** What folding adds and hides, as it is built. */ +export interface Folding { + folds: Map & {presents: string[]}> + /** Each hidden row and the card or link drawn for it. */ + hidden: Map + rows: ComparisonModel['entities'] + links: ComparisonModel['relationships'] + stands: Map + /** Each fold's container and the link that puts the card in it. */ + holders: Map +} + +/** The cards for every group of `minimum` or more, and the link from each card's container. */ +export function foldGroups( + model: ComparisonModel, + tree: Containment, + groups: readonly SiblingGroup[], + options: MassFoldOptions, +): Folding { + const minimum = Math.max(2, options.minimum ?? massFoldMinimum) + const open = options.open ?? new Set() + const rows = new Map(model.entities.map(row => [row.id, row])) + const folding: Folding = {folds: new Map(), hidden: new Map(), rows: [], links: [], stands: new Map(), holders: new Map()} + for (const {status, parent, kind, items} of groups) { + if (items.length < minimum) continue + const side = sideOf(status) + const id = `${massFoldPrefix}${status}:${kind}:${parent ?? ''}` + const opened = open.has(id) + // The items and every part they hold that leaves (or arrives) with them. + const members: string[] = [] + const stack = items.toReversed() + for (let item = stack.pop(); item !== undefined; item = stack.pop()) { + members.push(item) + stack.push(...(tree.childrenOf[side].get(item) ?? []).filter(child => rows.get(child)?.status === status).toReversed()) + } + if (!opened) for (const member of members) folding.hidden.set(member, id) + const label = massFoldLabel(items.length, status, options.noun?.(kind) ?? humanizeKind(kind), opened, options.locale) + folding.folds.set(id, {id, status, kind, items, presents: members, open: opened, label}) + folding.stands.set(id, items) + const entity: X['entities'][number] = {id, kind, label, data: {count: items.length, ...(opened ? {open: true} : {})}} + folding.rows.push({id, [side]: entity, status, correspondence: 'exact'}) + const holder = parent === undefined ? undefined : rows.get(parent)?.[side] + if (parent === undefined || !holder) continue + const link = `${id}:contains` + const contains: X['relationships'][number] = {id: link, kind: 'contains', from: holder.id, to: id} + folding.links.push({id: link, [side]: contains, status, correspondence: 'exact'}) + folding.stands.set(link, items) + folding.holders.set(id, {parent, link}) + } + return folding +} diff --git a/packages/renderers/kit/src/mass-fold/links.ts b/packages/renderers/kit/src/mass-fold/links.ts new file mode 100644 index 000000000..cfcb3e5f7 --- /dev/null +++ b/packages/renderers/kit/src/mass-fold/links.ts @@ -0,0 +1,60 @@ +// Folding mass changes: the relationships to what folds. +import {isContainment} from '@githubnext/projections-renderer-sdk/presentation' +import type {Extraction} from '@githubnext/projections-schemas' +import type {ComparisonModel} from '../model.js' +import {sides, type Side} from '../scope-parts.js' +import {massFoldPrefix} from './model.js' +import type {Folding} from './groups.js' + +/** + * The relationships that stay, with the folds' links added to `folding`: a relationship among one fold's items is the + * card's, its container holding an item is the card's own containment, and one to an item that stays is drawn once + * from the card for each other end, kind and direction. + */ +export function foldRelationships( + model: ComparisonModel, + folding: Folding, +): ComparisonModel['relationships'] { + const kept: ComparisonModel['relationships'] = [] + const merged = new Map>}>() + const containment = {before: isContainment(model.before), after: isContainment(model.after)} + const hiddenEntities = new Map(folding.hidden) + const present = (fold: string, row: string) => { + const presents = folding.folds.get(fold)?.presents + if (presents && !presents.includes(row)) presents.push(row) + } + for (const row of model.relationships) { + const touched = sides.flatMap(side => { + const item = row[side] + return item && [item.from, item.to].some(end => hiddenEntities.has(model.entityRow[side].get(end) ?? '')) ? [{side, item}] : [] + }) + if (!touched.length) kept.push(row) + for (const {side, item} of touched) { + const fromRow = model.entityRow[side].get(item.from) ?? '' + const from = hiddenEntities.get(fromRow) + const to = hiddenEntities.get(model.entityRow[side].get(item.to) ?? '') + const holder = to === undefined ? undefined : folding.holders.get(to) + const own = + from !== undefined && from === to + ? from + : holder && from === undefined && fromRow === holder.parent && containment[side](item) + ? holder.link + : undefined + const id = own ?? `${massFoldPrefix}link:${item.kind}:${from ?? item.from}->${to ?? item.to}` + folding.hidden.set(row.id, id) + present(from ?? to ?? '', row.id) + if (own !== undefined) continue + const link = merged.get(id) ?? {rows: [], ends: {}} + if (!link.rows.includes(row.id)) link.rows.push(row.id) + link.ends[side] = {kind: item.kind, from: from ?? item.from, to: to ?? item.to} + merged.set(id, link) + } + } + for (const [id, {rows, ends}] of merged) { + const status = ends.before && ends.after ? 'modified' : ends.before ? 'removed' : 'added' + const items = Object.fromEntries(Object.entries(ends).map(([side, end]) => [side, {id, ...end}])) + folding.links.push({id, ...items, status, correspondence: 'exact'}) + folding.stands.set(id, rows) + } + return kept +} diff --git a/packages/renderers/kit/src/mass-fold/model.ts b/packages/renderers/kit/src/mass-fold/model.ts new file mode 100644 index 000000000..07c822594 --- /dev/null +++ b/packages/renderers/kit/src/mass-fold/model.ts @@ -0,0 +1,75 @@ +// Mass changes (see `foldMassChanges`): what a fold is, how its card is labeled, and what shapes it. +import type {SummaryNoun} from '@githubnext/projections-renderer-sdk/protocol' +import type {Extraction} from '@githubnext/projections-schemas' +import type {ComparisonModel} from '../model.js' +import type {Side} from '../scope-parts.js' + +/** + * The fewest sibling items removed (or added) together that fold into one card: twice a sibling block's + * `blockMinimum`, two full lines of its tray, past which more cards add height without saying more than their count. + * It is also where a stack of removed database tables alone outgrows a frame: on one schema, 48 removed tables drew a + * frame 81,546 px tall, about 1,700 px a table, so a dozen pass the 20,000 px most hosts render. + */ +export const massFoldMinimum = 12 + +/** The ID prefix of the cards and links `foldMassChanges` adds. */ +export const massFoldPrefix = 'pk-mass:' + +/** Whether an item is a card or link `foldMassChanges` adds. */ +export const isMassFold = (id: string) => id.startsWith(massFoldPrefix) + +/** The statuses that fold: items that only one revision has. */ +export type MassStatus = 'removed' | 'added' + +/** One fold of sibling items removed or added together. */ +export interface MassFold { + /** The fold card's row ID (`massFoldPrefix`). */ + id: string + status: MassStatus + /** The folded items' kind, which the card takes. */ + kind: string + /** The sibling entity rows it folds, in the model's order. */ + items: readonly string[] + /** + * Every row the card presents while closed: the siblings, the parts they contain and the relationships among them + * or to them, for the card's `data-entity-aliases`. + */ + presents: readonly string[] + /** Whether it is open: its items drawn on their own, and the card the way to fold them again. */ + open: boolean + /** The card's label: `48 tables removed`, or open, `Hide 48 removed tables`. */ + label: string +} + +/** A model with its mass changes folded (`foldMassChanges`), and what each fold stands for. */ +export interface MassFolded { + model: ComparisonModel + /** Each fold, by its card's ID; empty when nothing folds (and `model` is the one passed). */ + folds: ReadonlyMap + /** Each row a closed fold hides (entity or relationship), and the card or link drawn for it. */ + folded: ReadonlyMap + /** Each card and link a fold adds, and the rows it stands for: their step and emphasis are its. */ + stands: ReadonlyMap +} + +/** How `foldMassChanges` folds. */ +export interface MassFoldOptions { + /** Folds the person opened, by card ID: their items are drawn, and the card stays as the way to fold them again. */ + open?: ReadonlySet + /** The fewest siblings that fold (`massFoldMinimum` by default). */ + minimum?: number + /** A kind's words (the definition's noun); `humanizeKind` by default. */ + noun?: (kind: string) => SummaryNoun | undefined + /** BCP 47 locale for the count (`en-US` by default). */ + locale?: string +} + +/** The side that has an item of this status. */ +export const sideOf = (status: MassStatus): Side => (status === 'removed' ? 'before' : 'after') + +/** A fold's card label: `48 tables removed`; open, `Hide 48 removed tables`. */ +export function massFoldLabel(count: number, status: MassStatus, noun: SummaryNoun, open = false, locale = 'en-US'): string { + const words = count === 1 ? noun.singular : noun.plural + const number = count.toLocaleString(locale) + return open ? `Hide ${number} ${status} ${words}` : `${number} ${words} ${status}` +} From 8de5d4a6683a33e0f333ca7f1cb37f178a4a3f5c Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:41:42 +0000 Subject: [PATCH 6/9] Kit: the card grid page emphasizes only changed cards Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- packages/renderers/kit/browser/card-grid-page.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/renderers/kit/browser/card-grid-page.ts b/packages/renderers/kit/browser/card-grid-page.ts index 17fb5d23b..5afb71598 100644 --- a/packages/renderers/kit/browser/card-grid-page.ts +++ b/packages/renderers/kit/browser/card-grid-page.ts @@ -44,7 +44,7 @@ globalThis.showGrid = ({diff, emphasis, rows, scoped = false}) => { globalThis.selected.push(id) }, change: row, - emphasis, + emphasis: row.status === 'unchanged' ? 0 : emphasis, ...(diff && row.status !== 'unchanged' ? {mark: row} : {}), }), ) From c2a6c8e8ae3c215d839864f6662c276bf25426e2 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:57:23 +0000 Subject: [PATCH 7/9] Kit: document MassFold.status and MassFolded.model Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- packages/renderers/kit/src/mass-fold/model.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/renderers/kit/src/mass-fold/model.ts b/packages/renderers/kit/src/mass-fold/model.ts index 07c822594..aa03f7470 100644 --- a/packages/renderers/kit/src/mass-fold/model.ts +++ b/packages/renderers/kit/src/mass-fold/model.ts @@ -25,6 +25,7 @@ export type MassStatus = 'removed' | 'added' export interface MassFold { /** The fold card's row ID (`massFoldPrefix`). */ id: string + /** Whether its items were removed or added: the card's status, and so its style. */ status: MassStatus /** The folded items' kind, which the card takes. */ kind: string @@ -43,6 +44,7 @@ export interface MassFold { /** A model with its mass changes folded (`foldMassChanges`), and what each fold stands for. */ export interface MassFolded { + /** The model with each fold's card and links in place of what they stand for, steps included. */ model: ComparisonModel /** Each fold, by its card's ID; empty when nothing folds (and `model` is the one passed). */ folds: ReadonlyMap From 84f909d89091e1de1265bcc52024006ab03878b1 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:01:02 +0000 Subject: [PATCH 8/9] Changelog: fold mass changes in the renderer kit (#396) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- changelog.d/396-kit.md | 5 +++++ changelog.d/396-renderer-authors.md | 5 +++++ changelog.d/396.md | 5 +++++ 3 files changed, 15 insertions(+) create mode 100644 changelog.d/396-kit.md create mode 100644 changelog.d/396-renderer-authors.md create mode 100644 changelog.d/396.md diff --git a/changelog.d/396-kit.md b/changelog.d/396-kit.md new file mode 100644 index 000000000..f44e7def1 --- /dev/null +++ b/changelog.d/396-kit.md @@ -0,0 +1,5 @@ +--- +section: kit +--- + +- **The renderer kit folds mass changes in `GraphCanvas` and `CardGrid`** (#396). `GraphCanvas` folds a dozen or more sibling cards (`massFoldMinimum`) removed or added together into one card that presents them in `data-entity-aliases` and opens in place. `CardGrid` folds its `EntityCard`s the same way, and folds a run of a dozen or more unchanged cards into a full-width `Fold` band ("14 unchanged services") outside the Changes scope. `foldMassChanges` folds a `ComparisonModel` for a renderer with its own layout, and `Fold` takes an `id` and the IDs it `presents`. See [the graph canvas guide](docs/guides/renderer-kit-graphs.md). diff --git a/changelog.d/396-renderer-authors.md b/changelog.d/396-renderer-authors.md new file mode 100644 index 000000000..2ca697721 --- /dev/null +++ b/changelog.d/396-renderer-authors.md @@ -0,0 +1,5 @@ +--- +section: renderer-authors +--- + +- **`CardGrid` folds runs of cards in comparisons** (#396). A custom renderer's `CardGrid` now folds a dozen or more `EntityCard`s removed (or added) together, of one kind, into one card, and in the All scope folds a run of a dozen or more unchanged ones into a band; each opens in place. It reads each card's status and kind from the `change` row you pass, and folds nothing for a single revision. The `diff-changes`, `diff-neutral` and `highlight-scope` checks accept a change drawn on a card that lists it in `data-entity-aliases`, and the selection round trip passes by an entity element marked `data-projections-action`, as a fold's card is. diff --git a/changelog.d/396.md b/changelog.d/396.md new file mode 100644 index 000000000..7f2a7e081 --- /dev/null +++ b/changelog.d/396.md @@ -0,0 +1,5 @@ +--- +section: renderers +--- + +- **Graph renderers fold a dozen or more cards removed together into one card** (#396). A comparison that removes a whole set of siblings (tables in a schema, reports a service ran, packages a workspace dropped) used to draw every removed card, which could make a frame too tall to render as an image. The graph, DAG, architecture, infrastructure and dependency graphs now draw one card in the removed style, such as "48 tables removed", worded with the definition's noun, with each relationship to what stays drawn once from it. Activating the card opens its cards in place. The host's selection, hover, filter and focus (`--entity`) of a folded item find the card. Additions of a dozen or more fold the same way. From 4b94739b82be1fc7a8d8f531536ea3cc6916fca7 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:29:46 +0000 Subject: [PATCH 9/9] Kit: fold scattered removals apart; grid folds keep their cards' parts and timing Siblings with no container fold only when they share their neighbours, so a dependency graph's scattered removals stay apart. A relationship rewired from a folded item keeps the revision that still has both ends. A card grid keeps the cards a fold takes, hidden, with their parts, so a fold presents those too; it leaves an unchanged card whose relationships change out of its bands, and takes its presence and emphasis from all its cards. A click anywhere in an element that is its own action selects nothing. Regenerated the reference pages. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- docs/reference/renderer-kit.md | 139 ++++++++++- docs/reference/renderers.md | 2 +- packages/cli/browser/starter.spec.ts | 2 +- .../renderers/kit/browser/card-grid-page.ts | 21 +- .../renderers/kit/browser/card-grid.spec.ts | 38 ++- .../renderers/kit/src/mass-fold/groups.ts | 55 ++++- packages/renderers/kit/src/mass-fold/links.ts | 19 +- .../renderers/kit/src/react/grid-folds.tsx | 228 ++++++++++++------ .../renderers/kit/src/react/kind-nouns.ts | 6 + .../kit/src/react/layout-components.tsx | 13 +- .../kit/src/react/shell/kit-renderer.tsx | 91 ++++--- .../kit/src/react/shell/selection.ts | 6 +- .../renderers/kit/test/mass-fold.test.mjs | 60 +++++ 13 files changed, 536 insertions(+), 144 deletions(-) diff --git a/docs/reference/renderer-kit.md b/docs/reference/renderer-kit.md index a2089ed36..919cac7d1 100644 --- a/docs/reference/renderer-kit.md +++ b/docs/reference/renderer-kit.md @@ -1623,6 +1623,30 @@ A list with every run of items `shown` leaves out folded into one entry, keyed b names is listed after its fold, `open`. A run of one item stays, as its fold would take as much room. Every item is shown when `shown` is undefined. Fold the union of a comparison (or each pane's list in the union's order) so both revisions fold alike. +### `foldMassChanges` + +```ts +foldMassChanges(model: ComparisonModel, options?: MassFoldOptions): MassFolded +``` + +Folds every run of `minimum` or more sibling items removed together, or added together, into one card: items of +one kind with the same status in the same container (or at the top level, outside any) when the container itself +stays. The card takes their kind and status, so it is drawn in the removed (or added) style, and counts them with the +definition's noun (`48 tables removed`). It stands for the items, the parts they contain and the relationships among +them; a relationship from one of them to an item that stays is drawn once from the card, for each item, kind and +direction. Steps place the card and its links in the first step that changes what they stand for. A fold in `open` +draws its items, and its card stays, labeled `Hide 48 removed tables`, as the way to fold them again. A model with no +such run is returned as it is. + +### `foldMassSteps` + +```ts +foldMassSteps(steps: Array, folding: Pick, "folded" | "folds" | "stands">): Array +``` + +Steps (a model's, or a schedule) with a fold's cards and links in place of what they stand for: each in the first +step that changes any of it, and in no other. A step left with nothing keeps its place, so timing doesn't move. + ### `foldPrefix` ```ts @@ -1951,6 +1975,14 @@ isKind(change: EntityChange, ...kinds: Array): false | true Whether either version of the row has one of `kinds`, so a row that changed kind matches both. +### `isMassFold` + +```ts +isMassFold(id: string): false | true +``` + +Whether an item is a card or link `foldMassChanges` adds. + ### `isSortable` ```ts @@ -2005,6 +2037,15 @@ kindNote(kind: KindLineText | undefined, inferred: false | true): string The note after a kind line (the renderer's, then `Inferred`), or nothing. +### `kindNoun` + +```ts +kindNoun(kind: string, kinds?: Record | undefined, nouns?: Readonly> | undefined | { (kind: string, collection: "entities" | "relationships"): SummaryKindCount | SummaryNoun | false | undefined }): SummaryNoun +``` + +A kind's words, as the summary bar words its count: the definition's noun (`presentation.kinds..noun`), else +the renderer's (`SummaryNouns`), else the host's (`humanizeKind`). + ### `kindText` ```ts @@ -2177,6 +2218,89 @@ lineSpline(from: Point, to: Point): Spline A straight segment as one cubic, so every route is a uniform chain. +### `MassFold` + +```ts +interface MassFold +``` + +One fold of sibling items removed or added together. + +| Member | Signature | Description | +|---|---|---| +| `id` | `"id": string` | The fold card's row ID (`massFoldPrefix`). | +| `items` | `"items": Array` | The sibling entity rows it folds, in the model's order. | +| `kind` | `"kind": string` | The folded items' kind, which the card takes. | +| `label` | `"label": string` | The card's label: `48 tables removed`, or open, `Hide 48 removed tables`. | +| `open` | `"open": false \| true` | Whether it is open: its items drawn on their own, and the card the way to fold them again. | +| `presents` | `"presents": Array` | Every row the card presents while closed: the siblings, the parts they contain and the relationships among them or to them, for the card's `data-entity-aliases`. | +| `status` | `"status": MassStatus` | Whether its items were removed or added: the card's status, and so its style. | + +### `MassFolded` + +```ts +interface MassFolded +``` + +A model with its mass changes folded (`foldMassChanges`), and what each fold stands for. + +| Member | Signature | Description | +|---|---|---| +| `folded` | `"folded": ReadonlyMap` | Each row a closed fold hides (entity or relationship), and the card or link drawn for it. | +| `folds` | `"folds": ReadonlyMap` | Each fold, by its card's ID; empty when nothing folds (and `model` is the one passed). | +| `model` | `"model": ComparisonModel` | The model with each fold's card and links in place of what they stand for, steps included. | +| `stands` | `"stands": ReadonlyMap>` | Each card and link a fold adds, and the rows it stands for: their step and emphasis are its. | + +### `massFoldLabel` + +```ts +massFoldLabel(count: number, status: MassStatus, noun: SummaryNoun, open?: false | true, locale?: string): string +``` + +A fold's card label: `48 tables removed`; open, `Hide 48 removed tables`. + +### `massFoldMinimum` + +```ts +massFoldMinimum: 12 +``` + +The fewest sibling items removed (or added) together that fold into one card: twice a sibling block's +`blockMinimum`, two full lines of its tray, past which more cards add height without saying more than their count. +It is also where a stack of removed database tables alone outgrows a frame: on one schema, 48 removed tables drew a +frame 81,546 px tall, about 1,700 px a table, so a dozen pass the 20,000 px most hosts render. + +### `MassFoldOptions` + +```ts +interface MassFoldOptions +``` + +How `foldMassChanges` folds. + +| Member | Signature | Description | +|---|---|---| +| `locale` | `"locale"?: string` | BCP 47 locale for the count (`en-US` by default). | +| `minimum` | `"minimum"?: number` | The fewest siblings that fold (`massFoldMinimum` by default). | +| `noun` | `"noun"?: { (kind: string): SummaryNoun \| undefined }` | A kind's words (the definition's noun); `humanizeKind` by default. | +| `open` | `"open"?: ReadonlySet` | Folds the person opened, by card ID: their items are drawn, and the card stays as the way to fold them again. | + +### `massFoldPrefix` + +```ts +massFoldPrefix: "pk-mass:" +``` + +The ID prefix of the cards and links `foldMassChanges` adds. + +### `MassStatus` + +```ts +type MassStatus = "added" | "removed" +``` + +The statuses that fold: items that only one revision has. + ### `maxZoom` ```ts @@ -3986,7 +4110,10 @@ The corner radius a graph card's shape is drawn with, in card units, where the t CardGrid(__0: { "children": ReactNode; "label"?: string }): Element ``` -Cards in a responsive grid: as many columns as fit, one on a phone. +Cards in a responsive grid: as many columns as fit, one on a phone. In a comparison, a dozen or more of its +`EntityCard`s removed (or added) together, of one kind, fold into one card that counts them and opens in place +(`GridFoldCard`), and a run of a dozen or more unchanged ones folds into a band across the grid (`GridBand`), except +under the Changes scope. ### `CategoriesView` @@ -4302,12 +4429,14 @@ labels ("Runs on"), use `Facts` and `Fact`. ### `Fold` ```ts -Fold(__0: { "as"?: ElementType; "className"?: string; "columns"?: number; "count": number; "noun": string; "onToggle": { (): void }; "open"?: false | true | undefined }): Element +Fold(__0: { "as"?: ElementType; "className"?: string; "columns"?: number; "count": number; "id"?: string | undefined; "noun": string; "onToggle": { (): void }; "open"?: false | true | undefined; "presents"?: Array | undefined }): Element ``` A fold: "12 unchanged declarations", a button that opens the run in place; `open`, "Hide 12 unchanged declarations" above the opened run, which folds it again. `as` sets its element (`div` by default, `tr` or `li` in tables and lists; -a `tr` puts the button in one cell spanning `columns`). +a `tr` puts the button in one cell spanning `columns`). Given an `id`, the fold is an item the host sees, and while +closed it presents the items it folds (`presents`, in `data-entity-aliases`), so the host's selection, hover and +filter of one find it. ### `GeneratedMark` @@ -4362,7 +4491,9 @@ The staged graph canvas shared by the graph, DAG and architecture renderers: ELK layouts per comparison step (laid out off the main thread before the first paint), identity-stable cards, spline relationships that morph on the same clock as their cards, stable framing across the whole transition, and -host-driven change emphasis. +host-driven change emphasis. A dozen or more sibling cards removed (or added) +together fold into one card that counts them and opens in place +(`foldMassChanges`). ### `graphCanvasControls` diff --git a/docs/reference/renderers.md b/docs/reference/renderers.md index 34383901f..392637343 100644 --- a/docs/reference/renderers.md +++ b/docs/reference/renderers.md @@ -99,7 +99,7 @@ Built-in Projections graph renderer: staged, identity-stable graph transitions ( - Handles: `graph`, `graph-horizontal`, `dag`, `architecture`, `infrastructure`, `dependencies` - Comparison modes: `diff`, `side-by-side`, `animated`, `swipe` - Package: `@githubnext/projections-renderer-graph` -- Example scenarios ([`scenarios.json`](../../packages/renderers/graph/scenarios.json)): Service platform; Service platform, payments first (custom order); Test timings with volatile durations; Class summaries, generated by a model; Source references, left to right; Declared rename; Feature flags; Feature flags, one revision; Single extraction; CI pipeline restructure; Release workflow; Platform gains a worker; Storage module split; Single extraction; Card icons; OpenRewrite: JUnit 4 to JUnit 5; Terraform: the database is replaced; Bicep: a private endpoint subnet; Terraform: one revision's plan; React 19.2 and clsx; Express 5 and React 19; npm workspace (one revision); NuGet package update; NuGet library with long package names; A layered module graph; A layered module graph (one revision); A wide module graph; A wide module graph (one revision); A hub-heavy module graph (one revision); MCP tools, toolsets and OAuth scopes; An architecture of 42 components (one revision); Who may reach what: 6 callers, 16 owners, 74 relationships (graph); Who may reach what: 6 callers, 16 owners, 74 relationships (architecture) +- Example scenarios ([`scenarios.json`](../../packages/renderers/graph/scenarios.json)): Service platform; Service platform, payments first (custom order); Reporting retired, 16 reports with it; Test timings with volatile durations; Class summaries, generated by a model; Source references, left to right; Declared rename; Feature flags; Feature flags, one revision; Single extraction; CI pipeline restructure; Release workflow; Platform gains a worker; Storage module split; Single extraction; Card icons; OpenRewrite: JUnit 4 to JUnit 5; Terraform: the database is replaced; Bicep: a private endpoint subnet; Terraform: one revision's plan; React 19.2 and clsx; Express 5 and React 19; npm workspace (one revision); NuGet package update; NuGet library with long package names; A layered module graph; A layered module graph (one revision); A wide module graph; A wide module graph (one revision); A hub-heavy module graph (one revision); MCP tools, toolsets and OAuth scopes; An architecture of 42 components (one revision); Who may reach what: 6 callers, 16 owners, 74 relationships (graph); Who may reach what: 6 callers, 16 owners, 74 relationships (architecture) ## `runtime-policy` diff --git a/packages/cli/browser/starter.spec.ts b/packages/cli/browser/starter.spec.ts index f9ddfea38..c7c0b135d 100644 --- a/packages/cli/browser/starter.spec.ts +++ b/packages/cli/browser/starter.spec.ts @@ -53,7 +53,7 @@ test('the starter renderer folds a run of unchanged cards into a band in All, wh const band = stage.frame.locator('.pk-grid-band') await expect(band).toHaveCount(1) await expect(band).toHaveText(/14 unchanged services/u) - await expect(stage.frame.locator('[data-entity-id="service:search"]')).toHaveCount(0) + await expect(stage.frame.locator('[data-entity-id="service:search"]')).toBeHidden() await expect(stage.frame.locator('[data-entity-id="service:wallet"]')).toBeVisible() // The host's selection of a folded service finds the band. await stage.select('service:search') diff --git a/packages/renderers/kit/browser/card-grid-page.ts b/packages/renderers/kit/browser/card-grid-page.ts index 5afb71598..ef14a0e11 100644 --- a/packages/renderers/kit/browser/card-grid-page.ts +++ b/packages/renderers/kit/browser/card-grid-page.ts @@ -3,7 +3,7 @@ import {createElement as h} from 'react' import {flushSync} from 'react-dom' import {createRoot} from 'react-dom/client' -import {CardGrid, ContentView, EntityCard, Group} from '../src/react/layout-components.js' +import {CardGrid, ContentView, EntityCard, Group, RelationshipItem, RelationshipList} from '../src/react/layout-components.js' import '../react.css' export interface GridMode { @@ -13,6 +13,10 @@ export interface GridMode { rows: 'removed' | 'unchanged' /** Under the Changes scope (`data-scope="changes"` on the kit's root). */ scoped?: boolean + /** The first removed job has already gone (presence 0) while the others are halfway (0.5). */ + staggered?: boolean + /** The seventh unchanged step draws a changed relationship (marked in the diff). */ + touched?: boolean } declare global { @@ -32,7 +36,7 @@ const container = document.getElementById('root') if (!container) throw new Error('The page has no #root') const root = createRoot(container) globalThis.selected = [] -globalThis.showGrid = ({diff, emphasis, rows, scoped = false}) => { +globalThis.showGrid = ({diff, emphasis, rows, scoped = false, staggered = false, touched = false}) => { const cards = sets[rows].map(row => h(EntityCard, { key: row.id, @@ -46,6 +50,19 @@ globalThis.showGrid = ({diff, emphasis, rows, scoped = false}) => { change: row, emphasis: row.status === 'unchanged' ? 0 : emphasis, ...(diff && row.status !== 'unchanged' ? {mark: row} : {}), + ...(staggered && row.status === 'removed' ? {presence: row.id === 'legacy-01' ? 0 : 0.5} : {}), + // Each job draws what it needs, a relationship of its own. + children: h( + RelationshipList, + null, + h(RelationshipItem, { + id: `${row.id}:needs`, + selected: false, + onSelect: () => undefined, + ...(touched && row.id === 'step-07' ? {mark: {status: 'added' as const}} : {}), + children: 'needs → setup', + }), + ), }), ) flushSync(() => { diff --git a/packages/renderers/kit/browser/card-grid.spec.ts b/packages/renderers/kit/browser/card-grid.spec.ts index 4d2d28924..dc0750637 100644 --- a/packages/renderers/kit/browser/card-grid.spec.ts +++ b/packages/renderers/kit/browser/card-grid.spec.ts @@ -55,21 +55,22 @@ for (const mode of [ await expect(fold).toHaveText(/14 jobs removed/u) await expect(fold).toHaveAttribute('data-fold', 'closed') // Closed, the fold presents every job it folds, so the host's selection of one finds it, and they take no room. - expect(JSON.parse((await fold.getAttribute('data-entity-aliases')) ?? '[]')).toEqual(legacy) - await expect(target.locator('[data-entity-id^="legacy-"]')).toHaveCount(0) + // Its jobs and what is drawn in them, their relationships. + expect(JSON.parse((await fold.getAttribute('data-entity-aliases')) ?? '[]')).toEqual(legacy.flatMap(id => [id, `${id}:needs`])) + await expect(target.locator('.pk-entity-card[data-entity-id^="legacy-"]:visible')).toHaveCount(0) await expect(target.locator('[data-entity-id="build"]')).toBeVisible() // It is drawn in the removed style its jobs share. if (mode.diff) await expect(fold).toHaveAttribute('data-change', 'removed') else await expect(fold).toHaveAttribute('data-status', 'removed') // Opening it draws the jobs after it, and selects nothing; the fold stays, as the way to fold them again. await fold.getByRole('button').click() - await expect(target.locator('[data-entity-id^="legacy-"]')).toHaveCount(14) + await expect(target.locator('.pk-entity-card[data-entity-id^="legacy-"]:visible')).toHaveCount(14) await expect(fold).toHaveText(/Hide 14 removed jobs/u) await expect(fold.getByRole('button')).toHaveAttribute('aria-expanded', 'true') expect(await fold.getAttribute('data-entity-aliases')).toBeNull() expect(await target.evaluate(() => globalThis.selected)).toEqual([]) await fold.getByRole('button').click() - await expect(target.locator('[data-entity-id^="legacy-"]')).toHaveCount(0) + await expect(target.locator('.pk-entity-card[data-entity-id^="legacy-"]:visible')).toHaveCount(0) }) } @@ -80,8 +81,8 @@ test('a card grid folds a run of 14 unchanged jobs into a band across it, but no await expect(band).toHaveCount(1) await expect(band).toHaveText(/14 unchanged jobs/u) await expect(band).toHaveAttribute('data-fold', 'closed') - expect(JSON.parse((await band.getAttribute('data-entity-aliases')) ?? '[]')).toHaveLength(14) - await expect(target.locator('[data-entity-id^="step-"]')).toHaveCount(0) + expect(JSON.parse((await band.getAttribute('data-entity-aliases')) ?? '[]')).toHaveLength(28) + await expect(target.locator('.pk-entity-card[data-entity-id^="step-"]:visible')).toHaveCount(0) await expect(target.locator('[data-entity-id="deploy"]')).toBeVisible() // The band spans the grid's columns. const spans = await band.evaluate(element => { @@ -92,10 +93,31 @@ test('a card grid folds a run of 14 unchanged jobs into a band across it, but no }) expect(spans).toBeLessThan(1) await band.getByRole('button').click() - await expect(target.locator('[data-entity-id^="step-"]')).toHaveCount(14) + await expect(target.locator('.pk-entity-card[data-entity-id^="step-"]:visible')).toHaveCount(14) await expect(band).toHaveText(/Hide 14 unchanged jobs/u) // The Changes scope shows its unchanged cards as context: no band. await target.evaluate(shown => globalThis.showGrid(shown), {diff: true, emphasis: 1, rows: 'unchanged', scoped: true} satisfies GridMode) await expect(target.locator('.pk-grid-band')).toHaveCount(0) - await expect(target.locator('[data-entity-id^="step-"]')).toHaveCount(14) + await expect(target.locator('.pk-entity-card[data-entity-id^="step-"]:visible')).toHaveCount(14) +}) + +test('a fold shows from the first of its cards that is present, whichever comes first in the grid', async ({page: target}) => { + await target.setContent(await gridPage()) + await target.evaluate(shown => globalThis.showGrid(shown), { + diff: false, + emphasis: 1, + rows: 'removed', + staggered: true, + } satisfies GridMode) + const fold = target.locator('.pk-mass-fold') + await expect(fold).toBeVisible() + expect(await fold.evaluate(element => getComputedStyle(element).opacity)).toBe('0.5') +}) + +test('an unchanged card that draws a change breaks a run of unchanged cards', async ({page: target}) => { + await target.setContent(await gridPage()) + await target.evaluate(shown => globalThis.showGrid(shown), {diff: true, emphasis: 1, rows: 'unchanged', touched: true} satisfies GridMode) + await expect(target.locator('[data-entity-id="step-07:needs"]')).toBeVisible() + // Six and seven unchanged steps either side: too few to fold. + await expect(target.locator('.pk-grid-band')).toHaveCount(0) }) diff --git a/packages/renderers/kit/src/mass-fold/groups.ts b/packages/renderers/kit/src/mass-fold/groups.ts index 57257aa0e..079691bfe 100644 --- a/packages/renderers/kit/src/mass-fold/groups.ts +++ b/packages/renderers/kit/src/mass-fold/groups.ts @@ -36,10 +36,15 @@ export interface SiblingGroup { items: string[] } -/** Entity rows only one revision has, by status, container and kind; a part leaving (or arriving) with its container goes with it. */ +/** + * Entity rows only one revision has, by status, container and kind; a part leaving (or arriving) with its container + * goes with it. Items with no container are siblings only when they also share their neighbours: the same + * relationships, by kind and direction, to the same items outside the group (`neighbourhood`), so removals scattered + * through a graph never fold together. + */ export function siblingGroups(model: ComparisonModel, tree: Containment): SiblingGroup[] { const statusOf = new Map(model.entities.map(row => [row.id, row.status])) - const groups = new Map() + const candidates = new Map() for (const row of model.entities) { if (row.status !== 'removed' && row.status !== 'added') continue const status = row.status @@ -47,14 +52,54 @@ export function siblingGroups(model: ComparisonModel, tree: Containment): Siblin const entity = row[side] const parent = tree.parentOf[side].get(row.id) if (!entity || (parent !== undefined && statusOf.get(parent) === status)) continue - const key = `${status}\n${parent ?? ''}\n${entity.kind}` - const group = groups.get(key) ?? {status, parent, kind: entity.kind, items: []} - group.items.push(row.id) + candidates.set(row.id, {status, parent, kind: entity.kind, id: row.id}) + } + const near = neighbourhood(model, candidates) + const groups = new Map() + for (const {status, parent, kind, id} of candidates.values()) { + const key = `${status}\n${parent ?? ''}\n${kind}\n${parent === undefined ? (near.get(id) ?? '') : ''}` + const group = groups.get(key) ?? {status, parent, kind, items: []} + group.items.push(id) groups.set(key, group) } return [...groups.values()] } +/** + * Each top-level candidate's neighbours outside its own kind and status, as one key: every relationship's direction, + * kind and other end, in the revision that has it. Containment is left out: a part goes with its container. + */ +function neighbourhood( + model: ComparisonModel, + candidates: ReadonlyMap, +): Map { + const ends = new Map>() + const group = (id: string) => { + const candidate = candidates.get(id) + return candidate && candidate.parent === undefined ? `${candidate.status}\n${candidate.kind}` : undefined + } + for (const side of sides) { + const contains = isContainment(model[side]) + const rowOf = model.entityRow[side] + for (const relationship of model[side].relationships) { + if (contains(relationship)) continue + const from = rowOf.get(relationship.from) ?? '' + const to = rowOf.get(relationship.to) ?? '' + for (const [own, other, direction] of [ + [from, to, 'out'], + [to, from, 'in'], + ] as const) { + const mine = group(own) + if (mine === undefined || group(other) === mine) continue + const set = ends.get(own) ?? new Set() + set.add(`${direction}\t${relationship.kind}\t${other}`) + ends.set(own, set) + } + } + } + return new Map([...ends].map(([id, set]) => [id, [...set].toSorted().join('\n')])) +} + /** What folding adds and hides, as it is built. */ export interface Folding { folds: Map & {presents: string[]}> diff --git a/packages/renderers/kit/src/mass-fold/links.ts b/packages/renderers/kit/src/mass-fold/links.ts index cfcb3e5f7..52da3d5bf 100644 --- a/packages/renderers/kit/src/mass-fold/links.ts +++ b/packages/renderers/kit/src/mass-fold/links.ts @@ -29,6 +29,18 @@ export function foldRelationships( return item && [item.from, item.to].some(end => hiddenEntities.has(model.entityRow[side].get(end) ?? '')) ? [{side, item}] : [] }) if (!touched.length) kept.push(row) + // A revision whose ends all stay keeps the row, with that revision alone (a relationship rewired from a folded + // item to one that stays is still drawn where it now goes); the folded revision goes to the fold. + const untouched = sides.filter(side => row[side] && !touched.some(each => each.side === side)) + const [stays] = untouched + if (touched.length && stays) { + kept.push({ + id: row.id, + [stays]: row[stays], + status: stays === 'after' ? 'added' : 'removed', + correspondence: row.correspondence ?? 'exact', + }) + } for (const {side, item} of touched) { const fromRow = model.entityRow[side].get(item.from) ?? '' const from = hiddenEntities.get(fromRow) @@ -41,8 +53,11 @@ export function foldRelationships( ? holder.link : undefined const id = own ?? `${massFoldPrefix}link:${item.kind}:${from ?? item.from}->${to ?? item.to}` - folding.hidden.set(row.id, id) - present(from ?? to ?? '', row.id) + // A row still drawn on its own is no alias of the fold. + if (!untouched.length) { + folding.hidden.set(row.id, id) + present(from ?? to ?? '', row.id) + } if (own !== undefined) continue const link = merged.get(id) ?? {rows: [], ends: {}} if (!link.rows.includes(row.id)) link.rows.push(row.id) diff --git a/packages/renderers/kit/src/react/grid-folds.tsx b/packages/renderers/kit/src/react/grid-folds.tsx index 9dcff3052..6291531af 100644 --- a/packages/renderers/kit/src/react/grid-folds.tsx +++ b/packages/renderers/kit/src/react/grid-folds.tsx @@ -1,24 +1,41 @@ // A card grid's folds: a dozen or more of its cards removed (or added) together, of one kind, drawn as one card that // counts them and opens in place, as a graph canvas folds them (`foldMassChanges`); and a run of a dozen or more // unchanged cards drawn as one band across the grid, the Changes scope's `Fold`. -import {createContext, use, useCallback, useMemo, useState} from 'react' +import {createContext, use, useCallback, useLayoutEffect, useMemo, useRef, useState, type RefObject} from 'react' +import type {SummaryNoun} from '@githubnext/projections-renderer-sdk/protocol' import {entityAliasesAttribute} from '@githubnext/projections-renderer-sdk/interactions' import {massFoldLabel, massFoldMinimum, massFoldPrefix, type MassStatus} from '../mass-fold.js' import {foldPrefix} from '../scope-parts.js' import {changeMark} from '../diff/model.js' import {ChangeFooter} from './components.js' import {Fold, FoldGlyph} from './fold.js' -import {useKindNoun} from './kind-nouns.js' +import {TouchedRows, useKindNoun} from './kind-nouns.js' -/** A card's slot in its grid (`gridSlot`): its ID, status and kind, kept in place (hidden) while a fold takes it. */ +/** + * A card's slot in its grid (`useGridSlot`): its ID, status, kind, presence and emphasis, on the card's element, which + * stays in place (hidden) while a fold takes it, its parts with it. + */ const slotAttribute = 'data-pk-grid-card' const statusAttribute = 'data-pk-grid-status' const kindAttribute = 'data-pk-grid-kind' +const presenceAttribute = 'data-pk-grid-presence' +const emphasisAttribute = 'data-pk-grid-emphasis' /** The grid's own folds, which stand in a run rather than break it. */ const ownFolds = '.pk-mass-fold, .pk-grid-band' -/** One of a grid's children in order: a card's slot, or anything else (a Changes scope fold, a note), which breaks a run. */ -type GridEntry = {id: string; status: string; kind: string} | null +/** A card in a grid, as drawn: what folds it, and what a fold of it presents and shows. */ +interface GridCard { + id: string + status: string + kind: string + presence: number + emphasis: number + /** Its ID and every item drawn in it (its parts, such as relationships), with their aliases. */ + ids: string[] +} + +/** One of a grid's children in order: a card, or anything else (a Changes scope fold, a note), which breaks a run. */ +type GridEntry = GridCard | null /** One fold of a grid's cards. */ export interface GridFold { @@ -29,12 +46,19 @@ export interface GridFold { id: string /** `mass`: cards removed (or added) together, in their style; `unchanged`: a run of unchanged cards, as a band. */ type: 'mass' | 'unchanged' + /** Whether its cards were removed, added or left unchanged. */ status: MassStatus | 'unchanged' - /** The cards it folds, in the grid's order: their IDs are its `data-entity-aliases` while it is closed. */ + /** The cards it folds, in the grid's order. */ members: readonly string[] + /** What it presents while closed (`data-entity-aliases`): its cards and every item drawn in them. */ + presents: readonly string[] /** A mass fold's label (`48 jobs removed`); a band's plural noun (`jobs`), which `Fold` counts as unchanged. */ label: string open: boolean + /** How present its cards are: the most present of them, so it shows from the first step that brings one. */ + presence: number + /** Its cards' emphasis: the strongest of them. */ + emphasis: number } interface GridFolds { @@ -47,9 +71,31 @@ const GridFoldsContext = createContext(undefined) /** Provides a grid's folds to its cards. */ export const GridFoldsProvider = GridFoldsContext +const number = (value: string | null) => { + const parsed = Number(value) + return Number.isFinite(parsed) ? parsed : 1 +} + +/** The items drawn in a card, its own ID first, with the aliases of each. */ +function drawnIds(card: Element): string[] { + const ids: string[] = [] + for (const element of [card, ...card.querySelectorAll('[data-entity-id]')]) { + const id = element.getAttribute('data-entity-id') + if (id !== null) ids.push(id) + try { + const aliases: unknown = JSON.parse(element.getAttribute(entityAliasesAttribute) ?? '[]') + if (Array.isArray(aliases)) ids.push(...aliases.filter((alias): alias is string => typeof alias === 'string')) + } catch { + // An unreadable alias list presents nothing more. + } + } + return [...new Set(ids)] +} + /** * What a grid's children say, in order (`GridEntry`), and whether the Changes scope is shown. A single revision (the - * kit shell's `data-mode`) folds nothing: its cards have no change, however a renderer passes its rows. + * kit shell's `data-mode`) folds nothing: its cards have no change, however a renderer passes its rows. An unchanged + * card that draws a change inside it (`data-change`) is no unchanged card: a band would hide that change. */ function readGrid(element: Element): {key: string; entries: readonly GridEntry[]; scoped: boolean} { const scoped = element.closest('[data-scope="changes"]') !== null @@ -58,36 +104,99 @@ function readGrid(element: Element): {key: string; entries: readonly GridEntry[] const entries = children.flatMap((child): GridEntry[] => { if (child.matches(ownFolds)) return [] const id = child.getAttribute(slotAttribute) - return [id === null ? null : {id, status: child.getAttribute(statusAttribute) ?? '', kind: child.getAttribute(kindAttribute) ?? ''}] + if (id === null) return [null] + const status = child.getAttribute(statusAttribute) ?? '' + const marked = status === 'unchanged' && child.querySelector('[data-change]') !== null + return [ + { + id, + status: marked ? 'touched' : status, + kind: child.getAttribute(kindAttribute) ?? '', + presence: number(child.getAttribute(presenceAttribute)), + emphasis: number(child.getAttribute(emphasisAttribute)), + ids: drawnIds(child), + }, + ] }) return {key: JSON.stringify([scoped, entries]), entries, scoped} } +/** Each card's fold: a dozen or more cards of one kind removed (or added), and runs of a dozen or more unchanged ones. */ +function gridFolds( + read: {entries: readonly GridEntry[]; scoped: boolean}, + open: ReadonlySet, + noun: (kind: string) => SummaryNoun, +): Map { + const byCard = new Map() + const fold = (id: string, type: GridFold['type'], status: GridFold['status'], cards: readonly GridCard[], label: string) => { + const result: GridFold = { + id, + type, + status, + members: cards.map(card => card.id), + presents: [...new Set(cards.flatMap(card => card.ids))], + label, + open: open.has(id), + presence: Math.max(0, ...cards.map(card => card.presence)), + emphasis: Math.max(0, ...cards.map(card => card.emphasis)), + } + for (const card of cards) byCard.set(card.id, result) + } + const groups = new Map() + for (const entry of read.entries) { + if (entry?.status !== 'removed' && entry?.status !== 'added') continue + const key = `${entry.status}\n${entry.kind}` + const group = groups.get(key) ?? {status: entry.status, kind: entry.kind, cards: []} + group.cards.push(entry) + groups.set(key, group) + } + for (const {status, kind, cards} of groups.values()) { + const [first] = cards + if (first === undefined || cards.length < massFoldMinimum) continue + const id = `${massFoldPrefix}${status}:${kind}:${first.id}` + fold(id, 'mass', status, cards, massFoldLabel(cards.length, status, noun(kind), open.has(id))) + } + if (read.scoped) return byCard + let run: GridCard[] = [] + const flush = () => { + const [first] = run + if (first !== undefined && run.length >= massFoldMinimum) { + const kinds = new Set(run.map(card => card.kind)) + fold(`${foldPrefix}grid:${first.id}`, 'unchanged', 'unchanged', run, kinds.size === 1 ? noun(first.kind).plural : 'items') + } + run = [] + } + for (const entry of read.entries) { + if (entry?.status === 'unchanged') run.push(entry) + else flush() + } + flush() + return byCard +} + /** - * A grid's folds, read from its children in order as they are drawn (`attach` is the grid element's `ref`): a dozen or + * A grid's folds, read from its children in order as they are drawn, after every render and before it is painted, so + * a fold's presence and emphasis follow its cards' on the same frame (`attach` is the grid element's `ref`): a dozen or * more cards of one kind removed (or added) fold into one card in the place of the first (`GridFoldCard`); a run of a * dozen or more unchanged cards, nothing else between them, folds into a band across the grid (`GridBand`), except * under the Changes scope, which shows its unchanged cards as context. What the person opened stays open. */ -export function useGridFolds(): {folds: GridFolds; attach: (element: HTMLElement | null) => (() => void) | undefined} { +export function useGridFolds(): {folds: GridFolds; attach: RefObject} { const noun = useKindNoun() + const attach = useRef(null) const [read, setRead] = useState<{key: string; entries: readonly GridEntry[]; scoped: boolean}>({key: '', entries: [], scoped: false}) const [open, setOpen] = useState>(() => new Set()) - // The cards as drawn, read once the grid is attached and again whenever its cards change, before the next paint: a - // folded grid never draws its cards first. - const attach = useCallback((element: HTMLElement | null) => { - if (!element) return undefined - const update = () => { - const next = readGrid(element) - setRead(previous => (previous.key === next.key ? previous : next)) - } - update() - const observer = new MutationObserver(update) - observer.observe(element, {childList: true, subtree: true, attributeFilter: [slotAttribute, statusAttribute, kindAttribute]}) - const root = element.closest('.pk') - if (root) observer.observe(root, {attributeFilter: ['data-scope', 'data-mode']}) - return () => observer.disconnect() - }, []) + // After every render, as the grid's cards may have changed with it: the read settles at once, as an unchanged grid + // keeps its state. + // eslint-disable-next-line react-hooks/exhaustive-deps -- no dependencies: it reads the DOM this render committed + useLayoutEffect(() => { + const element = attach.current + if (!element) return + const next = readGrid(element) + // What the grid draws decides its folds: reading it before the paint draws the folds on the same frame. + // eslint-disable-next-line react-hooks/set-state-in-effect -- the grid's own DOM is the input, read before paint + setRead(previous => (previous.key === next.key ? previous : next)) + }) const toggle = useCallback( (fold: string) => setOpen(previous => { @@ -98,52 +207,7 @@ export function useGridFolds(): {folds: GridFolds; attach: (element: HTMLElement }), [], ) - const byId = useMemo(() => { - const byCard = new Map() - const groups = new Map() - for (const entry of read.entries) { - if (entry?.status !== 'removed' && entry?.status !== 'added') continue - const key = `${entry.status}\n${entry.kind}` - const group = groups.get(key) ?? {status: entry.status, kind: entry.kind, members: []} - group.members.push(entry.id) - groups.set(key, group) - } - for (const {status, kind, members} of groups.values()) { - const [first] = members - if (first === undefined || members.length < massFoldMinimum) continue - const id = `${massFoldPrefix}${status}:${kind}:${first}` - const opened = open.has(id) - const fold: GridFold = { - id, - type: 'mass', - status, - members, - open: opened, - label: massFoldLabel(members.length, status, noun(kind), opened), - } - for (const member of members) byCard.set(member, fold) - } - if (!read.scoped) { - let run: {id: string; kind: string}[] = [] - const flush = () => { - const [first] = run - if (first !== undefined && run.length >= massFoldMinimum) { - const id = `${foldPrefix}grid:${first.id}` - const kinds = new Set(run.map(card => card.kind)) - const label = kinds.size === 1 ? noun(first.kind).plural : 'items' - const fold: GridFold = {id, type: 'unchanged', status: 'unchanged', members: run.map(card => card.id), open: open.has(id), label} - for (const card of run) byCard.set(card.id, fold) - } - run = [] - } - for (const entry of read.entries) { - if (entry?.status === 'unchanged') run.push(entry) - else flush() - } - flush() - } - return byCard - }, [read, open, noun]) + const byId = useMemo(() => gridFolds(read, open, noun), [read, open, noun]) const foldOf = useCallback((id: string) => byId.get(id), [byId]) const folds = useMemo(() => ({foldOf, toggle}), [foldOf, toggle]) return {folds, attach} @@ -166,12 +230,23 @@ export interface GridSlot { export function useGridSlot( id: string, row: {status?: string; before?: {kind?: unknown}; after?: {kind?: unknown}} | undefined, + presence: number, + emphasis: number, ): GridSlot | undefined { const grid = use(GridFoldsContext) + const touched = use(TouchedRows) if (!grid) return undefined const entity = row?.status === 'removed' ? row.before : (row?.after ?? row?.before) const kind = typeof entity?.kind === 'string' ? entity.kind : '' - const slot = {[slotAttribute]: id, [statusAttribute]: row?.status ?? '', [kindAttribute]: kind} + // An unchanged card whose relationships change isn't unchanged to a band. + const status = row?.status === 'unchanged' && touched.has(id) ? 'touched' : (row?.status ?? '') + const slot = { + [slotAttribute]: id, + [statusAttribute]: status, + [kindAttribute]: kind, + [presenceAttribute]: String(Math.round(presence * 1000) / 1000), + [emphasisAttribute]: String(Math.round(emphasis * 1000) / 1000), + } const fold = grid.foldOf(id) const toggle = () => { if (fold) grid.toggle(fold.id) @@ -190,7 +265,7 @@ export function GridBand({fold, onToggle}: {fold: GridFold; onToggle: () => void open={fold.open} onToggle={onToggle} id={fold.id} - presents={fold.members} + presents={fold.presents} /> ) } @@ -203,16 +278,13 @@ export function GridBand({fold, onToggle}: {fold: GridFold; onToggle: () => void export function GridFoldCard({ fold, onToggle, - emphasis, mark, - presence, }: { fold: GridFold onToggle: () => void - emphasis: number mark: Parameters[0] | undefined - presence: number }) { + const {presence, emphasis} = fold const style = { '--emphasis': emphasis, ...(presence < 1 ? {opacity: presence, visibility: presence > 0 ? ('visible' as const) : ('hidden' as const)} : {}), @@ -222,7 +294,7 @@ export function GridFoldCard({
    • SummaryNoun>(kind => kindNoun(kind)) +/** + * The entity rows a changed relationship starts or ends at, though the row itself may be unchanged: a card grid + * doesn't fold one into a band of unchanged cards, which would hide the change. Empty outside a kit renderer. + */ +export const TouchedRows = createContext>(new Set()) + /** A kind's words in this frame, as the summary bar words it (see `KindNouns`). */ export function useKindNoun(): (kind: string) => SummaryNoun { return use(KindNouns) diff --git a/packages/renderers/kit/src/react/layout-components.tsx b/packages/renderers/kit/src/react/layout-components.tsx index 6ba7838bb..57139214c 100644 --- a/packages/renderers/kit/src/react/layout-components.tsx +++ b/packages/renderers/kit/src/react/layout-components.tsx @@ -236,7 +236,7 @@ export function EntityCard({ children, }: EntityCardProps) { const selectControl = useSelectControl() - const place = useGridSlot(id, change ?? (typeof mark === 'object' ? mark : undefined)) + const place = useGridSlot(id, change ?? (typeof mark === 'object' ? mark : undefined), presence, emphasis) const style = {'--emphasis': emphasis, ...(presence < 1 ? {opacity: presence, visibility: presence > 0 ? 'visible' : 'hidden'} : {})} const name = ( @@ -249,9 +249,9 @@ export function EntityCard({ ) const fold = place?.fold - // A card a closed fold takes keeps its place, hidden; the fold is drawn in the place of its first card. - const hidden =