perf: Load templates on demand, add fetchAllIfNeeded to stores (#13895)

* perf: Load templates on demand and cache fetchAll results

fetchAll on the base store now returns the first result for repeat calls
with the same params, with a force option for callers that need fresh
data. Templates load when the command bar, document header, or block
menu needs them instead of on every page load.

* Make fetchAll caching opt-in via fetchAllIfNeeded

fetchAll always fetches again. fetchAllIfNeeded returns the previous
result for the same params until a model is added to or removed from
the store. Mount-effect callers for reference lists use it.
This commit is contained in:
Tom Moor authored and GitHub committed 2026-09-26 13:41:58 -04:00
1 parent aacc98475d
commit 0e704e6ed2
11 files changed
+67 -17

No files matched your search

@@ -1,3 +1,4 @@
import { useKBar } from "kbar";
import { NewDocumentIcon, ShapesIcon } from "outline-icons";
import { useEffect, useMemo } from "react";
import Icon from "@shared/components/Icon";
@@ -12,10 +13,16 @@ import { newDocumentPath } from "~/utils/routeHelpers";
const useTemplatesAction = () => {
const { templates } = useStores();
const { showing } = useKBar((state) => ({
showing: state.visualState !== "hidden",
}));
// Templates are only needed once the command bar is opened.
useEffect(() => {
void templates.fetchAll();
}, [templates]);
if (showing) {
void templates.fetchAllIfNeeded();
}
}, [showing, templates]);
const actions = useMemo(
() =>
+1 -1
View File
@@ -173,7 +173,7 @@ const IconPicker = ({
React.useEffect(() => {
if (open) {
void emojis.fetchAll();
void emojis.fetchAllIfNeeded();
}
}, [open, emojis]);
+1 -1
View File
@@ -59,7 +59,7 @@ function AppSidebar() {
}, [history]);
useEffect(() => {
void collections.fetchAll();
void collections.fetchAllIfNeeded();
if (!user.isViewer) {
void documents.fetchDrafts();
+11 -3
View File
@@ -1,7 +1,7 @@
import { DocumentIcon, ShapesIcon } from "outline-icons";
import { cloneDeep } from "es-toolkit/compat";
import { observer } from "mobx-react";
import { useCallback, useMemo } from "react";
import { useCallback, useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import Icon from "@shared/components/Icon";
import type { MenuItem } from "@shared/editor/types";
@@ -18,8 +18,10 @@ import SuggestionsMenuItem from "./SuggestionsMenuItem";
/**
* Hook that returns a template menu item with children for inserting template
* content into the editor, or undefined if no templates are available.
*
* @param isActive whether the block menu is open, templates load when it is.
*/
function useTemplateMenuItem(): MenuItem | undefined {
function useTemplateMenuItem(isActive: boolean): MenuItem | undefined {
const { t } = useTranslation();
const user = useCurrentUser({ rejectOnEmpty: false });
const { documents, templates: templatesStore } = useStores();
@@ -28,6 +30,12 @@ function useTemplateMenuItem(): MenuItem | undefined {
const document = documentId ? documents.get(documentId) : undefined;
const collectionId = document?.collectionId;
useEffect(() => {
if (isActive && user) {
void templatesStore.fetchAllIfNeeded();
}
}, [isActive, user, templatesStore]);
return useMemo(() => {
if (!user) {
return undefined;
@@ -109,7 +117,7 @@ type Props = Omit<SuggestionsMenuProps, "renderMenuItem" | "items"> &
function BlockMenu(props: Props) {
const { t } = useTranslation();
const { elementRef } = useEditor();
const templateMenuItem = useTemplateMenuItem();
const templateMenuItem = useTemplateMenuItem(props.isActive);
const items = useMemo(() => {
const baseItems = getMenuItems(t, elementRef);
+1 -1
View File
@@ -74,7 +74,7 @@ const useSettingsConfig = () => {
const { t } = useTranslation();
useEffect(() => {
void integrations.fetchAll();
void integrations.fetchAllIfNeeded();
}, [integrations]);
const config = useComputed(() => {
+7 -1
View File
@@ -1,5 +1,5 @@
import { DocumentIcon } from "outline-icons";
import { useCallback } from "react";
import { useCallback, useEffect } from "react";
import { useTranslation } from "react-i18next";
import Icon from "@shared/components/Icon";
import { TextHelper } from "@shared/utils/TextHelper";
@@ -38,6 +38,12 @@ export function useTemplateMenuActions({
const { t } = useTranslation();
const document = documents.get(documentId);
useEffect(() => {
if (onSelectTemplate) {
void templatesStore.fetchAllIfNeeded();
}
}, [onSelectTemplate, templatesStore]);
const templateToAction = useCallback(
(template: Template): Action =>
createAction({
+33 -4
View File
@@ -133,6 +133,7 @@ export default abstract class Store<T extends Model> {
@action
clear() {
this.data.clear();
this.fetchAllResults.clear();
void this.persistence?.clear();
}
@@ -252,9 +253,13 @@ export default abstract class Store<T extends Model> {
const newModel: T = new ModelClass(item, this);
this.data.set(newModel.id, newModel);
this.persistence?.persist(newModel.id);
this.fetchAllResults.clear();
return newModel;
}
if (!this.data.has(item.id)) {
this.fetchAllResults.clear();
}
this.data.set(item.id, item);
this.persistence?.persist(item.id);
return item;
@@ -315,6 +320,7 @@ export default abstract class Store<T extends Model> {
}
LifecycleManager.executeHooks(model.constructor, "afterRemove", model);
this.fetchAllResults.clear();
// Persists the soft-deleted model, or removes the persisted record if the
// model was hard-deleted from the store.
@@ -527,12 +533,17 @@ export default abstract class Store<T extends Model> {
return this.fetchPaginated(`/${this.apiEndpoint}.list`, params);
};
/**
* Fetches every page of the list endpoint.
*
* @param params the request parameters.
* @returns all fetched items.
*/
@action
fetchAll = async (
// oxlint-disable-next-line no-explicit-any
params?: Record<string, any>
params: FetchPageParams = {}
): Promise<PaginatedResponse<T>> => {
const limit = params?.limit ?? Pagination.defaultLimit;
const limit = params.limit ?? Pagination.defaultLimit;
const response = await this.fetchPage({ ...params, limit });
invariant(
@@ -553,15 +564,30 @@ export default abstract class Store<T extends Model> {
...(fetchPages.length ? await Promise.all(fetchPages) : []),
]);
if (params?.withRelations) {
if (params.withRelations) {
await Promise.all(
this.orderedData.map((integration) => integration.loadRelations())
);
}
this.fetchAllResults.set(JSON.stringify(params), results);
return results;
};
/**
* Fetches every page of the list endpoint unless the same params were
* fetched before and no model has been added to or removed from the store
* since. Use for reference lists that are loaded on mount.
*
* @param params the request parameters.
* @returns all fetched items.
*/
fetchAllIfNeeded = async (
params: FetchPageParams = {}
): Promise<PaginatedResponse<T>> =>
this.fetchAllResults.get(JSON.stringify(params)) ??
(await this.fetchAll(params));
@computed
get orderedData(): T[] {
return orderBy(Array.from(this.data.values()), "createdAt", "desc");
@@ -635,4 +661,7 @@ export default abstract class Store<T extends Model> {
});
}
}
/** Results of `fetchAll` calls keyed by their params, see `fetchAllIfNeeded`. */
private fetchAllResults = new Map<string, PaginatedResponse<T>>();
}
+1 -1
View File
@@ -32,7 +32,7 @@ function GitHub() {
const githubAppName = env.GITHUB_APP_NAME;
React.useEffect(() => {
void integrations.fetchAll({
void integrations.fetchAllIfNeeded({
service: IntegrationService.GitHub,
withRelations: true,
});
+1 -1
View File
@@ -31,7 +31,7 @@ function GitLab() {
const appName = env.APP_NAME;
React.useEffect(() => {
void integrations.fetchAll({
void integrations.fetchAllIfNeeded({
service: IntegrationService.GitLab,
withRelations: true,
});
+1 -1
View File
@@ -29,7 +29,7 @@ function Linear() {
const appName = env.APP_NAME;
React.useEffect(() => {
void integrations.fetchAll({
void integrations.fetchAllIfNeeded({
service: IntegrationService.Linear,
withRelations: true,
});
+1 -1
View File
@@ -34,7 +34,7 @@ function Slack() {
const error = query.get("error");
React.useEffect(() => {
void collections.fetchAll();
void collections.fetchAllIfNeeded();
}, [collections, integrations]);
const commandIntegration = integrations.find({