Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

16.9 KB
Raw Blame
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
// A DOM small enough to mount dash's grid into, and no smaller.
//
// WHY THIS EXISTS. The two things `scripts/test-dash-a11y.ts` and
// `scripts/test-dash-frontier.ts` have to prove are both about the DOM the grid
// EMITS — `aria-rowindex` on a row that is not in the DOM window, and
// `document.activeElement` after a click. Neither can be asserted from a pure
// function, and dash pulls in no jsdom (its whole shape is "no dependencies").
// So this is a parser and a node tree covering exactly the surface grid.ts,
// find.ts and select.ts touch when they mount and paint.
//
// WHAT IT IS NOT. It is not a browser and it does not lay anything out: there
// is no CSS, no `position: sticky`, and every measurement (`clientHeight`,
// `getBoundingClientRect`) is whatever the fixture sets. A grid that draws in
// the wrong PLACE is a thing you look at, and it is looked at in a browser. A
// grid that tells a screen reader the wrong ROW NUMBER is invisible in a
// browser and exactly what belongs in a rig, which is the division these two
// files are written to.
//
// The markup it parses is machine-generated by grid.ts and find.ts — double
// quoted attributes, no self-closing oddities, a known set of void elements —
// so the parser can be strict rather than forgiving. If it ever meets markup it
// cannot read it THROWS, because a shim that silently drops an attribute would
// turn every assertion below it into a passing test of nothing.

const VOID = new Set(['input', 'br', 'img', 'hr', 'meta', 'link'])

export class El {
  tagName: string
  attrs = new Map<string, string>()
  children: El[] = []
  parentElement: El | null = null
  text = ''
  style: Record<string, string> & { setProperty(k: string, v: string): void }
  dataset: Record<string, string> = {}
  private listeners = new Map<string, Array<(e: unknown) => void>>()
  /** whatever the fixture says; nothing here measures anything */
  clientHeight = 0
  clientWidth = 0
  scrollTop = 0
  scrollLeft = 0
  offsetHeight = 0
  value = ''
  ownerDocument: Doc

  constructor(tag: string, doc: Doc) {
    this.tagName = tag.toUpperCase()
    this.ownerDocument = doc
    const st: Record<string, string> = {}
    this.style = Object.assign(st, {
      setProperty(k: string, v: string) { st[k] = v },
    }) as El['style']
  }

  // --- attributes ------------------------------------------------------------

  setAttribute(k: string, v: string): void {
    this.attrs.set(k, v)
    if (k.startsWith('data-')) this.dataset[camel(k.slice(5))] = v
  }

  getAttribute(k: string): string | null { return this.attrs.get(k) ?? null }
  hasAttribute(k: string): boolean { return this.attrs.has(k) }

  removeAttribute(k: string): void {
    this.attrs.delete(k)
    if (k.startsWith('data-')) delete this.dataset[camel(k.slice(5))]
  }

  /**
   * `id` as an ATTRIBUTE, not a stray JS property. `style.id = 'dx-theme'` is
   * how settings.ts names the theme override, and a shim that let that land as
   * a plain property would make `getElementById` miss it — a test of nothing,
   * passing.
   */
  get id(): string { return this.attrs.get('id') ?? '' }
  set id(v: string) { this.setAttribute('id', v) }

  get className(): string { return this.attrs.get('class') ?? '' }
  set className(v: string) { this.setAttribute('class', v) }

  get classList() {
    const read = (): string[] => this.className.split(/\s+/).filter(Boolean)
    const write = (xs: string[]): void => { this.className = xs.join(' ') }
    return {
      add: (...xs: string[]) => write([...new Set([...read(), ...xs])]),
      remove: (...xs: string[]) => write(read().filter((c) => !xs.includes(c))),
      contains: (x: string) => read().includes(x),
    }
  }

  get hidden(): boolean { return this.hasAttribute('hidden') }
  set hidden(v: boolean) { if (v) { this.setAttribute('hidden', '') } else { this.removeAttribute('hidden') } }

  get tabIndex(): number {
    const v = this.attrs.get('tabindex')
    return v === undefined ? -1 : Number(v)
  }

  set tabIndex(v: number) { this.setAttribute('tabindex', String(v)) }

  get contentEditable(): string { return this.attrs.get('contenteditable') ?? 'false' }
  set contentEditable(v: string) { this.setAttribute('contenteditable', v) }
  get isContentEditable(): boolean { return this.contentEditable === 'true' }

