From f680d5dec9fef54fb1402668e01f7e8359a26d71 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 8 Nov 2026 08:11:31 -0500 Subject: [PATCH] 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 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 --- app/editor/components/PasteMenu.tsx | 19 +- app/editor/extensions/SelectionToolbar.tsx | 9 + server/editor/rules/mentions.test.ts | 10 + server/editor/rules/mentions.ts | 5 +- server/models/helpers/DocumentHelper.test.ts | 95 ++++++++ server/models/helpers/DocumentHelper.tsx | 39 +++ server/presenters/unfurl.ts | 22 +- server/routes/api/urls/urls.test.ts | 77 ++++++ server/routes/api/urls/urls.ts | 2 + shared/editor/components/MentionCard.tsx | 214 +++++++++++++++++ shared/editor/components/Mentions.tsx | 228 +++++++++++------- shared/editor/components/Styles.ts | 43 +++- shared/editor/lib/mention.ts | 19 ++ shared/editor/nodes/Mention.test.ts | 238 ++++++++++++++++++- shared/editor/nodes/Mention.tsx | 173 +++++++++++--- shared/editor/rules/mention.test.ts | 73 ++++++ shared/editor/rules/mention.ts | 64 ++++- shared/i18n/locales/en_US/translation.json | 4 + shared/types/unfurl.ts | 10 + shared/utils/ProsemirrorDataHelper.test.ts | 80 +++++++ shared/utils/ProsemirrorDataHelper.ts | 31 +++ 21 files changed, 1320 insertions(+), 135 deletions(-) create mode 100644 shared/editor/components/MentionCard.tsx diff --git a/app/editor/components/PasteMenu.tsx b/app/editor/components/PasteMenu.tsx index 12a3efafb7..016cda69d8 100644 --- a/app/editor/components/PasteMenu.tsx +++ b/app/editor/components/PasteMenu.tsx @@ -1,11 +1,11 @@ import { observer } from "mobx-react"; import { v4 as uuidv4 } from "uuid"; -import { EmailIcon, LinkIcon } from "outline-icons"; +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 { MentionType } from "@shared/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"; @@ -142,6 +142,21 @@ function useItems({ }, appendSpace: true, }, + { + name: "mention", + title: t("Card"), + icon: , + 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"), diff --git a/app/editor/extensions/SelectionToolbar.tsx b/app/editor/extensions/SelectionToolbar.tsx index caef03b2eb..67f438fe95 100644 --- a/app/editor/extensions/SelectionToolbar.tsx +++ b/app/editor/extensions/SelectionToolbar.tsx @@ -4,6 +4,7 @@ import { NodeSelection, Plugin, TextSelection } from "prosemirror-state"; import type { EditorView } from "prosemirror-view"; import type { WidgetProps } from "@shared/editor/lib/Extension"; import Extension from "@shared/editor/lib/Extension"; +import { canDisplayAsCard } from "@shared/editor/lib/mention"; import { isInNotice } from "@shared/editor/queries/isInNotice"; import { isMarkActive } from "@shared/editor/queries/isMarkActive"; import { isNodeActive } from "@shared/editor/queries/isNodeActive"; @@ -177,6 +178,14 @@ export default class SelectionToolbarExtension extends Extension { return selection; } + if ( + selection instanceof NodeSelection && + view.editable && + canDisplayAsCard(selection.node) + ) { + return selection; + } + if (selection instanceof NodeSelection) { return false; } diff --git a/server/editor/rules/mentions.test.ts b/server/editor/rules/mentions.test.ts index 2630d74256..5851a2eb74 100644 --- a/server/editor/rules/mentions.test.ts +++ b/server/editor/rules/mentions.test.ts @@ -26,6 +26,16 @@ describe("mention type rule", () => { expect(mention?.attrs.label).toBe("Fix parser"); }); + it("should keep a card as a generic link mention", () => { + const mention = firstMention( + '@[Fix parser](https://github.com/acme/infra/issues/2 "card")' + ); + + expect(mention?.attrs.type).toBe(MentionType.URL); + expect(mention?.attrs.display).toBe("card"); + expect(mention?.attrs.href).toBe("https://github.com/acme/infra/issues/2"); + }); + it("should resolve a GitHub pull request link", () => { const mention = firstMention( "@[Add parser](https://github.com/acme/infra/pull/5)" diff --git a/server/editor/rules/mentions.ts b/server/editor/rules/mentions.ts index 9d4f53ec3f..79c40baba0 100644 --- a/server/editor/rules/mentions.ts +++ b/server/editor/rules/mentions.ts @@ -1,5 +1,6 @@ import type MarkdownIt from "markdown-it"; import type StateCore from "markdown-it/lib/rules_core/state_core.mjs"; +import { MentionDisplay } from "@shared/types"; import { Hook, PluginManager } from "@server/utils/PluginManager"; /** @@ -21,7 +22,9 @@ function resolveMentionTypes(state: StateCore) { for (const child of token.children) { const href = child.type === "mention" ? child.attrGet("href") : null; - if (!href) { + + // Cards keep the generic URL type, as the client does after an unfurl. + if (!href || child.attrGet("display") === MentionDisplay.Card) { continue; } diff --git a/server/models/helpers/DocumentHelper.test.ts b/server/models/helpers/DocumentHelper.test.ts index 20635ee1ad..87cf1eddb4 100644 --- a/server/models/helpers/DocumentHelper.test.ts +++ b/server/models/helpers/DocumentHelper.test.ts @@ -532,6 +532,60 @@ describe("DocumentHelper", () => { }); describe("applyMarkdownToDocument", () => { + it("should keep mention cards when the whole document is replaced", async () => { + const modelId = "6f4e9a32-5b1c-4d2e-9f3a-8b7c6d5e4f30"; + const mention = (attrs: Record) => ({ + type: "paragraph", + content: [ + { + type: "mention", + attrs: { + id: "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + modelId, + display: "card", + ...attrs, + }, + }, + ], + }); + const document = await buildDocument({ + content: { + type: "doc", + content: [ + mention({ + type: "url", + label: "Example", + href: "https://example.com/a?b=c", + }), + mention({ type: "document", label: "Roadmap" }), + mention({ type: "collection", label: "Product" }), + ], + }, + }); + + const markdown = await DocumentHelper.toMarkdown(document, { + includeTitle: false, + }); + const result = DocumentHelper.applyMarkdownToDocument( + document, + markdown, + TextEditMode.Replace + ); + + const mentions: Array> = []; + DocumentHelper.toProsemirror(result).descendants((node) => { + if (node.type.name === "mention") { + mentions.push(node.attrs); + } + }); + expect(mentions[0].href).toBe("https://example.com/a?b=c"); + expect(mentions.map((attrs) => [attrs.type, attrs.display])).toEqual([ + ["url", "card"], + ["document", "card"], + ["collection", "card"], + ]); + }); + it("should merge prepended text into the first paragraph", async () => { const document = await buildDocument({ text: "Existing" }); const result = DocumentHelper.applyMarkdownToDocument( @@ -1260,6 +1314,47 @@ In a cell }); }); + describe("getPreviewImage", () => { + const image = (src: string, width?: number, height?: number) => ({ + type: "paragraph", + content: [{ type: "image", attrs: { src, alt: "", width, height } }], + }); + + it("returns the first image larger than the minimum size", () => { + const data: ProsemirrorData = { + type: "doc", + content: [ + image("/icon.png", 32, 32), + image("/narrow.png", 400, 80), + image("/large.png", 800, 600), + image("/second.png", 800, 600), + ], + }; + expect(DocumentHelper.getPreviewImage(data)).toBe("/large.png"); + }); + + it("skips images without a stored size", () => { + const data: ProsemirrorData = { + type: "doc", + content: [image("/unknown.png")], + }; + expect(DocumentHelper.getPreviewImage(data)).toBeUndefined(); + }); + + it("finds images nested in other blocks", () => { + const data: ProsemirrorData = { + type: "doc", + content: [ + { + type: "blockquote", + content: [image("/quoted.png", 200, 200)], + }, + ], + }; + expect(DocumentHelper.getPreviewImage(data)).toBe("/quoted.png"); + }); + }); + describe("getAnchorContent", () => { it("should return the section content for a matching heading anchor", async () => { const document = await buildDocument({ diff --git a/server/models/helpers/DocumentHelper.tsx b/server/models/helpers/DocumentHelper.tsx index f3351de24c..bb4abc086c 100644 --- a/server/models/helpers/DocumentHelper.tsx +++ b/server/models/helpers/DocumentHelper.tsx @@ -27,6 +27,9 @@ import type { MentionAttrs } from "./ProsemirrorHelper"; import { ProsemirrorHelper } from "./ProsemirrorHelper"; import { TextHelper } from "./TextHelper"; +/** The minimum width and height, in pixels, of an image used as a preview. */ +const previewImageMinSize = 100; + /** Maps a range of text-content offsets to ProseMirror Fragment offsets. */ interface InlineSegment { textFrom: number; @@ -320,6 +323,42 @@ export class DocumentHelper { .trim(); } + /** + * Returns the source of the first image in the document that is larger than + * the minimum preview size. Images without a stored size are skipped, so + * small images such as icons are not used. + * + * @param document the document, revision or prosemirror data to read. + * @returns the image source, or undefined if there is no suitable image. + */ + static getPreviewImage( + document: Document | Revision | ProsemirrorData + ): string | undefined { + const node = DocumentHelper.toProsemirror(document); + let src: string | undefined; + + node.descendants((child) => { + if (src) { + return false; + } + const { attrs } = child; + if ( + child.type.name === "image" && + typeof attrs.src === "string" && + attrs.src && + typeof attrs.width === "number" && + typeof attrs.height === "number" && + attrs.width > previewImageMinSize && + attrs.height > previewImageMinSize + ) { + src = attrs.src; + } + return true; + }); + + return src; + } + /** * Returns the document as Markdown. This is a lossy conversion and should only be used for export. * diff --git a/server/presenters/unfurl.ts b/server/presenters/unfurl.ts index 6b99d4e694..1a0c8d847b 100644 --- a/server/presenters/unfurl.ts +++ b/server/presenters/unfurl.ts @@ -3,9 +3,11 @@ import { t } from "i18next"; import type { UnfurlResponse } from "@shared/types"; import { UnfurlResourceType } from "@shared/types"; import { dateLocale } from "@shared/utils/date"; +import { Hour } from "@shared/utils/time"; import type { Document, User, Group } from "@server/models"; import { View } from "@server/models"; import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; +import { TextHelper } from "@server/models/helpers/TextHelper"; import { opts } from "@server/utils/i18n"; // oxlint-disable-next-line @typescript-eslint/no-explicit-any -- heterogeneous payload from internal callers and third-party unfurl plugins. @@ -96,9 +98,9 @@ const presentGroup = async ( }; }; -const presentDocument = ( +const presentDocument = async ( data: UnfurlData -): UnfurlResponse[UnfurlResourceType.Document] => { +): Promise => { const document: Document = data.document; const viewer: User | undefined = data.viewer; const url: string | undefined = data.url; @@ -116,6 +118,7 @@ const presentDocument = ( id: document.id, title: document.displayTitle, summary: sectionSummary || document.getSummary(), + thumbnailUrl: await presentThumbnailUrl(document, !!data.signedUrls), lastActivityByViewer: viewer ? presentLastActivityInfoFor(document, viewer) : undefined, @@ -235,4 +238,19 @@ const presentLastActivityInfoFor = (document: Document, viewer: User) => { return info; }; +/** + * Returns the preview image of a document. Signed URLs are used for viewers of + * a public share, who cannot load attachments through the redirect URL. + */ +const presentThumbnailUrl = async ( + document: Document, + signedUrls: boolean +): Promise => { + const src = DocumentHelper.getPreviewImage(document); + if (!src || !signedUrls) { + return src; + } + return TextHelper.attachmentsToSignedUrls(src, document.teamId, Hour.seconds); +}; + export default presentUnfurl; diff --git a/server/routes/api/urls/urls.test.ts b/server/routes/api/urls/urls.test.ts index 87029375da..7e1683acd9 100644 --- a/server/routes/api/urls/urls.test.ts +++ b/server/routes/api/urls/urls.test.ts @@ -6,6 +6,7 @@ import env from "@server/env"; import type { User } from "@server/models"; import { View } from "@server/models"; import { + buildAttachment, buildCollection, buildDocument, buildShare, @@ -435,6 +436,82 @@ Install instructions here.` expect(body.lastActivityByViewer).toBeUndefined(); }); + describe("preview image", () => { + const buildDocumentWithImage = async (src: string) => + buildDocument({ + teamId: user.teamId, + content: { + type: "doc", + content: [ + { + type: "paragraph", + content: [ + { + type: "image", + attrs: { src, alt: "", width: 400, height: 300 }, + }, + ], + }, + ], + }, + }); + + it("should return the redirect url for a team member", async () => { + const attachment = await buildAttachment({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocumentWithImage(attachment.redirectUrl); + + const res = await server.post("/api/urls.unfurl", user, { + body: { url: `${env.URL}/doc/${document.urlId}` }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.thumbnailUrl).toEqual(attachment.redirectUrl); + }); + + it("should return a signed url for a public share", async () => { + const attachment = await buildAttachment({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocumentWithImage(attachment.redirectUrl); + const share = await buildShare({ + teamId: user.teamId, + userId: user.id, + documentId: document.id, + published: true, + }); + + const res = await server.post("/api/urls.unfurl", { + body: { url: `${env.URL}/s/${share.id}/doc/${document.urlId}` }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.thumbnailUrl).toBeTruthy(); + expect(body.thumbnailUrl).not.toContain("attachments.redirect"); + }); + + it("should not sign an attachment from another team for a public share", async () => { + const attachment = await buildAttachment(); + const document = await buildDocumentWithImage(attachment.redirectUrl); + const share = await buildShare({ + teamId: user.teamId, + userId: user.id, + documentId: document.id, + published: true, + }); + + const res = await server.post("/api/urls.unfurl", { + body: { url: `${env.URL}/s/${share.id}/doc/${document.urlId}` }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.thumbnailUrl).toEqual(attachment.redirectUrl); + }); + }); + it("should return share-scoped url in unfurl response", async () => { const document = await buildDocument({ teamId: user.teamId, diff --git a/server/routes/api/urls/urls.ts b/server/routes/api/urls/urls.ts index c7185390ec..1311cb1367 100644 --- a/server/routes/api/urls/urls.ts +++ b/server/routes/api/urls/urls.ts @@ -75,10 +75,12 @@ router.post( return; } + // The share page signs this document's attachments, so this adds no access. ctx.body = await presentUnfurl({ type: UnfurlResourceType.Document, document, anchor: urlObj.hash, + signedUrls: true, url: `${share.canonicalUrl}/doc/${document.url.replace("/doc/", "")}${urlObj.hash}`, }); return; diff --git a/shared/editor/components/MentionCard.tsx b/shared/editor/components/MentionCard.tsx new file mode 100644 index 0000000000..d6477ae0af --- /dev/null +++ b/shared/editor/components/MentionCard.tsx @@ -0,0 +1,214 @@ +import * as React from "react"; +import styled from "styled-components"; +import { Backticks } from "../../components/Backticks"; +import Flex from "../../components/Flex"; +import type { + JSONValue, + UnfurlResourceType, + UnfurlResponse, +} from "../../types"; +import { sanitizeImageSrc, toDisplayUrl } from "../../utils/urls"; + +type LinkCardProps = Record & { + /** Class names from the mention node. */ + className: string; + /** The URL of the link. */ + url?: string; + /** The unfurled data for the link. */ + unfurl: Partial; +}; + +/** + * A preview card for a link, showing its image, title and description. + * + * @param props the attributes of the mention and the unfurled link data. + * @returns the card element. + */ +export const LinkCard = ({ + className, + url, + unfurl, + ...attrs +}: LinkCardProps) => ( + + + {unfurl.faviconUrl ? ( + + ) : null} + {url ? {toDisplayUrl(url)} : null} + + } + /> + +); + +interface MentionCardProps { + /** An icon shown before the title. */ + icon?: React.ReactNode; + /** The title of the card. */ + title: string; + /** Secondary text shown after the title, on the same line. */ + titleSuffix?: React.ReactNode; + /** A short plain text description. */ + description?: string; + /** Content shown below the description, such as the source of the link. */ + source?: React.ReactNode; + /** An image shown at the side of the card. */ + thumbnailUrl?: string; +} + +/** + * The content of a mention that is displayed as a card. The caller renders the + * outer link element. + * + * @param props the content of the card. + * @returns the card content. + */ +export const MentionCard = ({ + icon, + title, + titleSuffix, + description, + source, + thumbnailUrl, +}: MentionCardProps) => { + const imageSrc = thumbnailUrl ? sanitizeImageSrc(thumbnailUrl) : undefined; + + return ( + <> + + + {icon} + <TitleText> + <Backticks content={title} /> + {titleSuffix ? ( + <> + {" "} + <TitleSuffix>{titleSuffix}</TitleSuffix> + </> + ) : null} + </TitleText> + + {description ? {description} : null} + {source ? ( + + {source} + + ) : null} + + {imageSrc ? : null} + + ); +}; + +/** + * The image of a card. It is hidden until it loads and removed if it fails, as + * the viewer may not have access to it. + */ +const Thumbnail = ({ src }: { src: string }) => { + const [status, setStatus] = React.useState<"loading" | "loaded" | "failed">( + "loading" + ); + + if (status === "failed") { + return null; + } + + return ( + + setStatus("loaded")} + onError={() => setStatus("failed")} + /> + + ); +}; + +const Favicon = styled.img` + width: 16px; + height: 16px; +`; + +const Content = styled.span` + display: flex; + flex-direction: column; + justify-content: center; + gap: 4px; + flex: 1; + min-width: 0; + padding: 12px 14px; +`; + +const Title = styled(Flex)` + min-width: 0; + font-weight: 500; + color: ${(props) => props.theme.text}; +`; + +const TitleText = styled.span` + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +`; + +const TitleSuffix = styled.span` + font-weight: normal; + color: ${(props) => props.theme.textTertiary}; +`; + +const Description = styled.span` + font-weight: normal; + font-size: 14px; + color: ${(props) => props.theme.textSecondary}; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + white-space: normal; +`; + +const Source = styled(Flex)` + margin-top: 2px; + min-width: 0; +`; + +const SourceText = styled.span` + font-weight: normal; + font-size: 13px; + color: ${(props) => props.theme.textTertiary}; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +`; + +// The frame takes the height of the card, so the image does not change it. +const ImageFrame = styled.span<{ $loaded: boolean }>` + display: ${(props) => (props.$loaded ? "block" : "none")}; + position: relative; + flex-shrink: 0; + width: 30%; + max-width: 200px; + border-left: 1px solid ${(props) => props.theme.divider}; +`; + +const Image = styled.img` + position: absolute; + inset: 0; + width: 100%; + height: 100%; + object-fit: cover; +`; diff --git a/shared/editor/components/Mentions.tsx b/shared/editor/components/Mentions.tsx index 1ff4c8a592..acb9c2a5d7 100644 --- a/shared/editor/components/Mentions.tsx +++ b/shared/editor/components/Mentions.tsx @@ -27,6 +27,7 @@ import useShare from "../../hooks/useShare"; import env from "../../env"; import theme from "../../styles/theme"; import { + MentionDisplay, UnfurlResourceType, type JSONValue, type UnfurlResponse, @@ -37,13 +38,22 @@ import lazyWithRetry from "../../utils/lazyWithRetry"; import { sharedModelPath } from "../../utils/routeHelpers"; import { toDisplayUrl, cdnPath, sanitizeImageSrc } from "../../utils/urls"; import Squircle from "../../components/Squircle"; +import { LinkCard, MentionCard } from "./MentionCard"; +import { ProsemirrorDataHelper } from "../../utils/ProsemirrorDataHelper"; type Attrs = { className: string; unfurl?: UnfurlResponse[keyof UnfurlResponse]; } & Record; -const getAttributesFromNode = (node: Node): Attrs => { +/** + * Returns mention attributes with the selection class applied. + * + * @param node the mention node. + * @param isSelected whether the mention is selected. + * @returns the attributes for the rendered mention. + */ +const getAttributesFromNode = (node: Node, isSelected = false): Attrs => { const spec = node.type.spec.toDOM?.(node) as unknown as Record< string, JSONValue @@ -51,7 +61,9 @@ const getAttributesFromNode = (node: Node): Attrs => { const { class: className, "data-unfurl": unfurl, ...attrs } = spec[1]; return { - className: className as Attrs["className"], + className: cn(typeof className === "string" ? className : undefined, { + "ProseMirror-selectednode": isSelected, + }), unfurl: unfurl ? (JSON.parse(unfurl as string) as Attrs["unfurl"]) : undefined, @@ -80,15 +92,13 @@ export const MentionUser = observer(function MentionUser_( const { isSelected, node } = props; const { users } = useStores(); const user = users.get(node.attrs.modelId); - const { className, unfurl, ...attrs } = getAttributesFromNode(node); + const { className, unfurl, ...attrs } = getAttributesFromNode( + node, + isSelected + ); return ( - + {user?.name || node.attrs.label} @@ -101,15 +111,10 @@ export const MentionGroup = observer(function MentionGroup_( const { isSelected, node } = props; const { groups } = useStores(); const group = groups.get(node.attrs.modelId); - const { className, ...attrs } = getAttributesFromNode(node); + const { className, ...attrs } = getAttributesFromNode(node, isSelected); return ( - + {group?.name || node.attrs.label} @@ -120,12 +125,26 @@ export const MentionDocument = observer(function MentionDocument_( props: ComponentProps ) { const { isSelected, node } = props; - const { documents } = useStores(); + const { t } = useTranslation(); + const { documents, collections, unfurls } = useStores(); const doc = documents.get(node.attrs.modelId); const modelId = node.attrs.modelId; const anchorId = node.attrs.anchorId; - const { className, unfurl, ...attrs } = getAttributesFromNode(node); + const isCard = node.attrs.display === MentionDisplay.Card; + const { className, unfurl, ...attrs } = getAttributesFromNode( + node, + isSelected + ); const sharePath = useSharePath(); + const { shareId } = useShare(); + const hash = anchorId ? `#${anchorId}` : ""; + + // The summary is specific to the viewer, so it is kept in the store and not + // written to the node. The share id is always included, even for a root + // share, so that the server can check access through the share. + const unfurlUrl = isCard + ? `${env.URL}${shareId ? `/s/${shareId}` : ""}/doc/${modelId}${hash}` + : undefined; React.useEffect(() => { if (modelId) { @@ -133,27 +152,58 @@ export const MentionDocument = observer(function MentionDocument_( } }, [modelId, documents]); + React.useEffect(() => { + if (unfurlUrl) { + void unfurls.fetchUnfurl({ url: unfurlUrl }); + } + }, [unfurlUrl, unfurls]); + const documentPath = sharePath(doc?.path ?? `/doc/${node.attrs.modelId}`); + const icon = doc?.icon ? ( + + ) : ( + + ); + const title = doc?.title || node.attrs.label; + + if (isCard) { + const documentUnfurl = unfurlUrl ? unfurls.get(unfurlUrl)?.data : undefined; + const isDocumentUnfurl = + documentUnfurl?.type === UnfurlResourceType.Document; + const collection = doc?.collectionId + ? collections.get(doc.collectionId) + : undefined; + + return ( + + + + ); + } return ( - - {doc?.icon ? ( - - ) : ( - - )} - {doc?.title || node.attrs.label} + + {icon} + {title} ); }); @@ -165,7 +215,10 @@ export const MentionCollection = observer(function MentionCollection_( const { collections } = useStores(); const collection = collections.get(node.attrs.modelId); const modelId = node.attrs.modelId; - const { className, unfurl, ...attrs } = getAttributesFromNode(node); + const { className, unfurl, ...attrs } = getAttributesFromNode( + node, + isSelected + ); const sharePath = useSharePath(); React.useEffect(() => { @@ -174,25 +227,39 @@ export const MentionCollection = observer(function MentionCollection_( } }, [modelId, collections]); - return ( - - {collection?.icon ? ( - + ) : ( + + ); + const title = collection?.title || node.attrs.label; + const to = sharePath(collection?.path ?? `/collection/${node.attrs.modelId}`); + + if (node.attrs.display === MentionDisplay.Card) { + return ( + + - ) : ( - - )} - {collection?.title || node.attrs.label} + + ); + } + + return ( + + {icon} + {title} ); }); @@ -219,7 +286,7 @@ export const MentionURL = (props: IssueUrlProps) => { className, unfurl: unfurlAttr, ...attrs - } = getAttributesFromNode(node); + } = getAttributesFromNode(node, isSelected); const url = typeof attrs.href === "string" ? attrs.href : undefined; const unfurl = url ? (unfurls.get(url)?.data ?? unfurlAttr) : undefined; @@ -286,12 +353,16 @@ export const MentionURL = (props: IssueUrlProps) => { ); } + if (node.attrs.display === MentionDisplay.Card) { + return ( + + ); + } + return ( { className, unfurl: unfurlAttr, ...attrs - } = getAttributesFromNode(node); + } = getAttributesFromNode(node, isSelected); const unfurl = unfurls.get(attrs.href)?.data ?? unfurlAttr; @@ -364,9 +435,7 @@ export const MentionIssue = observer((props: IssuePrProps) => { return ( { className, unfurl: unfurlAttr, ...attrs - } = getAttributesFromNode(node); + } = getAttributesFromNode(node, isSelected); const unfurl = unfurls.get(attrs.href)?.data ?? unfurlAttr; @@ -444,9 +513,7 @@ export const MentionProject = observer((props: ProjectProps) => { return ( { className, unfurl: unfurlAttr, ...attrs - } = getAttributesFromNode(node); + } = getAttributesFromNode(node, isSelected); const unfurl = unfurls.get(attrs.href)?.data ?? unfurlAttr; @@ -515,17 +582,11 @@ export const MentionPullRequest = observer((props: IssuePrProps) => { }; }, [unfurls, attrs.href, onChangeUnfurl]); - const sharedProps = { - className: cn(className, { - "ProseMirror-selectednode": isSelected, - }), - }; - if (!unfurl) { return !loaded ? ( - + ) : ( - + ); } @@ -534,7 +595,7 @@ export const MentionPullRequest = observer((props: IssuePrProps) => { return ( + {display} ); diff --git a/shared/editor/components/Styles.ts b/shared/editor/components/Styles.ts index 35740c3524..b2d33e7c64 100644 --- a/shared/editor/components/Styles.ts +++ b/shared/editor/components/Styles.ts @@ -801,7 +801,7 @@ width: 100%; &[data-type="issue"], &[data-type="pull_request"], &[data-type="project"], - &[data-type="url"] { + &[data-type="url"]:not([data-display="card"]) { max-width: 100%; white-space: nowrap; overflow: hidden; @@ -853,6 +853,47 @@ width: 100%; &.mention-document::before { content: "+"; } + + &[data-display="card"] { + display: flex; + align-items: stretch; + gap: 0; + box-sizing: border-box; + width: 100%; + min-height: 88px; + margin: 4px 0; + padding: 0; + overflow: hidden; + white-space: normal; + font-size: 15px; + line-height: 1.4; + border-radius: 8px; + border: 1px solid ${props.theme.divider}; + background: ${props.theme.background}; + cursor: pointer; + vertical-align: top; + + &:${hover} { + background: ${props.theme.backgroundSecondary}; + } + + &.ProseMirror-selectednode { + outline: 2px solid ${props.theme.selected}; + outline-offset: -1px; + } + } +} + +.component-mention:has([data-display="card"]) { + display: block; +} + +// Cards are inline nodes displayed as blocks, so hide the forced line below +.component-mention:has([data-display="card"]) + img.ProseMirror-separator, +.component-mention:has([data-display="card"]) + + img.ProseMirror-separator + + br.ProseMirror-trailingBreak { + display: none; } .${EditorStyleHelper.suggestionTrigger} { diff --git a/shared/editor/lib/mention.ts b/shared/editor/lib/mention.ts index b90e7c0352..f0e52d3549 100644 --- a/shared/editor/lib/mention.ts +++ b/shared/editor/lib/mention.ts @@ -1,8 +1,27 @@ import type { Node, Schema } from "prosemirror-model"; import type { Primitive } from "utility-types"; import { v4 as uuidv4 } from "uuid"; +import { MentionType } from "../../types"; import { isList } from "../queries/isList"; +/** + * Whether a mention can be displayed as a preview card. + * + * @param node the node to check. + * @returns true if the node is a mention that supports the card display. + */ +export function canDisplayAsCard(node: Node): boolean { + return ( + node.type.name === "mention" && cardMentionTypes.includes(node.attrs.type) + ); +} + +const cardMentionTypes: string[] = [ + MentionType.URL, + MentionType.Document, + MentionType.Collection, +]; + export function transformListToMentions( listNode: Node, schema: Schema, diff --git a/shared/editor/nodes/Mention.test.ts b/shared/editor/nodes/Mention.test.ts index e8183034bc..e0b0835f66 100644 --- a/shared/editor/nodes/Mention.test.ts +++ b/shared/editor/nodes/Mention.test.ts @@ -1,6 +1,12 @@ import type { EditorState } from "prosemirror-state"; -import { MentionType } from "../../types"; -import { createEditorState, schema, serializer } from "../../test/editor"; +import { NodeSelection } from "prosemirror-state"; +import { MentionDisplay, MentionType } from "../../types"; +import { + createEditorState, + parser, + schema, + serializer, +} from "../../test/editor"; import Mention from "./Mention"; const id = "0c440212-8b40-49fa-8a64-2548d6b60d59"; @@ -246,3 +252,231 @@ describe("Mention ids", () => { expect(ids(newState)[0]).toEqual(expect.any(String)); }); }); + +describe("Mention display", () => { + const href = "https://example.com/article"; + + const urlMention = (attrs: Record = {}) => + schema.nodes.mention.create({ + id, + modelId, + type: MentionType.URL, + label: "Article", + href, + ...attrs, + }); + + const selectMention = (node: ReturnType) => { + const state = createEditorState( + schema.nodes.doc.create(null, [ + schema.nodes.paragraph.create(null, [node]), + ]) + ); + return state.apply( + state.tr.setSelection(NodeSelection.create(state.doc, 1)) + ); + }; + + const setDisplay = (state: EditorState, display: MentionDisplay) => { + const commands = new Mention().commands({ + type: schema.nodes.mention, + schema, + }); + let next = state; + const handled = commands.mentionDisplay({ display })(state, (tr) => { + next = state.apply(tr); + }); + return { handled, next }; + }; + + it("keeps the JSON of an existing inline mention unchanged", () => { + const json = { + type: "mention", + attrs: { type: MentionType.URL, label: "Article", modelId, id, href }, + }; + const node = schema.nodeFromJSON(json); + + expect(node.attrs.display).toBeUndefined(); + expect(JSON.stringify(node.toJSON())).toBe(JSON.stringify(json)); + }); + + it.each([undefined, MentionDisplay.Card])( + "writes display %s to the DOM and reads it back", + (display) => { + const spec = schema.nodes.mention.spec; + const node = urlMention({ display }); + const [, domAttrs] = spec.toDOM!(node) as [ + string, + Record, + ]; + expect(domAttrs["data-display"]).toBe(display); + + const rule = spec.parseDOM?.[0] as { + getAttrs: (dom: unknown) => Record; + }; + const attrs = rule.getAttrs({ + dataset: { type: MentionType.URL, id: modelId, display }, + innerText: "Article", + id, + getAttribute: () => href, + }); + expect(attrs.display).toBe(display); + } + ); + + it("switches a selected link mention between inline and card", () => { + const state = selectMention(urlMention()); + + const toCard = setDisplay(state, MentionDisplay.Card); + expect(toCard.handled).toBe(true); + expect(toCard.next.doc.nodeAt(1)?.attrs.display).toBe(MentionDisplay.Card); + expect(toCard.next.selection).toBeInstanceOf(NodeSelection); + + const toInline = setDisplay(toCard.next, MentionDisplay.Inline); + expect(toInline.next.doc.nodeAt(1)?.attrs.display).toBeUndefined(); + expect(JSON.stringify(toInline.next.doc.toJSON())).toBe( + JSON.stringify(state.doc.toJSON()) + ); + }); + + it.each([MentionType.Document, MentionType.Collection])( + "switches a selected %s mention to a card", + (type) => { + const state = selectMention(urlMention({ type, href: undefined })); + const toCard = setDisplay(state, MentionDisplay.Card); + expect(toCard.handled).toBe(true); + expect(toCard.next.doc.nodeAt(1)?.attrs.display).toBe( + MentionDisplay.Card + ); + } + ); + + it("does not change the display of other mention types", () => { + const state = selectMention(urlMention({ type: MentionType.User })); + expect(setDisplay(state, MentionDisplay.Card).handled).toBe(false); + }); + + it("creates a paragraph below a selected card on Enter", () => { + const state = selectMention(urlMention({ display: MentionDisplay.Card })); + let next = state; + const handled = new Mention().keys().Enter(state, (tr) => { + next = state.apply(tr); + }); + + expect(handled).toBe(true); + expect(next.doc.childCount).toBe(2); + expect(next.doc.child(0).firstChild?.attrs.display).toBe( + MentionDisplay.Card + ); + expect(next.doc.child(1).content.size).toBe(0); + expect(next.selection.$head.parent).toBe(next.doc.child(1)); + }); + + it("creates a paragraph below a selected card in a heading", () => { + const state = createEditorState( + schema.nodes.doc.create(null, [ + schema.nodes.heading.create({ level: 2 }, [ + urlMention({ display: MentionDisplay.Card }), + ]), + ]) + ); + const selected = state.apply( + state.tr.setSelection(NodeSelection.create(state.doc, 1)) + ); + let next = selected; + new Mention().keys().Enter(selected, (tr) => { + next = selected.apply(tr); + }); + + expect(next.doc.child(0).type.name).toBe("heading"); + expect(next.doc.child(1).type.name).toBe("paragraph"); + expect(next.selection.$head.parent).toBe(next.doc.child(1)); + }); +}); + +describe("Mention markdown round trip", () => { + const roundTrip = ( + attrs: Record, + options?: { commonMark?: boolean } + ) => { + const markdown = serializeMention(attrs, options); + let mention: ReturnType | undefined; + parser.parse(markdown)?.descendants((node) => { + if (node.type.name === "mention") { + mention = node; + } + }); + return { markdown, mention }; + }; + + const cases: Record> = { + url: { + type: MentionType.URL, + label: "Example", + href: "https://example.com/a?b=c", + }, + document: { type: MentionType.Document, label: "Roadmap" }, + collection: { type: MentionType.Collection, label: "Product" }, + }; + + describe.each([false, true])("with commonMark %s", (commonMark) => { + it.each(Object.keys(cases))("keeps a %s card", (key) => { + const { markdown, mention } = roundTrip( + { ...cases[key], display: MentionDisplay.Card }, + { commonMark } + ); + expect(markdown).toContain('"card")'); + expect(mention?.attrs.type).toBe(cases[key].type); + expect(mention?.attrs.display).toBe(MentionDisplay.Card); + }); + + it.each(Object.keys(cases))( + "does not add a title to an inline %s", + (key) => { + const { markdown } = roundTrip(cases[key], { commonMark }); + expect(markdown).not.toContain('"card"'); + } + ); + }); + + it.each([false, true])( + "keeps the url of a link card with commonMark %s", + (commonMark) => { + const { markdown, mention } = roundTrip( + { ...cases.url, display: MentionDisplay.Card }, + { commonMark } + ); + expect(markdown).toBe('@[Example](https://example.com/a?b=c "card")'); + expect(mention?.attrs.href).toBe("https://example.com/a?b=c"); + } + ); + + it("keeps the model id of a document card", () => { + const { mention } = roundTrip({ + ...cases.document, + display: MentionDisplay.Card, + }); + expect(mention?.attrs.modelId).toBe(modelId); + }); + + it("keeps the anchor of a document card", () => { + const { markdown, mention } = roundTrip({ + ...cases.document, + anchorId: "h-goals", + display: MentionDisplay.Card, + }); + expect(markdown).toBe(`@[Roadmap](/doc/${modelId}#h-goals "card")`); + expect(mention?.attrs.anchorId).toBe("h-goals"); + }); + + it("keeps inline document mentions as plain links", () => { + expect(serializeMention(cases.document)).toBe(`[Roadmap](/doc/${modelId})`); + }); + + it("omits the display from an inline mention parsed from Markdown", () => { + const { mention } = roundTrip(cases.url, { commonMark: true }); + + expect(mention).toBeDefined(); + expect(JSON.stringify(mention?.toJSON())).not.toContain('"display"'); + }); +}); diff --git a/shared/editor/nodes/Mention.tsx b/shared/editor/nodes/Mention.tsx index c369e820f1..403cb21c29 100644 --- a/shared/editor/nodes/Mention.tsx +++ b/shared/editor/nodes/Mention.tsx @@ -13,7 +13,9 @@ import type { Primitive } from "utility-types"; import { v4 as uuidv4 } from "uuid"; import env from "../../env"; import type { UnfurlResponse } from "../../types"; -import { MentionType, UnfurlResourceType } from "../../types"; +import { t } from "i18next"; +import { AlignImageRightIcon, EmailIcon } from "outline-icons"; +import { MentionDisplay, MentionType, UnfurlResourceType } from "../../types"; import { dateToReadable } from "../../utils/date"; import { MentionCollection, @@ -26,14 +28,20 @@ import { MentionURL, MentionUser, } from "../components/Mentions"; +import { selectBlockLikeVertically } from "../commands/selectBlockLikeVertically"; import type { MarkdownSerializerState } from "../lib/markdown/serializer"; -import { transformListToMentions } from "../lib/mention"; +import { canDisplayAsCard, transformListToMentions } from "../lib/mention"; import { findParentNodeClosestToPos } from "../queries/findParentNode"; import { isInList } from "../queries/isInList"; import { isList } from "../queries/isList"; import { RepairPlugin } from "../plugins/RepairPlugin"; import mentionRule from "../rules/mention"; -import type { ComponentProps, NodeWithPos } from "../types"; +import { isNodeActive } from "../queries/isNodeActive"; +import type { + ComponentProps, + NodeWithPos, + SelectionToolbarMenuDescriptor, +} from "../types"; import Node from "./Node"; /** @@ -118,6 +126,9 @@ export default class Mention extends Node { unfurl: { default: undefined, }, + display: { + default: undefined, + }, }, inline: true, marks: "", @@ -147,6 +158,10 @@ export default class Mention extends Node { unfurl: dom.dataset.unfurl ? JSON.parse(dom.dataset.unfurl) : undefined, + display: + dom.dataset.display === MentionDisplay.Card + ? MentionDisplay.Card + : undefined, }; }, }, @@ -157,10 +172,11 @@ export default class Mention extends Node { ? "span" : "a", { - // Date mentions are self-contained and have nothing to unfurl, so - // they opt out of the hover preview behaviour. + // Dates have nothing to unfurl and cards already show the preview, + // so both opt out of the hover preview behaviour. class: - node.attrs.type === MentionType.Date + node.attrs.type === MentionType.Date || + node.attrs.display === MentionDisplay.Card ? node.type.name : `${node.type.name} use-hover-preview`, id: node.attrs.id, @@ -184,6 +200,10 @@ export default class Mention extends Node { ? sanitizeUrl(node.attrs.href) : `mention://${node.attrs.id}/${node.attrs.type}/${node.attrs.modelId}`, "data-unfurl": JSON.stringify(node.attrs.unfurl), + "data-display": + node.attrs.display === MentionDisplay.Card + ? MentionDisplay.Card + : undefined, }, toPlainText(node), ], @@ -242,6 +262,41 @@ export default class Mention extends Node { return [mentionRule]; } + selectionToolbarMenus(): SelectionToolbarMenuDescriptor[] { + return [ + { + priority: 50, + matches: (ctx) => + !ctx.readOnly && + ctx.selection instanceof NodeSelection && + canDisplayAsCard(ctx.selection.node), + getItems: (ctx) => { + const { schema } = ctx; + return [ + { + name: "mentionDisplay", + tooltip: t("Display as mention"), + attrs: { display: MentionDisplay.Inline }, + active: (state) => + state.selection instanceof NodeSelection && + state.selection.node.attrs.display !== MentionDisplay.Card, + icon: , + }, + { + name: "mentionDisplay", + tooltip: t("Display as card"), + attrs: { display: MentionDisplay.Card }, + active: isNodeActive(schema.nodes.mention, { + display: MentionDisplay.Card, + }), + icon: , + }, + ]; + }, + }, + ]; + } + get plugins() { return [ // Ensure mentions have unique IDs. Unchanged mentions keep their id, so @@ -283,10 +338,27 @@ export default class Mention extends Node { MentionType.PullRequest, MentionType.Project, ]; + const isCard = (node: ProsemirrorNode) => + node.type.name === this.name && + node.attrs.display === MentionDisplay.Card; return { - Enter: (state) => { + ArrowUp: selectBlockLikeVertically(-1, isCard), + ArrowDown: selectBlockLikeVertically(1, isCard), + Enter: (state, dispatch) => { const { selection } = state; + if (selection instanceof NodeSelection && isCard(selection.node)) { + const tr = state.tr.split(selection.to, 1, [ + { type: state.schema.nodes.paragraph }, + ]); + dispatch?.( + tr + .setSelection(TextSelection.create(tr.doc, selection.to + 2)) + .scrollIntoView() + ); + return true; + } + if ( selection instanceof NodeSelection && selection.node.type.name === this.name && @@ -342,6 +414,29 @@ export default class Mention extends Node { dispatch?.(transaction); return true; }, + mentionDisplay: + (attrs: { display: MentionDisplay }): Command => + (state, dispatch) => { + const { selection } = state; + if ( + !(selection instanceof NodeSelection) || + !canDisplayAsCard(selection.node) + ) { + return false; + } + + const tr = state.tr.setNodeAttribute( + selection.from, + "display", + attrs.display === MentionDisplay.Card + ? MentionDisplay.Card + : undefined + ); + dispatch?.( + tr.setSelection(NodeSelection.create(tr.doc, selection.from)) + ); + return true; + }, mention_list: (attrs: Record): Command => (state, dispatch) => { @@ -394,29 +489,33 @@ export default class Mention extends Node { const label = mType === MentionType.Date ? dateMentionLabel(node) : node.attrs.label; const id = node.attrs.id; + const isCard = node.attrs.display === MentionDisplay.Card; - // Use regular links for document and collection mentions - if (mType === MentionType.Document) { - state.write( - `[${label}](/doc/${mId}${ - node.attrs.anchorId ? `#${node.attrs.anchorId}` : "" - })` - ); - } else if (mType === MentionType.Collection) { - state.write(`[${label}](/collection/${mId})`); + // The link title stores the card display, so the URL is not changed. + const title = isCard ? ` "${MentionDisplay.Card}"` : ""; + + // Use regular links for document and collection mentions. Cards add the + // "@" prefix so they are parsed back into a mention. + if (mType === MentionType.Document || mType === MentionType.Collection) { + const href = + mType === MentionType.Document + ? `/doc/${mId}${node.attrs.anchorId ? `#${node.attrs.anchorId}` : ""}` + : `/collection/${mId}`; + state.write(`${isCard ? "@" : ""}[${label}](${href}${title})`); } else if ( - state.options.commonMark && + (state.options.commonMark || isCard) && (isExternalMention(mType) || mType === MentionType.URL) && node.attrs.href ) { // Markdown that leaves Outline cannot resolve a mention:// reference, so - // external mentions fall back to the URL they already carry. The "@" - // prefix allows them to be parsed back into a mention on the way in. - state.write(`@[${label}](${sanitizeUrl(node.attrs.href)})`); + // external mentions fall back to the URL they already carry. Cards need + // the URL to render, so they always use it. The "@" prefix allows them to + // be parsed back into a mention on the way in. + state.write(`@[${label}](${sanitizeUrl(node.attrs.href)}${title})`); } else { // Keep the mention:// format for everything else, it round-trips back // into a live mention through Outline's own parser. - state.write(`@[${label}](mention://${id}/${mType}/${mId})`); + state.write(`@[${label}](mention://${id}/${mType}/${mId}${title})`); } } @@ -428,7 +527,12 @@ export default class Mention extends Node { type: tok.attrGet("type"), modelId: tok.attrGet("modelId"), href: tok.attrGet("href") ?? undefined, + anchorId: tok.attrGet("anchorId") ?? undefined, label: tok.content, + display: + tok.attrGet("display") === MentionDisplay.Card + ? MentionDisplay.Card + : undefined, }), }; } @@ -459,16 +563,21 @@ export default class Mention extends Node { }; handleChangeUnfurl = - ({ - node, - getPos, - }: { - node: ProsemirrorNode; - getPos: () => number | undefined; - }) => + ({ getPos }: { node: ProsemirrorNode; getPos: () => number | undefined }) => (unfurl: UnfurlResponse[keyof UnfurlResponse]) => { const { view } = this.editor; const { tr } = view.state; + const pos = getPos(); + if (pos === undefined) { + return; + } + + // The node may have changed while the unfurl was loading, for example + // when it was switched to a card, so the current node is used. + const node = tr.doc.nodeAt(pos); + if (!node || node.type.name !== this.name) { + return; + } // Only unfurls of a resource the mention can represent are stored, others // such as documents depend on the viewer and change between views. @@ -492,19 +601,15 @@ export default class Mention extends Node { // The resource an external link points at is only known once it has been // unfurled, so narrow a generic URL mention to the type it turned out to // be – an issue, pull request or project. + // Cards keep the generic URL type so their display survives the unfurl. if ( node.attrs.type === MentionType.URL && + node.attrs.display !== MentionDisplay.Card && unfurledType !== node.attrs.type ) { overrides.type = unfurledType; } - const pos = getPos(); - - if (pos === undefined) { - return; - } - if (!isMatch(node.attrs, overrides)) { const transaction = tr.setNodeMarkup(pos, undefined, { ...node.attrs, diff --git a/shared/editor/rules/mention.test.ts b/shared/editor/rules/mention.test.ts index 65193101ae..a1e61bd9be 100644 --- a/shared/editor/rules/mention.test.ts +++ b/shared/editor/rules/mention.test.ts @@ -234,4 +234,77 @@ describe("mention rule", () => { expect(mentions).toHaveLength(0); }); }); + + describe("documents and collections", () => { + const docId = "6f4e9a32-5b1c-4d2e-9f3a-8b7c6d5e4f30"; + + const firstMention = (markdown: string) => { + const inline = md.parse(markdown, {}).find((t) => t.type === "inline"); + return inline?.children?.find((t) => t.type === "mention"); + }; + + it("should parse a document link with @ prefix as a document mention", () => { + const mention = firstMention(`@[Roadmap](/doc/${docId})`); + expect(mention?.attrGet("type")).toEqual(MentionType.Document); + expect(mention?.attrGet("modelId")).toEqual(docId); + expect(mention?.attrGet("id")).toBeTruthy(); + expect(mention?.attrGet("display")).toBeNull(); + expect(mention?.content).toEqual("Roadmap"); + }); + + it("should keep the anchor of a document link", () => { + const mention = firstMention(`@[Roadmap](/doc/${docId}#h-goals)`); + expect(mention?.attrGet("anchorId")).toEqual("h-goals"); + }); + + it("should parse a collection link with @ prefix as a collection mention", () => { + const mention = firstMention(`@[Product](/collection/${docId})`); + expect(mention?.attrGet("type")).toEqual(MentionType.Collection); + expect(mention?.attrGet("modelId")).toEqual(docId); + }); + + it("should not parse a document link that uses a slug", () => { + expect(firstMention("@[Roadmap](/doc/roadmap-abc123)")).toBeUndefined(); + }); + + it("should not parse a collection link with an anchor", () => { + expect( + firstMention(`@[Product](/collection/${docId}#h-goals)`) + ).toBeUndefined(); + }); + + it("should not parse a document link without @ prefix", () => { + expect(firstMention(`[Roadmap](/doc/${docId})`)).toBeUndefined(); + }); + }); + + describe("card display", () => { + const displayOf = (markdown: string) => { + const inline = md.parse(markdown, {}).find((t) => t.type === "inline"); + return inline?.children + ?.find((t) => t.type === "mention") + ?.attrGet("display"); + }; + + it("should read the card display from the link title", () => { + expect(displayOf('@[Example](https://example.com/a?b=c "card")')).toEqual( + "card" + ); + expect( + displayOf( + '@[Roadmap](/doc/6f4e9a32-5b1c-4d2e-9f3a-8b7c6d5e4f30 "card")' + ) + ).toEqual("card"); + }); + + it("should ignore other link titles", () => { + expect(displayOf('@[Example](https://example.com "other")')).toBeNull(); + }); + + it("should render the display in HTML", () => { + expect(md.render('@[Example](https://example.com "card")')).toContain( + 'data-display="card"' + ); + }); + }); }); diff --git a/shared/editor/rules/mention.ts b/shared/editor/rules/mention.ts index 20539b558f..c08db255a1 100644 --- a/shared/editor/rules/mention.ts +++ b/shared/editor/rules/mention.ts @@ -2,7 +2,8 @@ import type MarkdownIt from "markdown-it"; import type StateCore from "markdown-it/lib/rules_core/state_core.mjs"; import type Token from "markdown-it/lib/token.mjs"; import { v4 as uuidv4 } from "uuid"; -import { MentionType } from "../../types"; +import isUUID from "validator/lib/isUUID"; +import { MentionDisplay, MentionType } from "../../types"; import parseMentionUrl from "@shared/utils/parseMentionUrl"; import { sanitizeUrl } from "@shared/utils/urls"; @@ -35,6 +36,34 @@ function parseExternalHref(href: string): URL | undefined { } } +/** Matches the links that document and collection mentions are written as. */ +const internalHrefRegex = /^\/(doc|collection)\/([^/#?]+)(?:#(.+))?$/; + +/** + * Parse an href that points at a document or collection by id. + * + * @param href the URL string to parse. + * @returns the mention type, model id and anchor, or undefined when the href + * does not point at a document or collection by id. + */ +function parseInternalHref( + href: string +): { type: MentionType; modelId: string; anchorId?: string } | undefined { + const match = internalHrefRegex.exec(href); + if (!match) { + return undefined; + } + + const [, kind, modelId, anchorId] = match; + if (!isUUID(modelId)) { + return undefined; + } + if (kind === "collection") { + return anchorId ? undefined : { type: MentionType.Collection, modelId }; + } + return { type: MentionType.Document, modelId, anchorId }; +} + /** * Parse a mention:// href into the id, type and modelId needed by the editor. * For 2-segment URLs (no instance id) a fresh UUID is generated. @@ -68,10 +97,14 @@ const renderMention = (md: MarkdownIt) => (tokens: Token[], idx: number) => { const mId = esc(tokens[idx].attrGet("modelId")); const href = tokens[idx].attrGet("href"); const label = esc(tokens[idx].content); + const display = + tokens[idx].attrGet("display") === MentionDisplay.Card + ? ` data-display="${MentionDisplay.Card}"` + : ""; return href - ? `${label}` - : `${label}`; + ? `${label}` + : `${label}`; }; function parseMentions(state: StateCore) { @@ -110,7 +143,9 @@ function parseMentions(state: StateCore) { !( attr && attr[0] === "href" && - (isMentionHref(attr[1]) || parseExternalHref(attr[1])) + (isMentionHref(attr[1]) || + parseExternalHref(attr[1]) || + parseInternalHref(attr[1])) ) ) { return false; @@ -129,11 +164,19 @@ function parseMentions(state: StateCore) { // href must be present, otherwise the href test would've failed const href = openToken.attrs![0][1]; const mentionToken = new state.Token("mention", "", 0); - const externalUrl = isMentionHref(href) - ? undefined - : parseExternalHref(href); + const isMention = isMentionHref(href); + const internal = isMention ? undefined : parseInternalHref(href); + const externalUrl = + isMention || internal ? undefined : parseExternalHref(href); - if (externalUrl) { + if (internal) { + mentionToken.attrSet("id", uuidv4()); + mentionToken.attrSet("type", internal.type); + mentionToken.attrSet("modelId", internal.modelId); + if (internal.anchorId) { + mentionToken.attrSet("anchorId", internal.anchorId); + } + } else if (externalUrl) { // External links carry their identity in the href, so the ids are // generated the same way a paste in the editor would. The mention is // generic here and is narrowed to the resource it points at by the @@ -151,6 +194,11 @@ function parseMentions(state: StateCore) { mentionToken.content = textToken.content; + // The link title stores the display, so the URL is not changed. + if (openToken.attrGet("title") === MentionDisplay.Card) { + mentionToken.attrSet("display", MentionDisplay.Card); + } + // "link_open", followed by "text" and "link_close" tokens are coalesced // into "mention" token, hence removed return [precToken, mentionToken]; diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index eec0c364fb..15d9f48228 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -793,6 +793,7 @@ "Members of “{{ groupName }}” with access to this document will be notified": "Members of “{{ groupName }}” with access to this document will be notified", "Keep as link": "Keep as link", "Mention": "Mention", + "Card": "Card", "Embed": "Embed", "Not supported": "Not supported", "Sorry, that link won’t work for this embed type": "Sorry, that link won’t work for this embed type", @@ -1970,6 +1971,7 @@ "Click to copy": "Click to copy", "Empty diagram": "Empty diagram", "Double-click to edit": "Double-click to edit", + "in {{ collectionName }}": "in {{ collectionName }}", "Loading": "Loading", "Error loading data": "Error loading data", "Uploading {{ name }}": "Uploading {{ name }}", @@ -1978,6 +1980,8 @@ "Hide completed": "Hide completed", "Sorry, the link could not be copied": "Sorry, the link could not be copied", "Write a caption": "Write a caption", + "Display as mention": "Display as mention", + "Display as card": "Display as card", "Add title": "Add title", "Add content": "Add content", "Tomorrow": "Tomorrow", diff --git a/shared/types/unfurl.ts b/shared/types/unfurl.ts index 195a62aa98..51caa9d370 100644 --- a/shared/types/unfurl.ts +++ b/shared/types/unfurl.ts @@ -11,6 +11,14 @@ export enum MentionType { Date = "date", } +/** How a mention is presented in a document. */ +export enum MentionDisplay { + /** Rendered inline with surrounding text. */ + Inline = "inline", + /** Rendered as a preview card with image, title and description. */ + Card = "card", +} + /** The kinds of resource that a link can unfurl to. */ export enum UnfurlResourceType { URL = "url", @@ -82,6 +90,8 @@ export type UnfurlResponse = { title: string; /** Document summary */ summary: string; + /** Source of an image from the document to use as a preview */ + thumbnailUrl?: string; /** Viewer's last activity on this document */ lastActivityByViewer?: string; }; diff --git a/shared/utils/ProsemirrorDataHelper.test.ts b/shared/utils/ProsemirrorDataHelper.test.ts index 9697812be1..2705f65e89 100644 --- a/shared/utils/ProsemirrorDataHelper.test.ts +++ b/shared/utils/ProsemirrorDataHelper.test.ts @@ -62,4 +62,84 @@ describe("ProsemirrorDataHelper", () => { expect(ProsemirrorDataHelper.isEmpty(data)).toBe(false); }); }); + + describe("getFirstText", () => { + it("returns the text of the first block with text", () => { + const data: ProsemirrorData = { + type: "doc", + content: [ + { type: "paragraph", content: [] }, + { + type: "paragraph", + content: [ + { type: "text", text: "Hello " }, + { type: "text", text: "world", marks: [{ type: "strong" }] }, + ], + }, + { + type: "paragraph", + content: [{ type: "text", text: "Second" }], + }, + ], + }; + expect(ProsemirrorDataHelper.getFirstText(data)).toBe("Hello world"); + }); + + it("reads text nested in other blocks", () => { + const data: ProsemirrorData = { + type: "doc", + content: [ + { + type: "blockquote", + content: [ + { type: "paragraph", content: [{ type: "text", text: "Quote" }] }, + ], + }, + ], + }; + expect(ProsemirrorDataHelper.getFirstText(data)).toBe("Quote"); + }); + + it("stops at a hard break", () => { + const data: ProsemirrorData = { + type: "doc", + content: [ + { + type: "paragraph", + content: [ + { type: "text", text: "First line" }, + { type: "br" }, + { type: "text", text: "Second line" }, + ], + }, + ], + }; + expect(ProsemirrorDataHelper.getFirstText(data)).toBe("First line"); + }); + + it("stops at the end of a nested block", () => { + const data: ProsemirrorData = { + type: "doc", + content: [ + { + type: "blockquote", + content: [ + { type: "paragraph", content: [{ type: "text", text: "First" }] }, + { + type: "paragraph", + content: [{ type: "text", text: "Second" }], + }, + ], + }, + ], + }; + expect(ProsemirrorDataHelper.getFirstText(data)).toBe("First"); + }); + + it("returns undefined for an empty document", () => { + expect( + ProsemirrorDataHelper.getFirstText(ProsemirrorDataHelper.getEmpty()) + ).toBeUndefined(); + }); + }); }); diff --git a/shared/utils/ProsemirrorDataHelper.ts b/shared/utils/ProsemirrorDataHelper.ts index f90af5536f..976bd02bf1 100644 --- a/shared/utils/ProsemirrorDataHelper.ts +++ b/shared/utils/ProsemirrorDataHelper.ts @@ -44,4 +44,35 @@ export class ProsemirrorDataHelper { return !data.content || data.content.length === 0; } + + /** + * Returns the first line of text in the document, useful for a short plain + * text preview. Text blocks and hard breaks start a new line. + * + * @param data the ProsemirrorData to read. + * @returns the trimmed first line with text, or undefined. + */ + static getFirstText(data: ProsemirrorData): string | undefined { + return ProsemirrorDataHelper.toLines(data) + .map((line) => line.trim()) + .find(Boolean); + } + + private static toLines(node: ProsemirrorData): string[] { + if (node.type === "text") { + return [node.text ?? ""]; + } + + // Text joins the current line. Any other node, such as a paragraph or a + // hard break, is on its own lines. + const lines = [""]; + for (const child of node.content ?? []) { + if (child.type === "text") { + lines[lines.length - 1] += child.text ?? ""; + } else { + lines.push(...ProsemirrorDataHelper.toLines(child), ""); + } + } + return lines; + } }