Skip to content

Commit

Permalink
refactor: move getComputedStyleWithCache() to utils.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
canalun committed Feb 25, 2024
1 parent 3a37a9d commit cc6fec5
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 23 deletions.
8 changes: 6 additions & 2 deletions src/game/getBlockElements.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { getComputedStyleWithCache } from "./getComputedStyleWithCache"
import { isBBAElement, isFrameElement, isPenetrableFrame } from "./utils"
import {
getComputedStyleWithCache,
isBBAElement,
isFrameElement,
isPenetrableFrame
} from "./utils"

export function getBlockElements(): Element[] {
const blockElements: Element[] = []
Expand Down
20 changes: 0 additions & 20 deletions src/game/getComputedStyleWithCache.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/game/updateBlocks.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { getRectOfBlock, type Block } from "./blocks"
import { getComputedStyleWithCache } from "./getComputedStyleWithCache"
import type { Scoreboard } from "./scoreboard"
import {
assert,
getComputedStyleWithCache,
isFrameElement,
isPenetrableFrame,
isSVGElement,
Expand Down
21 changes: 21 additions & 0 deletions src/game/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,24 @@ export function isBBAElement(element: Element): boolean {
element.classList.contains(collisionPointOnBallClass)
)
}

// getComputedStyle() is expensive, so we should cache the result.
// We can assume that the style of an element doesn't change, because the page is frozen.
// Please note that DOMRect-related settings can't be used in this function,
// because they can change by removing blocks. Use getBoundingClientRect() instead.
const styleCache = new Map<Element, CSSStyleDeclaration>()
export function getComputedStyleWithCache(
element: Element
): Omit<
CSSStyleDeclaration,
keyof ReturnType<typeof Element.prototype.getBoundingClientRect>
> {
const cache = styleCache.get(element)
if (cache) {
return cache
} else {
const style = getComputedStyle(element)
styleCache.set(element, style)
return style
}
}

0 comments on commit cc6fec5

Please sign in to comment.