All files / apps / web/src / features / conversation / lib format.ts

95.65% Statements 22/23
90% Branches 9/10
100% Functions 5/5
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                  4x                 4x 3x 5x 2x                       21x   21x 13x 13x   13x     13x 2x   2x     11x             8x   8x   8x 21x 21x 21x     10x     21x            
export type FormatAction =
  'bold' | 'italic' | 'strike' | 'link' | 'numbered' | 'bulleted' | 'quote' | 'code' | 'codeBlock'
 
export interface TextEdit {
  value: string
  selectionStart: number
  selectionEnd: number
}
 
const WRAPS: Partial<Record<FormatAction, [open: string, close: string]>> = {
  bold: ['**', '**'],
  italic: ['_', '_'],
  strike: ['~~', '~~'],
  code: ['`', '`'],
  codeBlock: ['```\n', '\n```'],
  link: ['[', ']()'],
}
 
const LINE_PREFIXES: Partial<Record<FormatAction, (lineIndex: number) => string>> = {
  numbered: (lineIndex) => `${lineIndex + 1}. `,
  bulleted: () => '- ',
  quote: () => '> ',
}
 
// Puts the Markdown markers of `action` around the selection (or in front of each selected line)
// and says where the selection goes next. The composer writes markers; lib/inline.ts and
// lib/blocks.ts read them back.
export function applyFormat(
  value: string,
  selectionStart: number,
  selectionEnd: number,
  action: FormatAction,
): TextEdit {
  const wrap = WRAPS[action]
 
  if (wrap) {
    const [open, close] = wrap
    const selected = value.slice(selectionStart, selectionEnd)
    const next =
      value.slice(0, selectionStart) + open + selected + close + value.slice(selectionEnd)
 
    // A link puts the caret between its parentheses, ready for the address.
    if (action === 'link') {
      const caret = selectionStart + open.length + selected.length + 2
 
      return { value: next, selectionStart: caret, selectionEnd: caret }
    }
 
    return {
      value: next,
      selectionStart: selectionStart + open.length,
      selectionEnd: selectionEnd + open.length,
    }
  }
 
  const prefix = LINE_PREFIXES[action]
 
  Iif (!prefix) return { value, selectionStart, selectionEnd }
 
  const lineStart = selectionStart === 0 ? 0 : value.lastIndexOf('\n', selectionStart - 1) + 1
  const lineEndIndex = value.indexOf('\n', selectionEnd)
  const lineEnd = lineEndIndex === -1 ? value.length : lineEndIndex
  const block = value
    .slice(lineStart, lineEnd)
    .split('\n')
    .map((line, index) => prefix(index) + line)
    .join('\n')
 
  return {
    value: value.slice(0, lineStart) + block + value.slice(lineEnd),
    selectionStart: lineStart,
    selectionEnd: lineStart + block.length,
  }
}