File size: 1,680 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import React from 'react'
import {
  decodeMagicIdentifier,
  MAGIC_IDENTIFIER_REGEX,
} from '../../../../shared/lib/magic-identifier'

const linkRegex = /https?:\/\/[^\s/$.?#].[^\s)'"]*/i

const splitRegexp = new RegExp(`(${MAGIC_IDENTIFIER_REGEX.source}|\\s+)`)

export const HotlinkedText: React.FC<{
  text: string
  matcher?: (text: string) => boolean
}> = function HotlinkedText(props) {
  const { text, matcher } = props

  const wordsAndWhitespaces = text.split(splitRegexp)

  return (
    <>
      {wordsAndWhitespaces.map((word, index) => {
        if (linkRegex.test(word)) {
          const link = linkRegex.exec(word)!
          const href = link[0]
          // If link matcher is present but the link doesn't match, don't turn it into a link
          if (typeof matcher === 'function' && !matcher(href)) {
            return word
          }
          return (
            <React.Fragment key={`link-${index}`}>
              <a href={href} target="_blank" rel="noreferrer noopener">
                {word}
              </a>
            </React.Fragment>
          )
        }
        try {
          const decodedWord = decodeMagicIdentifier(word)
          if (decodedWord !== word) {
            return (
              <i key={`ident-${index}`}>
                {'{'}
                {decodedWord}
                {'}'}
              </i>
            )
          }
        } catch (e) {
          return (
            <i key={`ident-${index}`}>
              {'{'}
              {word} (decoding failed: {'' + e}){'}'}
            </i>
          )
        }
        return <React.Fragment key={`text-${index}`}>{word}</React.Fragment>
      })}
    </>
  )
}