session-desktop/ts/components/conversation/Emojify.tsx

122 lines
2.6 KiB
TypeScript
Raw Normal View History

import React from 'react';
import classNames from 'classnames';
import is from '@sindresorhus/is';
2020-07-24 03:16:40 +02:00
import { getRegex, SizeClassType } from '../../util/emoji';
2019-01-14 22:49:58 +01:00
import { LocalizerType, RenderTextCallbackType } from '../../types/Util';
2020-07-22 06:57:45 +02:00
import { Twemoji } from 'react-emoji-render';
interface Props {
text: string;
/** A class name to be added to the generated emoji images */
2019-01-02 20:56:33 +01:00
sizeClass?: SizeClassType;
/** Allows you to customize now non-newlines are rendered. Simplest is just a <span>. */
2019-01-14 22:49:58 +01:00
renderNonEmoji?: RenderTextCallbackType;
i18n: LocalizerType;
isGroup?: boolean;
convoId: string;
}
export class Emojify extends React.Component<Props> {
public static defaultProps: Partial<Props> = {
renderNonEmoji: ({ text }) => text || '',
isGroup: false,
};
public render() {
const {
text,
sizeClass,
renderNonEmoji,
i18n,
isGroup,
convoId,
} = this.props;
const results: Array<any> = [];
const regex = getRegex();
// We have to do this, because renderNonEmoji is not required in our Props object,
// but it is always provided via defaultProps.
if (!renderNonEmoji) {
return null;
}
let match = regex.exec(text);
let last = 0;
let count = 1;
if (!match) {
return renderNonEmoji({ text, key: 0, isGroup, convoId });
}
while (match) {
if (last < match.index) {
const textWithNoEmoji = text.slice(last, match.index);
2019-09-23 03:00:51 +02:00
results.push(
renderNonEmoji({
text: textWithNoEmoji,
key: count++,
isGroup,
convoId,
})
2019-09-23 03:00:51 +02:00
);
}
2020-07-24 03:16:40 +02:00
let size = 1.0;
2020-07-22 06:57:45 +02:00
switch (sizeClass) {
case 'jumbo':
2020-07-24 03:16:40 +02:00
size = 2.0;
2020-07-22 06:57:45 +02:00
break;
case 'large':
2020-07-24 03:16:40 +02:00
size = 1.8;
2020-07-22 06:57:45 +02:00
break;
case 'medium':
2020-07-24 03:16:40 +02:00
size = 1.5;
2020-07-22 06:57:45 +02:00
break;
case 'small':
2020-07-24 03:16:40 +02:00
size = 1.1;
2020-07-22 06:57:45 +02:00
break;
default:
}
2020-07-24 03:16:40 +02:00
const style = { fontSize: `${size}em` };
2020-07-22 09:46:17 +02:00
const emojiText = match[0] ?? match[1];
2020-07-22 06:57:45 +02:00
results.push(
2020-11-24 23:14:22 +01:00
<span style={style} key={count++}>
2020-07-22 09:46:17 +02:00
<Twemoji
2020-11-24 23:14:22 +01:00
key={count}
2020-07-22 09:46:17 +02:00
text={emojiText}
2020-07-24 03:16:40 +02:00
options={
{
baseUrl: 'images/twemoji/',
protocol: '',
ext: 'png',
} as any
}
2020-07-22 09:46:17 +02:00
/>
</span>
2020-07-22 06:57:45 +02:00
);
last = regex.lastIndex;
match = regex.exec(text);
}
if (last < text.length) {
2019-09-23 03:00:51 +02:00
results.push(
renderNonEmoji({
text: text.slice(last),
key: count++,
isGroup,
convoId,
})
2019-09-23 03:00:51 +02:00
);
}
return results;
}
}