Skip to content

Commit 0ea1bae

Browse files
authored
Merge pull request #19 from wajeshubham/dev
Optimise width handler and replace createRef with useRef to persist th…
2 parents fa87856 + 52ba3d5 commit 0ea1bae

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

components/editor/SnippngCodeArea.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { createRef, useState } from "react";
1+
import { useRef, useState } from "react";
22

33
import { DEFAULT_BASE_SETUP } from "@/lib/constants";
44
import { clsx, getEditorWrapperBg, getLanguage, getTheme } from "@/utils";
@@ -26,7 +26,7 @@ import {
2626
import { addDoc, collection, doc, updateDoc } from "firebase/firestore";
2727

2828
const SnippngCodeArea = () => {
29-
const editorRef = createRef<HTMLDivElement>();
29+
const editorRef = useRef<HTMLDivElement>(null); // useRef to persist existing ref. Might be useful when dealing with background image in future
3030
const [saving, setSaving] = useState(false);
3131
const [updating, setUpdating] = useState(false);
3232

lib/width-handler/WidthHandler.tsx

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,18 @@ interface Props {
66
onChange: (width: number) => void;
77
}
88

9-
const edgeCase = (value: number, min: number, max: number) => {
9+
const edgeCase = (
10+
value: number,
11+
min: number,
12+
max: number
13+
): [number, boolean] => {
1014
if (value < min) {
11-
return min;
15+
return [min, false];
1216
}
1317
if (value > max) {
14-
return max;
18+
return [max, false];
1519
}
16-
return value;
20+
return [value, true];
1721
};
1822

1923
const WidthHandler: React.FC<Props> = ({ innerRef, onChange }) => {
@@ -27,8 +31,10 @@ const WidthHandler: React.FC<Props> = ({ innerRef, onChange }) => {
2731
if (!startX.current || !startWidth.current) return;
2832
const delta = e.pageX - startX.current; // leftOrRight === 'left' ? startX - e.pageX : (startX - e.pageX) * -1
2933
const calculated = startWidth.current + delta * window.devicePixelRatio;
30-
const newWidth = edgeCase(calculated, minWidth, maxWidth);
31-
onChange(newWidth);
34+
const [newWidth, isChanging] = edgeCase(calculated, minWidth, maxWidth);
35+
if (isChanging) {
36+
onChange(newWidth);
37+
}
3238
};
3339
window.addEventListener("mousemove", handleMouseMove);
3440
return () => window.removeEventListener("mousemove", handleMouseMove);

0 commit comments

Comments
 (0)