Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as React from 'react';
- import * as unified from 'unified';
- import { useContext } from 'react';
- import classNames from '../libs/classNames';
- import mentions from './remark-mentions';
- import { StateContext } from '..';
- import { traverseMentions } from '../traverse-mentions';
- import { User } from '../types';
- import { createComponentFromProcessor } from 'remark-react-component/build/es6';
- import {
- emojis,
- addEmojiClasses,
- } from 'remark-react-component/build/es6/emojis';
- const markdown = require('remark-parse');
- interface Props {
- text: string;
- className?: string;
- }
- enum ClassNames {
- Emoji = 'emoji',
- EmojiLarge = 'emoji-large',
- Mention = 'mention',
- MentionCurrentUser = 'mention--you',
- }
- const pipeline = unified()
- // This is the Markdown parser
- .use(markdown)
- // Parse @mentions and :emojis: to AST nodes
- .use(emojis)
- .use(mentions);
- // Build a renderer component based on the Unified pipeline above
- const Renderer = createComponentFromProcessor(pipeline);
- const findUserFromMention = (users: User[], mention: string) =>
- users ? users.find((u) => u.username === mention) : null;
- /**
- * A general text component which renders nice things from a single
- * text string.
- *
- * Currently supports:
- *
- * - Markdown
- * - Emojis (shortcodes and unicode)
- * - @mentions
- */
- const Text: React.FunctionComponent<Props> = (props) => {
- const ctx = useContext(StateContext);
- return (
- <Renderer
- text={props.text}
- className={classNames('markdown-content', props.className)}
- // Here we can attach "transformers" of the AST. With them, we can
- // spruce up the nodes a bit, such as attaching custom class names and title
- // attributes.
- transformers={[
- addEmojiClasses({
- className: ClassNames.Emoji,
- classNameForOnlyEmojis: ClassNames.EmojiLarge,
- }),
- traverseMentions({
- title: (mention) => {
- const user =
- ctx.state.users &&
- findUserFromMention(ctx.state.users, mention);
- if (!user) {
- return '';
- }
- return user._id === ctx.state.userID
- ? 'This is you!'
- : user.profile.fullname;
- },
- className: (mention) => {
- const user =
- ctx.state.users &&
- findUserFromMention(ctx.state.users, mention);
- if (!user) {
- return '';
- }
- return user._id === ctx.state.userID
- ? `${ClassNames.Mention} ${
- ClassNames.MentionCurrentUser
- }`
- : ClassNames.Mention;
- },
- }),
- ]}
- />
- );
- };
- // tslint:disable-next-line no-object-mutation
- Text.displayName = 'Text';
- // tslint:disable-next-line no-object-mutation
- Renderer.displayName = 'Renderer';
- export default React.memo(Text);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement