Browse Source

fix: some perf issues

Peng Xiao 3 years ago
parent
commit
dff55b10f9

+ 1 - 1
tldraw/apps/tldraw-logseq/src/lib/shapes/TextShape.tsx

@@ -214,7 +214,7 @@ export class TextShape extends TLTextShape<TextShapeProps> {
 
   validateProps = (props: Partial<TextShapeProps>) => {
     if (props.isSizeLocked || this.props.isSizeLocked) {
-      props.size = this.getAutoSizedBoundingBox(props)
+      // props.size = this.getAutoSizedBoundingBox(props)
     }
     return withClampedStyles(props)
   }

+ 29 - 24
tldraw/apps/tldraw-logseq/src/lib/shapes/text/getTextSize.ts

@@ -38,12 +38,21 @@ if (typeof window !== 'undefined') {
   melm = getMeasurementDiv()
 }
 
-let prevText = ''
-let prevFont = ''
-let prevSize = [0, 0]
-
-export function clearPrevSize() {
-  prevText = ''
+const cache = new Map<string, [number, number]>()
+const getKey = (text: string, font: string) => {
+  return `${text}-${font}`
+}
+const hasCached = (text: string, font: string) => {
+  const key = getKey(text, font)
+  return cache.has(key)
+}
+const getCached = (text: string, font: string) => {
+  const key = getKey(text, font)
+  return cache.get(key)
+}
+const saveCached = (text: string, font: string, size: [number, number]) => {
+  const key = getKey(text, font)
+  cache.set(key, size)
 }
 
 export function getTextLabelSize(text: string, font: string) {
@@ -51,27 +60,23 @@ export function getTextLabelSize(text: string, font: string) {
     return [16, 32]
   }
 
-  if (!melm) {
-    // We're in SSR
-    return [10, 10]
-  }
-
-  if (!melm.parent) document.body.appendChild(melm)
+  if (!hasCached(text, font)) {
+    if (!melm) {
+      // We're in SSR
+      return [10, 10]
+    }
 
-  if (text === prevText && font === prevFont) {
-    return prevSize
-  }
+    if (!melm.parent) document.body.appendChild(melm)
 
-  prevText = text
-  prevFont = font
+    melm.textContent = text
+    melm.style.font = font
 
-  melm.textContent = text
-  melm.style.font = font
+    // In tests, offsetWidth and offsetHeight will be 0
+    const width = melm.offsetWidth || 1
+    const height = melm.offsetHeight || 1
 
-  // In tests, offsetWidth and offsetHeight will be 0
-  const width = melm.offsetWidth || 1
-  const height = melm.offsetHeight || 1
+    saveCached(text, font, [width, height])
+  }
 
-  prevSize = [width, height]
-  return prevSize
+  return getCached(text, font)
 }