Skip to content

Commit

Permalink
fix: apply suggested changes for PR #4288
Browse files Browse the repository at this point in the history
  • Loading branch information
iwestlin committed Jun 26, 2023
1 parent 534dedc commit ac2b647
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 14 deletions.
22 changes: 8 additions & 14 deletions packages/mermaid/src/diagrams/pie/pieRenderer.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
/** Created by AshishJ on 11-09-2019. */
import { select, scaleOrdinal, pie as d3pie, arc } from 'd3';
import { log } from '../../logger';
import { configureSvgSize } from '../../setupGraphViewbox';
import * as configApi from '../../config';
import { parseFontSize } from '../../utils';
import { log } from '../../logger.js';
import { configureSvgSize } from '../../setupGraphViewbox.js';
import * as configApi from '../../config.js';
import { parseFontSize } from '../../utils.js';
import { getTextWidth } from '../../rendering-util/getTextWidth';

let conf = configApi.getConfig();
// https://stackoverflow.com/a/35373030/3469145
const getTextWidth = (function () {
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
return text => context.measureText(text).width * window.devicePixelRatio
})();

/**
* Draws a Pie Chart with the data given in text.
Expand Down Expand Up @@ -79,15 +74,14 @@ export const draw = (txt, id, _version, diagObj) => {
sum += data[key];
});

const legendShowData = diagObj.db.getShowData() || conf.showData || conf.pie.showData;
const legendShowData = diagObj.db.getShowData() || conf.showData || conf.pie.showData || false;
const legendTexts = Object.keys(data).map(key => {
if (!legendShowData) {
return key;
}
return key + ' [' + data[key] + ']';
return `${key} [${data[key]}]`;
})
const legendTextWidths = legendTexts.map(v => getTextWidth(v)).sort((a, b) => a - b);
const longestTextWidth = parseInt(legendTextWidths.pop());
const longestTextWidth = Math.max(legendTexts.map(v => getTextWidth(v)));
const newWidth = width + margin + legendRectSize + legendSpacing + longestTextWidth;
elem.setAttribute("viewBox", "0 0 " + newWidth + " " + height);

Expand Down
7 changes: 7 additions & 0 deletions packages/mermaid/src/rendering-util/getTextWidth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// https://stackoverflow.com/a/35373030/3469145
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d') as CanvasRenderingContext2D;

const getTextWidth = (text: string) => context.measureText(text).width * window.devicePixelRatio;

export { getTextWidth };

0 comments on commit ac2b647

Please sign in to comment.