diff --git a/components/Blocks/Block.tsx b/components/Blocks/Block.tsx index c4ca7100..30b32678 100644 --- a/components/Blocks/Block.tsx +++ b/components/Blocks/Block.tsx @@ -87,6 +87,7 @@ export const Block = memo(function Block( return (
{ //scroll to page - document.getElementById(elementId.page(pageID).container)?.scrollIntoView({ - behavior: "smooth", - inline: "nearest", - }); + + scrollIntoViewIfNeeded( + document.getElementById(elementId.page(pageID).container), + false, + "smooth", + ); // if we asked that the function focus the first block, focus the first block if (focusFirstBlock === "focusFirstBlock") { diff --git a/src/utils/focusBlock.ts b/src/utils/focusBlock.ts index 0cf010bd..9f77fe17 100644 --- a/src/utils/focusBlock.ts +++ b/src/utils/focusBlock.ts @@ -1,22 +1,33 @@ import { TextSelection } from "prosemirror-state"; import { useUIState } from "src/useUIState"; import { Block } from "components/Blocks/Block"; +import { elementId } from "src/utils/elementId"; import { setEditorState, useEditorStates } from "src/state/useEditorState"; +import { scrollIntoViewIfNeeded } from "./scrollIntoViewIfNeeded"; export function focusBlock( block: Pick, position: Position, ) { + // focus the block useUIState.getState().setSelectedBlock(block); useUIState.getState().setFocusedBlock({ entityType: "block", entityID: block.value, parent: block.parent, }); + scrollIntoViewIfNeeded( + document.getElementById(elementId.block(block.value).container), + false, + ); + + // if its not a text block, that's all we need to do if (block.type !== "text" && block.type !== "heading") { return true; } + // if its a text block, and not an empty block that is last on the page, + // focus the editor using the mouse position if needed let nextBlockID = block.value; let nextBlock = useEditorStates.getState().editorStates[nextBlockID]; if (!nextBlock || !nextBlock.view) return; diff --git a/src/utils/scrollIntoViewIfNeeded.ts b/src/utils/scrollIntoViewIfNeeded.ts index 116623b8..583d762d 100644 --- a/src/utils/scrollIntoViewIfNeeded.ts +++ b/src/utils/scrollIntoViewIfNeeded.ts @@ -1,10 +1,14 @@ export function scrollIntoViewIfNeeded( el: Element | null, centerIfNeeded: boolean = true, + behavior?: ScrollBehavior, ) { - if (!el) return; + if (!el) { + return; + } let observer = new IntersectionObserver(function ([entry]) { const ratio = entry.intersectionRatio; + if (ratio < 1) { let place = ratio <= 0 && centerIfNeeded @@ -13,6 +17,7 @@ export function scrollIntoViewIfNeeded( el.scrollIntoView({ block: place, inline: place, + behavior: behavior ? behavior : "auto", }); } observer.disconnect();