  // --- tree ------------------------------------------------------------------

  appendChild(c: El): El { c.parentElement = this; this.children.push(c); return c }

  /**
   * `append(a, b, …)`, which the panel builders use where the grid uses
   * `appendChild`. Strings become text, as the DOM's does — panels.ts never
   * passes one, but a shim that silently dropped it would be worse than one
   * that throws.
   */
  append(...nodes: Array<El | string>): void {
    for (const n of nodes) {
      if (typeof n === 'string') addText(this, n)
      else this.appendChild(n)
    }
  }

  /**
   * `insertBefore` and `replaceChildren`, which the dialogs use: a paste panel
   * lands ABOVE the footer (appending it puts it below the Close button, where
   * it reads as "nothing happened"), and the version list replaces its own
   * contents when the timeline comes back from IndexedDB.
   */
  insertBefore(node: El, ref: El | null): El {
    node.parentElement = this
    const at = ref ? this.children.indexOf(ref) : -1
    if (at < 0) this.children.push(node)
    else this.children.splice(at, 0, node)
    return node
  }

  replaceChildren(...nodes: El[]): void {
    for (const c of this.children) c.parentElement = null
    this.children = []
    this.text = ''
    for (const n of nodes) this.appendChild(n)
  }

  /** Detach from the parent. `.dx-pop` and `.dx-ask-back` both remove themselves. */
  remove(): void {
    const p = this.parentElement
    if (!p) return
    p.children = p.children.filter((c) => c !== this)
    this.parentElement = null
  }

  get innerHTML(): string { return this.children.map(serialize).join('') + this.text }

  set innerHTML(html: string) {
    for (const c of this.children) c.parentElement = null
    this.children = []
    this.text = ''
    parseInto(this, html, this.ownerDocument)
  }

  get textContent(): string {
    return this.text + this.children.map((c) => c.textContent).join('')
  }

  set textContent(v: string) {
    for (const c of this.children) c.parentElement = null
    this.children = []
    this.text = v
  }

  insertAdjacentHTML(_where: string, html: string): void {
    parseInto(this, html, this.ownerDocument)
  }

  contains(other: unknown): boolean {
    for (let n: El | null = other as El; n; n = n.parentElement) if (n === this) return true
    return false
  }

  /** depth-first, self first — the order a real querySelectorAll returns. */
  private *walk(): Generator<El> {
    for (const c of this.children) { yield c; yield* c.walk() }
  }

  querySelector(sel: string): El | null {
    for (const n of this.walk()) if (matchesIn(n, sel, this)) return n
    return null
  }

  querySelectorAll(sel: string): El[] {
    const out: El[] = []
    for (const n of this.walk()) if (matchesIn(n, sel, this)) out.push(n)
    return out
  }

  matches(sel: string): boolean { return sel.split(',').some((s) => matchCompound(this, s.trim())) }

  closest(sel: string): El | null {
    for (let n: El | null = this; n; n = n.parentElement) if (n.matches(sel)) return n
    return null
  }

  // --- events and focus --------------------------------------------------------

  addEventListener(type: string, fn: (e: unknown) => void): void {
    const xs = this.listeners.get(type) ?? []
    xs.push(fn)
    this.listeners.set(type, xs)
  }

  removeEventListener(type: string, fn: (e: unknown) => void): void {
    this.listeners.set(type, (this.listeners.get(type) ?? []).filter((f) => f !== fn))
  }

  /**
   * Bubbling, because grid.ts wires drags with `on<x>` PROPERTIES and find.ts
   * with `addEventListener`, and a click has to reach both.
   */
  dispatchEvent(e: { type: string; target?: El } & Record<string, unknown>): void {
    e.target = e.target ?? this
    for (let n: El | null = this; n; n = n.parentElement) {
      const prop = (n as unknown as Record<string, unknown>)[`on${e.type}`]
      if (typeof prop === 'function') (prop as (ev: unknown) => void).call(n, e)
      for (const fn of n.listeners.get(e.type) ?? []) fn.call(n, e)
    }
  }

  focus(_opts?: unknown): void { this.ownerDocument.activeElement = this }
  blur(): void { if (this.ownerDocument.activeElement === this) this.ownerDocument.activeElement = this.ownerDocument.body }
  getBoundingClientRect() { return { left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0 } }
  scrollIntoView(): void { /* nothing to scroll */ }
}

export class Doc {
  body: El
  documentElement: El
  activeElement: El

