Files
outline/shared/editor/nodes/Emoji.tsx
T
Tom Moor bb0f59f562 fix: Resolve text node event targets in editor handlers (#14719)
In Firefox an editor mouse event can target a Text node. Use
getEventTargetElement so handlers no longer throw on closest() or skip
the event.
2026-11-25 20:20:26 -05:00

206 lines
5.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 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 { Plugin, TextSelection } from "prosemirror-state";
import type { Primitive } from "utility-types";
import Extension from "../lib/Extension";
import { getEmojiFromName, loadEmojiData } from "../lib/emoji";
import type { MarkdownSerializerState } from "../lib/markdown/serializer";
import emojiRule from "../rules/emoji";
import { isUUID } from "validator";
import type { ComponentProps } from "../types";
import { getEventTargetElement } from "../lib/eventTarget";
import { CustomEmoji } from "../../components/CustomEmoji";
export default class Emoji extends Extension {
constructor() {
super();
// Begin loading emoji data as soon as this extension is instantiated so
// it is available by the time the editor renders emoji nodes.
void loadEmojiData();
}
get type() {
return "node";
}
get name() {
return "emoji";
}
get schema(): NodeSpec {
return {
attrs: {
"data-name": {
default: "grey_question",
validate: "string",
},
},
inline: true,
// Legacy documents contain emoji nodes with text content, so the schema
// stays permissive – `atom` is what prevents content being added or edited.
content: "text*",
marks: "",
group: "inline",
atom: true,
selectable: false,
parseDOM: [
{
priority: 100,
tag: "strong.emoji",
preserveWhitespace: "full",
getAttrs: (dom: HTMLElement) =>
dom.dataset.name
? {
"data-name": dom.dataset.name,
}
: false,
},
],
toDOM: (node) => {
const name = node.attrs["data-name"];
return [
"strong",
{
class: `emoji ${name}`,
"data-name": name,
},
getEmojiFromName(name),
];
},
leafText: (node) => {
const name = node.attrs["data-name"];
// Custom emojis are stored as UUIDs, preserve the shortcode format
// so they can be rendered by EmojiText component
if (isUUID(name)) {
return `:${name}:`;
}
return getEmojiFromName(name);
},
};
}
get rulePlugins() {
return [emojiRule];
}
get plugins() {
return [
new Plugin({
props: {
// Placing the caret in front of an emoji is tricky as click events directly
// on the emoji will not behave the same way as clicks on text characters, this
// plugin ensures that clicking on an emoji behaves more naturally.
handleClickOn: (view, _pos, node, nodePos, event) => {
const element = getEventTargetElement(event);
if (element && node.type.name === this.name) {
const rect = element.getBoundingClientRect();
const clickX = event.clientX - rect.left;
const side = clickX < rect.width / 2 ? -1 : 1;
// If the click is in the left half of the emoji, place the caret before it
const tr = view.state.tr.setSelection(
TextSelection.near(
view.state.doc.resolve(
side === -1 ? nodePos : nodePos + node.nodeSize
),
side
)
);
view.dispatch(tr);
return true;
}
return false;
},
},
}),
];
}
component = (props: ComponentProps) => {
const name = props.node.attrs["data-name"];
return (
<strong className="emoji" data-name={name}>
{isUUID(name) ? (
<CustomEmoji value={name} size="1em" />
) : (
getEmojiFromName(name)
)}
</strong>
);
};
commands({ type }: { type: NodeType; schema: Schema }) {
return (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;
};
}
keys(): Record<string, Command> {
return {
Backspace: this.deleteAdjacentEmoji(-1),
Delete: this.deleteAdjacentEmoji(1),
};
}
toMarkdown(state: MarkdownSerializerState, node: ProsemirrorNode) {
const name = node.attrs["data-name"];
if (name) {
state.write(`:${name}:`);
}
}
parseMarkdown() {
return {
node: "emoji",
getAttrs: (tok: Token) => ({ "data-name": tok.markup.trim() }),
};
}
/**
* Deletes the whole emoji node next to the cursor. The node is uneditable, so
* some browsers, such as Chrome on Android, do not delete it natively.
*
* @param dir -1 to delete the emoji before the cursor, 1 for after.
* @returns a command.
*/
private deleteAdjacentEmoji(dir: -1 | 1): Command {
return (state, dispatch) => {
const { selection } = state;
if (!(selection instanceof TextSelection) || !selection.$cursor) {
return false;
}
const { $cursor } = selection;
const node = dir === -1 ? $cursor.nodeBefore : $cursor.nodeAfter;
if (node?.type.name !== this.name) {
return false;
}
const from = dir === -1 ? $cursor.pos - node.nodeSize : $cursor.pos;
dispatch?.(state.tr.delete(from, from + node.nodeSize).scrollIntoView());
return true;
};
}
}