garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/lib/markdown.tsx

raw

import m from '@garage44/mithril'

import {highlight} from '@/lib/highlight'

/**
 * An agent's Markdown as vnodes: paragraphs, headings, lists, fenced code,
 * quotes, rules, tables, and inline code, bold, italic and links. Built as elements,
 * never as HTML, so what an agent writes is text however it is written; a link
 * goes only to http(s), or to a session of this hub. A session named in the text
 * (`S123`, `s3`, `session-s3`) links to it, opened in this window.
 */
export function markdown(src: string): m.Children[] {
    const lines = src.replace(/\r\n/g, '\n').split('\n')
    const out: m.Children[] = []
    let i = 0
    while (i < lines.length) {
        const line = lines[i]
        const fence = line.match(/^\s*(```|~~~)\s*([\w+-]*)\s*$/)
        if (fence) {
            const body: string[] = []
            i++
            while (i < lines.length && !lines[i].trim().startsWith(fence[1])) body.push(lines[i++])
            i++
            if (fence[2] === 'analysis' || fence[2] === 'new-session' || fence[2] === 'impact') {
                out.push(panel(fence[2], body))
                continue
            }
            out.push(
                <pre class="md__code hl">
                    <code>{highlight(body.join('\n'), fence[2] ?? '')}</code>
                </pre>,
            )
            continue
        }
        if (!line.trim()) {
            i++
            continue
        }
        const heading = line.match(/^(#{1,6})\s+(.*)$/)
        if (heading) {
            out.push(m(`h${Math.min(heading[1].length + 2, 6)}.md__h`, inline(heading[2])))
            i++
            continue
        }
        if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
            out.push(<hr />)
            i++
            continue
        }
        const item = /^\s*([-*+]|\d+[.)])\s+/
        if (item.test(line)) {
            const ordered = /^\s*\d/.test(line)
            const items: string[] = []
            while (i < lines.length && (item.test(lines[i]) || (/^\s{2,}\S/.test(lines[i]) && items.length))) {
                if (item.test(lines[i])) items.push(lines[i].replace(item, ''))
                else items[items.length - 1] += ` ${lines[i].trim()}`
                i++
            }
            out.push(m(ordered ? 'ol' : 'ul', items.map((t) => <li>{inline(t)}</li>)))
            continue
        }
        // A table: a row of cells, a line of dashes under it, then its rows.
        if (isRow(line) && i + 1 < lines.length && DIVIDER.test(lines[i + 1])) {
            const align = cells(lines[i + 1]).map((c) => (c.startsWith(':') && c.endsWith(':') ? 'center' : c.endsWith(':') ? 'right' : null))
            const head = cells(line)
            i += 2
            const rows: string[][] = []
            while (i < lines.length && isRow(lines[i])) rows.push(cells(lines[i++]))
            const cell = (tag: 'th' | 'td', text: string, k: number) => m(tag, align[k] ? {style: {textAlign: align[k]}} : {}, ...inline(text))
            out.push(
                <div class="md__table">
                    <table>
                        <thead>
                            <tr>{head.map((h, k) => cell('th', h, k))}</tr>
                        </thead>
                        <tbody>
                            {rows.map((r) => (
                                <tr>{head.map((_, k) => cell('td', r[k] ?? '', k))}</tr>
                            ))}
                        </tbody>
                    </table>
                </div>,
            )
            continue
        }
        if (line.startsWith('>')) {
            const quote: string[] = []
            while (i < lines.length && lines[i].startsWith('>')) quote.push(lines[i++].replace(/^>\s?/, ''))
            out.push(<blockquote>{markdown(quote.join('\n'))}</blockquote>)
            continue
        }
        const para: string[] = []
        const tableAt = (k: number) => isRow(lines[k]) && k + 1 < lines.length && DIVIDER.test(lines[k + 1])
        while (i < lines.length && lines[i].trim() && !/^(\s*(```|~~~)|#{1,6}\s|>|\s*([-*+]|\d+[.)])\s)/.test(lines[i]) && !tableAt(i)) para.push(lines[i++])
        if (!para.length) para.push(lines[i++])
        out.push(<p>{inline(para.join('\n'))}</p>)
    }
    return out
}

/**
 * A panel the session brief asks for, its Markdown set apart so the person knows
 * it at a glance: an analysis (a fence of language `analysis`, before a question),
 * a proposal to take a wish to a new session (`new-session`, before asking
 * whether to), or what a finished branch changes once it lands (`impact`, before
 * "Shall it land?"). The `### Recommendation` part, or an impact's
 * `### Before it works`, sits apart at its foot.
 */
function panel(kind: 'analysis' | 'new-session' | 'impact', body: string[]): m.Children {
    const foot = kind === 'impact' ? /^#{1,6}\s+before it works/i : /^#{1,6}\s+recommend/i
    const at = body.findIndex((l) => foot.test(l))
    const parts = at < 0 ? [body, []] : [body.slice(0, at), body.slice(at)]
    return (
        <div class={kind === 'analysis' ? 'md__analysis' : `md__analysis md__analysis--${kind}`}>
            <div class="md__analysis-tag">
                {kind === 'analysis' ? (
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true">
                        <circle cx="11" cy="11" r="7" />
                        <path d="M20 20l-4-4" />
                    </svg>
                ) : kind === 'new-session' ? (
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                        <path d="M5 12h12" />
                        <path d="M13 6l6 6-6 6" />
                    </svg>
                ) : (
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                        <circle cx="12" cy="12" r="8" />
                        <path d="M8.5 12.5l2.5 2.5 4.5-5" />
                    </svg>
                )}
                {kind === 'analysis' ? 'Analysis' : kind === 'new-session' ? 'New session?' : 'Once it lands'}
            </div>
            {markdown(parts[0].join('\n'))}
            {parts[1].length ? <div class="md__analysis-rec">{markdown(parts[1].join('\n'))}</div> : null}
        </div>
    )
}

/** A table's line under its head: `|---|:--:|`, the outer pipes optional. */
const DIVIDER = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/

const isRow = (line: string) => line.trim().includes('|') && line.trim().length > 1

/** A table row's cells, trimmed: the outer pipes dropped, `\|` a pipe inside a cell. */
function cells(line: string): string[] {
    const t = line.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '')
    return t.split(/(?<!\\)\|/).map((c) => c.trim().replace(/\\\|/g, '|'))
}

