From 69334843ce7c3d4e80f5cfe3a1851f60d9eb0bad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcus=20Bl=C3=A4ttermann?= Date: Tue, 24 Jan 2023 18:10:55 +0100 Subject: [PATCH] Simplify `TypeAnnotation` to remove dependency for Prism --- website/src/components/typeAnnotation.js | 41 ++++++++++-------------- 1 file changed, 17 insertions(+), 24 deletions(-) diff --git a/website/src/components/typeAnnotation.js b/website/src/components/typeAnnotation.js index 0a054b6e5..ba4ec6657 100644 --- a/website/src/components/typeAnnotation.js +++ b/website/src/components/typeAnnotation.js @@ -1,43 +1,38 @@ -import React, { Fragment } from 'react' +import React from 'react' import classNames from 'classnames' -import Prism from 'prismjs' import CUSTOM_TYPES from '../../meta/type-annotations.json' -import { isString, htmlToReact } from './util' import Link from './link' import classes from '../styles/code.module.sass' export const WRAP_THRESHOLD = 30 -function linkType(el, showLink = true) { - if (!isString(el) || !el.length) return el +const specialCharacterList = ['[', ']', ',', ', '] + +const highlight = (element) => + specialCharacterList.includes(element) ? ( + {element} + ) : ( + element + ) + +function linkType(el, showLink = true, key) { + if (!el.length) return el const elStr = el.trim() if (!elStr) return el const typeUrl = CUSTOM_TYPES[elStr] const url = typeUrl == true ? DEFAULT_TYPE_URL : typeUrl - const ws = el[0] == ' ' return url && showLink ? ( - - {ws && ' '} - - {elStr} - - + + {elStr} + ) : ( - el + highlight(el) ) } export const TypeAnnotation = ({ lang = 'python', link = true, children }) => { - // Hacky, but we're temporarily replacing a dot to prevent it from being split during highlighting - const TMP_DOT = '۔' const code = Array.isArray(children) ? children.join('') : children || '' const [rawText, meta] = code.split(/(?= \(.+\)$)/) - const rawStr = rawText.replace(/\./g, TMP_DOT) - const rawHtml = - lang === 'none' || !code ? code : Prism.highlight(rawStr, Prism.languages[lang], lang) - const html = rawHtml.replace(new RegExp(TMP_DOT, 'g'), '.').replace(/\n/g, ' ') - const result = htmlToReact(html) - const elements = Array.isArray(result) ? result : [result] const annotClassNames = classNames( 'type-annotation', `language-${lang}`, @@ -49,9 +44,7 @@ export const TypeAnnotation = ({ lang = 'python', link = true, children }) => { ) return ( - {elements.map((el, i) => ( - {linkType(el, !!link)} - ))} + {rawText.split(/(\[|\]|,)/).map((el, i) => linkType(el, !!link, i))} {meta && {meta}} )