Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

8.0 KB
Raw Blame
import { translate } from '../../i18n/mobile-i18n'
import { createMarkdownInlineMatcher } from '../markdown-inline-matcher'
import { splitTableRow } from '../rich-markdown/markdown-table-rows'

// Use small pure/total PR Markdown parser: old third-party RN renderer hung JS thread. Unknown/unbalanced content stays paragraph text.

export type InlineToken =
  | { kind: 'text'; text: string }
  | { kind: 'bold'; text: string }
  | { kind: 'italic'; text: string }
  | { kind: 'code'; text: string }
  | { kind: 'link'; text: string; url: string }

export type CellAlign = 'left' | 'center' | 'right'

export type MarkdownBlock =
  | { kind: 'heading'; level: number; text: string }
  // `lang` carries the fence info string (e.g. 'mermaid'); empty when unspecified.
  | { kind: 'code'; text: string; lang: string }
  | { kind: 'quote'; text: string }
  | { kind: 'list'; ordered: boolean; items: string[] }
  | { kind: 'hr' }
  | { kind: 'paragraph'; text: string }
  // GitHub comments use <details><summary>…</summary>…</details> for collapsibles.
  | { kind: 'details'; summary: string; body: MarkdownBlock[] }
  // GFM pipe table. `align` is per-column, parallel to `headers`.
  | { kind: 'table'; headers: string[]; rows: string[][]; align: CellAlign[] }

