refactor: Attach observers in ref callbacks instead of effects (#13881)

* refactor: Attach observers in ref callbacks instead of effects

Use React 19 ref callback cleanup for the ResizeObserver in Scrollable and
PDF and the IntersectionObserver in useOnScreen, which now returns a ref
callback rather than taking a ref object.

* fix: Remove unused ts-expect-error directives
This commit is contained in:
Tom Moor authored and GitHub committed 2026-09-25 07:30:34 -04:00
1 parent 018d386030
commit 9e405b50a4
6 files changed
+128 -113

No files matched your search

+4 -2
View File
@@ -1,5 +1,6 @@
import isPrintableKeyEvent from "is-printable-key-event";
import * as React from "react";
import { useMergeRefs } from "react-merge-refs";
import styled from "styled-components";
import { s } from "@shared/styles";
import { TextHelper } from "@shared/utils/TextHelper";
@@ -137,7 +138,8 @@ function ContentEditable({
// case the component may be rendered with display: none. React 18 may solve
// this in the future by delaying useEffect hooks:
// https://github.com/facebook/react/issues/14536#issuecomment-861980492
const isVisible = useOnScreen(contentRef);
const [onScreenRef, isVisible] = useOnScreen();
const mergedRef = useMergeRefs([contentRef, onScreenRef]);
React.useEffect(() => {
if (autoFocus && isVisible && !disabled && !readOnly) {
@@ -195,7 +197,7 @@ function ContentEditable({
<div className={className} dir={dir} onClick={onClick} tabIndex={-1}>
{children}
<Content
ref={contentRef}
ref={mergedRef}
contentEditable={contentEditable}
onInput={wrappedEvent(onInput)}
onFocus={wrappedEvent(onFocus)}
+37 -27
View File
@@ -1,6 +1,6 @@
import { observer } from "mobx-react";
import * as React from "react";
import { mergeRefs } from "react-merge-refs";
import { useMergeRefs } from "react-merge-refs";
import styled, { css } from "styled-components";
import { hideScrollbars } from "@shared/styles";
@@ -41,7 +41,6 @@ function Scrollable({
ref,
...rest
}: Props) {
const localRef = React.useRef<HTMLDivElement>(null);
const [topShadowVisible, setTopShadow] = React.useState(false);
const [bottomShadowVisible, setBottomShadow] = React.useState(false);
@@ -53,40 +52,51 @@ function Scrollable({
const trackTop = !!(shadow || topShadow || fadeTop);
const trackBottom = !!(shadow || bottomShadow || fadeBottom);
const updateShadows = React.useCallback(() => {
const c = localRef.current;
if (!c) {
return;
}
const scrollTop = c.scrollTop;
setTopShadow(trackTop && scrollTop > 0);
const updateShadows = React.useCallback(
(c: HTMLDivElement) => {
const scrollTop = c.scrollTop;
setTopShadow(trackTop && scrollTop > 0);
const wrapperHeight = c.scrollHeight - c.clientHeight;
setBottomShadow(trackBottom && wrapperHeight - scrollTop > 1);
}, [trackTop, trackBottom]);
const wrapperHeight = c.scrollHeight - c.clientHeight;
setBottomShadow(trackBottom && wrapperHeight - scrollTop > 1);
},
[trackTop, trackBottom]
);
React.useEffect(() => {
const c = localRef.current;
if (!c) {
return;
}
const handleScroll = React.useCallback(
(event: React.UIEvent<HTMLDivElement>) => {
updateShadows(event.currentTarget);
},
[updateShadows]
);
updateShadows();
// Observe the container and its children for size changes.
const observeRef = React.useCallback(
(c: HTMLDivElement | null) => {
if (!c) {
return;
}
const observer = new ResizeObserver(updateShadows);
observer.observe(c);
updateShadows(c);
for (const child of Array.from(c.children)) {
observer.observe(child);
}
const observer = new ResizeObserver(() => updateShadows(c));
observer.observe(c);
return () => observer.disconnect();
}, [updateShadows]);
for (const child of Array.from(c.children)) {
observer.observe(child);
}
return () => observer.disconnect();
},
[updateShadows]
);
const mergedRef = useMergeRefs([observeRef, ref]);
return (
<Wrapper
ref={mergeRefs([localRef, ref])}
onScroll={updateShadows}
ref={mergedRef}
onScroll={handleScroll}
$flex={flex}
$hiddenScrollbars={hiddenScrollbars}
$topShadowVisible={topShadowVisible && !fadeTop}
+4 -10
View File
@@ -1,6 +1,6 @@
import { observer } from "mobx-react";
import { SearchIcon, HomeIcon, SidebarIcon } from "outline-icons";
import { useEffect, useState, useCallback, useRef } from "react";
import { useEffect, useState, useCallback } from "react";
import {
DragActiveProvider,
SidebarScrollProvider,
@@ -66,15 +66,9 @@ function AppSidebar() {
}
}, [documents, collections, user.isViewer]);
// Scrollable reads ref.current internally for its shadow/ResizeObserver
// logic, so we must pass an object ref — a callback ref would leave those
// reads undefined. We mirror the attached node into state so the
// SidebarScrollProvider can re-render descendants with the scroll element.
const scrollRef = useRef<HTMLDivElement>(null);
// Hold the scroll element in state so the SidebarScrollProvider can
// re-render descendants with it.
const [scrollArea, setScrollArea] = useState<HTMLElement | null>(null);
useEffect(() => {
setScrollArea(scrollRef.current);
}, []);
const sectionOrder = normalizeSidebarSectionOrder(
user.getPreference(UserPreference.SidebarSectionOrder, [])
@@ -139,7 +133,7 @@ function AppSidebar() {
{can.createDocument && <DraftsLink />}
</Section>
</Overflow>
<Scrollable flex shadow ref={scrollRef}>
<Scrollable flex shadow ref={setScrollArea}>
<SidebarScrollProvider value={scrollArea}>
{sectionOrder.map((section) => (
<DraggableSection key={section} section={section}>
@@ -1,6 +1,7 @@
import type { Location } from "history";
import { observer } from "mobx-react";
import * as React from "react";
import { useMergeRefs } from "react-merge-refs";
import { useTranslation } from "react-i18next";
import type { match } from "react-router";
import { useHistory } from "react-router-dom";
@@ -154,7 +155,8 @@ const DocumentLink = observer(function DocumentLink(props: Props) {
() => ({ root: scrollRoot, rootMargin: ROOT_MARGIN }),
[scrollRoot]
);
const isOnScreen = useOnScreen(placeholderRef, observerOptions);
const [onScreenRef, isOnScreen] = useOnScreen(observerOptions);
const mergedRef = useMergeRefs<HTMLDivElement>([placeholderRef, onScreenRef]);
const isDragActive = useIsDragActive();
const [mounted, setMounted] = React.useState(false);
@@ -189,7 +191,7 @@ const DocumentLink = observer(function DocumentLink(props: Props) {
return (
<>
<div ref={placeholderRef} style={{ minHeight: ROW_HEIGHT }}>
<div ref={mergedRef} style={{ minHeight: ROW_HEIGHT }}>
{mounted ? (
<DocumentLinkInner {...props} hasChildren={nodeChildren.length > 0} />
) : null}
+40 -39
View File
@@ -19,14 +19,15 @@ function parseRootMargin(
}
/**
* Hook to return if a given ref is visible on screen.
* Hook to track whether an element is visible on screen.
*
* @returns boolean if the node is visible
* @param options - intersection observer options.
* @returns a tuple of a ref callback to attach to the element and a boolean
* that is true when the element is visible.
*/
export default function useOnScreen(
ref: React.RefObject<HTMLElement | null>,
options?: IntersectionObserverInit
) {
): [React.RefCallback<HTMLElement>, boolean] {
const root = options?.root;
const rootMargin = options?.rootMargin;
const threshold = Array.isArray(options?.threshold)
@@ -35,47 +36,47 @@ export default function useOnScreen(
const [isIntersecting, setIntersecting] = React.useState(!isSupported);
React.useLayoutEffect(() => {
const element = ref.current;
if (!element) {
return undefined;
}
const ref = React.useCallback(
(element: HTMLElement | null) => {
if (!element) {
return;
}
// Synchronous initial check so the first paint is correct.
const [mt, mr, mb, ml] = parseRootMargin(rootMargin);
const rect = element.getBoundingClientRect();
const rootRect =
root instanceof Element
? root.getBoundingClientRect()
: {
top: 0,
left: 0,
bottom: window.innerHeight,
right: window.innerWidth,
};
const initialVisible =
rect.bottom >= rootRect.top - mt &&
rect.top <= rootRect.bottom + mb &&
rect.right >= rootRect.left - ml &&
rect.left <= rootRect.right + mr;
// Synchronous initial check so the first paint is correct.
const [mt, mr, mb, ml] = parseRootMargin(rootMargin);
const rect = element.getBoundingClientRect();
const rootRect =
root instanceof Element
? root.getBoundingClientRect()
: {
top: 0,
left: 0,
bottom: window.innerHeight,
right: window.innerWidth,
};
const initialVisible =
rect.bottom >= rootRect.top - mt &&
rect.top <= rootRect.bottom + mb &&
rect.right >= rootRect.left - ml &&
rect.left <= rootRect.right + mr;
setIntersecting(initialVisible);
setIntersecting(initialVisible);
if (!isSupported) {
return undefined;
}
if (!isSupported) {
return;
}
const observer = new IntersectionObserver(([entry]) => {
setIntersecting(entry.isIntersecting);
}, options);
observer.observe(element);
const observer = new IntersectionObserver(([entry]) => {
setIntersecting(entry.isIntersecting);
}, options);
observer.observe(element);
return () => {
observer.unobserve(element);
};
return () => observer.disconnect();
},
// Re-create when option primitives change; options object identity ignored
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ref, root, rootMargin, threshold]);
[root, rootMargin, threshold]
);
return isIntersecting;
return [ref, isIntersecting];
}
+39 -33
View File
@@ -1,4 +1,5 @@
import React, { useEffect, useRef } from "react";
import React, { useCallback, useRef } from "react";
import { useMergeRefs } from "react-merge-refs";
import styled from "styled-components";
import useDragResize from "./hooks/useDragResize";
import { ResizeLeft, ResizeRight } from "./ResizeHandle";
@@ -39,48 +40,53 @@ export default function PdfViewer(props: Props) {
});
// force embed to reload, so the content fits the new size.
useEffect(() => {
// firefox handles resizing on its own
// and forced reload causes the parent to collapse while resizing
if (isFirefox || !ref.current) {
return;
}
const observer = new ResizeObserver(() => {
if (dragging) {
const observeRef = useCallback(
(element: HTMLDivElement | null) => {
// firefox handles resizing on its own
// and forced reload causes the parent to collapse while resizing
if (isFirefox || !element) {
return;
}
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
debounceTimerRef.current = setTimeout(() => {
if (embedRef.current) {
embedRef.current.src = "";
requestAnimationFrame(() => {
if (embedRef.current) {
embedRef.current.src = sanitizeUrl(href) ?? "";
}
});
const observer = new ResizeObserver(() => {
if (dragging) {
return;
}
}, 250);
});
observer.observe(ref.current);
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
return () => {
observer.disconnect();
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
};
}, [dragging, href]);
debounceTimerRef.current = setTimeout(() => {
if (embedRef.current) {
embedRef.current.src = "";
requestAnimationFrame(() => {
if (embedRef.current) {
embedRef.current.src = sanitizeUrl(href) ?? "";
}
});
}
}, 250);
});
observer.observe(element);
return () => {
observer.disconnect();
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
};
},
[dragging, href]
);
const mergedRef = useMergeRefs([ref, observeRef]);
return (
<PDFWrapper
contentEditable={false}
ref={ref}
ref={mergedRef}
className={
isSelected || dragging
? "pdf-wrapper ProseMirror-selectednode"