From 5f4e942d3157297dde962c127317c824c8c6d050 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 1 Jun 2023 10:25:44 +0100 Subject: [PATCH] stash --- app/editor/index.tsx | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/app/editor/index.tsx b/app/editor/index.tsx index c55c38bb1..0efc56cec 100644 --- a/app/editor/index.tsx +++ b/app/editor/index.tsx @@ -487,15 +487,15 @@ export class Editor extends React.PureComponent< return view; } - public scrollToAnchor(hash: string) { + public async scrollToAnchor(hash: string) { if (!hash) { return; } try { - const element = document.querySelector(hash); + const element = await observe(hash); if (element) { - setTimeout(() => element.scrollIntoView({ behavior: "smooth" }), 0); + element.scrollIntoView({ behavior: "smooth" }); } } catch (err) { // querySelector will throw an error if the hash begins with a number @@ -851,4 +851,19 @@ const LazyLoadedEditor = React.forwardRef( ) ); +const observe = ( + selector: string, + targetNode = document.body +): Promise => + new Promise((res) => { + new MutationObserver((mutations) => { + const match = [...mutations] + .flatMap((mutation) => [...mutation.addedNodes]) + .find((node: HTMLElement) => node.matches?.(selector)); + if (match) { + res(match as HTMLElement); + } + }).observe(targetNode, { childList: true, subtree: true }); + }); + export default LazyLoadedEditor;