import React, { PureComponent } from 'react'; import { Image, Text } from 'react-native'; import { Node, Parser } from 'commonmark'; import Renderer from 'commonmark-react-renderer'; import removeMarkdown from 'remove-markdown'; import shortnameToUnicode from '../../utils/shortnameToUnicode'; import I18n from '../../i18n'; import { themes } from '../../constants/colors'; import MarkdownLink from './Link'; import MarkdownList from './List'; import MarkdownListItem from './ListItem'; import MarkdownAtMention from './AtMention'; import MarkdownHashtag from './Hashtag'; import MarkdownBlockQuote from './BlockQuote'; import MarkdownEmoji from './Emoji'; import MarkdownTable from './Table'; import MarkdownTableRow from './TableRow'; import MarkdownTableCell from './TableCell'; import mergeTextNodes from './mergeTextNodes'; import styles from './styles'; import { isValidURL } from '../../utils/url'; interface IMarkdownProps { msg: string; getCustomEmoji: Function; baseUrl: string; username: string; tmid: string; isEdited: boolean; numberOfLines: number; customEmojis: boolean; useRealName: boolean; channels: { name: string; _id: number; }[]; mentions: object[]; navToRoomInfo: Function; preview: boolean; theme: string; testID: string; style: any; onLinkPress: Function; } type TLiteral = { literal: string; } // Support const formatText = (text: string) => text.replace( new RegExp('(?:<|<)((?:https|http):\\/\\/[^\\|]+)\\|(.+?)(?=>|>)(?:>|>)', 'gm'), (match, url, title) => `[${ title }](${ url })`, ); const emojiRanges = [ '\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]', // unicode emoji from https://www.regextester.com/106421 ':.{1,40}:', // custom emoji ' |\n', // allow spaces and line breaks ].join('|'); const removeSpaces = (str: string) => str && str.replace(/\s/g, ''); const removeAllEmoji = (str: string) => str.replace(new RegExp(emojiRanges, 'g'), ''); const isOnlyEmoji = (str: string) => { str = removeSpaces(str); return !removeAllEmoji(str).length; }; const removeOneEmoji = (str: string) => str.replace(new RegExp(emojiRanges), ''); const emojiCount = (str: string) => { str = removeSpaces(str); let oldLength = 0; let counter = 0; while (oldLength !== str.length) { oldLength = str.length; str = removeOneEmoji(str); if (oldLength !== str.length) { counter += 1; } } return counter; }; const parser = new Parser(); class Markdown extends PureComponent { private renderer: any; private isMessageContainsOnlyEmoji!: boolean; constructor(props: IMarkdownProps) { super(props); this.renderer = this.createRenderer(); } createRenderer = () => new Renderer({ renderers: { text: this.renderText, emph: Renderer.forwardChildren, strong: Renderer.forwardChildren, del: Renderer.forwardChildren, code: this.renderCodeInline, link: this.renderLink, image: this.renderImage, atMention: this.renderAtMention, emoji: this.renderEmoji, hashtag: this.renderHashtag, paragraph: this.renderParagraph, heading: this.renderHeading, codeBlock: this.renderCodeBlock, blockQuote: this.renderBlockQuote, list: this.renderList, item: this.renderListItem, hardBreak: this.renderBreak, thematicBreak: this.renderBreak, softBreak: this.renderBreak, htmlBlock: this.renderText, htmlInline: this.renderText, table: this.renderTable, table_row: this.renderTableRow, table_cell: this.renderTableCell, editedIndicator: this.renderEditedIndicator, }, renderParagraphsInLists: true, }); editedMessage = (ast: any) => { const { isEdited } = this.props; if (isEdited) { const editIndicatorNode = new Node('edited_indicator'); if (ast.lastChild && ['heading', 'paragraph'].includes(ast.lastChild.type)) { ast.lastChild.appendChild(editIndicatorNode); } else { const node = new Node('paragraph'); node.appendChild(editIndicatorNode); ast.appendChild(node); } } }; renderText = ({ context, literal }: {context: []; literal: string}) => { const { numberOfLines, style = [], } = this.props; const defaultStyle = [ this.isMessageContainsOnlyEmoji ? styles.textBig : {}, ...context.map((type) => styles[type]), ]; return ( {literal} ); } renderCodeInline = ({ literal }: TLiteral) => { const { theme, style = [] } = this.props; return ( {literal} ); }; renderCodeBlock = ({ literal }: TLiteral) => { const { theme, style = [] } = this.props; return ( {literal} ); }; renderBreak = () => { const { tmid } = this.props; return {tmid ? ' ' : '\n'}; } renderParagraph = ({ children }: any) => { const { numberOfLines, style, theme } = this.props; if (!children || children.length === 0) { return null; } return ( {children} ); }; renderLink = ({ children, href }: any) => { const { theme, onLinkPress } = this.props; return ( {children} ); } renderHashtag = ({ hashtag }: {hashtag: string}) => { const { channels, navToRoomInfo, style, theme } = this.props; return ( ); } renderAtMention = ({ mentionName }: { mentionName: string }) => { const { username, mentions, navToRoomInfo, useRealName, style, theme } = this.props; return ( ); } renderEmoji = ({ literal }: TLiteral) => { const { getCustomEmoji, baseUrl, customEmojis, style, theme } = this.props; return ( ); } renderImage = ({ src }: {src: string}) => { if (!isValidURL(src)) { return null; } return ( ); } renderEditedIndicator = () => { const { theme } = this.props; return ({I18n.t('edited')}); } renderHeading = ({ children, level }: any) => { const { numberOfLines, theme } = this.props; const textStyle = styles[`heading${ level }Text`]; return ( {children} ); }; renderList = ({ children, start, tight, type }: any) => { const { numberOfLines } = this.props; return ( {children} ); }; renderListItem = ({ children, context, ...otherProps }: any) => { const { theme } = this.props; const level = context.filter((type: string) => type === 'list').length; return ( {children} ); }; renderBlockQuote = ({ children }: {children: JSX.Element}) => { const { theme } = this.props; return ( {children} ); } renderTable = ({ children, numColumns }: { children: JSX.Element; numColumns: number }) => { const { theme } = this.props; return ( {children} ); } renderTableRow = (args: any) => { const { theme } = this.props; return ; } renderTableCell = (args: any) => { const { theme } = this.props; return ; } render() { const { msg, numberOfLines, preview = false, theme, style = [], testID, } = this.props; if (!msg) { return null; } let m = formatText(msg); // Ex: '[ ](https://open.rocket.chat/group/test?msg=abcdef) Test' // Return: 'Test' m = m.replace(/^\[([\s]*)\]\(([^)]*)\)\s/, '').trim(); if (preview) { m = shortnameToUnicode(m); // Removes sequential empty spaces m = m.replace(/\s+/g, ' '); m = removeMarkdown(m); m = m.replace(/\n+/g, ' '); return ( {m} ); } let ast = parser.parse(m); ast = mergeTextNodes(ast); this.isMessageContainsOnlyEmoji = isOnlyEmoji(m) && emojiCount(m) <= 3; this.editedMessage(ast); return this.renderer.render(ast); } } export default Markdown;