Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
HHongSeungWoo authored and Gabriel Mercier committed Nov 23, 2023
1 parent 7d4db5e commit 706a726
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/util/DOMUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,23 @@ export const getStyleString = (style: CSSProperties) =>
'',
);

function removeInvalidKeys(obj: Record<string, any>) {
const copyObj = { ...obj };
Object.keys(copyObj).forEach(key => {
if (!copyObj[key]) {
delete copyObj[key];
}
});
return copyObj;
}

export const getStringSize = (text: string | number, style: CSSProperties = {}): Size => {
if (text === undefined || text === null || Global.isSsr) {
return { width: 0, height: 0 };
}

const str = `${text}`;
const styleString = getStyleString(style);
const cacheKey = `${str}-${styleString}`;
const copyStyle = removeInvalidKeys(style);
const cacheKey = JSON.stringify({ text, copyStyle });

if (stringCache.widthCache[cacheKey]) {
return stringCache.widthCache[cacheKey];
Expand All @@ -96,13 +105,10 @@ export const getStringSize = (text: string | number, style: CSSProperties = {}):
}
// Need to use CSS Object Model (CSSOM) to be able to comply with Content Security Policy (CSP)
// https://en.wikipedia.org/wiki/Content_Security_Policy
const measurementSpanStyle: Record<string, any> = { ...SPAN_STYLE, ...style };
Object.keys(measurementSpanStyle).map(styleKey => {
(measurementSpan.style as Record<string, any>)[styleKey] = measurementSpanStyle[styleKey];
return styleKey;
});
const measurementSpanStyle: Record<string, any> = { ...SPAN_STYLE, ...copyStyle };
Object.assign(measurementSpan.style, measurementSpanStyle);

measurementSpan.textContent = str;
measurementSpan.textContent = `${text}`;

const rect = measurementSpan.getBoundingClientRect();
const result = { width: rect.width, height: rect.height };
Expand Down

0 comments on commit 706a726

Please sign in to comment.