Skip to content

Commit

Permalink
refactor bounding box logic to hook
Browse files Browse the repository at this point in the history
  • Loading branch information
ayan4m1 committed Jan 13, 2024
1 parent 5c30049 commit 4040ce8
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 8 deletions.
9 changes: 2 additions & 7 deletions src/components/mahjongBoard.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
isMatch
} from 'utils/mahjong';
import useTimer from 'hooks/useTimer';
import useBoundingBoxRef from 'hooks/useBoundingBoxRef';

export default function MahjongBoard({ images }) {
const {
Expand All @@ -50,8 +51,8 @@ export default function MahjongBoard({ images }) {
const [solved, setSolved] = useState(false);
const [failed, setFailed] = useState(false);
const [showHints, setShowHints] = useState(false);
const [boardRect, setBoardRect] = useState(null);
const [activeTile, setActiveTile] = useState(null);
const boardRect = useBoundingBoxRef(boardRef, [solved, failed]);
const [layout, setLayout] = useState(generateLayout('turtle'));
const matches = useMemo(() => getAvailableMatches(layout), [layout]);
const completePct = useMemo(() => 1 - layout.length / 144, [layout]);
Expand Down Expand Up @@ -102,12 +103,6 @@ export default function MahjongBoard({ images }) {
resetTimer();
}, [setLayout, resetTimer]);

useEffect(() => {
if (boardRef.current) {
setBoardRect(boardRef.current.getBoundingClientRect());
}
}, [boardRef, solved, failed]);

useEffect(() => {
if (!layout.length) {
setSolved(true);
Expand Down
2 changes: 1 addition & 1 deletion src/components/mahjongTile.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ export default function MahjongTile({
<rect
x={0}
y={0}
height={64}
width={53}
height={64}
fill={active ? '#ff0000' : '#00ff00'}
fillOpacity={0.4}
stroke={active ? '#ff0000' : '#00ff00'}
Expand Down
13 changes: 13 additions & 0 deletions src/hooks/useBoundingBoxRef.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useEffect, useState } from 'react';

export default function useBoundingBoxRef(ref, dependencies = []) {
const [rect, setRect] = useState(null);

useEffect(() => {
if (ref.current) {
setRect(ref.current.getBoundingClientRect());
}
}, [ref, ...dependencies]);

return rect;
}

0 comments on commit 4040ce8

Please sign in to comment.