Fix wrong exceeded chars highlighting

This commit is contained in:
Lim Chee Aun 2024-07-07 22:56:24 +08:00
parent 9ea7a1f4db
commit 180a23f116

View file

@ -147,23 +147,22 @@ const SCAN_RE = new RegExp(
); );
const segmenter = new Intl.Segmenter(); const segmenter = new Intl.Segmenter();
function highlightText(text, { maxCharacters = Infinity }) { function escapeHTML(text) {
// Accept text string, return formatted HTML string return text
// Escape all HTML special characters
let html = text
.replace(/&/g, '&') .replace(/&/g, '&')
.replace(/</g, '&lt;') .replace(/</g, '&lt;')
.replace(/>/g, '&gt;') .replace(/>/g, '&gt;')
.replace(/"/g, '&quot;') .replace(/"/g, '&quot;')
.replace(/'/g, '&apos;'); .replace(/'/g, '&apos;');
}
function highlightText(text, { maxCharacters = Infinity }) {
// Exceeded characters limit // Exceeded characters limit
const { composerCharacterCount } = states; const { composerCharacterCount } = states;
if (composerCharacterCount > maxCharacters) { if (composerCharacterCount > maxCharacters) {
// Highlight exceeded characters // Highlight exceeded characters
let withinLimitHTML = '', let withinLimitHTML = '',
exceedLimitHTML = ''; exceedLimitHTML = '';
const htmlSegments = segmenter.segment(html); const htmlSegments = segmenter.segment(text);
for (const { segment, index } of htmlSegments) { for (const { segment, index } of htmlSegments) {
if (index < maxCharacters) { if (index < maxCharacters) {
withinLimitHTML += segment; withinLimitHTML += segment;
@ -174,13 +173,13 @@ function highlightText(text, { maxCharacters = Infinity }) {
if (exceedLimitHTML) { if (exceedLimitHTML) {
exceedLimitHTML = exceedLimitHTML =
'<mark class="compose-highlight-exceeded">' + '<mark class="compose-highlight-exceeded">' +
exceedLimitHTML + escapeHTML(exceedLimitHTML) +
'</mark>'; '</mark>';
} }
return withinLimitHTML + exceedLimitHTML; return escapeHTML(withinLimitHTML) + exceedLimitHTML;
} }
return html return escapeHTML(text)
.replace(urlRegexObj, '$2<mark class="compose-highlight-url">$3</mark>') // URLs .replace(urlRegexObj, '$2<mark class="compose-highlight-url">$3</mark>') // URLs
.replace(MENTION_RE, '$1<mark class="compose-highlight-mention">$2</mark>') // Mentions .replace(MENTION_RE, '$1<mark class="compose-highlight-mention">$2</mark>') // Mentions
.replace(HASHTAG_RE, '$1<mark class="compose-highlight-hashtag">$2</mark>') // Hashtags .replace(HASHTAG_RE, '$1<mark class="compose-highlight-hashtag">$2</mark>') // Hashtags