Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit c61eca8

Browse files
authored
Don't consider textual characters to be emoji (#12582)
* Don't consider textual characters to be emoji We were using emojibase-regex to match emoji within messages. However, the docs (https://emojibase.dev/docs/regex/) state that this regex matches both emoji and text presentation characters. This is not what we want, and will result in false positives for characters like '↔' that could turn into an emoji if paired with a variation selector. Unfortunately, none of the other regexes provided by Emojibase do what we want either (milesj/emojibase#174). In the meantime, browser support for the RGI_Emoji character sequence class has made it feasible to write an emoji regex by hand, so that's what I've done. * Add a fallback for BIGEMOJI_REGEX as well
1 parent 489bc32 commit c61eca8

File tree

6 files changed

+98
-12
lines changed

6 files changed

+98
-12
lines changed

.eslintrc.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,11 @@ module.exports = {
7878
name: "matrix-react-sdk/",
7979
message: "Please use matrix-react-sdk/src/index instead",
8080
},
81+
{
82+
name: "emojibase-regex",
83+
message:
84+
"This regex doesn't actually test for emoji. See the docs at https://emojibase.dev/docs/regex/ and prefer our own EMOJI_REGEX from HtmlUtils.",
85+
},
8186
],
8287
patterns: [
8388
{
@@ -141,6 +146,11 @@ module.exports = {
141146
],
142147
message: "Please use matrix-js-sdk/src/matrix instead",
143148
},
149+
{
150+
group: ["emojibase-regex/emoji*"],
151+
message:
152+
"This regex doesn't actually test for emoji. See the docs at https://emojibase.dev/docs/regex/ and prefer our own EMOJI_REGEX from HtmlUtils.",
153+
},
144154
],
145155
},
146156
],

src/HtmlUtils.tsx

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ limitations under the License.
2020
import React, { LegacyRef, ReactNode } from "react";
2121
import sanitizeHtml from "sanitize-html";
2222
import classNames from "classnames";
23-
import EMOJIBASE_REGEX from "emojibase-regex";
2423
import katex from "katex";
2524
import { decode } from "html-entities";
2625
import { IContent } from "matrix-js-sdk/src/matrix";
@@ -46,10 +45,35 @@ const SURROGATE_PAIR_PATTERN = /([\ud800-\udbff])([\udc00-\udfff])/;
4645
const SYMBOL_PATTERN = /([\u2100-\u2bff])/;
4746

4847
// Regex pattern for non-emoji characters that can appear in an "all-emoji" message
49-
// (Zero-Width Joiner, Zero-Width Space, Emoji presentation character, other whitespace)
50-
const EMOJI_SEPARATOR_REGEX = /[\u200D\u200B\s]|\uFE0F/g;
48+
// (Zero-Width Space, other whitespace)
49+
const EMOJI_SEPARATOR_REGEX = /[\u200B\s]/g;
50+
51+
// Regex for emoji. This includes any RGI_Emoji sequence followed by an optional
52+
// emoji presentation VS (U+FE0F), but not those sequences that are followed by
53+
// a text presentation VS (U+FE0E). We also count lone regional indicators
54+
// (U+1F1E6-U+1F1FF). Technically this regex produces false negatives for emoji
55+
// followed by U+FE0E when the emoji doesn't have a text variant, but in
56+
// practice this doesn't matter.
57+
export const EMOJI_REGEX = (() => {
58+
try {
59+
// Per our support policy, v mode is available to us, but we still don't
60+
// want the app to completely crash on older platforms. We use the
61+
// constructor here to avoid a syntax error on such platforms.
62+
return new RegExp("\\p{RGI_Emoji}(?!\\uFE0E)(?:(?<!\\uFE0F)\\uFE0F)?|[\\u{1f1e6}-\\u{1f1ff}]", "v");
63+
} catch (_e) {
64+
// v mode not supported; fall back to matching nothing
65+
return /(?!)/;
66+
}
67+
})();
5168

