diff --git a/docs/guides/renderer-kit-components.md b/docs/guides/renderer-kit-components.md index 33254ede..49a3734e 100644 --- a/docs/guides/renderer-kit-components.md +++ b/docs/guides/renderer-kit-components.md @@ -114,15 +114,20 @@ line, in the change's hue. The kit's change runs (`pk-region-run`, for rows that meet edge to edge) draw their edges on the lines around them: one stroke outside the run, over a neighbouring row's line, a header's bottom line or the container's edge. Where two runs meet, the later one's top edge is the boundary. -`Group` clips to its outer edge (`clip-path`), so a run at its edge covers the -group's border there. So a run needs that stroke to stay visible: a scrolling -container reaches over its card's edge by the line's width and pads itself by it -(as text diff's output does), and a row that draws a line of its own on a side -gives that line the hue (`--pk-region-line`, fading to `--pk-line`) instead of -an edge beside it (as runtime policy's rows, whose lines are their bottom -borders, and text diff's After column do). A changed `EntityCard` that is a -change region takes the hue on its own border, and a pill whose label is a -`ValueChange` draws no frame around its two pills. +`Group` clips to its outer edge (`overflow: clip` with the border's width as its +margin, or a `clip-path` where the browser lacks that margin), so a run at its +edge covers the group's border there. What reaches a group's corner takes its +inner radius (`--pk-group-inner-radius`, the radius less the border), so it is +concentric with the border and never covers it: the header band takes it at the +top, and a renderer's last row or band at the bottom (as runtime policy's last +rows and text diff's last line do). So a run needs that stroke to stay visible: +a scrolling container reaches over its card's edge by the line's width and pads +itself by it (as text diff's output does), and a row that draws a line of its +own on a side gives that line the hue (`--pk-region-line`, fading to +`--pk-line`) instead of an edge beside it (as runtime policy's rows, whose lines +are their bottom borders, and text diff's After column do). A changed +`EntityCard` that is a change region takes the hue on its own border, and a pill +whose label is a `ValueChange` draws no frame around its two pills. ## Item rings diff --git a/docs/reference/renderer-kit.md b/docs/reference/renderer-kit.md index 705e1830..988035ad 100644 --- a/docs/reference/renderer-kit.md +++ b/docs/reference/renderer-kit.md @@ -3597,9 +3597,11 @@ CardChangeMarks(__0: { "change": { "renamed"?: false | true | undefined; "status ``` A changed card's marks, as every kit card draws them: the card filled with its change's soft hue under a strong -edge of the same hue (inset by `inset`, see `emphasisInset`), and a footer band `footer` tall across its bottom, -ruled off from the body, holding the status words centred (see `SvgChangeStatus`). The edge is drawn again over -the band, so the band never covers the border or its corners. Draw it over the card's surface and under its text; +edge of the same hue (inset by `inset`, see `emphasisInset`, with its radius less the inset, so it is concentric with +the card's border), and a footer band `footer` tall across its bottom, ruled off from the body, holding the status +words centred (see `SvgChangeStatus`). The band is clipped to the card's shape (`node-card-shape`, rounded as the +card's surface is), so its corners follow the card's, and the edge is drawn again over it, so the band never covers +the border or pokes outside its corners. Draw it over the card's surface and under its text; everything fades with `emphasis`, and nothing is drawn at zero. `fill: false` leaves the body's fill to the caller, for a card whose parts tint their own slices of it. @@ -3611,7 +3613,8 @@ The box is in card units: `x` and `y` are its top-left corner. cardCornerRadius: 6 ``` -The corner radius of a graph card's shape, in card units: the footer band's bottom corners follow it. +The corner radius a graph card's shape is drawn with, in card units, where the theme's radius (`rx` in CSS, +`--projections-radius`) doesn't reach: a shape's CSS `rx` wins over it. ### `CardGrid` diff --git a/packages/renderers/harness/browser/corners.spec.ts b/packages/renderers/harness/browser/corners.spec.ts new file mode 100644 index 00000000..d3f8637e --- /dev/null +++ b/packages/renderers/harness/browser/corners.spec.ts @@ -0,0 +1,118 @@ +import {expect, test} from '@playwright/test' +import type {CornerReport} from '@githubnext/projections-renderer-testing/playwright' +import {cornerReport, openStage} from '@githubnext/projections-renderer-testing/playwright' +import {harnessInspector} from '@githubnext/projections-renderer-harness/playwright' + +/** + * Rounded corners, in pixels (see `cornerReport`): a bordered container's border keeps its thickness around each + * curve, and nothing it holds paints over its border or outside its curve. Nested radii are concentric: a header band, + * a last changed row or a card's change edge takes its container's radius less the inset. + */ +test.use({deviceScaleFactor: 2}) + +async function attachPictures(report: CornerReport, label: string) { + for (const [name, url] of Object.entries(report.pictures ?? {})) + await test.info().attach(`${label} ${name}.png`, {body: Buffer.from(url.split(',')[1]!, 'base64'), contentType: 'image/png'}) +} + +const cases = [ + {what: "a section's header band", scenario: 'runtime-policy/token-guard', selector: '.rp-panel', text: 'Network'}, + {what: 'a group ending in a changed line', scenario: 'text-diff/cli-output-release', selector: '.text-diff-command'}, + {what: "a workflow group's header band", scenario: 'agentic-workflows/docs-bot', selector: '.aw-group'}, + {what: "a card's change edge and status band", scenario: 'dependency-injection/nestjs-orders', selector: 'rect.node-emphasis-edge.added'}, +] as const + +for (const colorMode of ['light', 'dark'] as const) { + for (const {what, scenario, selector, ...rest} of cases) { + test(`${scenario}: ${what} keeps the border's corners whole (${colorMode})`, async ({page}, info) => { + test.skip(!info.project.name.endsWith('desktop'), 'Corners measure the same at every width.') + const stage = await openStage(page, harnessInspector(), {scenario, progress: 1, comparisonMode: 'diff', colorMode}) + await stage.measure('settle') + let target = stage.frame.locator(selector) + if ('text' in rest) target = target.filter({hasText: rest.text}) + const report = await cornerReport(page, target.first(), {label: selector}) + await attachPictures(report, selector) + expect(report.corners.length, 'corners measured').toBeGreaterThan(0) + expect(report.failures).toEqual([]) + }) + } +} + +/** + * Table frames: a data table's frame, which its heading and rows draw (`frame`: the line's width), and a database + * card's, its inset outline over its header band and rows; each at rest, then with the row in its bottom corners (or + * its first row) selected and hovered, whose ring and hue reach those corners. + */ +const tables = [ + {what: "a data table's frame", scenario: 'code-statistics/gateway-table', selector: '.pk-table-scroll', frame: 1, rows: '.pk-table-row'}, + { + what: "a database table's card", + scenario: 'database/prisma-shop', + selector: '.database-table:not(.database-enum-card):has(> header)', + rows: '.database-column[data-entity-id]', + }, +] as const + +for (const colorMode of ['light', 'dark'] as const) { + for (const {what, scenario, selector, rows, ...rest} of tables) { + test(`${scenario}: ${what} keeps its corners whole at rest, selected and hovered (${colorMode})`, async ({page}, info) => { + test.skip(!info.project.name.endsWith('desktop'), 'Corners measure the same at every width.') + const stage = await openStage(page, harnessInspector(), {scenario, progress: 1, comparisonMode: 'diff', colorMode}) + await stage.measure('settle') + const target = stage.frame.locator(selector).first() + const options = {label: selector, ...('frame' in rest ? {frame: rest.frame} : {})} + const ids = await target.evaluate((element, rows) => { + const all = [...element.querySelectorAll(rows)].filter(row => row.getAttribute('data-entity-id')) + const bottom = [...all].sort((a, b) => b.getBoundingClientRect().bottom - a.getBoundingClientRect().bottom) + return [...new Set([all[0], bottom[0]].filter(row => row !== undefined).map(row => row.getAttribute('data-entity-id')!))] + }, rows as string) + expect(ids.length, 'rows to ring').toBeGreaterThan(0) + const states: [string, () => Promise][] = [ + ['at rest', async () => {}], + ...ids.flatMap((id): [string, () => Promise][] => [ + [`${id} selected`, () => stage.select(id)], + [`${id} hovered`, async () => (await stage.select(null), await stage.hover(id))], + ]), + ] + for (const [state, enter] of states) { + await enter() + await stage.measure('settle') + const report = await cornerReport(page, target, {...options, label: `${selector} ${state}`}) + await attachPictures(report, `${selector} ${state}`) + expect(report.corners.length, `${state}: corners measured`).toBeGreaterThan(0) + expect(report.failures).toEqual([]) + } + await stage.hover(null) + }) + } +} + +test("the report finds a data table's square heading poking past its frame", async ({page}, info) => { + test.skip(info.project.name !== 'chromium-desktop', 'One engine shows the report reads the pictures.') + const stage = await openStage(page, harnessInspector(), {scenario: 'code-statistics/gateway-table', progress: 1, comparisonMode: 'diff'}) + await stage.measure('settle') + await stage.frame.locator('head').evaluate(head => { + const style = document.createElement('style') + style.textContent = + '.pk .pk-table > .pk-table-head, .pk .pk-table > .pk-table-head > .pk-table-cell:first-child { border-radius: 0 !important }' + head.append(style) + }) + await stage.measure('settle') + const report = await cornerReport(page, stage.frame.locator('.pk-table-scroll').first(), {frame: 1}) + expect(report.failures.some(failure => /^box top-left corner/.test(failure))).toBe(true) + expect(report.failures.some(failure => /^box top-right corner/.test(failure))).toBe(true) +}) + +test('the report finds a square header band covering its group border', async ({page}, info) => { + test.skip(info.project.name !== 'chromium-desktop', 'One engine shows the report reads the pictures.') + const stage = await openStage(page, harnessInspector(), {scenario: 'runtime-policy/token-guard', progress: 1, comparisonMode: 'diff'}) + await stage.measure('settle') + await stage.frame.locator('head').evaluate(head => { + const style = document.createElement('style') + style.textContent = '.pk .pk-group-header { border-radius: 0 !important }' + head.append(style) + }) + await stage.measure('settle') + const report = await cornerReport(page, stage.frame.locator('.rp-panel').filter({hasText: 'Network'}).first()) + expect(report.failures.filter(failure => /^box top-(left|right) corner at 45°: the border is/.test(failure))).toHaveLength(2) +}) diff --git a/packages/renderers/kit/src/react/graph-canvas/card-change.tsx b/packages/renderers/kit/src/react/graph-canvas/card-change.tsx index cdee15c7..20679946 100644 --- a/packages/renderers/kit/src/react/graph-canvas/card-change.tsx +++ b/packages/renderers/kit/src/react/graph-canvas/card-change.tsx @@ -1,18 +1,23 @@ // A card's change marks in a comparison: its tinted fill and change edge, and its status footer band. +import {useId} from 'react' import {cardTextMetrics} from '../../card-text.js' import {SvgChangeStatus} from '../components.js' import type {ChangeClassification, StatusPart} from '../../emphasis.js' import {cardFooterHeight} from '../../layout.js' -import {footerBand} from './cards.js' -/** The corner radius of a graph card's shape, in card units: the footer band's bottom corners follow it. */ +/** + * The corner radius a graph card's shape is drawn with, in card units, where the theme's radius (`rx` in CSS, + * `--projections-radius`) doesn't reach: a shape's CSS `rx` wins over it. + */ export const cardCornerRadius = 6 /** * A changed card's marks, as every kit card draws them: the card filled with its change's soft hue under a strong - * edge of the same hue (inset by `inset`, see `emphasisInset`), and a footer band `footer` tall across its bottom, - * ruled off from the body, holding the status words centred (see `SvgChangeStatus`). The edge is drawn again over - * the band, so the band never covers the border or its corners. Draw it over the card's surface and under its text; + * edge of the same hue (inset by `inset`, see `emphasisInset`, with its radius less the inset, so it is concentric with + * the card's border), and a footer band `footer` tall across its bottom, ruled off from the body, holding the status + * words centred (see `SvgChangeStatus`). The band is clipped to the card's shape (`node-card-shape`, rounded as the + * card's surface is), so its corners follow the card's, and the edge is drawn again over it, so the band never covers + * the border or pokes outside its corners. Draw it over the card's surface and under its text; * everything fades with `emphasis`, and nothing is drawn at zero. `fill: false` leaves the body's fill to the * caller, for a card whose parts tint their own slices of it. * @@ -47,14 +52,26 @@ export function CardChangeMarks({ footer?: number fill?: boolean }) { + const shape = useId() if (emphasis <= 0.01) return null const bottom = y + height const rule = bottom - footer - const edge = {x: x + inset, y: y + inset, width: width - 2 * inset, height: height - 2 * inset, rx: cardCornerRadius} + const edge = {x: x + inset, y: y + inset, width: width - 2 * inset, height: height - 2 * inset, rx: Math.max(0, cardCornerRadius - inset)} return ( <> {fill && } - + + + + )} diff --git a/packages/renderers/kit/styles/graph.css b/packages/renderers/kit/styles/graph.css index be4088c3..09197f94 100644 --- a/packages/renderers/kit/styles/graph.css +++ b/packages/renderers/kit/styles/graph.css @@ -86,13 +86,24 @@ .graph-group .node-surface { rx: var(--projections-radius-lg); } +/* + * A change edge is inset so its outer edge is the plain border's (`emphasisInset`: half the difference of the two + * strokes), and its radius is the card's less that inset, so its curve is concentric with the border's. A card's shape + * (`node-card-shape`, which a change band is clipped to) is the card's surface without its stroke. + */ +.pk { + --pk-emphasis-inset: max(0px, calc((var(--stroke-strong) - var(--stroke)) / 2)); +} .node-emphasis { pointer-events: none; stroke-width: var(--stroke-strong); - rx: var(--projections-radius); + rx: max(0px, calc(var(--projections-radius) - var(--pk-emphasis-inset))); } .graph-group .node-emphasis { - rx: var(--projections-radius-lg); + rx: max(0px, calc(var(--projections-radius-lg) - var(--pk-emphasis-inset))); +} +.node-card-shape { + rx: var(--projections-radius); } .node-emphasis.added { fill: var(--green-soft); diff --git a/packages/renderers/kit/styles/layout.css b/packages/renderers/kit/styles/layout.css index a2e26788..41fa93b2 100644 --- a/packages/renderers/kit/styles/layout.css +++ b/packages/renderers/kit/styles/layout.css @@ -16,9 +16,15 @@ * title in a header band inside its edge. The band holds one line: the title, which truncates with an ellipsis, muted * meta, then actions and the status cell at its end (`--pk-status-width`, reserved on every group in a comparison). * It clips to its outer edge (`clip-path`), not inside its border as `overflow` would, so a change region at its edge - * draws its own edge over the group's: one line there, in the change's hue. + * draws its own edge over the group's: one line there, in the change's hue. Where the browser can, it clips with + * `overflow: clip` instead, its margin the border's width: the same outer edge, but snapped to whole pixels with the + * border, where a `clip-path` isn't and would cut off part of a border on a fractional edge. Its children's paint is + * not clipped inside the border, so what reaches a corner takes the inner radius (`--pk-group-inner-radius`, the radius + * less the border), concentric with the border, and never covers it: the header band its top corners, and a + * renderer's last row or band its bottom ones. */ .pk .pk-group { + --pk-group-inner-radius: max(0px, calc(var(--projections-radius) - var(--projections-border-width))); display: flow-root; min-width: 0; border: var(--projections-border-width) solid var(--divider); @@ -26,6 +32,13 @@ background: var(--raised); clip-path: inset(0 round var(--projections-radius)); } +@supports (overflow-clip-margin: 1px) { + .pk .pk-group { + clip-path: none; + overflow: clip; + overflow-clip-margin: var(--projections-border-width); + } +} .pk .pk-content-view > .pk-group + .pk-group { margin-top: var(--projections-space-3); } @@ -37,6 +50,8 @@ padding: var(--projections-space-1) var(--projections-space-3); background: var(--band); border-bottom: var(--projections-border-width) solid var(--divider); + border-start-start-radius: var(--pk-group-inner-radius); + border-start-end-radius: var(--pk-group-inner-radius); } .pk .pk-group-title { display: flex; diff --git a/packages/renderers/testing/README.md b/packages/renderers/testing/README.md index 688a0b87..a0317204 100644 --- a/packages/renderers/testing/README.md +++ b/packages/renderers/testing/README.md @@ -223,6 +223,26 @@ with a capital H and check that the space above the E, below it, left of its stem and right of the H's right stem match. Take it at a device scale of 2 or more, and divide by the drawing's own scale when it is zoomed or fitted. +## Corners in pixels + +`cornerReport(page, target, {label, frame})` checks a bordered box's rounded +corners in pictures of them: the border keeps its thickness around each curve, +within a quarter CSS px plus half a device pixel of its sides (or between them, +where the sides differ), no third color shows in it and no paint shows outside +the curve. That is what a filled band in a rounded container breaks when it +isn't concentric with it: a header, footer or last changed row with square +corners covers the inside of the border's curve, and one with the container's +own radius pokes out past it. Nested radii are the container's less the inset. +The `target` is a locator (an element's border box, radii and solid borders, its +solid outline where it has no border, or an SVG `rect`'s stroked outline, read +by `cornerBox`) or a `CornerBox` of your own. For a frame its contents draw (a +data table's scroll box, whose heading and rows draw its lines), pass `frame`, +the line's width; each corner is measured where its sides are painted, since a +browser may snap a border to whole pixels, and a box taller than the view is +scrolled for its top and then its bottom corners. Dashed outlines and corners no +larger than their border are skipped. Take the page at a device scale of 2 or +more; failing corners' pictures come back in `pictures`, to attach. + ## Your own assertions ```ts diff --git a/packages/renderers/testing/playwright/corners.ts b/packages/renderers/testing/playwright/corners.ts new file mode 100644 index 00000000..109ccfd4 --- /dev/null +++ b/packages/renderers/testing/playwright/corners.ts @@ -0,0 +1,226 @@ +/* + * Rounded corners, checked in pixels: a bordered box's border keeps its thickness around each curve, and nothing + * inside it paints over the border or outside its curve. A filled band in a rounded container (a header, a footer, a + * change row at its edge) must follow the container's inner radius (its outer radius less the border), or be clipped + * to it; one with square corners covers the inside of the border's curve, and the border thins there. + */ +import type {Locator, Page} from '@playwright/test' +import type {CornerMeasure, CornerProbe} from './corners/analyze.js' +import {measureCorners} from './corners/analyze.js' + +export type {CornerMeasure, CornerProbe, CornerRay, CornerSide} from './corners/analyze.js' + +/** A bordered box with rounded corners, by its outer edge in page CSS px. */ +export interface CornerBox { + left: number + top: number + right: number + bottom: number + /** Outer radii: top-left, top-right, bottom-right, bottom-left. */ + radii: [number, number, number, number] + /** Border widths: top, right, bottom, left. */ + borders: [number, number, number, number] +} + +/** What `cornerReport` found: each corner's measures and, for a corner out of line, why. */ +export interface CornerReport { + corners: CornerMeasure[] + failures: string[] + /** With failures, each failing corner's picture (a PNG data URL), to attach. */ + pictures?: {[corner: string]: string} +} + +/** + * The box a locator draws, scrolled into view (`align`: its top or its bottom edge first, for a box taller than the + * view): an element's border box, radii and solid border widths, or its solid outline where it has no border (an edge + * drawn inside its box with a negative `outline-offset`, as database cards do), or an SVG `rect`'s stroked outline (its + * stroke centred on its edge; none when dashed). `frame` is the width of an edge its contents draw instead, along its + * rounded edge: a data table's scroll box, whose rows draw its lines. `null` when it has no rounded, edged corner. + */ +export async function cornerBox( + locator: Locator, + {align, frame}: {align?: 'start' | 'end'; frame?: number} = {}, +): Promise { + if (align) { + await locator.evaluate((element, block) => element.scrollIntoView({block, inline: 'nearest'}), align) + // With room past the edge for its corners' pictures, scrolling the host page too: a sandboxed frame as tall as its + // content can't scroll it (WebKit). + const placed = await locator.boundingBox() + const view = locator.page().viewportSize() + const room = 24 + if (placed && view) { + const by = align === 'start' ? placed.y - room : placed.y + placed.height + room - view.height + await locator.page().evaluate(by => window.scrollBy(0, by), by) + } + } else await locator.scrollIntoViewIfNeeded() + const box = await locator.boundingBox() + if (!box) return null + const drawn = await locator.evaluate((element, frame) => { + const style = getComputedStyle(element) + const rect = element.getBoundingClientRect() + if (element instanceof SVGRectElement) { + const matrix = element.getScreenCTM() + const unit = matrix ? Math.hypot(matrix.a, matrix.b) : 1 + // A dashed outline has no thickness to keep around its curve. + const stroke = style.stroke === 'none' || style.strokeDasharray !== 'none' ? 0 : parseFloat(style.strokeWidth) * unit + // CSS `rx` wins where it applies, `0px` included; the attribute only where it is `auto` or unset. + const css = parseFloat(style.getPropertyValue('rx')) + const rx = Number.isNaN(css) ? element.rx.baseVal.value : css + return { + svg: true, + width: rect.width, + height: rect.height, + radii: [rx, rx, rx, rx].map(r => r * unit), + borders: [stroke, stroke, stroke, stroke], + outset: 0, + } + } + const radius = (value: string) => + value.endsWith('%') ? (parseFloat(value) / 100) * Math.min(rect.width, rect.height) : parseFloat(value) || 0 + // Its layout width, before any transform on it or its ancestors, so the scale below takes them in. + const laid = element instanceof HTMLElement && element.offsetWidth ? element.offsetWidth : rect.width + const radii = [style.borderTopLeftRadius, style.borderTopRightRadius, style.borderBottomRightRadius, style.borderBottomLeftRadius].map( + radius, + ) + const borders = (['top', 'right', 'bottom', 'left'] as const).map(side => + style.getPropertyValue(`border-${side}-style`) === 'solid' ? parseFloat(style.getPropertyValue(`border-${side}-width`)) : 0, + ) + if (frame !== undefined) return {svg: false, width: laid, height: rect.height, radii, borders: [frame, frame, frame, frame], outset: 0} + const outline = style.outlineStyle === 'solid' ? parseFloat(style.outlineWidth) : 0 + if (borders.some(width => width > 0) || !outline) return {svg: false, width: laid, height: rect.height, radii, borders, outset: 0} + // An outline's outer edge lies its offset plus its width outside the box, and its corners follow the radii there. + const outset = parseFloat(style.outlineOffset) + outline + return {svg: false, width: laid, height: rect.height, radii, borders: [outline, outline, outline, outline], outset} + }, frame) + // How much it is scaled, by a transform on it, an ancestor or the host's frame (a transformed stage): the box in the + // page against its own layout box (an SVG rect's is already in screen units). + const scale = drawn.width ? box.width / drawn.width : 1 + const inflate = drawn.svg ? drawn.borders[0]! / 2 : drawn.outset + const left = box.x - inflate * scale, + top = box.y - inflate * scale + const width = box.width + 2 * inflate * scale, + height = box.height + 2 * inflate * scale + let radii = drawn.radii.map(r => (r > 0 ? Math.max(0, r + inflate) : 0) * scale) as CornerBox['radii'] + // As a browser does, scale every radius down when two on a side overlap. + const fit = Math.min( + 1, + width / (radii[0] + radii[1] || 1), + width / (radii[3] + radii[2] || 1), + height / (radii[0] + radii[3] || 1), + height / (radii[1] + radii[2] || 1), + ) + radii = radii.map(r => r * fit) as CornerBox['radii'] + const borders = drawn.borders.map(b => b * scale) as CornerBox['borders'] + if (!radii.some(r => r >= 2) || !borders.some(b => b > 0)) return null + return {left, top, right: left + width, bottom: top + height, radii, borders} +} + +const names = ['top-left', 'top-right', 'bottom-right', 'bottom-left'] as const + +/** Where to picture each of a box's corners, and how to measure it there. */ +function cornerProbes( + box: CornerBox, + corners: number[], + viewport: {width: number; height: number} | null, +): {clip: {x: number; y: number; width: number; height: number}; probe: Omit}[] { + const probes: {clip: {x: number; y: number; width: number; height: number}; probe: Omit}[] = [] + for (const index of corners) { + const name = names[index]! + const radius = box.radii[index]! + const vertical = box.borders[index === 0 || index === 3 ? 3 : 1], + horizontal = box.borders[index < 2 ? 0 : 2] + if (!vertical || vertical !== horizontal || radius < vertical + 1) continue + const width = vertical + const out = {x: index === 0 || index === 3 ? -1 : 1, y: index < 2 ? -1 : 1} + const cornerX = out.x < 0 ? box.left : box.right, + cornerY = out.y < 0 ? box.top : box.bottom + // On each side, a point past the curve (or the side's middle on a short side), with the inward normal there. + const alongY = Math.min(radius + 3, (box.bottom - box.top) / 2), + alongX = Math.min(radius + 3, (box.right - box.left) / 2) + const sides: CornerProbe['sides'] = [ + {x: cornerX, y: cornerY - out.y * alongY, nx: -out.x, ny: 0}, + {x: cornerX - out.x * alongX, y: cornerY, nx: 0, ny: -out.y}, + ] + const reach = Math.max(radius, alongX, alongY) + width + 4 + const x = Math.floor(out.x < 0 ? cornerX - 5 : cornerX - reach), + y = Math.floor(out.y < 0 ? cornerY - 5 : cornerY - reach) + const clip = {x, y, width: Math.ceil(reach + 5), height: Math.ceil(reach + 5)} + if (viewport && (clip.x < 0 || clip.y < 0 || clip.x + clip.width > viewport.width || clip.y + clip.height > viewport.height)) continue + probes.push({ + clip, + probe: { + name, + origin: {x: clip.x, y: clip.y}, + centre: {x: cornerX - out.x * radius, y: cornerY - out.y * radius}, + out, + radius, + width, + sides, + }, + }) + } + return probes +} + +/** + * Measures a box's rounded corners in pixels and returns what is wrong with them: a border that thins or thickens + * around a curve against its own sides, a third colour inside it (a fill that isn't concentric with it) or paint + * outside the curve. Corners need the same border on both their sides and a radius larger than it; others are skipped. Take the page at a device scale of 2 or more for a precise measure. + */ +export async function cornerReport( + page: Page, + target: Locator | CornerBox, + {label = 'box', frame}: {label?: string; frame?: number} = {}, +): Promise { + const scale = await page.evaluate(() => devicePixelRatio) + const probes: CornerProbe[] = [] + // A locator's top corners, then its bottom ones, each pair in view in turn, so a box taller than the view is measured. + const passes: [() => Promise, number[]][] = + 'left' in target + ? [[async () => target, [0, 1, 2, 3]]] + : [ + [() => cornerBox(target, {align: 'start', ...(frame === undefined ? {} : {frame})}), [0, 1]], + [() => cornerBox(target, {align: 'end', ...(frame === undefined ? {} : {frame})}), [2, 3]], + ] + for (const [find, corners] of passes) { + const box = await find() + if (!box) continue + for (const {clip, probe} of cornerProbes(box, corners, page.viewportSize())) { + const buffer = await page.screenshot({clip, animations: 'disabled', caret: 'hide', scale: 'device'}) + probes.push({...probe, url: `data:image/png;base64,${buffer.toString('base64')}`}) + } + } + const corners = await page.evaluate(measureCorners, [probes, scale] as [CornerProbe[], number]) + const failing = corners.map(corner => cornerFailures(corner, scale, label)) + const failures = failing.flat() + if (!failures.length) return {corners, failures} + const pictures = Object.fromEntries(probes.filter((_, index) => failing[index]!.length).map(probe => [probe.name, probe.url])) + return {corners, failures, pictures} +} + +/** + * Within a quarter CSS pixel, plus half a device pixel of antialiasing, of its sides; between them where they differ + * (a change run's strong side edge turning into a plain bottom border). + */ +function cornerFailures(corner: CornerMeasure, scale: number, label: string): string[] { + const tolerance = 0.25 + 0.5 / scale + // A colour this far from every blend of outside, border and inside, or from the outside past the curve. + const stray = 60 + const sides = corner.sides.filter((side): side is number => side !== null) + const failures: string[] = [] + for (const ray of corner.rays) { + const at = `${label} ${corner.name} corner at ${ray.angle}°` + if (ray.thickness !== null && sides.length) { + const low = Math.min(...sides) - tolerance, + high = Math.max(...sides) + tolerance + if (ray.thickness < low || ray.thickness > high) + failures.push( + `${at}: the border is ${ray.thickness.toFixed(2)} px around the curve but ${sides.map(side => side.toFixed(2)).join(' and ')} px on its sides`, + ) + } + if (ray.foreign > stray) + failures.push(`${at}: a colour that is neither the border nor what it edges shows in the border (a fill not concentric with it)`) + if (ray.outside > stray) failures.push(`${at}: paint shows outside the curve`) + } + return failures +} diff --git a/packages/renderers/testing/playwright/corners/analyze.ts b/packages/renderers/testing/playwright/corners/analyze.ts new file mode 100644 index 00000000..2fc9477d --- /dev/null +++ b/packages/renderers/testing/playwright/corners/analyze.ts @@ -0,0 +1,157 @@ +// The pixel analysis of a rounded corner, which runs in the page: it must stay self-contained. + +/** A point on one of a corner's straight sides, clear of its curve, and the inward normal there. */ +export interface CornerSide { + x: number + y: number + nx: number + ny: number +} + +/** One corner of a bordered box and its picture, in page CSS px. */ +export interface CornerProbe { + name: string + url: string + /** The picture's top-left corner. */ + origin: {x: number; y: number} + /** The centre of the corner's outer arc. */ + centre: {x: number; y: number} + /** Which way the corner points: -1 or 1 on each axis. */ + out: {x: number; y: number} + radius: number + width: number + /** The vertical side, then the horizontal one. */ + sides: [CornerSide, CornerSide] +} + +/** One ray across a corner's curve, from its arc's centre outward: what crosses the border there. */ +export interface CornerRay { + /** Degrees from the vertical side (0) to the horizontal one (90). */ + angle: number + /** The border's thickness across the curve there, in CSS px (null where it is too faint to measure). */ + thickness: number | null + /** The largest difference from any blend of outside, border and inside: a third colour in the border. */ + foreign: number + /** The largest difference from the outside past the outer curve: paint outside the corner. */ + outside: number +} + +/** A corner's border measured in pixels, on its two sides and along rays around its curve. */ +export interface CornerMeasure { + name: string + /** The border's thickness on the vertical and horizontal side (null where it is too faint to measure). */ + sides: [number | null, number | null] + rays: CornerRay[] +} + +/** Measures each corner's border across its curve and on its sides; runs in a page. */ +export function measureCorners([probes, scale]: [CornerProbe[], number]): Promise { + type Rgb = [number, number, number] + type Picture = {width: number; height: number; data: Uint8ClampedArray} + const load = async (url: string): Promise => { + const image = new Image() + image.src = url + await image.decode() + const canvas = document.createElement('canvas') + canvas.width = image.naturalWidth + canvas.height = image.naturalHeight + const context = canvas.getContext('2d', {willReadFrequently: true})! + context.drawImage(image, 0, 0) + return {width: canvas.width, height: canvas.height, data: context.getImageData(0, 0, canvas.width, canvas.height).data} + } + const sample = (picture: Picture, origin: {x: number; y: number}, x: number, y: number): Rgb => { + // Bilinear, in device pixels, at pixel centres. + const fx = (x - origin.x) * scale - 0.5, + fy = (y - origin.y) * scale - 0.5 + const x0 = Math.max(0, Math.min(picture.width - 1, Math.floor(fx))), + y0 = Math.max(0, Math.min(picture.height - 1, Math.floor(fy))) + const x1 = Math.min(picture.width - 1, x0 + 1), + y1 = Math.min(picture.height - 1, y0 + 1) + const tx = Math.max(0, Math.min(1, fx - x0)), + ty = Math.max(0, Math.min(1, fy - y0)) + const at = (px: number, py: number, channel: number) => picture.data[(py * picture.width + px) * 4 + channel]! + return [0, 1, 2].map( + channel => + at(x0, y0, channel) * (1 - tx) * (1 - ty) + + at(x1, y0, channel) * tx * (1 - ty) + + at(x0, y1, channel) * (1 - tx) * ty + + at(x1, y1, channel) * tx * ty, + ) as Rgb + } + const distance = (a: Rgb, b: Rgb) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) + // How far a colour is along a segment (0 at its start, 1 at its end) and how far off it. + const along = (p: Rgb, from: Rgb, to: Rgb) => { + const d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]] as Rgb + const length = d[0] ** 2 + d[1] ** 2 + d[2] ** 2 + const projected = length ? ((p[0] - from[0]) * d[0] + (p[1] - from[1]) * d[1] + (p[2] - from[2]) * d[2]) / length : 0 + const t = Math.max(0, Math.min(1, projected)) + return {t, off: distance(p, [from[0] + d[0] * t, from[1] + d[1] * t, from[2] + d[2] * t])} + } + // How much of a colour is border, between the outside and the inside, and how far it is from any such blend. + const membership = (p: Rgb, outside: Rgb, border: Rgb, inside: Rgb) => { + const outer = along(p, outside, border), + inner = along(p, border, inside) + return outer.off <= inner.off ? {weight: outer.t, off: outer.off} : {weight: 1 - inner.t, off: inner.off} + } + // Too little contrast between the border and either neighbour to tell how much of a pixel it covers. + const faint = 40 + const step = 0.25 / scale + return Promise.all(probes.map(async probe => ({probe, picture: await load(probe.url)}))).then(loaded => + loaded.map(({probe, picture}) => { + const at = (x: number, y: number) => sample(picture, probe.origin, x, y) + const {radius, width} = probe + // Each side's painted edge (a browser may snap a box's edges to whole pixels), outside (just past its antialiasing: + // a neighbour may be a pixel or two away), border and thickness. + const sides = probe.sides.map(side => { + const point = (t: number) => at(side.x + side.nx * t, side.y + side.ny * t) + const far = point(-1.75) + let border = far + for (let t = -1; t <= width + 1; t += step) if (distance(point(t), far) > distance(border, far)) border = point(t) + const contrast = distance(border, far) + let edge = 0 + for (let t = -1.75; t <= width + 1; t += step) + if (distance(point(t), far) >= contrast / 2) { + edge = t + break + } + const outside = point(edge - 0.75), + inside = point(edge + width + 1.5) + border = point(edge + width / 2) + if (contrast < faint || distance(border, outside) < faint || distance(border, inside) < faint) + return {edge, outside, border, thickness: null} + let thickness = 0 + for (let t = edge - 1; t <= edge + width + 1.5; t += step) thickness += membership(point(t), outside, border, inside).weight * step + return {edge, outside, border, thickness} + }) + // The arc's centre, moved with its sides' painted edges. + const centre = {x: probe.centre.x + probe.sides[0].nx * sides[0]!.edge, y: probe.centre.y + probe.sides[1].ny * sides[1]!.edge} + const rays = [10, 25, 45, 65, 80].map(angle => { + const radians = (angle * Math.PI) / 180 + const dx = probe.out.x * Math.cos(radians), + dy = probe.out.y * Math.sin(radians) + const point = (t: number) => at(centre.x + dx * t, centre.y + dy * t) + const start = Math.max(0, radius - width - 1.5) + // Past the outer curve, but inside the box's square corner: what is there is the box's own paint. + const end = Math.max(radius + 0.5, Math.min(radius + 4, radius * Math.SQRT2 - 0.5)) + const inside = point(start) + const nearest = angle < 45 ? [sides[0]!] : angle > 45 ? [sides[1]!] : sides + const measures = nearest.map(side => { + let thickness = 0, + foreign = 0, + outside = 0 + for (let t = start; t <= end; t += step) { + const p = point(t) + const {weight, off} = membership(p, side.outside, side.border, inside) + thickness += weight * step + if (t <= radius) foreign = Math.max(foreign, off) + else if (t > radius + 1 / scale) outside = Math.max(outside, Math.min(...sides.map(other => distance(p, other.outside)))) + } + const measurable = side.thickness !== null && distance(side.border, inside) >= faint + return {angle, thickness: measurable ? thickness : null, foreign, outside} + }) + return measures.reduce((best, next) => (next.foreign < best.foreign ? next : best)) + }) + return {name: probe.name, sides: [sides[0]!.thickness, sides[1]!.thickness] as [number | null, number | null], rays} + }), + ) +} diff --git a/packages/renderers/testing/playwright/index.ts b/packages/renderers/testing/playwright/index.ts index 3f45e5fe..6ce2cd1c 100644 --- a/packages/renderers/testing/playwright/index.ts +++ b/packages/renderers/testing/playwright/index.ts @@ -247,3 +247,4 @@ export {ringGeometry} from './rings/geometry.js' export * from './rings.js' export {opticalInsets} from './optical.js' export type {OpticalInsets} from './optical.js' +export * from './corners.js' diff --git a/packages/renderers/text-diff/src/styles.css b/packages/renderers/text-diff/src/styles.css index f8c1db63..564cdba3 100644 --- a/packages/renderers/text-diff/src/styles.css +++ b/packages/renderers/text-diff/src/styles.css @@ -41,6 +41,23 @@ .text-diff-command > .td-body:last-child { margin-bottom: calc(-1 * var(--projections-border-width)); padding-bottom: var(--projections-border-width); + border-end-start-radius: var(--projections-radius); + border-end-end-radius: var(--projections-radius); +} +/* + * At the card's end the body's corners are the card's, so it clips what it holds to the card's curve. What fills its + * last line takes the card's inner radius there (kit `--pk-group-inner-radius`), concentric with the card's border, so + * it never covers it: the row in one column, each side of the pair in two, and the gutter that starts either. + */ +.text-diff-command > .td-body:last-child > * > .td-row:last-child, +.text-diff-command > .td-body:last-child > * > .td-row:last-child > .td-num:first-child, +.text-diff-command > .td-body:last-child > * > .td-pair:last-child > .td-side-before, +.text-diff-command > .td-body:last-child > * > .td-pair:last-child > .td-side-before > .td-num:first-child { + border-end-start-radius: var(--pk-group-inner-radius); +} +.text-diff-command > .td-body:last-child > * > .td-row:last-child, +.text-diff-command > .td-body:last-child > * > .td-pair:last-child > .td-side-after { + border-end-end-radius: var(--pk-group-inner-radius); } .td-body[data-presentation='formatted'] { font-family: var(--font-mono);