Simplify TypeAnnotation to remove dependency for Prism

This commit is contained in:
Marcus Blättermann 2023-01-24 18:10:55 +01:00
parent befd20d13d
commit 69334843ce
No known key found for this signature in database
GPG Key ID: A1E1F04008AC450D

View File

@ -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) ? (
<span className={classes['cli-arg-subtle']}>{element}</span>
) : (
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 ? (
<Fragment>
{ws && ' '}
<Link to={url} hideIcon>
{elStr}
</Link>
</Fragment>
<Link to={url} hideIcon key={key}>
{elStr}
</Link>
) : (
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 (
<span className={annotClassNames} role="code" aria-label="Type annotation">
{elements.map((el, i) => (
<Fragment key={i}>{linkType(el, !!link)}</Fragment>
))}
{rawText.split(/(\[|\]|,)/).map((el, i) => linkType(el, !!link, i))}
{meta && <span className={classes['type-annotation-meta']}>{meta}</span>}
</span>
)