Files
outline/shared/editor/nodes/Mention.tsx
T
Tom Moor a46968c3f4 feat: Hover menu to switch mentions between inline and card display (#14588)
* feat: Show a display menu on hover for mentions that can be cards

Mentions that can display as a card show an overflow button on hover,
inside the end of the pill or in the top corner of the card. The button
opens a menu to switch between the mention and card display, which
replaces the selection toolbar for these mentions.

* fix: Resolve the mention position on click and hide the button on scroll

The menu looks up the mention position when an item is chosen, as edits
by collaborators can move it while the menu is open. The button follows
the mention when content above it changes and hides when a table is
scrolled.

* feat: Show the mention display button for a selected mention

The button shows for the selected mention as well as the hovered one, so
keyboard users can reach it. Touch devices show it for the selected mention
only. Only the button takes the pointer, so the fade does not block clicks
on short mentions.
2026-11-19 18:05:06 -05:00

586 lines
18 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 { isMatch } from "es-toolkit/compat";
import { sanitizeUrl } from "../../utils/urls";
import type Token from "markdown-it/lib/token.mjs";
import type {
NodeSpec,
Node as ProsemirrorNode,
NodeType,
Schema,
} from "prosemirror-model";
import type { Command } from "prosemirror-state";
import { NodeSelection, TextSelection } from "prosemirror-state";
import type { Primitive } from "utility-types";
import { v4 as uuidv4 } from "uuid";
import env from "../../env";
import type { UnfurlResponse } from "../../types";
import { MentionDisplay, MentionType, UnfurlResourceType } from "../../types";
import { dateToReadable } from "../../utils/date";
import {
MentionCollection,
MentionDocument,
MentionGroup,
MentionIssue,
MentionProject,
MentionPullRequest,
MentionDate,
MentionURL,
MentionUser,
} from "../components/Mentions";
import { selectBlockLikeVertically } from "../commands/selectBlockLikeVertically";
import type { MarkdownSerializerState } from "../lib/markdown/serializer";
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 Node from "./Node";
/**
* Formats a date mention's stored value (a date-only or time-specific ISO
* string) into a human-readable label for display and serialization.
*
* @param node the date mention node.
* @returns the readable label, e.g. "February 3rd at 1:00 PM".
*/
function dateMentionLabel(node: ProsemirrorNode): string {
const modelId = node.attrs.modelId;
return typeof modelId === "string"
? dateToReadable(modelId)
: node.attrs.label;
}
/**
* Whether a mention points at a resource outside of Outline, in which case the
* real URL is stored in `attrs.href` rather than addressed with a `mention://`
* reference.
*
* @param type the mention type.
* @returns true if the mention links to an external URL.
*/
function isExternalMention(type: MentionType): boolean {
return (
type === MentionType.Issue ||
type === MentionType.PullRequest ||
type === MentionType.Project
);
}
/** The mention type that represents each kind of unfurled resource. */
const MentionTypeForResource: Partial<Record<UnfurlResourceType, MentionType>> =
{
[UnfurlResourceType.Issue]: MentionType.Issue,
[UnfurlResourceType.PR]: MentionType.PullRequest,
[UnfurlResourceType.Project]: MentionType.Project,
[UnfurlResourceType.URL]: MentionType.URL,
};
export default class Mention extends Node {
get name() {
return "mention";
}
/** The component requires stores and a router, neither of which exist outside the app. */
get allowComponentInStaticHTML() {
return false;
}
get schema(): NodeSpec {
const toPlainText = (node: ProsemirrorNode) => {
if (node.attrs.type === MentionType.User) {
return `@${node.attrs.label}`;
}
if (node.attrs.type === MentionType.Date) {
return dateMentionLabel(node);
}
return node.attrs.label;
};
return {
attrs: {
type: {
default: MentionType.User,
},
label: {},
modelId: {},
actorId: {
default: undefined,
},
id: {
default: undefined,
},
anchorId: {
default: undefined,
},
href: {
default: undefined,
},
unfurl: {
default: undefined,
},
display: {
default: undefined,
},
},
inline: true,
marks: "",
group: "inline",
atom: true,
parseDOM: [
{
tag: `.${this.name}`,
preserveWhitespace: "full",
priority: 100,
getAttrs: (dom: HTMLElement) => {
const type = dom.dataset.type;
const modelId = dom.dataset.id;
if (!type || !modelId) {
return false;
}
return {
type,
modelId,
actorId: dom.dataset.actorid,
label: dom.innerText,
id: dom.id,
anchorId:
dom.dataset.anchorId ?? dom.getAttribute("href")?.split("#")[1],
href: dom.getAttribute("href"),
unfurl: dom.dataset.unfurl
? JSON.parse(dom.dataset.unfurl)
: undefined,
display:
dom.dataset.display === MentionDisplay.Card
? MentionDisplay.Card
: undefined,
};
},
},
],
toDOM: (node) => [
node.attrs.type === MentionType.User ||
node.attrs.type === MentionType.Date
? "span"
: "a",
{
// 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.display === MentionDisplay.Card
? node.type.name
: `${node.type.name} use-hover-preview`,
id: node.attrs.id,
href: sanitizeUrl(
node.attrs.type === MentionType.User ||
node.attrs.type === MentionType.Date
? undefined
: node.attrs.type === MentionType.Document
? `${env.URL}/doc/${node.attrs.modelId}${
node.attrs.anchorId ? `#${node.attrs.anchorId}` : ""
}`
: node.attrs.type === MentionType.Collection
? `${env.URL}/collection/${node.attrs.modelId}`
: node.attrs.href
),
"data-type": node.attrs.type,
"data-id": node.attrs.modelId,
"data-actorid": node.attrs.actorId,
"data-anchor-id": node.attrs.anchorId,
"data-url": isExternalMention(node.attrs.type)
? 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),
],
leafText: toPlainText,
};
}
component = (props: ComponentProps) => {
switch (props.node.attrs.type) {
case MentionType.User:
return <MentionUser {...props} />;
case MentionType.Group:
return <MentionGroup {...props} />;
case MentionType.Document:
return <MentionDocument {...props} />;
case MentionType.Collection:
return <MentionCollection {...props} />;
case MentionType.Issue:
return (
<MentionIssue
{...props}
onChangeUnfurl={this.handleChangeUnfurl(props)}
/>
);
case MentionType.PullRequest:
return (
<MentionPullRequest
{...props}
onChangeUnfurl={this.handleChangeUnfurl(props)}
/>
);
case MentionType.Project:
return (
<MentionProject
{...props}
onChangeUnfurl={this.handleChangeUnfurl(props)}
/>
);
case MentionType.URL:
return (
<MentionURL
{...props}
onChangeUnfurl={this.handleChangeUnfurl(props)}
/>
);
case MentionType.Date:
return (
<MentionDate {...props} onChangeDate={this.handleChangeDate(props)} />
);
default:
return null;
}
};
get rulePlugins() {
return [mentionRule];
}
get plugins() {
return [
// Ensure mentions have unique IDs. Unchanged mentions keep their id, so
// a pasted copy is given a new id rather than the original.
new RepairPlugin({
needsRepair: (node) => node.type.name === this.name,
repair: (state, mentions) => {
const changed = mentions.filter((mention) => mention.changed);
const changedPositions = new Set(changed.map(({ pos }) => pos));
const ordered: NodeWithPos[] = [];
state.doc.descendants((node, pos) => {
if (node.type.name === this.name && !changedPositions.has(pos)) {
ordered.push({ node, pos });
}
});
ordered.push(...changed);
const seen = new Set<string>();
const tr = state.tr;
ordered.forEach(({ node, pos }) => {
const { id } = node.attrs;
if (id && !seen.has(id)) {
seen.add(id);
return;
}
tr.setNodeAttribute(pos, "id", uuidv4());
});
return tr.docChanged ? tr : null;
},
}),
];
}
keys(): Record<string, Command> {
const NavigableMention = [
MentionType.Collection,
MentionType.Document,
MentionType.Issue,
MentionType.PullRequest,
MentionType.Project,
];
const isCard = (node: ProsemirrorNode) =>
node.type.name === this.name &&
node.attrs.display === MentionDisplay.Card;
return {
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 &&
NavigableMention.includes(selection.node.attrs.type)
) {
const mentionType = selection.node.attrs.type;
let link: string | undefined;
if (isExternalMention(mentionType)) {
link = sanitizeUrl(selection.node.attrs.href);
} else {
const { modelId } = selection.node.attrs;
const linkType =
selection.node.attrs.type === MentionType.Document
? "doc"
: "collection";
link = `/${linkType}/${modelId}${
selection.node.attrs.anchorId
? `#${selection.node.attrs.anchorId}`
: ""
}`;
}
if (link) {
this.editor.props.onClickLink?.(link);
}
return true;
}
return false;
},
};
}
commands({ type }: { type: NodeType; schema: Schema }) {
return {
mention:
(attrs: Record<string, Primitive>): Command =>
(state, dispatch) => {
const { selection } = state;
const position =
selection instanceof TextSelection
? selection.$cursor?.pos
: selection.$to.pos;
if (position === undefined) {
return false;
}
const node = type.create(attrs);
const transaction = state.tr.insert(position, node);
dispatch?.(transaction);
return true;
},
mentionDisplay:
(attrs: { display: MentionDisplay; pos: number | null }): Command =>
(state, dispatch) => {
const { selection } = state;
const { pos } = attrs;
if (pos === null) {
return false;
}
const node = state.doc.nodeAt(pos);
if (!node || !canDisplayAsCard(node)) {
return false;
}
const tr = state.tr.setNodeAttribute(
pos,
"display",
attrs.display === MentionDisplay.Card
? MentionDisplay.Card
: undefined
);
// Keep the mention selected if it was selected before the change.
if (selection instanceof NodeSelection && selection.from === pos) {
tr.setSelection(NodeSelection.create(tr.doc, pos));
}
dispatch?.(tr);
return true;
},
mention_list:
(attrs: Record<string, Primitive>): Command =>
(state, dispatch) => {
const { selection } = state;
const position =
selection instanceof TextSelection
? selection.$cursor?.pos
: selection.$to.pos;
if (position === undefined || !isInList(state)) {
return false;
}
const resolvedPos = state.tr.doc.resolve(position);
const nodeWithPos = findParentNodeClosestToPos(resolvedPos, (node) =>
isList(node, this.editor.schema)
);
if (!nodeWithPos) {
return false;
}
const listNode = nodeWithPos.node,
from = nodeWithPos.pos,
to = from + listNode.nodeSize;
const listNodeWithMentions = transformListToMentions(
listNode,
this.editor.schema,
attrs
);
const tr = state.tr.deleteRange(from, to);
dispatch?.(
tr
.setSelection(TextSelection.near(tr.doc.resolve(from)))
.replaceSelectionWith(listNodeWithMentions)
);
return true;
},
};
}
toMarkdown(state: MarkdownSerializerState, node: ProsemirrorNode) {
const mType = node.attrs.type;
const mId = node.attrs.modelId;
// Date mentions store a machine-readable value, so the label is derived to
// keep the serialized output legible outside of the editor.
const label =
mType === MentionType.Date ? dateMentionLabel(node) : node.attrs.label;
const id = node.attrs.id;
const isCard = node.attrs.display === MentionDisplay.Card;
// 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 || 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. 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}${title})`);
}
}
parseMarkdown() {
return {
node: "mention",
getAttrs: (tok: Token) => ({
id: tok.attrGet("id"),
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,
}),
};
}
handleChangeDate =
({
node,
getPos,
}: {
node: ProsemirrorNode;
getPos: () => number | undefined;
}) =>
(modelId: string) => {
const { view } = this.editor;
const { tr } = view.state;
const pos = getPos();
if (pos === undefined || node.attrs.modelId === modelId) {
return;
}
const transaction = tr.setNodeMarkup(pos, undefined, {
...node.attrs,
modelId,
label: modelId,
});
view.dispatch(transaction);
};
handleChangeUnfurl =
({ 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.
const unfurledType = MentionTypeForResource[unfurl.type];
if (!unfurledType) {
return;
}
const label =
unfurl.type === UnfurlResourceType.Issue ||
unfurl.type === UnfurlResourceType.PR ||
unfurl.type === UnfurlResourceType.URL
? unfurl.title
: unfurl.type === UnfurlResourceType.Project
? unfurl.name
: undefined;
const overrides: Record<string, unknown> = label ? { label } : {};
overrides.unfurl = unfurl;
// 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;
}
if (!isMatch(node.attrs, overrides)) {
const transaction = tr.setNodeMarkup(pos, undefined, {
...node.attrs,
...overrides,
});
view.dispatch(transaction);
}
};
}