signal-desktop/ts/components/MessageBodyHighlight.tsx

107 lines
2.3 KiB
TypeScript
Raw Normal View History

2019-01-14 21:49:58 +00:00
import React from 'react';
import { MessageBody } from './conversation/MessageBody';
import { Emojify } from './conversation/Emojify';
import { AddNewLines } from './conversation/AddNewLines';
import { SizeClassType } from './emoji/lib';
2019-01-14 21:49:58 +00:00
import { LocalizerType, RenderTextCallbackType } from '../types/Util';
export interface Props {
2019-01-14 21:49:58 +00:00
text: string;
i18n: LocalizerType;
}
const renderNewLines: RenderTextCallbackType = ({ text, key }) => (
<AddNewLines key={key} text={text} />
);
const renderEmoji = ({
text,
key,
sizeClass,
renderNonEmoji,
}: {
i18n: LocalizerType;
text: string;
key: number;
sizeClass?: SizeClassType;
renderNonEmoji: RenderTextCallbackType;
}) => (
<Emojify
key={key}
text={text}
sizeClass={sizeClass}
renderNonEmoji={renderNonEmoji}
/>
);
export class MessageBodyHighlight extends React.Component<Props> {
2020-09-12 00:46:52 +00:00
public render(): JSX.Element | Array<JSX.Element> {
2019-01-14 21:49:58 +00:00
const { text, i18n } = this.props;
2020-09-12 00:46:52 +00:00
const results: Array<JSX.Element> = [];
2019-01-14 21:49:58 +00:00
const FIND_BEGIN_END = /<<left>>(.+?)<<right>>/g;
let match = FIND_BEGIN_END.exec(text);
let last = 0;
let count = 1;
if (!match) {
return (
2020-09-12 00:46:52 +00:00
<MessageBody disableJumbomoji disableLinks text={text} i18n={i18n} />
2019-01-14 21:49:58 +00:00
);
}
const sizeClass = '';
while (match) {
if (last < match.index) {
const beforeText = text.slice(last, match.index);
2020-09-12 00:46:52 +00:00
count += 1;
2019-01-14 21:49:58 +00:00
results.push(
renderEmoji({
text: beforeText,
sizeClass,
2020-09-12 00:46:52 +00:00
key: count,
2019-01-14 21:49:58 +00:00
i18n,
renderNonEmoji: renderNewLines,
})
);
}
const [, toHighlight] = match;
2020-09-12 00:46:52 +00:00
count += 2;
2019-01-14 21:49:58 +00:00
results.push(
2020-09-12 00:46:52 +00:00
<span className="module-message-body__highlight" key={count - 1}>
2019-01-14 21:49:58 +00:00
{renderEmoji({
text: toHighlight,
sizeClass,
2020-09-12 00:46:52 +00:00
key: count,
2019-01-14 21:49:58 +00:00
i18n,
renderNonEmoji: renderNewLines,
})}
</span>
);
last = FIND_BEGIN_END.lastIndex;
match = FIND_BEGIN_END.exec(text);
}
if (last < text.length) {
2020-09-12 00:46:52 +00:00
count += 1;
2019-01-14 21:49:58 +00:00
results.push(
renderEmoji({
text: text.slice(last),
sizeClass,
2020-09-12 00:46:52 +00:00
key: count,
2019-01-14 21:49:58 +00:00
i18n,
renderNonEmoji: renderNewLines,
})
);
}
return results;
}
}