Skip to content

Commit bd8a429

Browse files
fix(react): prevent intra-word _ and * from rendering as emphasis
1 parent 0654e5c commit bd8a429

1 file changed

Lines changed: 24 additions & 1 deletion

File tree

‎packages/react/src/lib/contentEditableComposer.js‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,26 @@ const findLink = (text, start) => {
4444
};
4545
};
4646

47+
const isAlphanumeric = (ch) => Boolean(ch && /[a-zA-Z0-9]/.test(ch));
48+
const isWhitespace = (ch) => Boolean(ch && /\s/.test(ch));
49+
50+
const isValidEmphasis = (marker, text, start, end) => {
51+
if (marker === '`' || marker === '~~') {
52+
return true;
53+
}
54+
const prevChar = start > 0 ? text[start - 1] : '';
55+
const firstInside = text[start + marker.length];
56+
const lastInside = text[end - 1];
57+
const nextChar =
58+
end + marker.length < text.length ? text[end + marker.length] : '';
59+
60+
if (isWhitespace(firstInside) || isWhitespace(lastInside)) return false;
61+
if (isAlphanumeric(prevChar)) return false;
62+
if (isAlphanumeric(nextChar)) return false;
63+
64+
return true;
65+
};
66+
4767
const appendMarkdown = (parent, text) => {
4868
const tokens = [
4969
['**', 'strong'],
@@ -92,7 +112,10 @@ const appendMarkdown = (parent, text) => {
92112
if (token) {
93113
const [marker, tagName] = token;
94114
const end = text.indexOf(marker, index + marker.length);
95-
if (end > index + marker.length) {
115+
if (
116+
end > index + marker.length &&
117+
isValidEmphasis(marker, text, index, end)
118+
) {
96119
flush();
97120
const formatted = document.createElement(tagName);
98121
const content = text.slice(index + marker.length, end);

0 commit comments

Comments
 (0)