about summary refs log tree commit diff
path: root/src/view/com/composer/text-input/web/LinkDecorator.ts
blob: 4843f0ddfc53463063a11bb181d0452f3e31238b (plain) (blame)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/**
 * TipTap is a stateful rich-text editor, which is extremely useful
 * when you _want_ it to be stateful formatting such as bold and italics.
 *
 * However we also use "stateless" behaviors, specifically for URLs
 * where the text itself drives the formatting.
 *
 * This plugin uses a regex to detect URIs and then applies
 * link decorations (a <span> with the "autolink") class. That avoids
 * adding any stateful formatting to TipTap's document model.
 *
 * We then run the URI detection again when constructing the
 * RichText object from TipTap's output and merge their features into
 * the facet-set.
 */

import {URL_REGEX} from '@atproto/api'
import {Mark} from '@tiptap/core'
import {type Node as ProsemirrorNode} from '@tiptap/pm/model'
import {Plugin, PluginKey} from '@tiptap/pm/state'
import {Decoration, DecorationSet} from '@tiptap/pm/view'

import {isValidDomain} from '#/lib/strings/url-helpers'

export const LinkDecorator = Mark.create({
  name: 'link-decorator',
  priority: 1000,
  keepOnSplit: false,
  inclusive() {
    return true
  },
  addProseMirrorPlugins() {
    return [linkDecorator()]
  },
})

function getDecorations(doc: ProsemirrorNode) {
  const decorations: Decoration[] = []

  doc.descendants((node, pos) => {
    if (node.isText && node.text) {
      const textContent = node.textContent

      // links
      iterateUris(textContent, (from, to) => {
        decorations.push(
          Decoration.inline(pos + from, pos + to, {
            class: 'autolink',
          }),
        )
      })
    }
  })

  return DecorationSet.create(doc, decorations)
}

function linkDecorator() {
  const linkDecoratorPlugin: Plugin = new Plugin({
    key: new PluginKey('link-decorator'),

    state: {
      init: (_, {doc}) => getDecorations(doc),
      apply: (transaction, decorationSet) => {
        if (transaction.docChanged) {
          return getDecorations(transaction.doc)
        }
        return decorationSet.map(transaction.mapping, transaction.doc)
      },
    },

    props: {
      decorations(state) {
        return linkDecoratorPlugin.getState(state)
      },
    },
  })
  return linkDecoratorPlugin
}

function iterateUris(str: string, cb: (from: number, to: number) => void) {
  let match
  const re = URL_REGEX
  while ((match = re.exec(str))) {
    let uri = match[2]
    if (!uri.startsWith('http')) {
      const domain = match.groups?.domain
      if (!domain || !isValidDomain(domain)) {
        continue
      }
      uri = `https://${uri}`
    }
    let from = str.indexOf(match[2], match.index)
    let to = from + match[2].length
    // strip ending puncuation
    if (/[.,;!?]$/.test(uri)) {
      uri = uri.slice(0, -1)
      to--
    }
    if (/[)]$/.test(uri) && !uri.includes('(')) {
      uri = uri.slice(0, -1)
      to--
    }
    cb(from, to)
  }
}