Files
outline/app/editor/components/MentionMenu.tsx
T
Tom Moor 6a6987ec2d perf: Faster mention suggestions (#14583)
* perf: Faster mention suggestions

Limit each section of suggestions.mention to 1s so a slow query does not
delay the others, debounce mention and link editor requests, ignore stale
responses, and use title search in the link editor.

* fix: Include presentation in the mention suggestion time limits

* test: Use a fixed name in the collection member name filter test
2026-11-13 22:37:49 -05:00

305 lines
9.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { observer } from "mobx-react";
import { v4 as uuidv4 } from "uuid";
import { runInAction } from "mobx";
import { useState, useCallback, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { MentionType } from "@shared/types";
import {
dateToReadable,
dateToRelativeReadable,
parseISODate,
toISODate,
toISODateTime,
} from "@shared/utils/date";
import parseDocumentSlug from "@shared/utils/parseDocumentSlug";
import { parseNaturalLanguageDate } from "@shared/utils/parseNaturalLanguageDate";
import { Avatar, AvatarSize, GroupAvatar } from "~/components/Avatar";
import { DynamicCalendarIcon } from "@shared/components/DynamicCalendarIcon";
import { DateSection } from "~/actions/sections";
import type { MentionMenuItem } from "~/editor/menus/mention";
import {
collectionMentionItem,
createDocumentMentionItems,
documentMentionItem,
groupMentionItem,
userMentionItem,
} from "~/editor/menus/mention";
import useDebouncedValue from "~/hooks/useDebouncedValue";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
import useUserLocale from "~/hooks/useUserLocale";
import { useLocationSelector } from "~/hooks/useLocationSelector";
import type Model from "~/models/base/Model";
import { client } from "~/utils/ApiClient";
import { useEditor } from "./EditorContext";
import type { Props as SuggestionsMenuProps } from "./SuggestionsMenu";
import SuggestionsMenu from "./SuggestionsMenu";
import SuggestionsMenuItem from "./SuggestionsMenuItem";
/** The time in milliseconds the search must stay the same before it is sent. */
const RequestDelay = 100;
type Props = Omit<
SuggestionsMenuProps<MentionMenuItem>,
"renderMenuItem" | "items" | "embeds"
>;
function MentionMenu({ search = "", isActive, ...rest }: Props) {
const [loaded, setLoaded] = useState(false);
// How familiar each suggested model is to the current user, keyed by model
// id. The score does not depend on the search term, so scores from earlier
// queries stay valid and are kept.
const [familiarity, setFamiliarity] = useState<ReadonlyMap<string, number>>(
new Map()
);
const { t } = useTranslation();
const { auth, documents, users, collections, groups } = useStores();
const { props: editorProps } = useEditor();
const actorId = auth.currentUserId;
const documentId = useLocationSelector((location) =>
parseDocumentSlug(location.pathname)
);
const userLocale = useUserLocale();
const maxResultsInSection = search ? 25 : 5;
// Surface a date suggestion when the search query parses as a natural
// language date (e.g. "tomorrow", "next friday", "jan 2", "1pm"). Parsing is
// asynchronous as chrono-node is loaded lazily, so the result is held in
// state and applied once resolved.
const [parsedISODate, setParsedISODate] = useState<string | undefined>();
useEffect(() => {
if (!search) {
setParsedISODate(undefined);
return;
}
let cancelled = false;
void parseNaturalLanguageDate(search)
.then((parsed) => {
if (!cancelled) {
setParsedISODate(
parsed
? parsed.hasTime
? toISODateTime(parsed.date)
: toISODate(parsed.date)
: undefined
);
}
})
.catch(() => {
// Parsing failed (e.g. the chrono chunk failed to load); drop the
// suggestion rather than leaving a stale one.
if (!cancelled) {
setParsedISODate(undefined);
}
});
return () => {
cancelled = true;
};
}, [search]);
let dateItems: MentionMenuItem[] = [];
if (actorId && parsedISODate) {
const title = dateToRelativeReadable(parsedISODate, t, userLocale);
const subtitle = dateToReadable(parsedISODate, userLocale);
dateItems = [
{
name: "mention",
icon: (
<DynamicCalendarIcon day={parseISODate(parsedISODate)?.getDate()} />
),
title,
subtitle: title !== subtitle ? subtitle : undefined,
section: DateSection,
appendSpace: true,
attrs: {
id: uuidv4(),
type: MentionType.Date,
modelId: parsedISODate,
label: parsedISODate,
actorId,
},
} as MentionMenuItem,
];
}
// Results from the store show at once, the server is only asked for more
// when the user stops typing.
const requestSearch = useDebouncedValue(search, RequestDelay);
const latestRequestId = useRef(0);
const { loading, request } = useRequest(
useCallback(async () => {
const requestId = ++latestRequestId.current;
const res = await client.post("/suggestions.mention", {
query: requestSearch,
limit: requestSearch ? 25 : 5,
});
// A newer request was sent while this one was in progress.
if (requestId !== latestRequestId.current) {
return;
}
runInAction(() => {
res.data.documents.map(documents.add);
res.data.users.map(users.add);
res.data.collections.map(collections.add);
res.data.groups.map(groups.add);
});
setFamiliarity(
(previous) =>
new Map([
...previous,
...Object.entries<number>(res.data.familiarity ?? {}),
])
);
}, [requestSearch, documents, users, collections, groups])
);
// Suggestions that the current user is familiar with, for example a member of
// one of their groups, are ranked above equally relevant ones.
const weight = useCallback(
(model: Model) => familiarity.get(model.id) ?? 1,
[familiarity]
);
useEffect(() => {
if (isActive) {
void request();
}
}, [request, isActive]);
useEffect(() => {
if (actorId && !loading) {
setLoaded(true);
}
}, [actorId, loading]);
// Computed in the render body so MobX observer can track store access
// (e.g. searchSuppressed). Previously this lived inside a useEffect which
// runs outside the reactive context and triggered MobX warnings.
const mentionItems: MentionMenuItem[] = actorId
? users
.findByQuery(search, { maxResults: maxResultsInSection, weight })
.map((user) => userMentionItem(t, user, actorId))
.concat(
groups
.findByQuery(search, { maxResults: maxResultsInSection, weight })
.map((group) => groupMentionItem(t, group, actorId))
)
.concat(
documents
.findByQuery(search, { maxResults: maxResultsInSection, weight })
.map((doc) => documentMentionItem(doc, actorId))
)
.concat(
collections
.findByQuery(search, { maxResults: maxResultsInSection, weight })
// A personal collection has no page for a mention to link to.
.filter((collection) => !collection.isPersonal)
.map((collection) => collectionMentionItem(collection, actorId))
)
.concat(
createDocumentMentionItems(t, {
search,
actorId,
documentId,
canCreate: !!editorProps.onCreateLink,
})
)
: [];
const items: MentionMenuItem[] = [...dateItems, ...mentionItems];
const handleSelect = useCallback(
async (item: MentionMenuItem) => {
if (
item.attrs.type === MentionType.Date ||
item.attrs.type === MentionType.Document ||
item.attrs.type === MentionType.Collection
) {
return;
}
if (!documentId) {
return;
}
if (item.attrs.type === MentionType.User) {
// Check if the mentioned user has access to the document
const res = await client.post("/documents.users", {
id: documentId,
userId: item.attrs.modelId,
});
if (!res.data.length) {
const user = users.get(item.attrs.modelId);
toast.message(
t(
"{{ userName }} won’t be notified, as they do not have access to this document",
{
userName: item.attrs.label,
}
),
{
icon: <Avatar model={user} size={AvatarSize.Toast} />,
duration: 10000,
}
);
}
} else if (item.attrs.type === MentionType.Group) {
const group = groups.get(item.attrs.modelId);
toast.message(
t(
"Members of “{{ groupName }}” with access to this document will be notified",
{
groupName: item.attrs.label,
}
),
{
icon: group ? <GroupAvatar group={group} /> : undefined,
duration: 10000,
}
);
}
},
[t, users, documentId, groups]
);
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}
onSelect={handleSelect}
renderMenuItem={renderMenuItem}
items={items}
/>
);
}
export default observer(MentionMenu);