Skip to content

Commit

Permalink
fix: center small graphs
Browse files Browse the repository at this point in the history
  • Loading branch information
broofa committed Nov 22, 2021
1 parent 71c1341 commit fd5a6b6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
7 changes: 7 additions & 0 deletions css/Graph.scss
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
#graph {
&.centered {
display: flex;
align-items: center;
justify-content: center;
}

flex-grow: 1;
height: 100vh;
overflow: auto;
Expand All @@ -7,6 +13,7 @@
-webkit-user-select: none;
padding-right: var(--splitter-size);


--warning0: #f6f6e0;
--warning1: #d9d9d9;
--stub: #f00;
Expand Down
28 changes: 19 additions & 9 deletions js/Graph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -445,15 +445,26 @@ export default function Graph() {
setPane(module ? 'module' : 'graph');
}

function applyZoom(svg = $('#graph svg')[0]) {
const vb = svg?.getAttribute('viewBox')?.split(' ');

function applyZoom() {
const graphEl = $<HTMLDivElement>('#graph')[0];
const svg = $<SVGSVGElement>('#graph svg')[0];
if (!svg) return;

// Note: Not using svg.getBBox() here because (for some reason???) it's
// smaller than the actual bounding box
const vb = svg.getAttribute('viewBox')?.split(' ').map(Number);
if (!vb) return;

const [, , w, h] = vb;
graphEl.classList.toggle(
'centered',
zoom === 0 && w < graphEl.clientWidth && h < graphEl.clientHeight
);

switch (zoom) {
case 0:
svg.setAttribute('width', vb[2]);
svg.setAttribute('height', vb[3]);
svg.setAttribute('width', String(w));
svg.setAttribute('height', String(h));
break;

case 1:
Expand Down Expand Up @@ -512,13 +523,12 @@ export default function Graph() {

// Parse markup
const svgDom = new DOMParser().parseFromString(svgMarkup, 'image/svg+xml')
.children[0];
.children[0] as SVGSVGElement;
svgDom.remove();

// Remove background element so page background shows thru
$(svgDom, '.graph > polygon').remove();

applyZoom(svgDom);
svgDom.setAttribute('preserveAspectRatio', 'xMidYMid meet');

// Inject into DOM
const el = $('#graph');
Expand Down Expand Up @@ -597,7 +607,7 @@ export default function Graph() {
}, [colorize, domSignal]);

// (Re)apply zoom if/when it changes
useEffect(applyZoom, [zoom]);
useEffect(applyZoom, [zoom, domSignal]);

$('title').innerText = `NPMGraph - ${query.join(', ')}`;

Expand Down

0 comments on commit fd5a6b6

Please sign in to comment.