Files
outline/app/editor/components/MentionMenu.tsx
T
Tom Moor f8496ea2f7 feat: Personal collections (#14062)
* feat: Personal collections backend

Adds an owner to collections. A personal collection is private, one per user
per team, created lazily through collections.personal, and only its owner can
see or manage it. Admin bypasses in policies, lists, exports, events, webhooks
and file operations exclude the personal collections of other users. Turning
off the PersonalDocs preference makes the collection read-only.

* test: Access matrix for personal collections

Checks that collection and document endpoints, list and search results, MCP
tools, collaboration and websocket rooms agree with the read policy for the
owner, collaborators, members, admins, guests and other teams.

* feat: Personal collection in the sidebar

Adds a Personal sidebar section that renders the personal collection with the
collection document tree, creates the collection on the first new document,
and keeps it out of the Collections section. Adds the workspace setting, the
personal sidebar context, and hides collection sharing and membership UI for
personal collections.

* fix: Drag and drop in shared with me trees

Anchors the reorder drop cursor inside the row, and prefetches documents on
hover so that nested rows that were never opened can be dragged.

* feat: Personal collection owner for collaborators, no collection page

Presents the owner of the personal collection on documents, so that
collaborators see the owner in the share popover. Root rows in the Personal
section show the default document icon. A personal collection has no page:
the scene shows not found, and the breadcrumb, command bar and delete redirect
no longer link to it.

* fix: Personal sidebar indent and breadcrumb items without a link

Children of rows at depth 0 skip a level so that they start beyond the row
icon. Breadcrumb items without a destination, such as the personal and deleted
collection, are shown as plain text.

* test: Reduce personal collection tests to list paths

Endpoints that authorize a single model are already covered by the policy
tests. Keeps the lists and searches, which filter in queries, and the
presenter.

* test: Move personal collection list tests into collections tests

* feat: Create documents in the personal collection by alias

documents.create, documents.import and the MCP create_document tool accept
the collectionId "personal", which refers to the personal collection of the
user and creates it when it does not exist yet.

* refactor: Remove collections.personal route

The sidebar creates its first personal document with the personal
collectionId alias, so documents.create is the only path that creates the
personal collection.

* feat: Personal collection name, starring, templates and default

Personal collections cannot be starred, renamed or hold templates, and the
PersonalDocs preference is on by default. The app shows collections through a
displayName getter, which is the translated "Personal" for a personal
collection.

* fix: Use the same policy for starring and unstarring collections

* fix: No pins or viewer insights for personal documents

* revert: Show personal collection events in the audit log

Admins with audit access should see events in personal collections, even when
they cannot open the documents.

* fix: Load collection owner in share scopes

* fix: Keep personal collections out of workspace exports and webhooks

Workspace exports skip all personal collections, while an explicit export of
a personal collection stays available to its owner. Events in personal
collections, including attachments and documents moved after queueing, are
never delivered to workspace webhooks. Personal collections cannot be
renamed or made public through any path, cannot hold pins, and are not
offered as mentions.

* Change icon to avatar

* fix: Personal documents cannot be unpublished

* feat: Personal collection context for MCP

Collections are presented with an isPersonal flag, the server instructions
explain the personal collection, and move_document and update_document accept
the personal collectionId alias.

* fix: Keep moved personal exports private and remove pins on move

Document exports record the owner of the personal collection they came from,
so they stay private after the document moves. Moving documents into a
personal collection removes their pins, including pins to home.

* fix: Only create the personal collection in MCP when it is used
2026-10-13 07:53:06 -04:00

290 lines
8.8 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 } 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 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";
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,
];
}
const { loading, request } = useRequest(
useCallback(async () => {
const res = await client.post("/suggestions.mention", {
query: search,
limit: maxResultsInSection,
});
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 ?? {}),
])
);
}, [search, documents, users, collections, groups, maxResultsInSection])
);
// 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 }}” that have 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);