52-
const BIGEMOJI_REGEX = new RegExp(`^(${EMOJIBASE_REGEX.source})+$`, "i");
69+
const BIGEMOJI_REGEX = (() => {
70+
try {
71+
return new RegExp(`^(${EMOJI_REGEX.source})+$`, "iv");
72+
} catch (_e) {
73+
// Fall back, just like for EMOJI_REGEX
74+
return /(?!)/;
75+
}
76+
})();
5377

5478
/*
5579
* Return true if the given string contains emoji
@@ -266,7 +290,7 @@ export function formatEmojis(message: string | undefined, isHtmlMessage?: boolea
266290
let key = 0;
267291

268292
for (const data of graphemeSegmenter.segment(message)) {
269-
if (EMOJIBASE_REGEX.test(data.segment)) {
293+
if (EMOJI_REGEX.test(data.segment)) {
270294
if (text) {
271295
result.push(text);
272296
text = "";

src/components/views/rooms/SendMessageComposer.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ limitations under the License.
1515
*/
1616

1717
import React, { createRef, KeyboardEvent, SyntheticEvent } from "react";
18-
import EMOJI_REGEX from "emojibase-regex";
1918
import {
2019
IContent,
2120
MatrixEvent,
@@ -70,6 +69,7 @@ import { doMaybeLocalRoomAction } from "../../../utils/local-room";
7069
import { Caret } from "../../../editor/caret";
7170
import { IDiff } from "../../../editor/diff";
7271
import { getBlobSafeMimeType } from "../../../utils/blobs";
72+
import { EMOJI_REGEX } from "../../../HtmlUtils";
7373

7474
/**
7575
* Build the mentions information based on the editor model (and any related events):

src/editor/parts.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,10 @@ See the License for the specific language governing permissions and
1515
limitations under the License.
1616
*/
1717

18-
import EMOJIBASE_REGEX from "emojibase-regex";
1918
import { MatrixClient, RoomMember, Room } from "matrix-js-sdk/src/matrix";
2019

2120
import AutocompleteWrapperModel, { GetAutocompleterComponent, UpdateCallback, UpdateQuery } from "./autocomplete";
22-
import { unicodeToShortcode } from "../HtmlUtils";
21+
import { EMOJI_REGEX, unicodeToShortcode } from "../HtmlUtils";
2322
import * as Avatar from "../Avatar";
2423
import defaultDispatcher from "../dispatcher/dispatcher";
2524
import { Action } from "../dispatcher/actions";
@@ -197,7 +196,7 @@ abstract class BasePart {
197196

198197
abstract class PlainBasePart extends BasePart {
199198
protected acceptsInsertion(chr: string, offset: number, inputType: string): boolean {
200-
if (chr === "\n" || EMOJIBASE_REGEX.test(chr)) {
199+
if (chr === "\n" || EMOJI_REGEX.test(chr)) {
201200
return false;
202201
}
203202
// when not pasting or dropping text, reject characters that should start a pill candidate
@@ -375,7 +374,7 @@ class NewlinePart extends BasePart implements IBasePart {
375374

376375
export class EmojiPart extends BasePart implements IBasePart {
377376
protected acceptsInsertion(chr: string, offset: number): boolean {
378-
return EMOJIBASE_REGEX.test(chr);
377+
return EMOJI_REGEX.test(chr);
379378
}
380379

381380
protected acceptsRemoval(position: number, chr: string): boolean {
@@ -573,7 +572,7 @@ export class PartCreator {
573572
case "\n":
574573
return new NewlinePart();
575574
default:
576-
if (EMOJIBASE_REGEX.test(getFirstGrapheme(input))) {
575+
if (EMOJI_REGEX.test(getFirstGrapheme(input))) {
577576
return new EmojiPart();
578577
}
579578
return new PlainPart();
@@ -650,7 +649,7 @@ export class PartCreator {
650649
let plainText = "";
651650

652651
for (const data of graphemeSegmenter.segment(text)) {
653-
if (EMOJIBASE_REGEX.test(data.segment)) {
652+
if (EMOJI_REGEX.test(data.segment)) {
654653
if (plainText) {
655654
parts.push(this.plain(plainText));
656655
plainText = "";

test/HtmlUtils-test.tsx

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,12 @@ describe("bodyToHtml", () => {
107107
expect(html).toMatchInlineSnapshot(`"<span class="mx_EventTile_searchHighlight">test</span> foo &lt;b&gt;bar"`);
108108
});
109109

110+
it("generates big emoji for emoji made of multiple characters", () => {
111+
const { asFragment } = render(bodyToHtml({ body: "👨‍👩‍👧‍👦 ↔️ 🇮🇸", msgtype: "m.text" }, [], {}) as ReactElement);
112+
113+
expect(asFragment()).toMatchSnapshot();
114+
});
115+
110116
it("should generate big emoji for an emoji-only reply to a message", () => {
111117
const { asFragment } = render(
112118
bodyToHtml(
@@ -132,6 +138,12 @@ describe("bodyToHtml", () => {
132138
expect(asFragment()).toMatchSnapshot();
133139
});
134140

141+
it("does not mistake characters in text presentation mode for emoji", () => {
142+
const { asFragment } = render(bodyToHtml({ body: "↔ ❗︎", msgtype: "m.text" }, [], {}) as ReactElement);
143+
144+
expect(asFragment()).toMatchSnapshot();
145+
});
146+
135147
describe("feature_latex_maths", () => {
136148
beforeEach(() => {
137149
jest.spyOn(SettingsStore, "getValue").mockImplementation((feature) => feature === "feature_latex_maths");

test/__snapshots__/HtmlUtils-test.tsx.snap

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,16 @@
11
// Jest Snapshot v1, https://goo.gl/fbAQLP
22

3+
exports[`bodyToHtml does not mistake characters in text presentation mode for emoji 1`] = `
4+
<DocumentFragment>
5+
<span
6+
class="mx_EventTile_body"
7+
dir="auto"
8+
>
9+
↔ ❗︎
10+
</span>
11+
</DocumentFragment>
12+
`;
13+
314
exports[`bodyToHtml feature_latex_maths should not mangle code blocks 1`] = `"<p>hello</p><pre><code>$\\xi$</code></pre><p>world</p>"`;
415

516
exports[`bodyToHtml feature_latex_maths should not mangle divs 1`] = `"<p>hello</p><div>world</div>"`;
@@ -8,6 +19,36 @@ exports[`bodyToHtml feature_latex_maths should render block katex 1`] = `"<p>hel
819

920
exports[`bodyToHtml feature_latex_maths should render inline katex 1`] = `"hello <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>ξ</mi></mrow><annotation encoding="application/x-tex">\\xi</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.04601em;">ξ</span></span></span></span> world"`;
1021

22+
exports[`bodyToHtml generates big emoji for emoji made of multiple characters 1`] = `
23+
<DocumentFragment>
24+
<span
25+
class="mx_EventTile_body mx_EventTile_bigEmoji"
26+
dir="auto"
27+
>
28+
<span
29+
class="mx_Emoji"
30+
title=":man-woman-girl-boy:"
31+
>
32+
👨‍👩‍👧‍👦
33+
</span>
34+
35+
<span
36+
class="mx_Emoji"
37+
title=":left_right_arrow:"
38+
>
39+
↔️
40+
</span>
41+
42+
<span
43+
class="mx_Emoji"
44+
title=":flag-is:"
45+
>
46+
🇮🇸
47+
</span>
48+
</span>
49+
</DocumentFragment>
50+
`;
51+
1152
exports[`bodyToHtml should generate big emoji for an emoji-only reply to a message 1`] = `
1253
<DocumentFragment>
1354
<span

0 commit comments

Comments
 (0)