Skip to content

Commit b6511ce

Browse files
DOT Graph edge labels now easier to see in dark mode
1 parent 3a2b7af commit b6511ce

4 files changed

Lines changed: 250 additions & 11 deletions

File tree

‎AGENTS.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,12 @@ coverage there when introducing new markup patterns.
158158
SVGs' embedded black strokes/fills are likewise re-themed to
159159
`--graph-line` (`#9fb0c0` dark = `CHART_LEGEND_TEXT.dark`) via
160160
`path[stroke]`/`polygon` selectors on `.fullscreen-svg` — red cycle
161-
edges stay red.
161+
edges stay red. Edge labels are glyph paths baked by vizdom, so CSS
162+
can't reach them: `withEdgeFontColor` in `lib/report-view.js` rewrites
163+
the DOT with `fontcolor = "#9fb0c0"` per edge when the dark palette
164+
is active (vizdom uppercases the hex in the SVG), and theme switches
165+
re-parse the graphs via `redrawGraphsForTheme` alongside the chart
166+
legend redraw in `bindThemeChartRedraw`.
162167

163168
## Report Tables (Enhanced)
164169

‎lib/report-view.js‎

Lines changed: 71 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -482,9 +482,13 @@ export function bindThemeChartRedraw() {
482482
const doc = typeof document === 'undefined' ? null : document;
483483
if (!doc || doc.documentElement.hasAttribute('data-rf-theme-redraw-bound')) return;
484484
doc.documentElement.setAttribute('data-rf-theme-redraw-bound', '');
485+
const redrawForTheme = () => {
486+
redrawChartsForTheme();
487+
redrawGraphsForTheme();
488+
};
485489
doc.addEventListener('change', event => {
486490
const target = event.target;
487-
if (target && target.name === 'rf-theme') redrawChartsForTheme();
491+
if (target && target.name === 'rf-theme') redrawForTheme();
488492
});
489493
if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
490494
try {
@@ -493,9 +497,9 @@ export function bindThemeChartRedraw() {
493497
// engines that never grew the modern one.
494498
systemThemeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
495499
if (systemThemeMediaQuery && typeof systemThemeMediaQuery.addEventListener === 'function') {
496-
systemThemeMediaQuery.addEventListener('change', redrawChartsForTheme);
500+
systemThemeMediaQuery.addEventListener('change', redrawForTheme);
497501
} else if (systemThemeMediaQuery && typeof systemThemeMediaQuery.addListener === 'function') {
498-
systemThemeMediaQuery.addListener(redrawChartsForTheme);
502+
systemThemeMediaQuery.addListener(redrawForTheme);
499503
}
500504
} catch {
501505
// Older engines without MQL listeners: explicit radios still redraw.
@@ -611,6 +615,68 @@ export function initDisharmonyCharts(disharmonies) {
611615
// vizdom WASM graph rendering (inline, pan/zoom-able SVGs).
612616
// ---------------------------------------------------------------------------
613617

618+
/**
619+
* Appends a Graphviz `fontcolor` attribute to every edge attribute list in
620+
* a DOT string so vizdom bakes the label color into the SVG at parse time
621+
* (the default black is unreadable on the dark palette). Edges that already
622+
* carry fontcolor are left untouched; node statements have no `->` in the
623+
* matched segment and are preserved verbatim.
624+
*
625+
* @param {string} dot - DOT graph source.
626+
* @param {string} color - Graphviz color value for edge labels.
627+
* @returns {string} DOT with fontcolor appended to each labeled edge.
628+
*/
629+
export function withEdgeFontColor(dot, color) {
630+
if (typeof dot !== 'string' || !color) return dot;
631+
return dot.replace(/(->[^;[\]{}]*?\[)([^\]]*?)(\s*\])/g, (match, open, attrs, close) => {
632+
if (/fontcolor\s*=/.test(attrs)) return match;
633+
return `${open}${attrs} fontcolor = "${color}"${close}`;
634+
});
635+
}
636+
637+
// Rendered graphs keyed by container id, so a theme switch can re-parse the
638+
// dots with the new palette's edge-label color — vizdom bakes fontcolor into
639+
// the SVG at parse time, so recoloring needs a re-render, like the charts.
640+
const wasmGraphDots = new Map();
641+
642+
/**
643+
* Re-renders every live WASM graph so edge labels re-resolve against the
644+
* newly active palette. Entries whose container left the DOM (report
645+
* re-rendered or torn down) are pruned instead of redrawn.
646+
*
647+
* @returns {void}
648+
*/
649+
function redrawGraphsForTheme() {
650+
const vizdom = typeof window !== 'undefined' ? window.Vizdom : null;
651+
if (!vizdom || !vizdom.DotParser) return;
652+
const parser = new vizdom.DotParser();
653+
for (const [containerId, dotString] of wasmGraphDots) {
654+
const el = typeof document !== 'undefined' ? document.getElementById(containerId) : null;
655+
if (!el || !el.isConnected) {
656+
wasmGraphDots.delete(containerId);
657+
continue;
658+
}
659+
renderGraphInto(parser, el, containerId, dotString);
660+
}
661+
}
662+
663+
/**
664+
* Parses a dot string (recolored for the active palette) into the graph
665+
* container's innerHTML and re-wires pan/zoom on the freshly injected SVG.
666+
*/
667+
function renderGraphInto(parser, el, containerId, dotString) {
668+
const themedDot = activeChartTheme() === 'dark'
669+
? withEdgeFontColor(dotString, CHART_LEGEND_TEXT.dark)
670+
: dotString;
671+
const parsed = parser.parse(themedDot).to_directed().layout();
672+
const svg = parsed.to_svg().to_string()
673+
.replace('<svg ', '<svg class="fullscreen-svg" ');
674+
el.innerHTML = svg;
675+
if (window.svgPanZoom) {
676+
window.svgPanZoom(`#${containerId} svg`, {zoomEnabled: true, controlIconsEnabled: true});
677+
}
678+
}
679+
614680
export async function initWasmGraphs(data) {
615681
try {
616682
// The vizdom WASM module is vendored and initialized by the bridge in
@@ -622,13 +688,8 @@ export async function initWasmGraphs(data) {
622688
const renderGraph = (containerId, dotString) => {
623689
const el = document.getElementById(containerId);
624690
if (!el || !dotString) return;
625-
const parsed = parser.parse(dotString).to_directed().layout();
626-
const svg = parsed.to_svg().to_string()
627-
.replace('<svg ', '<svg class="fullscreen-svg" ');
628-
el.innerHTML = svg;
629-
if (window.svgPanZoom) {
630-
window.svgPanZoom(`#${containerId} svg`, {zoomEnabled: true, controlIconsEnabled: true});
631-
}
691+
renderGraphInto(parser, el, containerId, dotString);
692+
wasmGraphDots.set(containerId, dotString);
632693
};
633694

634695
if (data.classMap && !data.classMap.dotThresholdExceeded) {

‎tests/e2e/dark-mode.spec.js‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,43 @@ test('non-red graph edges re-tint to the dark palette, cycle edges stay red', as
171171
expect(await strokeOf(REGULAR_EDGE)).toBe('rgb(0, 0, 0)');
172172
});
173173

174+
test('graph edge labels re-tint to the dark palette, restore in light', async ({ page }) => {
175+
test.skip(test.info().project.name !== 'chromium', 'wasm-heavy check runs once');
176+
// Mock GitHub raw content so the report page never hits the network.
177+
await page.route('**/raw.githubusercontent.com/**', route => {
178+
if (route.request().url().endsWith('refactor-first.json')) {
179+
route.fulfill({ status: 200, contentType: 'application/json', body: SAMPLE_REPORT });
180+
} else {
181+
route.continue();
182+
}
183+
});
184+
await page.goto('/refactorfirst/refactorfirst/master/');
185+
// vizdom parses/lays out the graph asynchronously via WASM. Edge labels
186+
// render as glyph paths whose fill carries the DOT fontcolor.
187+
await page.waitForSelector('#classGraph svg path[stroke="black"]', { timeout: 120000 });
188+
189+
// vizdom uppercases the DOT color when it writes the SVG fill attribute.
190+
const labelFills = () => page.evaluate(() =>
191+
Array.from(document.querySelectorAll('#classGraph svg path'))
192+
.filter(p => !p.getAttribute('stroke'))
193+
.map(p => (p.getAttribute('fill') || '').toLowerCase()));
194+
195+
// Light theme: labels keep the baked-in default (no fontcolor applied).
196+
expect((await labelFills()).some(f => f === '#9fb0c0')).toBe(false);
197+
198+
await page.locator('#rf-theme-dark').check();
199+
// Dark theme: the graph re-parses with fontcolor = "#9fb0c0" on edges.
200+
await page.waitForSelector('#classGraph svg path[fill="#9FB0C0"]');
201+
const darkFills = await labelFills();
202+
expect(darkFills.filter(f => f === '#9fb0c0').length).toBeGreaterThan(0);
203+
204+
// Switching back to light re-renders with the plain dot again.
205+
await page.locator('#rf-theme-light').check();
206+
await page.waitForFunction(() =>
207+
!document.querySelector('#classGraph svg path[fill="#9FB0C0"]'));
208+
expect((await labelFills()).some(f => f === '#9fb0c0')).toBe(false);
209+
});
210+
174211
test('breadcrumbs and the toggle share one vertically centered row on report pages', async ({ page }) => {
175212
test.skip(test.info().project.name !== 'chromium', 'geometry check runs once');
176213
// Mock GitHub raw content so the report page never hits the network.

‎tests/unit/report-view.test.js‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
22
import {
33
exposeGraphDots,
4+
withEdgeFontColor,
45
initBubbleChart,
56
initDisharmonyCharts,
67
initWasmGraphs,
@@ -441,7 +442,66 @@ describe('initDisharmonyCharts', () => {
441442
});
442443
});
443444

445+
describe('withEdgeFontColor (vizdom bakes label color at parse time)', () => {
446+
it('appends fontcolor to edge statements with an attribute list', () => {
447+
const dot = 'strict digraph G {\nActiveTestSuite -> TestSuite [ label = "6" weight = "6" ];\n}';
448+
expect(withEdgeFontColor(dot, '#9fb0c0')).toBe(
449+
'strict digraph G {\nActiveTestSuite -> TestSuite [ label = "6" weight = "6" fontcolor = "#9fb0c0" ];\n}');
450+
});
451+
452+
it('appends fontcolor to every edge in the graph', () => {
453+
const dot = 'strict digraph G {\nA -> B [ label = "1" ];\nB -> C [ label = "2" ];\n}';
454+
const themed = withEdgeFontColor(dot, '#9fb0c0');
455+
expect(themed).toContain('B [ label = "1" fontcolor = "#9fb0c0" ];');
456+
expect(themed).toContain('C [ label = "2" fontcolor = "#9fb0c0" ];');
457+
});
458+
459+
it('keeps red cycle edges red while recoloring their labels', () => {
460+
const dot = 'A -> B [ label = "2" weight = "2" color = "red" ];';
461+
expect(withEdgeFontColor(dot, '#9fb0c0')).toBe(
462+
'A -> B [ label = "2" weight = "2" color = "red" fontcolor = "#9fb0c0" ];');
463+
});
464+
465+
it('respects an edge-level fontcolor already set in the dot', () => {
466+
const dot = 'A -> B [ label = "1" fontcolor = "blue" ];';
467+
expect(withEdgeFontColor(dot, '#9fb0c0')).toBe(dot);
468+
});
469+
470+
it('does not touch node statements or graph headers', () => {
471+
const dot = 'strict digraph G {\nTestSuite [ label = "TestSuite" ];\n}';
472+
expect(withEdgeFontColor(dot, '#9fb0c0')).toBe(dot);
473+
});
474+
475+
it('returns non-string input unchanged', () => {
476+
expect(withEdgeFontColor(undefined, '#9fb0c0')).toBeUndefined();
477+
expect(withEdgeFontColor('', '#9fb0c0')).toBe('');
478+
});
479+
480+
it('handles compact attribute spacing', () => {
481+
expect(withEdgeFontColor('A -> B [label = "6"];', '#abc')).toBe('A -> B [label = "6" fontcolor = "#abc"];');
482+
});
483+
});
484+
444485
describe('initWasmGraphs', () => {
486+
// Minimal DotParser stub: records the parsed dot and yields a fixed SVG.
487+
function stubVizdom() {
488+
const captured = [];
489+
window.Vizdom = {
490+
DotParser: class {
491+
parse(dot) {
492+
captured.push(dot);
493+
return {
494+
to_directed() { return this; },
495+
layout() { return this; },
496+
to_svg() { return { to_string: () => '<svg width="1"></svg>' }; }
497+
};
498+
}
499+
}
500+
};
501+
return captured;
502+
}
503+
afterEach(() => { delete window.Vizdom; delete window.matchMedia; });
504+
445505
it('resolves gracefully when the WASM loader is unavailable', async () => {
446506
document.body.innerHTML = '<div id="classGraph"></div>';
447507
// No network/WASM in tests: must resolve, not reject
@@ -453,8 +513,84 @@ describe('initWasmGraphs', () => {
453513
await initWasmGraphs({ classMap: { dot: 'x', dotThresholdExceeded: true } });
454514
expect(document.getElementById('classGraph').innerHTML).toBe('');
455515
});
516+
517+
it('parses the dot unchanged while the light palette is active', async () => {
518+
installThemeRadios('light', false);
519+
const graph = document.createElement('div');
520+
graph.id = 'classGraph';
521+
document.body.appendChild(graph);
522+
const captured = stubVizdom();
523+
const dot = 'strict digraph G {\nA -> B [ label = "6" ];\n}';
524+
await initWasmGraphs({ classMap: { dot, dotThresholdExceeded: false } });
525+
expect(captured).toEqual([dot]);
526+
});
527+
528+
it('appends fontcolor = #9fb0c0 to edge labels while the dark palette is active', async () => {
529+
installThemeRadios('dark', false);
530+
const graph = document.createElement('div');
531+
graph.id = 'classGraph';
532+
document.body.appendChild(graph);
533+
const captured = stubVizdom();
534+
const dot = 'strict digraph G {\nA -> B [ label = "6" weight = "6" ];\n}';
535+
await initWasmGraphs({ classMap: { dot, dotThresholdExceeded: false } });
536+
expect(captured).toEqual([
537+
'strict digraph G {\nA -> B [ label = "6" weight = "6" fontcolor = "#9fb0c0" ];\n}'
538+
]);
539+
expect(graph.innerHTML).toBe('<svg class="fullscreen-svg" width="1"></svg>');
540+
});
541+
542+
it('re-parses graphs with fresh label colors when a theme radio changes', async () => {
543+
installThemeRadios('light', false);
544+
document.documentElement.removeAttribute('data-rf-theme-redraw-bound');
545+
bindThemeChartRedraw();
546+
const graph = document.createElement('div');
547+
graph.id = 'classGraph';
548+
document.body.appendChild(graph);
549+
const captured = stubVizdom();
550+
const dot = 'strict digraph G {\nA -> B [ label = "6" ];\n}';
551+
await initWasmGraphs({ classMap: { dot, dotThresholdExceeded: false } });
552+
const lightParses = captured.length;
553+
expect(captured.every(d => !d.includes('fontcolor'))).toBe(true);
554+
555+
const dark = document.getElementById('rf-theme-dark');
556+
dark.checked = true;
557+
dark.dispatchEvent(new window.Event('change', { bubbles: true }));
558+
await new Promise(resolve => setTimeout(resolve, 0));
559+
expect(captured.length).toBeGreaterThan(lightParses);
560+
expect(captured[captured.length - 1]).toContain('fontcolor = "#9fb0c0"');
561+
562+
// Switching back re-renders with the plain dot again.
563+
const lightBack = document.getElementById('rf-theme-light');
564+
lightBack.checked = true;
565+
lightBack.dispatchEvent(new window.Event('change', { bubbles: true }));
566+
await new Promise(resolve => setTimeout(resolve, 0));
567+
expect(captured[captured.length - 1]).toBe(dot);
568+
});
569+
570+
it('prunes graphs whose container left the DOM on theme change', async () => {
571+
installThemeRadios('light', false);
572+
document.documentElement.removeAttribute('data-rf-theme-redraw-bound');
573+
bindThemeChartRedraw();
574+
const graph = document.createElement('div');
575+
graph.id = 'classGraph';
576+
document.body.appendChild(graph);
577+
const captured = stubVizdom();
578+
const dot = 'strict digraph G {\nA -> B [ label = "6" ];\n}';
579+
await initWasmGraphs({ classMap: { dot, dotThresholdExceeded: false } });
580+
const initial = captured.length;
581+
582+
// The re-render threw the graph container away: next theme change must
583+
// not re-parse this graph at all.
584+
graph.remove();
585+
const dark = document.getElementById('rf-theme-dark');
586+
dark.checked = true;
587+
dark.dispatchEvent(new window.Event('change', { bubbles: true }));
588+
await new Promise(resolve => setTimeout(resolve, 0));
589+
expect(captured.length).toBe(initial);
590+
});
456591
});
457592

593+
458594
describe('popup helpers', () => {
459595
beforeEach(() => {
460596
document.body.innerHTML = `

0 commit comments

Comments
 (0)