Files
Tom Moor ef6e51401b perf: Reduce main-thread cost of opening a document from the sidebar (#14033)
* perf: Read active models lazily in ActionContextProvider

The root provider read the active document and models during render, so
every navigation rebuilt the context and re-rendered all consumers. These
values are now getters, and overrides are merged without evaluating them.

* perf: Skip urlId scan in Store.get for UUIDs

When an id was not loaded, get() searched every item by urlId, so each
sidebar row observed the whole store. A UUID cannot end with a urlId, so
the search is skipped for UUIDs.

* perf: Stop sidebar rows re-rendering on navigation

- Track expanded nodes in an observable map, as ObservableSet.has tracks
  the whole set.
- Do not rebuild the document tree rows when the active document changes.
- Auto-expand the active path in a reaction instead of reading the active
  document during render.
- Compute active state per row, and keep row props stable.

* perf: Add useLocationSelector for persistent components

useLocation re-renders on every navigation. The new hook re-renders only
when the selected value changes, and is used where components stay mounted
across navigation. AuthenticatedLayout now keeps its portal element in
state, as it no longer re-renders after mount.

* chore: Send Document-Policy js-profiling header in development

* docs: Add render performance guidance to AGENTS.md

* fix: Check document or collection star exclusively for active state

* fix: Read location from each action context provider's own history

Nested providers inherited the root location getter, so menus inside a
split view pane read the browser route instead of the pane's route.

* fix: Expand starred collection when the active document changes
2026-10-11 15:17:01 -04:00

130 lines
3.6 KiB
TypeScript

import { observer } from "mobx-react";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import parseDocumentSlug from "@shared/utils/parseDocumentSlug";
import { useLocationSelector } from "~/hooks/useLocationSelector";
import useStores from "~/hooks/useStores";
import type { MentionMenuItem } from "~/editor/menus/mention";
import {
createDocumentMentionItems,
documentMentionItem,
} from "~/editor/menus/mention";
import { useEditor } from "./EditorContext";
import type { Props as SuggestionsMenuProps } from "./SuggestionsMenu";
import SuggestionsMenu from "./SuggestionsMenu";
import SuggestionsMenuItem from "./SuggestionsMenuItem";
type Props = Omit<
SuggestionsMenuProps<MentionMenuItem>,
"renderMenuItem" | "items" | "embeds"
>;
/** Number of documents shown while searching. */
const MaxResults = 25;
/** Number of documents shown before a search term is entered. */
const MaxDefaultResults = 5;
function DocumentMenu({ search = "", isActive, ...rest }: Props) {
const [loaded, setLoaded] = useState(false);
const { t } = useTranslation();
const { auth, documents } = useStores();
const { props: editorProps } = useEditor();
const actorId = auth.currentUserId;
const documentId = useLocationSelector((location) =>
parseDocumentSlug(location.pathname)
);
// Spaces are allowed in the search term, so it may have trailing whitespace.
const query = search.trim();
useEffect(() => {
if (!isActive) {
return;
}
let cancelled = false;
const load = async () => {
try {
// A title search requires a query, so the most recently viewed
// documents are offered until the user starts typing.
await (query
? documents.searchTitles({
query,
limit: MaxResults,
filters: [
{ field: "archivedAt", operator: "isNull" },
{ field: "publishedAt", operator: "isNotNull" },
],
})
: documents.fetchRecentlyViewed({ limit: MaxDefaultResults }));
} catch {
// Fall back to whatever the store already holds rather than blocking
// the menu from opening.
}
if (!cancelled) {
setLoaded(true);
}
};
void load();
return () => {
cancelled = true;
};
}, [documents, query, isActive]);
// Computed in the render body, from the store rather than the request, so
// MobX observer keeps the results up to date.
const results = query
? documents.findByQuery(query, { maxResults: MaxResults })
: documents.recentlyViewed.slice(0, MaxDefaultResults);
const items: MentionMenuItem[] = actorId
? [
...results.map((document) => documentMentionItem(document, actorId)),
...createDocumentMentionItems(t, {
search,
actorId,
documentId,
canCreate: !!editorProps.onCreateLink,
}),
]
: [];
const renderMenuItem = useCallback<
SuggestionsMenuProps<MentionMenuItem>["renderMenuItem"]
>(
(item, _index, options) => (
<SuggestionsMenuItem
{...options}
subtitle={item.subtitle}
title={item.title}
icon={item.icon}
/>
),
[]
);
// Prevent showing the menu until we have data otherwise it will be positioned
// incorrectly due to the height being unknown.
if (!loaded) {
return null;
}
return (
<SuggestionsMenu
{...rest}
isActive={isActive}
filterable={false}
search={search}
renderMenuItem={renderMenuItem}
items={items}
/>
);
}
export default observer(DocumentMenu);