about summary refs log tree commit diff
path: root/src/lib/strings/mention-manip.ts
blob: 7b52f745b24d4fbbd1f4c7da89e767cf021c6554 (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
interface FoundMention {
  value: string
  index: number
}

export function getMentionAt(
  text: string,
  cursorPos: number,
): FoundMention | undefined {
  let re = /(^|\s)@([a-z0-9.-]*)/gi
  let match
  while ((match = re.exec(text))) {
    const spaceOffset = match[1].length
    const index = match.index + spaceOffset
    if (
      cursorPos >= index &&
      cursorPos <= index + match[0].length - spaceOffset
    ) {
      return {value: match[2], index}
    }
  }
  return undefined
}

export function insertMentionAt(
  text: string,
  cursorPos: number,
  mention: string,
) {
  const target = getMentionAt(text, cursorPos)
  if (target) {
    return `${text.slice(0, target.index)}@${mention} ${text.slice(
      target.index + target.value.length + 1, // add 1 to include the "@"
    )}`
  }
  return text
}