  constructor() {
    this.documentElement = new El('html', this)
    this.head = new El('head', this)
    this.body = new El('body', this)
    this.documentElement.appendChild(this.head)
    this.documentElement.appendChild(this.body)
    this.activeElement = this.body
  }

  /**
   * `head`, for the one node an app puts there: the transient <style> that
   * pins `color-scheme` for a theme choice (settings.ts, and the reason it is
   * a <style> and not an attribute on <html> is written there).
   */
  head: El

  createElement(tag: string): El { return new El(tag, this) }

  /**
   * A text node. Real enough for the checkbox labels, which are built as
   * `label.append(box, document.createTextNode(' ' + text))` — a shim that
   * dropped the text would make every one of them measure as an empty line.
   */
  createTextNode(text: string): El {
    const n = new El('#text', this)
    n.text = text
    return n
  }

  getElementById(id: string): El | null { return this.querySelector(`#${id}`) }
  createRange() { return { selectNodeContents() {}, collapse() {} } }

  /**
   * DOCUMENT-level listeners are KEPT, not dropped.
   *
   * They used to be discarded with the note "the rig calls handlers directly",
   * which was true while everything under test hung its handlers on elements.
   * A context menu does not: `popover` closes on a document keydown, and the
   * only way to prove Escape closes a menu is to deliver one to the document
   * the way a browser does. Nothing that previously relied on the no-op can
   * notice — a listener that is never fired behaves exactly like one that was
   * never registered. Use `fireDoc` to deliver an event.
   */
  docListeners = new Map<string, Array<(e: unknown) => void>>()

  addEventListener(type?: string, fn?: (e: unknown) => void): void {
    if (!type || !fn) return
    this.docListeners.set(type, [...(this.docListeners.get(type) ?? []), fn])
  }

  removeEventListener(type?: string, fn?: (e: unknown) => void): void {
    if (!type || !fn) return
    this.docListeners.set(type, (this.docListeners.get(type) ?? []).filter((f) => f !== fn))
  }
  querySelector(sel: string): El | null { return this.documentElement.querySelector(sel) }
  querySelectorAll(sel: string): El[] { return this.documentElement.querySelectorAll(sel) }
}

// --- the parser ---------------------------------------------------------------

const ATTR = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*"([^"]*)")?/g

function parseInto(root: El, html: string, doc: Doc): void {
  let cur = root
  let i = 0
  while (i < html.length) {
    const lt = html.indexOf('<', i)
    if (lt < 0) { addText(cur, html.slice(i)); break }
    if (lt > i) addText(cur, html.slice(i, lt))
    const gt = html.indexOf('>', lt)
    if (gt < 0) throw new Error(`dash-dom: unterminated tag near ${html.slice(lt, lt + 40)}`)
    const raw = html.slice(lt + 1, gt)
    if (raw.startsWith('/')) {
      const tag = raw.slice(1).trim().toUpperCase()
      if (cur.tagName !== tag) throw new Error(`dash-dom: </${tag}> closes <${cur.tagName}>`)
      cur = cur.parentElement!
      i = gt + 1
      continue
    }
    const selfClose = raw.endsWith('/')
    const body = selfClose ? raw.slice(0, -1) : raw
    const sp = body.search(/\s/)
    const tag = (sp < 0 ? body : body.slice(0, sp)).trim()
    const el = new El(tag, doc)
    if (sp >= 0) {
      ATTR.lastIndex = 0
      let m: RegExpExecArray | null
      while ((m = ATTR.exec(body.slice(sp))) !== null) el.setAttribute(m[1], unesc(m[2] ?? ''))
    }
    cur.appendChild(el)
    if (!selfClose && !VOID.has(tag.toLowerCase())) cur = el
    i = gt + 1
  }
  if (cur !== root) throw new Error(`dash-dom: unclosed <${cur.tagName}>`)
}

const addText = (el: El, s: string): void => {
  if (!s) return
  if (el.children.length) el.children[el.children.length - 1].text += unesc(s)
  else el.text += unesc(s)
}

const unesc = (s: string): string => s
  .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&')
const esc = (s: string): string => s
  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')

function serialize(el: El): string {
  const attrs = [...el.attrs].map(([k, v]) => ` ${k}="${esc(v)}"`).join('')
  const tag = el.tagName.toLowerCase()
  if (VOID.has(tag)) return `<${tag}${attrs}>`
  return `<${tag}${attrs}>${el.innerHTML}</${tag}>`
}

