Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

9.1 KB
Raw Blame
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
// Lightweight markdown affordances for text editing. Two entry points:
// - autoformatAtCaret: called on every input; when the text just before the
//   caret completes an inline pattern (**bold**, *italic*, `code`, ~~strike~~)
//   the markers collapse into the real element, Notion-style. "- " or "* " at
//   the start of a line becomes a bullet glyph (indented: a sub-bullet), and
//   [caption](https://…) becomes a link.
// - markdownToHtml: converts pasted plain text (inline patterns + bullets +
//   line breaks) into the sanitized inline-HTML subset text elements store.
//
// This module stays INLINE-ONLY, and now by choice rather than by necessity.
// A text box can hold real ul/ol/li and h1/h2 since the formatting bar landed
// (editor/richtext.ts), but typing "- " still yields a "• " glyph: autoformat
// fires mid-keystroke, and silently converting the line you are typing into a
// list item moves the caret and captures Enter from then on. The bar is where
// a list is asked for explicitly; this is where a bullet is typed.

import { isWebUrl } from '../model.ts'
import { insideOpenFence, textUpTo } from './codefence.ts'

const INLINE: Array<{ re: RegExp; tag: string }> = [
  { re: /\*\*([^*\n]+)\*\*$/, tag: 'b' },
  { re: /__([^_\n]+)__$/, tag: 'b' },
  { re: /(?<![*\w])\*([^*\n]+)\*$/, tag: 'i' },
  { re: /(?<![_\w])_([^_\n]+)_$/, tag: 'i' },
  { re: /~~([^~\n]+)~~$/, tag: 's' },
  { re: /`([^`\n]+)`$/, tag: 'code' },
]

/** The most recent conversion, revertible with ⌘Z until the next input. */
type LastFormat =
  | { kind: 'inline'; el: HTMLElement; source: string; tail: Text }
  | { kind: 'bullet'; node: Text; offset: number; source: string }
let lastFormat: LastFormat | null = null

/** Forget the revertible conversion (any input that isn't a fresh conversion). */
export function clearAutoformat() {
  lastFormat = null
}

/** ⌘Z immediately after a conversion: restore the literal typed markers.
 *  Returns true when it reverted (caller should preventDefault). */
export function undoAutoformat(): boolean {
  const last = lastFormat
  lastFormat = null
  if (!last) return false
  if (last.kind === 'bullet') {
    if (!last.node.isConnected) return false
    last.node.replaceData(last.offset, 2, last.source)
    placeCaret(last.node, last.offset + last.source.length)
    return true
  }
  if (!last.el.isConnected) return false
  const literal = document.createTextNode(last.source)
  last.el.replaceWith(literal)
  last.tail.remove()
  placeCaret(literal, literal.data.length)
  return true
}

/** Collapse a just-completed markdown marker before the caret. Returns true if it fired. */
export function autoformatAtCaret(): boolean {
  const sel = document.getSelection()
  if (!sel?.isCollapsed || !(sel.anchorNode instanceof Text)) return false
  const node = sel.anchorNode
  const off = sel.anchorOffset // capture — DOM mutation below resets the live selection
  // inside an open ``` fence the text is code: no marker, bullet or link
  // conversion, or `template` literals would lose their backticks before the
  // commit turns the fence into a Code element (codefence.ts)
  const root = node.parentElement?.closest<HTMLElement>('.bento-text-inner')
  if (root && insideOpenFence(textUpTo(root, node, off))) return false
  const upto = node.data.slice(0, off)

  // "- " or "* " at line start → bullet glyph (contentEditable renders the
  // trailing space as NBSP, so match both). The glyph is followed by an NBSP:
  // a plain space at the end of a text node is a collapsed trailing space that
  // the next typed character simply replaces — "•x", no gap (discussion
  // #501; measured: "- " then "x" gave U+2022 U+0078). Indented by two or more spaces → a hollow sub-bullet, the
  // indent kept (discussions #255, #368).
  const bullet = upto.match(/(?:^|\n)([  ]{2,})?[-*][  ]$/)
  if (bullet && off >= 2 && isLineStart(node, off - 2 - (bullet[1]?.length ?? 0))) {
    const source = node.data.slice(off - 2, off)
    node.replaceData(off - 2, 2, bullet[1] ? '◦ ' : '• ')
    placeCaret(node, off)
    lastFormat = { kind: 'bullet', node, offset: off - 2, source }
    return true
  }
  // [caption](https://…) → a link. Only a web URL: the same test the show and
  // the sanitizer apply, so a javascript: "link" is just the literal text.
  const link = upto.match(/\[([^\[\]\n]+)\]\((https?:\/\/[^\s()]+)\)$/i)
  if (link && isWebUrl(link[2])) {
    const start = off - link[0].length
    const a = document.createElement('a')
    a.setAttribute('href', link[2])
    a.textContent = link[1]
    const tail = document.createTextNode('\u200b')
    const range = document.createRange()
    range.setStart(node, start)
    range.setEnd(node, off)
    range.deleteContents()
    range.insertNode(tail)
    range.insertNode(a)
    placeCaret(tail, 1)
    lastFormat = { kind: 'inline', el: a, source: link[0], tail }
    return true
  }

  for (const { re, tag } of INLINE) {
    const m = upto.match(re)
    if (!m || !m[1]) continue
    const start = off - m[0].length
    // backslash escape: \*literal\* stays literal (stripped on commit)
    if (start > 0 && node.data[start - 1] === '\\') continue
    const range = document.createRange()
    range.setStart(node, start)
    range.setEnd(node, off)
    range.deleteContents()
    const el = document.createElement(tag)
    el.textContent = m[1]
    range.insertNode(el)
    // caret into a fresh text node AFTER the element so typing continues plain
    const tail = document.createTextNode('​')
    el.after(tail)
    placeCaret(tail, 1)
    lastFormat = { kind: 'inline', el, source: m[0], tail }
    return true
  }
  return false
}

