This commit is contained in:
Tom Moor
2023-06-01 10:25:44 +01:00
parent 874bdb1e11
commit 5f4e942d31

View File

@@ -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<Editor, Props>(
)
);
const observe = (
selector: string,
targetNode = document.body
): Promise<HTMLElement> =>
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;