From da59acd1424b4b878d612824ec261c285769d4f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonatan=20K=C5=82osko?= Date: Thu, 5 Sep 2024 22:22:14 +0700 Subject: [PATCH] Refactor scrolling --- assets/js/hooks/cell.js | 20 +++++++------------- assets/js/lib/utils.js | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/assets/js/hooks/cell.js b/assets/js/hooks/cell.js index 967a69b0f..5f2a440f4 100644 --- a/assets/js/hooks/cell.js +++ b/assets/js/hooks/cell.js @@ -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; }, }; diff --git a/assets/js/lib/utils.js b/assets/js/lib/utils.js index e58c53989..7022d013c 100644 --- a/assets/js/lib/utils.js +++ b/assets/js/lib/utils.js @@ -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); +}