/** True when offset sits at the start of a rendered line (node start or after
 *  a <br>). Zero-width caret spacers left by autoformat are see-through. */
function isLineStart(node: Text, offset: number): boolean {
  const before = node.data.slice(0, offset).replace(/​/g, '')
  if (before) return before.endsWith('\n')
  let prev = node.previousSibling
  while (prev && prev.nodeType === Node.TEXT_NODE && /^[​\s]*$/.test((prev as Text).data)) {
    prev = prev.previousSibling
  }
  return !prev || (prev instanceof Element && prev.tagName === 'BR')
}

function placeCaret(node: Node, offset: number) {
  const r = document.createRange()
  r.setStart(node, offset)
  r.collapse(true)
  const sel = document.getSelection()
  sel?.removeAllRanges()
  sel?.addRange(r)
}

const escapeHtml = (s: string) =>
  s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')

/** A formula on one line, in any of the four delimiters the renderer reads
 *  (maths/delimiters.ts). Markdown stays out of it: `\\_` is LaTeX's literal
 *  underscore and `a^*` is a starred superscript, not an escape or emphasis. */
const FORMULA = /(\$\$[^$\n]+?\$\$|(?<!\\)\\\([^\n]+?\\\)|(?<!\\)\\\[[^\n]+?\\\]|(?<![\\$])\$\S(?:[^$\n]*?\S)?\$(?!\d))/

/** Drop the backslash from escaped markdown markers (`\\*x\\*` → `*x*`) —
 *  outside formulas only (#540). */
export function stripMarkerEscapes(s: string): string {
  return s.split(FORMULA).map((part, i) => (i % 2 ? part : part.replace(/\\([*_~`-])/g, '$1'))).join('')
}

/** Pasted plain text → the inline-HTML subset (bold/italic/strike/code/bullets/<br>).
 *  Backslash escapes markers: \*x\* pastes as literal *x*. */
export function markdownToHtml(text: string): string {
  // park escaped markers in the private-use area so patterns can't see them
  const PARK = ''
  const parked: string[] = []
  const park = (c: string) => PARK + (parked.push(c) - 1) + PARK
  // fenced code before anything: kept literally, its ``` lines included, so no
  // marker rule reaches inside it and the commit can turn it into a Code
  // element (codefence.ts) instead of inline <code> fragments
  const unfenced = text.replace(/^[ \t]*```[^\n]*\n[\s\S]*?\n[ \t]*```[ \t]*$/gm,
    (block) => park(escapeHtml(block).replace(/\n/g, '<br>')))
  // formulas next, whole and escaped, so no marker rule reaches inside one
  const withParked = unfenced.split(FORMULA)
    .map((part, i) => (i % 2 ? park(escapeHtml(part)) : part.replace(/\\([*_~`-])/g, (_, c: string) => park(c))))
    .join('')
  const out = withParked
    .split('\n')
    .map((line) => {
      // "- " / "* " → bullet; indented two+ spaces → sub-bullet, indent kept as
      // NBSPs so it survives HTML whitespace collapsing
      let s = escapeHtml(line).replace(/^( {2,})[-*] /, (_, sp: string) => '\u00a0'.repeat(sp.length) + '◦ ')
        .replace(/^( ?)[-*] /, '$1• ')
      s = s.replace(/\[([^\[\]]+)\]\((https?:\/\/[^\s()]+)\)/gi, (m, cap: string, href: string) =>
        isWebUrl(href) ? `<a href="${href.replaceAll('"', '&quot;')}">${cap}</a>` : m)
      s = s.replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>')
      s = s.replace(/__([^_]+)__/g, '<b>$1</b>')
      s = s.replace(/(?<![*\w])\*([^*]+)\*/g, '<i>$1</i>')
      s = s.replace(/(?<![_\w])_([^_]+)_(?![\w])/g, '<i>$1</i>')
      s = s.replace(/~~([^~]+)~~/g, '<s>$1</s>')
      s = s.replace(/`([^`]+)`/g, '<code>$1</code>')
      return s
    })
    .join('<br>')
  return out.replace(/(\d+)/g, (_, i) => parked[+i])
}