const INLINE = /(`+)([\s\S]+?)\1|\*\*([\s\S]+?)\*\*|__([\s\S]+?)__|\*([^*\s][^*]*?)\*|_([^_\s][^_]*?)_(?!\w)|\[([^\]]+)\]\(([^)\s]+)\)|(https?:\/\/[^\s<>)]+)/g

/** One line's (or paragraph's) inline Markdown. */
export function inline(text: string): m.Children[] {
    const out: m.Children[] = []
    let last = 0
    for (const x of text.matchAll(INLINE)) {
        const at = x.index ?? 0
        if (at > last) out.push(...sessions(text.slice(last, at)))
        last = at + x[0].length
        if (x[2] != null) {
            // Code that is a session's name alone (`session-s3`) links too.
            const id = sessionOf(x[2].trim())
            out.push(id ? sessionLink(id, <code>{x[2]}</code>) : <code>{x[2]}</code>)
        }
        else if (x[3] != null || x[4] != null) out.push(<strong>{inline(x[3] ?? x[4])}</strong>)
        else if (x[5] != null || x[6] != null) out.push(<em>{inline(x[5] ?? x[6])}</em>)
        else if (x[7] != null) out.push(link(x[8], <span>{inline(x[7])}</span>))
        else if (x[9] != null) out.push(link(x[9], x[9]))
    }
    if (last < text.length) out.push(...sessions(text.slice(last)))
    return out
}

/** Whether `s3` is a session of this hub; none is until the page says which are (`linkSessions`). */
let isSession: (id: string) => boolean = () => false

/** Name the hub's sessions, so the text that names one links to it. */
export function linkSessions(known: (id: string) => boolean) {
    isSession = known
}

/** A session's name as the text says it — `S123`, `s3`, `session-s3` — and only one of this hub's. */
const SESSION = /\b(?:session-)?[sS](\d+)\b/g

/** The session a whole word names (`s3`, `S3`, `session-s3`), if it is one of this hub's. */
function sessionOf(word: string): string | null {
    const x = word.match(/^(?:session-)?[sS](\d+)$/)
    return x && isSession(`s${x[1]}`) ? `s${x[1]}` : null
}

const sessionLink = (id: string, label: m.Children) => (
    <a class="md__session" href={`/sessions/${id}`}>
        {label}
    </a>
)

/** Plain text with each session it names linked; the rest stays text. */
export function sessions(text: string): m.Children[] {
    const out: m.Children[] = []
    let last = 0
    for (const x of text.matchAll(SESSION)) {
        const id = `s${x[1]}`
        if (!isSession(id)) continue
        const at = x.index ?? 0
        if (at > last) out.push(text.slice(last, at))
        out.push(sessionLink(id, x[0]))
        last = at + x[0].length
    }
    if (last < text.length) out.push(text.slice(last))
    return out
}

function link(href: string, label: m.Children) {
    const own = href.match(/^\/sessions\/(s\d+)$/)
    if (own) return sessionLink(own[1], label)
    return /^https?:\/\//i.test(href) ? (
        <a href={href} target="_blank" rel="noopener noreferrer">
            {label}
        </a>
    ) : (
        label
    )
}