// --- selectors ------------------------------------------------------------------
//
// Compound (`.dg-cell[data-ci]`) and DESCENDANT (`.dg-row[data-rid] .dg-cell`),
// which is the whole grammar grid.ts and find.ts use between them. An `>` or a
// `~` would silently match the wrong thing, so they throw.

const COMPOUND = /^([a-zA-Z][-a-zA-Z0-9]*)?((?:[.#][-a-zA-Z0-9_]+|\[[^\]]+\])*)$/
const PIECE = /[.#][-a-zA-Z0-9_]+|\[[^\]]+\]/g

function matchCompound(el: El, sel: string): boolean {
  if (/[>~+]/.test(sel)) throw new Error(`dash-dom: unsupported selector "${sel}"`)
  const m = COMPOUND.exec(sel)
  if (!m) throw new Error(`dash-dom: unparsable selector "${sel}"`)
  if (m[1] && el.tagName !== m[1].toUpperCase()) return false
  PIECE.lastIndex = 0
  let p: RegExpExecArray | null
  while ((p = PIECE.exec(m[2] ?? '')) !== null) {
    const s = p[0]
    if (s[0] === '.') { if (!el.classList.contains(s.slice(1))) return false; continue }
    if (s[0] === '#') { if (el.getAttribute('id') !== s.slice(1)) return false; continue }
    const inner = s.slice(1, -1)
    const eq = inner.indexOf('=')
    if (eq < 0) { if (!el.hasAttribute(inner)) return false; continue }
    const k = inner.slice(0, eq)
    const v = inner.slice(eq + 1).replace(/^["']|["']$/g, '')
    if (el.getAttribute(k) !== v) return false
  }
  return true
}

function matchesIn(el: El, sel: string, root: El): boolean {
  return sel.split(',').some((one) => {
    const parts = one.trim().split(/\s+/)
    if (!matchCompound(el, parts[parts.length - 1])) return false
    let n = el.parentElement
    for (let i = parts.length - 2; i >= 0; i--) {
      let found = false
      while (n && n !== root.parentElement) {
        if (matchCompound(n, parts[i])) { found = true; n = n.parentElement; break }
        n = n.parentElement
      }
      if (!found) return false
    }
    return true
  })
}

const camel = (s: string): string => s.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase())

/**
 * Install the shim as the globals grid.ts reaches for, and hand back a host
 * element already in the tree. `ResizeObserver` is deliberately left undefined:
 * grid.ts guards on `typeof ResizeObserver !== 'undefined'`, and there is
 * nothing here that could resize.
 */
export function installDom(): { doc: Doc; host: El } {
  const doc = new Doc()
  const g = globalThis as unknown as Record<string, unknown>
  g.document = doc
  g.getSelection = () => ({ removeAllRanges() {}, addRange() {} })
  if (!g.navigator) g.navigator = { language: 'en', clipboard: { writeText: () => Promise.resolve() } }
  // `popover` clamps its position against the viewport. No layout happens here,
  // so the numbers only have to exist — but they DO have to exist, or every
  // menu opens at NaN and the test of where it opened is a test of nothing.
  if (g.innerWidth === undefined) g.innerWidth = 1200
  if (g.innerHeight === undefined) g.innerHeight = 800
  const host = doc.createElement('div')
  doc.body.appendChild(host)
  return { doc, host }
}

/**
 * Deliver an event to the DOCUMENT's own listeners — the ones a browser routes
 * through `document`, which no element dispatch can reach. A copy of the list
 * is iterated because a handler that closes a popover removes itself while it
 * runs.
 */
export function fireDoc(doc: Doc, type: string, ev: Record<string, unknown> = {}): void {
  for (const fn of [...(doc.docListeners.get(type) ?? [])]) fn(ev)
}

/** A right-click, which is what opens every menu in the grid. */
export const contextmenu = (el: El, extra: Record<string, unknown> = {}): void =>
  el.dispatchEvent({
    type: 'contextmenu', button: 2, clientX: 10, clientY: 20,
    preventDefault() {}, stopPropagation() {}, ...extra,
  })

/** A left mousedown on an element, the way the grid's own handlers see one. */
export const mousedown = (el: El, extra: Record<string, unknown> = {}): void =>
  el.dispatchEvent({ type: 'mousedown', button: 0, shiftKey: false, clientX: 0, clientY: 0, ...extra })