const HEADING = /^(#{1,6})\s+(.*)$/
const FENCE = /^```/
const FENCE_OPEN = /^```\s*([^\s`]*)/
const QUOTE = /^>\s?(.*)$/
const HR = /^(?:---+|\*\*\*+|___+)\s*$/
const UNORDERED = /^\s*[-*+]\s+(.*)$/
const ORDERED = /^\s*\d+[.)]\s+(.*)$/
// A top-level <details>…</details> or <blockquote>…</blockquote> region.
const HTML_BLOCK = /<(details|blockquote)\b[^>]*>([\s\S]*?)<\/\1>/i
const SUMMARY = /<summary\b[^>]*>([\s\S]*?)<\/summary>/i

// Strip tag-shaped HTML only; bare a < b prose stays literal.
export function stripHtmlTags(text: string): string {
  const end = text.lastIndexOf('>') + 1
  if (end === 0) {
    return text
  }
  // No tag can close in this suffix; keep it literal without retrying every opener.
  return (
    text.slice(0, end).replace(/<\/?[a-zA-Z][a-zA-Z0-9-]*(?:\s[^>]*)?\/?>/g, '') + text.slice(end)
  )
}

export function parseMarkdownBlocks(content: string): MarkdownBlock[] {
  // Drop HTML comments and normalize <br> before block parsing.
  const cleaned = content.replace(/<!--[\s\S]*?-->/g, '').replace(/<br\s*\/?>/gi, '\n')
  return parseSegment(cleaned)
}

// Split top-level details/blockquote regions in order; recurse nested details and keep unmatched input total via non-greedy parse.
function parseSegment(text: string): MarkdownBlock[] {
  const blocks: MarkdownBlock[] = []
  let rest = text
  let m = HTML_BLOCK.exec(rest)
  while (m) {
    const before = rest.slice(0, m.index)
    if (before.trim().length > 0) {
      blocks.push(...parseLines(before))
    }
    if (m[1].toLowerCase() === 'details') {
      const sm = SUMMARY.exec(m[2])
      const summary = sm ? stripHtmlTags(sm[1]).trim() : ''
      const body = m[2].replace(SUMMARY, '')
      blocks.push({
        kind: 'details',
        // Parsed blocks can outlive the active language.
        get summary() {
          return summary || translate('pullRequest.markdownBlocks.details', 'Details')
        },
        body: parseSegment(body)
      })
    } else {
      blocks.push({ kind: 'quote', text: stripHtmlTags(m[2]).trim() })
    }
    rest = rest.slice(m.index + m[0].length)
    m = HTML_BLOCK.exec(rest)
  }
  if (rest.trim().length > 0) {
    blocks.push(...parseLines(rest))
  }
  return blocks
}

function parseLines(content: string): MarkdownBlock[] {
  const lines = content.replace(/\r\n/g, '\n').split('\n')
  const blocks: MarkdownBlock[] = []
  let paragraph: string[] = []
  let i = 0

  const flushParagraph = (): void => {
    if (paragraph.length > 0) {
      blocks.push({ kind: 'paragraph', text: paragraph.join('\n').trim() })
      paragraph = []
    }
  }

  while (i < lines.length) {
    const line = lines[i]

    if (FENCE.test(line)) {
      flushParagraph()
      const lang = (FENCE_OPEN.exec(line)?.[1] ?? '').toLowerCase()
      const code: string[] = []
      i += 1
      while (i < lines.length && !FENCE.test(lines[i])) {
        code.push(lines[i])
        i += 1
      }
      i += 1
      blocks.push({ kind: 'code', text: code.join('\n'), lang })
      continue
    }

    // Require table delimiter row so stray prose pipe does not create table.
    if (line.includes('|') && i + 1 < lines.length && isTableDelimiter(lines[i + 1])) {
      flushParagraph()
      const headers = splitTableRow(line)
      const align = parseAlignRow(lines[i + 1])
      i += 2
      const rows: string[][] = []
      while (i < lines.length && lines[i].includes('|') && lines[i].trim() !== '') {
        rows.push(splitTableRow(lines[i]))
        i += 1
      }
      blocks.push({ kind: 'table', headers, rows, align })
      continue
    }

    if (line.trim() === '') {
      flushParagraph()
      i += 1
      continue
    }

    const heading = HEADING.exec(line)
    if (heading) {
      flushParagraph()
      blocks.push({ kind: 'heading', level: heading[1].length, text: heading[2].trim() })
      i += 1
      continue
    }

    if (HR.test(line)) {
      flushParagraph()
      blocks.push({ kind: 'hr' })
      i += 1
      continue
    }

    const quote = QUOTE.exec(line)
    if (quote) {
      flushParagraph()
      const quoted: string[] = []
      let q: RegExpExecArray | null = quote
      while (q) {
        quoted.push(q[1])
        i += 1
        q = i < lines.length ? QUOTE.exec(lines[i]) : null
      }
      blocks.push({ kind: 'quote', text: quoted.join('\n').trim() })
      continue
    }

    const ordered = ORDERED.test(line)
    if (ordered || UNORDERED.test(line)) {
      flushParagraph()
      const items: string[] = []
      let match = ordered ? ORDERED.exec(line) : UNORDERED.exec(line)
      while (match) {
        items.push(match[1].trim())
        i += 1
        if (i >= lines.length) {
          break
        }
        match = ordered ? ORDERED.exec(lines[i]) : UNORDERED.exec(lines[i])
      }
      blocks.push({ kind: 'list', ordered, items })
      continue
    }

    paragraph.push(line)
    i += 1
  }
  flushParagraph()
  return blocks
}

// A single dash is a delimiter cell here, unlike the editor's three-dash separator.
function isTableDelimiter(line: string): boolean {
  return splitTableRow(line).every((cell) => /^:?-+:?$/.test(cell))
}

// Reads alignment from a delimiter row's colons: `:--` left, `:-:` center, `--:` right.
function parseAlignRow(line: string): CellAlign[] {
  return splitTableRow(line).map((spec) => {
    const left = spec.startsWith(':')
    const right = spec.endsWith(':')
    if (left && right) {
      return 'center'
    }
    if (right) {
      return 'right'
    }
    return 'left'
  })
}

// Tokenize inline emphasis/code/links once, longest match first; preserve plain runs and unbalanced markers.
const INLINE = /(`[^`]+`)|(\*\*[^*]+\*\*)|(__[^_]+__)|(\*[^*]+\*)|(_[^_]+_)/g

export function parseInline(text: string): InlineToken[] {
  const tokens: InlineToken[] = []
  // Strip residual inline HTML before Markdown tokenization so tags do not display literally.
  const plain = stripHtmlTags(text)
  const matcher = createMarkdownInlineMatcher(plain, INLINE)
  let cursor = 0
  let guard = 0
  while (cursor < plain.length && guard < 5000) {
    guard += 1
    const m = matcher.exec()
    if (!m || m.index === undefined) {
      tokens.push({ kind: 'text', text: plain.slice(cursor) })
      break
    }
    if (m.index > cursor) {
      tokens.push({ kind: 'text', text: plain.slice(cursor, m.index) })
    }
    const token = m[0]
    if (token.startsWith('`')) {
      tokens.push({ kind: 'code', text: token.slice(1, -1) })
    } else if (token.startsWith('**') || token.startsWith('__')) {
      tokens.push({ kind: 'bold', text: token.slice(2, -2) })
    } else if (token.startsWith('[')) {
      const close = token.indexOf('](')
      tokens.push({
        kind: 'link',
        text: token.slice(1, close),
        url: token.slice(close + 2, -1)
      })
    } else {
      tokens.push({ kind: 'italic', text: token.slice(1, -1) })
    }
    cursor = matcher.lastIndex
  }
  return tokens
}