Skip to content

Commit

Permalink
Refactor scrolling
Browse files Browse the repository at this point in the history
  • Loading branch information
jonatanklosko committed Sep 5, 2024
1 parent da3c2da commit da59acd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 13 deletions.
20 changes: 7 additions & 13 deletions assets/js/hooks/cell.js
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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;
},
};

Expand Down
19 changes: 19 additions & 0 deletions assets/js/lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

0 comments on commit da59acd

Please sign in to comment.