From 39e1d32c669545ccc30e0d424323c6a01317c4be Mon Sep 17 00:00:00 2001 From: eug-vs Date: Sun, 5 Apr 2020 12:56:41 +0300 Subject: refactor: move some logic to InlineSyntax.tsx --- src/lib/Markdown/InlineSyntax.tsx | 81 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/lib/Markdown/InlineSyntax.tsx (limited to 'src/lib/Markdown/InlineSyntax.tsx') diff --git a/src/lib/Markdown/InlineSyntax.tsx b/src/lib/Markdown/InlineSyntax.tsx new file mode 100644 index 0000000..bf5669d --- /dev/null +++ b/src/lib/Markdown/InlineSyntax.tsx @@ -0,0 +1,81 @@ +import React from 'react'; +import { Link } from '@material-ui/core'; +import axios from 'axios'; + +import { InlineParserPropTypes } from './types'; + +interface RegexPair { + global: RegExp; + local: RegExp; +} + +interface Emoji { + name: string; + char: string; +} + +const enclosureRegex = (e: string): RegexPair => ({ + local: new RegExp(`${e}([^${e}]+)${e}`), + global: new RegExp(`(${e}[^${e}]+${e})`) +}); + +const regex: Record = { + conceal: { + global: /(!?\[.+?\]\(.+?\))/g, + local: /!?\[(.+?)\]\((.+?)\)/ + }, + rawLink: { + global: /((?:(?:[A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www\.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)(?:(?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[.!/\\\w]*))?)/, + local: /&^/ + }, + emoji: enclosureRegex(':'), + bold: enclosureRegex('\\*\\*'), + italic: enclosureRegex('\\*'), + code: enclosureRegex('`'), + strikeThrough: enclosureRegex('~~'), +} + +const splitter = new RegExp(Object.values(regex).map(pair => pair.global.source).join('|')); + +const emojiList: Emoji[] = []; +axios.get('https://unpkg.com/emojilib@2.4.0/emojis.json').then(response => { + Object.keys(response.data).forEach(name => emojiList.push({ name, char: response.data[name].char })); +}); + + +const InlineSyntax: React.FC = ({ line }) => { + if (!line) return null; + + const matchConceal = regex.conceal.local.exec(line); + if (matchConceal) { + if (line[0] === '!') return {matchConceal[1]}; + return {matchConceal[1]}; + } + + const matchEmoji = line.match(regex.emoji.local); + if (matchEmoji) { + const emoji = emojiList.find(emoji => emoji.name === matchEmoji[1]); + return {emoji ? emoji.char : line}; + } + + const matchCode = line.match(regex.code.local); + if (matchCode) return {matchCode[1]}; + + const matchBold = line.match(regex.bold.local); + if (matchBold) return {matchBold[1]}; + + const matchItalic = line.match(regex.italic.local); + if (matchItalic) return {matchItalic[1]}; + + const matchStrikeThrough = line.match(regex.strikeThrough.local); + if (matchStrikeThrough) return {matchStrikeThrough[1]}; + + if (line.match(regex.rawLink.global)) return {line}; + + return <>{line}; +} + + +export { splitter }; +export default InlineSyntax; + -- cgit v1.2.3