fix: Reduce layout shift on page load (#14843)

* fix: Reduce layout shift on page load

- Open the history sidebar on load without the slide-in animation
- Keep server task counts until the editor exists
- Measure the header before paint so actions do not switch to compact
- Do not mark a store loaded from a filtered list
- Show cached list items only once that list has been fetched
- Reserve space for the collection document count, search result count and document views

* fix: Clear the document sidebar before a replacement instance sets it

* test
This commit is contained in:
Tom Moor authored and GitHub committed 2026-12-02 22:50:43 -05:00
1 parent 7ab29ce676
commit 30da7e7ae6
8 files changed
+117 -38

No files matched your search

+5 -1
View File
@@ -137,7 +137,11 @@ class DocumentContext {
}
private updateTasks() {
const tasks = this.editor?.getTasks() ?? [];
// Without an editor, keep the task counts that the server sent.
if (!this.editor) {
return;
}
const tasks = this.editor.getTasks();
const total = tasks.length ?? 0;
const completed = tasks.filter((t) => t.completed).length ?? 0;
this.document?.updateTasks(total, completed);
+21 -3
View File
@@ -81,22 +81,40 @@ function Header({ left, title, actions, hasSidebar, className, ref }: Props) {
});
}, []);
const [wrapper, setWrapper] = React.useState<HTMLDivElement | null>(null);
const [breadcrumbs, setBreadcrumbs] = React.useState<Element | null>(null);
const setBreadcrumbRef = React.useCallback(
(node: HTMLDivElement | null) => {
if (node?.firstElementChild) {
breadcrumbsMeasureRef(node.firstElementChild as HTMLDivElement);
}
setBreadcrumbs(node?.firstElementChild ?? null);
},
[breadcrumbsMeasureRef]
);
const breadcrumbMakesCompact = breadcrumbsSize.width > size.width / 3;
const isCompact = size.width < 1000 || breadcrumbMakesCompact;
// useMeasure reports sizes after the first paint, measure before it so that
// the actions do not switch between compact and full on mount.
const [initialSize, setInitialSize] = React.useState({
width: 0,
breadcrumbs: 0,
});
React.useLayoutEffect(() => {
setInitialSize({
width: wrapper?.getBoundingClientRect().width ?? 0,
breadcrumbs: breadcrumbs?.getBoundingClientRect().width ?? 0,
});
}, [wrapper, breadcrumbs]);
const width = size.width || initialSize.width;
const breadcrumbsWidth = breadcrumbsSize.width || initialSize.breadcrumbs;
const breadcrumbMakesCompact = breadcrumbsWidth > width / 3;
const isCompact = width < 1000 || breadcrumbMakesCompact;
return (
<TooltipProvider>
<Wrapper
ref={mergeRefs([ref, internalMeasureRef])}
ref={mergeRefs<HTMLDivElement>([ref, internalMeasureRef, setWrapper])}
align="center"
shrink={false}
className={className}
+21 -2
View File
@@ -24,6 +24,13 @@ export interface PaginatedItem {
createdAt?: string;
}
/** Fetch functions mapped to the options of their completed first pages. */
const completedFetches = new WeakMap<object, Set<string>>();
// oxlint-disable-next-line no-explicit-any
const getOptionsKey = (options: Record<string, any> | undefined) =>
JSON.stringify(options ?? {});
/**
* Props for the PaginatedList component
* @template T Type of items in the list, must extend PaginatedItem
@@ -130,9 +137,16 @@ const PaginatedList = <T extends PaginatedItem>({
const [error, setError] = React.useState<Error | undefined>();
const [isFetchingMore, setIsFetchingMore] = React.useState(false);
const [isFetching, setIsFetching] = React.useState(false);
// The mount effect starts the fetch, so start in the fetching state.
const [isFetching, setIsFetching] = React.useState(!!fetch);
// Cached items are only in order once this list has been fetched, items that
// other requests put in the store would otherwise move when the page lands.
const [isFetchingInitial, setIsFetchingInitial] = React.useState(
!items?.length
() =>
!items?.length ||
(!!fetch && !completedFetches.get(fetch)?.has(getOptionsKey(options)))
);
const [fetchCounter, setFetchCounter] = React.useState(0);
const [renderCount, setRenderCount] = React.useState(Pagination.defaultLimit);
@@ -182,6 +196,11 @@ const PaginatedList = <T extends PaginatedItem>({
if (offset !== 0) {
setRenderCount((prevCount) => prevCount + limit);
} else {
completedFetches.set(
fetch,
(completedFetches.get(fetch) ?? new Set()).add(getOptionsKey(options))
);
}
if (results.length === 0 || results.length < limit) {
@@ -73,12 +73,14 @@ export const CollectionMeta = observer(function CollectionMeta_({
</Tooltip>
</>
)}
{documentCount !== undefined && (
<span>
<Separator />
{t("{{ count }} document", { count: documentCount })}
</span>
)}
{/* Reserve the space while the count loads, so the line does not grow. */}
<DocumentCount
$hidden={documentCount === undefined}
aria-hidden={documentCount === undefined}
>
<Separator />
{t("{{ count }} document", { count: documentCount ?? 0 })}
</DocumentCount>
{collection.ownerIds.length > 0 && (
<span>
<Separator />
@@ -89,6 +91,11 @@ export const CollectionMeta = observer(function CollectionMeta_({
);
});
const DocumentCount = styled.span<{ $hidden: boolean }>`
font-variant-numeric: tabular-nums;
visibility: ${(props) => (props.$hidden ? "hidden" : "visible")};
`;
const IconLabel = styled(Flex)`
gap: 2px;
cursor: default;
+28 -17
View File
@@ -109,28 +109,39 @@ function TitleDocumentMeta({ to, document, revision, rtl, ...rest }: Props) {
</MetaButton>
</>
)}
{totalViewers && can.listViews && !(document as Document).isDraft ? (
<Wrapper>
<Separator />
<MetaButton
ref={insightsRef}
action={openDocumentInsights}
onMouseEnter={handleInsightsMouseEnter}
onMouseLeave={handleInsightsMouseLeave}
>
{t("Viewed by")}{" "}
{onlyYou
? t("only you")
: `${totalViewers} ${
totalViewers === 1 ? t("person") : t("people")
}`}
</MetaButton>
</Wrapper>
{can.listViews && !(document as Document).isDraft ? (
totalViewers ? (
<Wrapper>
<Separator />
<MetaButton
ref={insightsRef}
action={openDocumentInsights}
onMouseEnter={handleInsightsMouseEnter}
onMouseLeave={handleInsightsMouseLeave}
>
{t("Viewed by")}{" "}
{onlyYou
? t("only you")
: `${totalViewers} ${
totalViewers === 1 ? t("person") : t("people")
}`}
</MetaButton>
</Wrapper>
) : (
// Reserve the line while views load, it stacks on mobile.
<ViewsPlaceholder aria-hidden>
{t("Viewed by")} {t("only you")}
</ViewsPlaceholder>
)
) : null}
</Meta>
);
}
const ViewsPlaceholder = styled.span`
visibility: hidden;
`;
export const Meta = styled(DocumentMeta)<{ $rtl?: boolean }>`
${headerMetaStyles}
`;
@@ -113,8 +113,9 @@ export default function useDocumentSidebar() {
const panel = ui.getRightSidebar(pane);
// A history panel outside of a history route is closed by the effect below,
// so it is treated as closed here – otherwise the sidebar renders open for a
// frame and then animates away again.
const isOpen = panel !== null && (panel !== "history" || isHistoryRoute);
// frame and then animates away again. A history route is open before the
// effect sets the panel, so that loading one does not animate the sidebar in.
const isOpen = isHistoryRoute || (panel !== null && panel !== "history");
const wasOpenRef = React.useRef(isOpen);
React.useEffect(() => {
@@ -156,7 +157,8 @@ export default function useDocumentSidebar() {
pane,
]);
React.useEffect(() => {
// A layout effect, so that a sidebar open on load is in the first paint.
React.useLayoutEffect(() => {
if (isOpen) {
setSidebar(
<DocumentSidebarContent skipInitialAnimation={wasOpenRef.current} />
@@ -167,7 +169,8 @@ export default function useDocumentSidebar() {
wasOpenRef.current = isOpen;
}, [isOpen, setSidebar]);
React.useEffect(
// A layout effect, so that it runs before the setup of a replacement instance.
React.useLayoutEffect(
() => () => {
setSidebar(null);
},
+18 -4
View File
@@ -218,6 +218,10 @@ function Search() {
const isResultCountStale = resultCount?.params !== requestParams;
const total = titleFilter || error ? undefined : resultCount?.total;
// Reserve the space of the first count, so the sort input does not move.
const isResultCountPending =
isSearchable && !titleFilter && !error && !resultCount;
// Only updatable documents are selectable, matching the per-item checkboxes.
const itemIds = React.useMemo(
() =>
@@ -451,11 +455,14 @@ function Search() {
aria-busy={isResultCountStale}
$disabled={isResultCountStale && total !== undefined}
>
{total !== undefined && (
<>
<span>{t("{{ count }} result", { count: total })}</span>
{(total !== undefined || isResultCountPending) && (
<ResultCount
$hidden={total === undefined}
aria-hidden={total === undefined}
>
<span>{t("{{ count }} result", { count: total ?? 0 })}</span>
<span aria-hidden>·</span>
</>
</ResultCount>
)}
{sortInput}
</ResultsMeta>
@@ -565,6 +572,13 @@ const FilterChips = styled(Flex)`
`};
`;
const ResultCount = styled.span<{ $hidden: boolean }>`
display: flex;
gap: 6px;
font-variant-numeric: tabular-nums;
visibility: ${(props) => (props.$hidden ? "hidden" : "visible")};
`;
const ResultsMeta = styled(Text)<{ $disabled: boolean }>`
display: flex;
align-items: center;
+4 -1
View File
@@ -673,7 +673,10 @@ export default abstract class Store<T extends Model> {
? res.data
: res.data[this.responseKey];
response = items.map(this.add);
this.isLoaded = true;
// A filtered list is a subset, so it does not mean the store is loaded.
if (!params?.filters) {
this.isLoaded = true;
}
});
response[PAGINATION_SYMBOL] = res.pagination;