Files
Tom MoorandClaude f680d5dec9 feat: Display links, documents and collections as preview cards (#14511)
* feat: Display links as preview cards

Adds a display attribute to mentions so a link can render either inline
or as a card with image, title and description from its unfurl. Pasting
a URL offers a "Card" option, and selecting a link mention shows a
toolbar to switch between the two displays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFgeTUqKhSTriUHfG3z

* feat: Arrow key selection, full width and Return for link cards

Cards fill the document width, hide the blank line below them, are selected
by the up and down arrow keys like images, and Return on a selected card
adds a paragraph below it.

* feat: Display document and collection mentions as cards

Document and collection mentions can be switched to a card from the
selection toolbar. Document cards show the summary, collection and the
first image larger than 100x100. Collection cards show the first line of
the description. On public shares the preview image is signed, as the
share page already signs the attachments of that document. Card images
are hidden until they load and removed if they fail.

* feat: Keep mention cards through Markdown

The card display is written as the link title, so URLs are not changed.
Document and collection cards are written as @ links to their id and
parsed back into mentions.

* refactor: Move mention cards to their own file

Document cards show the collection after the title instead of below it.

* fix: Address review feedback on mention cards

- Include the share id in the document card unfurl URL for root shares.
- Return on a card in a heading adds a paragraph.
- URL cards keep their URL in Markdown, and the server does not narrow
  their type.
- Unfurl results apply to the current node, not the node at first render.
- Collection card descriptions stop at the first line break.

* refactor: Reuse existing helpers for mention cards

- Sign the preview image with TextHelper.attachmentsToSignedUrls.
- Check document and collection ids with isUUID.
- Return lines from getFirstText without changing an input array.

* fix: Preserve JSON output for inline mentions

* refactor: Centralize mention selection classes

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-08 08:11:31 -05:00

219 lines
5.8 KiB
TypeScript

import { observer } from "mobx-react";
import { v4 as uuidv4 } from "uuid";
import { AlignImageRightIcon, EmailIcon, LinkIcon } from "outline-icons";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import type { EmbedDescriptor } from "@shared/editor/embeds";
import type { MenuItem } from "@shared/editor/types";
import { MentionDisplay, MentionType } from "@shared/types";
import { isInternalUrl, isUrl } from "@shared/utils/urls";
import type Integration from "~/models/Integration";
import useCurrentUser from "~/hooks/useCurrentUser";
import useStores from "~/hooks/useStores";
import { client } from "~/utils/ApiClient";
import { determineMentionType, isURLMentionable } from "~/utils/mention";
import type { Props as SuggestionsMenuProps } from "./SuggestionsMenu";
import SuggestionsMenu from "./SuggestionsMenu";
import SuggestionsMenuItem from "./SuggestionsMenuItem";
import { getMatchingEmbed } from "@shared/editor/lib/embeds";
type Props = Omit<
SuggestionsMenuProps,
"renderMenuItem" | "items" | "embeds" | "trigger"
> & {
pastedText: string | string[];
embeds: EmbedDescriptor[];
};
interface EmbedCheckState {
loading: boolean;
embeddable?: boolean;
}
export const PasteMenu = observer(({ pastedText, embeds, ...props }: Props) => {
const items = useItems({ pastedText, embeds });
const renderMenuItem = useCallback<SuggestionsMenuProps["renderMenuItem"]>(
(item, _index, options) => (
<SuggestionsMenuItem {...options} {...item} title={item.title} />
),
[]
);
if (!items) {
props.onClose();
return null;
}
return (
<SuggestionsMenu
{...props}
trigger=""
filterable={false}
renderMenuItem={renderMenuItem}
items={items}
/>
);
});
function useItems({
pastedText,
embeds,
}: Pick<Props, "pastedText" | "embeds">): MenuItem[] | undefined {
const { t } = useTranslation();
const { integrations } = useStores();
const user = useCurrentUser({ rejectOnEmpty: false });
const [embedCheck, setEmbedCheck] = useState<EmbedCheckState>({
loading: false,
});
const singleUrl =
typeof pastedText === "string" && isUrl(pastedText) ? pastedText : null;
const isInternal = singleUrl ? isInternalUrl(singleUrl) : false;
const matchedEmbed = singleUrl
? getMatchingEmbed(embeds, singleUrl)?.embed
: null;
const embed = matchedEmbed?.disabled ? null : matchedEmbed;
// Check embeddability for single URL
useEffect(() => {
if (!singleUrl || !embed || isInternal) {
setEmbedCheck({ loading: false });
return;
}
let cancelled = false;
setEmbedCheck({ loading: true });
client
.post<{ embeddable: boolean; reason?: string }>("/urls.checkEmbed", {
url: singleUrl,
})
.then((res) => {
if (!cancelled) {
setEmbedCheck({ loading: false, embeddable: res.embeddable });
}
})
.catch(() => {
if (!cancelled) {
// Optimistic on error - allow embedding attempt
setEmbedCheck({ loading: false, embeddable: true });
}
});
return () => {
cancelled = true;
};
}, [singleUrl, embed, isInternal]);
// single item is pasted.
if (typeof pastedText === "string") {
let mentionType: MentionType | undefined;
if (pastedText && isUrl(pastedText)) {
const url = new URL(pastedText);
const integration = integrations.find((intg: Integration) =>
isURLMentionable({ url, integration: intg })
);
mentionType = integration
? determineMentionType({ url, integration })
: MentionType.URL;
}
return [
{
name: "noop",
title: t("Keep as link"),
icon: <LinkIcon />,
},
{
name: "mention",
title: t("Mention"),
icon: <EmailIcon />,
visible: !!mentionType,
attrs: {
id: uuidv4(),
type: mentionType,
label: pastedText,
href: pastedText,
modelId: uuidv4(),
actorId: user?.id,
},
appendSpace: true,
},
{
name: "mention",
title: t("Card"),
icon: <AlignImageRightIcon />,
visible: mentionType === MentionType.URL && !isInternal,
attrs: {
id: uuidv4(),
type: MentionType.URL,
label: pastedText,
href: pastedText,
modelId: uuidv4(),
actorId: user?.id,
display: MentionDisplay.Card,
},
},
{
name: "embed",
title: t("Embed"),
subtitle:
embedCheck.embeddable === false || isInternal
? t("Not supported")
: undefined,
disabled: isInternal || embedCheck.loading || !embedCheck.embeddable,
icon: embed?.icon,
keywords: embed?.keywords,
},
];
}
// list is pasted.
// Check if the links can be converted to mentions.
const linksToMentionType: Record<string, MentionType> = {};
const convertibleToMentionList = pastedText.every((text) => {
if (!isUrl(text)) {
return false;
}
const url = new URL(text);
const integration = integrations.find((intg: Integration) =>
isURLMentionable({ url, integration: intg })
);
const mentionType = integration
? determineMentionType({ url, integration })
: MentionType.URL;
if (mentionType) {
linksToMentionType[text] = mentionType;
}
return !!mentionType;
});
// don't render the menu when it can't be converted to mentions.
if (!convertibleToMentionList) {
return;
}
return [
{
name: "noop",
title: t("Keep as link"),
icon: <LinkIcon />,
},
{
name: "mention_list",
title: t("Mention"),
visible: !!convertibleToMentionList,
icon: <EmailIcon />,
attrs: { actorId: user?.id, ...linksToMentionType },
},
];
}