From 4937215c891a5c7102ca1321e3d97876aba80307 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Issue=E5=93=A5?= Date: Tue, 27 Jun 2023 00:56:25 +0800 Subject: [PATCH] fix: apply suggested changes for PR #4288 --- packages/mermaid/src/diagrams/pie/pieRenderer.js | 14 ++++---------- .../mermaid/src/rendering-util/getTextWidth.ts | 7 +++++++ 2 files changed, 11 insertions(+), 10 deletions(-) create mode 100644 packages/mermaid/src/rendering-util/getTextWidth.ts diff --git a/packages/mermaid/src/diagrams/pie/pieRenderer.js b/packages/mermaid/src/diagrams/pie/pieRenderer.js index 5c420d33118..ca88d58a6ed 100644 --- a/packages/mermaid/src/diagrams/pie/pieRenderer.js +++ b/packages/mermaid/src/diagrams/pie/pieRenderer.js @@ -4,14 +4,9 @@ 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.ts'; 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. @@ -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); diff --git a/packages/mermaid/src/rendering-util/getTextWidth.ts b/packages/mermaid/src/rendering-util/getTextWidth.ts new file mode 100644 index 00000000000..da44f2a3fb3 --- /dev/null +++ b/packages/mermaid/src/rendering-util/getTextWidth.ts @@ -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 };