feat: simplify memoization logic

This commit is contained in:
Arnošt Pleskot 2023-07-14 23:23:41 +02:00
parent 132750f753
commit 4e9039e850
No known key found for this signature in database

View file

@ -224,7 +224,6 @@ import {
SidebarName, SidebarName,
SidebarTabName, SidebarTabName,
ScrollConstraints, ScrollConstraints,
NormalizedZoomValue,
} from "../types"; } from "../types";
import { import {
debounce, debounce,
@ -459,13 +458,9 @@ class App extends React.Component<AppProps, AppState> {
lastPointerDown: React.PointerEvent<HTMLElement> | null = null; lastPointerDown: React.PointerEvent<HTMLElement> | null = null;
lastPointerUp: React.PointerEvent<HTMLElement> | PointerEvent | null = null; lastPointerUp: React.PointerEvent<HTMLElement> | PointerEvent | null = null;
lastViewportPosition = { x: 0, y: 0 }; lastViewportPosition = { x: 0, y: 0 };
private memoizedScrollConstraints: { private memoizedScrollConstraints: ReturnType<
input: { App["calculateConstraints"]
scrollConstraints: AppState["scrollConstraints"]; > | null = null;
values: Omit<Partial<AppState>, "zoom"> & { zoom: NormalizedZoomValue };
};
result: ReturnType<App["calculateConstraints"]>;
} | null = null;
constructor(props: AppProps) { constructor(props: AppProps) {
super(props); super(props);
@ -1657,17 +1652,21 @@ class App extends React.Component<AppProps, AppState> {
} = this.state; } = this.state;
// TODO: this could be replaced with memoization function like _.memoize() // TODO: this could be replaced with memoization function like _.memoize()
const calculatedConstraints = const canUseMemoizedConstraints =
isShallowEqual( isShallowEqual(scrollConstraints, prevState.scrollConstraints ?? {}) &&
scrollConstraints,
this.memoizedScrollConstraints?.input.scrollConstraints ?? {},
) &&
isShallowEqual( isShallowEqual(
{ width, height, zoom: zoom.value, cursorButton }, { width, height, zoom: zoom.value, cursorButton },
this.memoizedScrollConstraints?.input.values ?? {}, {
) && width: prevState.width,
this.memoizedScrollConstraints height: prevState.height,
? this.memoizedScrollConstraints.result zoom: prevState.zoom.value,
cursorButton: prevState.cursorButton,
} ?? {},
);
const calculatedConstraints =
canUseMemoizedConstraints && !!this.memoizedScrollConstraints
? this.memoizedScrollConstraints
: this.calculateConstraints({ : this.calculateConstraints({
scrollConstraints, scrollConstraints,
width, width,
@ -1676,13 +1675,7 @@ class App extends React.Component<AppProps, AppState> {
cursorButton, cursorButton,
}); });
this.memoizedScrollConstraints = { this.memoizedScrollConstraints = calculatedConstraints;
input: {
scrollConstraints,
values: { width, height, zoom: zoom.value, cursorButton },
},
result: calculatedConstraints,
};
const constrainedScrollValues = this.constrainScrollValues({ const constrainedScrollValues = this.constrainScrollValues({
...calculatedConstraints, ...calculatedConstraints,