Refactor scrolling

This commit is contained in:
Jonatan Kłosko 2024-09-05 22:22:14 +07:00
parent da3c2da7c6
commit da59acd142
2 changed files with 26 additions and 13 deletions

View file

@ -1,11 +1,7 @@
import { parseHookProps } from "../lib/attribute";
import Markdown from "../lib/markdown";
import { globalPubsub } from "../lib/pubsub";
import {
md5Base64,
smoothlyScrollToElement,
waitUntilInViewport,
} from "../lib/utils";
import { md5Base64, smoothlyScrollToElement, withStyle } from "../lib/utils";
import scrollIntoView from "scroll-into-view-if-needed";
import { isEvaluable } from "../lib/notebook";
@ -366,15 +362,13 @@ const Cell = {
const element = this.currentEditor().getElementAtCursor();
// Scroll to the cursor, positioning it near the top of the viewport
element.style.scrollMarginTop = "128px";
scrollIntoView(element, {
scrollMode: "if-needed",
behavior: "instant",
block: "start",
withStyle(element, { scrollMarginTop: "128px" }, () => {
scrollIntoView(element, {
scrollMode: "if-needed",
behavior: "instant",
block: "start",
});
});
element.style.scrollMarginTop = undefined;
},
};

View file

@ -335,3 +335,22 @@ export function wait(milliseconds) {
export function isSafari() {
return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
}
/**
* Alters element style with the given properties for the callback
* execution.
*
* After the callback is executed, the initial style is restored.
*/
export function withStyle(element, style, callback) {
const initialStyle = {};
for (const key in style) {
initialStyle[key] = element.style[key];
element.style[key] = style[key];
}
callback();
Object.assign(element.style, initialStyle);
}