pretext icon indicating copy to clipboard operation
pretext copied to clipboard

[BUG] Pretext bidi: canvas.measureText vs DOM width divergence

Open sepcnt opened this issue 8 months ago • 4 comments

Pretext exposes segLevels in PreparedTextWithSegments, enabling consumers to build bidi-aware coordinate maps. However, the underlying segment widths come from canvas.measureText(segment) on isolated segments. For Arabic script the browser's DOM renderer may produce different effective widths due to contextual shaping, directional spacing, or font-level bidi adjustments.

Case dir bidi? max Δ (px) avg Δ (px)
LTR baseline ltr no 0.3 0.1
Short Arabic (LTR paragraph) ltr yes 7.4 4.1
Arabic words (LTR paragraph) ltr yes 8.4 4
Arabic words (RTL paragraph) rtl yes 8.4 4
Mixed LTR+Arabic+LTR ltr yes 78.6 45.9
Arabic + numbers ltr yes 8.4 1.8
LTR + short Arabic ltr yes 40.3 32.7

The PoC is attached below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pretext bidi: canvas vs DOM width divergence</title>
<style>
* { box-sizing: border-box; }
body { font: 15px/1.6 system-ui, sans-serif; max-width: 960px; margin: 2em auto; padding: 0 1em; }
h1 { font-size: 1.3em; }
h2 { font-size: 1.05em; margin-top: 2em; border-bottom: 1px solid #ddd; padding-bottom: .3em; }
table { border-collapse: collapse; margin: .8em 0; font-size: 13px; }
th, td { border: 1px solid #ddd; padding: 3px 8px; text-align: right; }
th { background: #f7f7f7; }
.bad { background: #fee; }
.ok  { background: #efe; }
pre { background: #f5f5f5; padding: .8em 1em; overflow-x: auto; font-size: 12px; border-radius: 4px; }
code { background: #f0f0f0; padding: .1em .3em; border-radius: 3px; font-size: .92em; }
.test-line { white-space: pre; position: absolute; visibility: hidden; }
.summary-table td:first-child { text-align: left; }
</style>
</head>
<body>
<h1>Pretext bidi: <code>canvas.measureText</code> vs DOM width divergence</h1>

<div id="issue"></div>
<div id="results"></div>
<div id="workspace" style="position:absolute;left:-9999px;top:0"></div>

<script type="module">
import {prepareWithSegments} from './node_modules/@chenglou/pretext/dist/layout.js'
import {getMeasureContext} from './node_modules/@chenglou/pretext/dist/measurement.js'

// ─── Canvas measurement (what pretext uses internally) ───

const ctx = getMeasureContext()

function canvasWidth(text, font) {
  ctx.font = font
  return ctx.measureText(text).width
}

// Per-grapheme prefix widths via canvas (sentinel trick for trailing whitespace)
function canvasPrefixWidth(text, offset, font) {
  if (offset <= 0) return 0
  ctx.font = font
  const prefix = text.slice(0, offset) + '|'
  return ctx.measureText(prefix).width - ctx.measureText('|').width
}

// ─── DOM measurement (what the browser actually renders) ───

function domCharRects(text, font, dir) {
  const div = document.createElement('div')
  div.className = 'test-line'
  div.style.font = font
  if (dir === 'rtl') div.style.direction = 'rtl'
  div.textContent = text
  document.getElementById('workspace').appendChild(div)
  div.style.visibility = 'visible'
  div.style.position = 'static'

  const node = div.firstChild
  const base = div.getBoundingClientRect().left
  const rects = []

  for (let i = 0; i < text.length; i++) {
    const r = document.createRange()
    r.setStart(node, i)
    r.setEnd(node, i + 1)
    const cr = r.getBoundingClientRect()
    rects.push({left: cr.left - base, right: cr.right - base, w: cr.width})
  }

  div.remove()
  return rects
}

// ─── Bidi reorder using pretext's segLevels ───

function computeVisualOrder(levels) {
  const n = levels.length, order = Array.from({length: n}, (_, i) => i)
  let maxLvl = 0
  for (let i = 0; i < n; i++) if (levels[i] > maxLvl) maxLvl = levels[i]
  for (let lvl = maxLvl; lvl >= 1; lvl--) {
    let i = 0
    while (i < n) {
      while (i < n && levels[order[i]] < lvl) i++
      const s = i
      while (i < n && levels[order[i]] >= lvl) i++
      for (let a = s, b = i - 1; a < b; a++, b--)
        { const t = order[a]; order[a] = order[b]; order[b] = t }
    }
  }
  return order
}

function pretextLayout(text, font) {
  const prepared = prepareWithSegments(text, font)
  const segs = prepared.segments
  const levels = prepared.segLevels
  const widths = prepared.widths

  // Build per-segment char offsets
  const segStart = [0]
  for (let i = 0; i < segs.length; i++) segStart.push(segStart[i] + segs[i].length)

  if (!levels) {
    // Pure LTR — trivial
    const xs = []
    for (let i = 0; i < text.length; i++)
      xs.push({left: canvasPrefixWidth(text, i, font), right: canvasPrefixWidth(text, i + 1, font)})
    return {xs, segs, levels: null, widths, visualOrder: null}
  }

  const visualOrder = computeVisualOrder(levels)

  // Visual x start per segment
  const segX = new Array(segs.length)
  let x = 0
  for (const vi of visualOrder) { segX[vi] = x; x += widths[vi] }

  const xs = []
  for (let ci = 0; ci < text.length; ci++) {
    let si = segs.length - 1
    for (let j = 0; j < segs.length; j++)
      if (ci < segStart[j + 1]) { si = j; break }
    const off = ci - segStart[si]
    const rtl = levels[si] % 2 === 1
    const seg = segs[si]

    let left, right
    if (rtl) {
      right = segX[si] + widths[si] - canvasPrefixWidth(seg, off, font)
      left  = segX[si] + widths[si] - canvasPrefixWidth(seg, off + 1, font)
    } else {
      left  = segX[si] + canvasPrefixWidth(seg, off, font)
      right = segX[si] + canvasPrefixWidth(seg, off + 1, font)
    }
    xs.push({left, right})
  }
  return {xs, segs, levels, widths, visualOrder}
}

// ─── Test cases ───

const font = '16px serif'
const cases = [
  {text: 'hello world',           dir: 'ltr', label: 'LTR baseline'},
  {text: 'فرخة',                  dir: 'ltr', label: 'Short Arabic (LTR paragraph)'},
  {text: 'واحد اثنان ثلاثة',      dir: 'ltr', label: 'Arabic words (LTR paragraph)'},
  {text: 'واحد اثنان ثلاثة',      dir: 'rtl', label: 'Arabic words (RTL paragraph)'},
  {text: 'one اثنان three',       dir: 'ltr', label: 'Mixed LTR+Arabic+LTR'},
  {text: 'واحد 444 اثنان',        dir: 'ltr', label: 'Arabic + numbers'},
  {text: 'one فرخة',              dir: 'ltr', label: 'LTR + short Arabic'},
]

// ─── Run ───

let summaryRows = []
let detailHtml = ''

for (const tc of cases) {
  const pt = pretextLayout(tc.text, font)
  const dom = domCharRects(tc.text, font, tc.dir)
  const hasBidi = pt.levels != null

  let maxDelta = 0, sumDelta = 0
  const rows = []

  for (let i = 0; i < tc.text.length; i++) {
    const ch = tc.text[i]
    const pLeft = pt.xs[i].left, pRight = pt.xs[i].right
    const dLeft = dom[i].left,   dRight = dom[i].right

    // Best-case delta: closest match between pretext edges and DOM edges
    const dL = Math.abs(pLeft - dLeft)
    const dR = Math.abs(pRight - dRight)
    const delta = Math.max(dL, dR)

    maxDelta = Math.max(maxDelta, delta)
    sumDelta += delta

    rows.push(`<tr class="${delta > 1 ? 'bad' : 'ok'}">
      <td>${i}</td><td style="text-align:center">${ch === ' ' ? '␣' : ch}</td>
      <td>${pLeft.toFixed(1)}</td><td>${pRight.toFixed(1)}</td>
      <td>${dLeft.toFixed(1)}</td><td>${dRight.toFixed(1)}</td>
      <td>${dL.toFixed(1)}</td><td>${dR.toFixed(1)}</td>
    </tr>`)
  }

  const avg = tc.text.length ? sumDelta / tc.text.length : 0
  const cls = maxDelta > 1 ? 'bad' : 'ok'
  summaryRows.push(`<tr class="${cls}">
    <td>${tc.label}</td><td><code>${tc.dir}</code></td>
    <td>${hasBidi ? 'yes' : 'no'}</td>
    <td>${maxDelta.toFixed(1)}</td><td>${avg.toFixed(1)}</td>
  </tr>`)

  detailHtml += `<h2>${tc.label} — <code>"${tc.text}"</code> (dir=${tc.dir})</h2>`
  if (hasBidi) {
    detailHtml += `<pre>segments: ${JSON.stringify(pt.segs)}
levels:   [${Array.from(pt.levels).join(', ')}]
widths:   [${pt.widths.map(w => w.toFixed(2)).join(', ')}]
visual:   [${pt.visualOrder.join(', ')}]</pre>`
  }
  detailHtml += `<table>
    <tr><th>i</th><th>ch</th><th>pt left</th><th>pt right</th>
        <th>DOM left</th><th>DOM right</th><th>ΔL</th><th>ΔR</th></tr>
    ${rows.join('\n')}</table>`
}

document.getElementById('issue').innerHTML = `
<h2>Summary</h2>
<table class="summary-table">
  <tr><th>Case</th><th>dir</th><th>bidi?</th><th>max&nbsp;Δ&nbsp;(px)</th><th>avg&nbsp;Δ&nbsp;(px)</th></tr>
  ${summaryRows.join('\n')}
</table>
<p>Cells highlighted <span class="bad" style="padding:1px 6px">red</span> have &gt;1px divergence.
The LTR baseline should be near-zero, confirming the issue is specific to bidi content.</p>
`

document.getElementById('results').innerHTML = '<h2>Per-character details</h2>' + detailHtml
</script>
</body>
</html>

sepcnt avatar Apr 01 '26 17:04 sepcnt

Thanks, I could reproduce this on current main.

The divergence is real when a consumer tries to reconstruct bidi x-coordinates from prepareWithSegments() data like segments, widths, and segLevels, especially for Arabic and mixed LTR/RTL text. Plain LTR stayed near zero in my repro, but Arabic and mixed bidi showed large deltas.

I don’t think this is a layout() / line-breaking bug though. Today segLevels is only simplified custom-rendering metadata, and PreparedTextWithSegments is an unstable rich-path escape hatch rather than a DOM-faithful glyph-positioning API.

So I think the right next step is to tighten the contract/docs around what prepareWithSegments() does and does not guarantee for bidi custom rendering. A true fix for precise bidi coordinate mapping would likely need shaping-aware measurement/positioning, not just a small patch to the current segment-width model.

chenglou avatar Apr 01 '26 18:04 chenglou

According to my experiment results with codemirror, it consists of one bug and a flaw. Could be mitigate like emoji correction but accurate line break still needs something like huffbuzz or opentype to resolve.

sepcnt avatar Apr 03 '26 14:04 sepcnt

Fixed in #103.

This takes the docs/contract route you mentioned on the issue: segLevels is now called out as custom-rendering metadata only, and the segment widths are described as line-breaking widths rather than a DOM-faithful bidi x-coordinate contract.

beeegee avatar Apr 05 '26 05:04 beeegee

Thanks!

chenglou avatar Apr 05 '26 06:04 chenglou