fix: set the width correctly using measureText in editor (#6162)

This commit is contained in:
Aakansha Doshi 2023-01-28 16:39:53 +05:30 committed by GitHub
parent b52c8943e4
commit e41ea9562b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 14 deletions

View file

@ -271,12 +271,11 @@ export const measureText = (
container.style.whiteSpace = "pre";
container.style.font = font;
container.style.minHeight = "1em";
const textWidth = getTextWidth(text, font);
if (maxWidth) {
const lineHeight = getApproxLineHeight(font);
container.style.width = `${String(Math.min(textWidth, maxWidth) + 1)}px`;
// since we are adding a span of width 1px later
container.style.maxWidth = `${maxWidth + 1}px`;
container.style.overflow = "hidden";
container.style.wordBreak = "break-word";
container.style.lineHeight = `${String(lineHeight)}px`;
@ -293,11 +292,7 @@ export const measureText = (
container.appendChild(span);
// Baseline is important for positioning text on canvas
const baseline = span.offsetTop + span.offsetHeight;
// Since span adds 1px extra width to the container
let width = container.offsetWidth;
if (maxWidth && textWidth > maxWidth) {
width = width - 1;
}
const width = container.offsetWidth;
const height = container.offsetHeight;
document.body.removeChild(container);
if (isTestEnv()) {
@ -332,8 +327,11 @@ const getLineWidth = (text: string, font: FontString) => {
if (isTestEnv()) {
return metrics.width * 10;
}
// Since measureText behaves differently in different browsers
// OS so considering a adjustment factor of 0.2
const adjustmentFactor = 0.2;
return metrics.width;
return metrics.width + adjustmentFactor;
};
export const getTextWidth = (text: string, font: FontString) => {