From 097bdbd40204d501a25a366a23b6e66e2e38537d Mon Sep 17 00:00:00 2001 From: wgw Date: Sat, 28 Nov 2026 12:31:51 +0800 Subject: [PATCH] fix(markdown): widen within cell on empty code lines in offsetAtIndexed and add linear equivalence tests --- cmd/viva/templates/markdown_index.go.txt | 210 ++++++++++------ cmd/viva/templates/tree.go.txt | 3 + components/markdown_index.go | 210 ++++++++++------ components/markdown_index_test.go | 298 +++++++++++++++++++++-- 4 files changed, 561 insertions(+), 160 deletions(-) diff --git a/cmd/viva/templates/markdown_index.go.txt b/cmd/viva/templates/markdown_index.go.txt index 6b7dc0988..0828f0d38 100644 --- a/cmd/viva/templates/markdown_index.go.txt +++ b/cmd/viva/templates/markdown_index.go.txt @@ -51,9 +51,8 @@ type mdBlockSpan struct { markerPiece int32 // Item bullet/number piece, or -1 } -// AllocatedBytes reports a conservative estimate of retained heap memory held -// by v, including backing slice capacities so callers can enforce strict -// per-document and global memory budgets. +// AllocatedBytes reports a conservative estimate of the heap bytes retained by +// v's backing slices, including spare slice capacity. func (v *MarkdownView) AllocatedBytes() int { total := cap(v.pieces)*int(unsafe.Sizeof(mdPiece{})) + cap(v.runs)*int(unsafe.Sizeof(mdCodeRun{})) + @@ -191,24 +190,25 @@ func (v *MarkdownView) visitVisibleRows(firstBlk, lastBlk int, clipped bool, cli } // offsetAtIndexed locates the rendered byte offset nearest (x, y) in local -// coordinates using the hierarchical spatial index. +// coordinates using the hierarchical spatial index. Because every block, table +// row, and visual row strictly encloses its pieces vertically, widening outward +// by increasing vertical distance and pruning once minDy*1_000_000 > bestScore +// produces the exact same result as a full linear scan over v.pieces. func (v *MarkdownView) offsetAtIndexed(x, y float32) (int, bool) { if len(v.blockSpans) == 0 { return 0, false } - // Find the block containing y, or the closest vertical neighbor(s) when y - // sits in a gap between blocks. - n := len(v.blockSpans) - bi := sort.Search(n, func(i int) bool { return v.blockSpans[i].bottom >= y }) - loBlk, hiBlk := bi, bi+1 - if bi >= n { - loBlk, hiBlk = n-1, n - } else if bi > 0 && y < v.blockSpans[bi].y { - // y is in the vertical gap between block bi-1 and block bi; check both. - loBlk = bi - 1 + best, bestScore := -1, float32(0) + + prevPlainPiece := func(pi int32) *mdPiece { + for j := pi - 1; j >= 0; j-- { + if v.pieces[j].plainLo >= 0 { + return &v.pieces[j] + } + } + return nil } - best, bestScore := -1, float32(0) checkRow := func(row *mdRowSpan) (int, bool) { var previous *mdPiece for pi := row.pieceLo; pi < row.pieceHi; pi++ { @@ -216,13 +216,17 @@ func (v *MarkdownView) offsetAtIndexed(x, y float32) (int, bool) { if piece.plainLo < 0 { continue } - if previous != nil && previous.y == piece.y && previous.plainHi < piece.plainLo && y >= piece.y && y <= piece.y+piece.h { - start := previous.x + v.caretAdvance(previous, int(previous.plainHi-previous.plainLo)) + prev := previous + if prev == nil && y >= piece.y && y <= piece.y+piece.h { + prev = prevPlainPiece(pi) + } + if prev != nil && prev.y == piece.y && prev.plainHi < piece.plainLo && y >= piece.y && y <= piece.y+piece.h { + start := prev.x + v.caretAdvance(prev, int(prev.plainHi-prev.plainLo)) end := piece.x + v.caretAdvance(piece, 0) if end > start && x >= start && x <= end { - gap := int(piece.plainLo - previous.plainHi) + gap := int(piece.plainLo - prev.plainHi) position := int(float32(gap)*(x-start)/(end-start) + 0.5) - return gfx.GraphemeStart(unsafe.String(unsafe.SliceData(v.plain), len(v.plain)), int(previous.plainHi)+min(max(position, 0), gap)), true + return gfx.GraphemeStart(unsafe.String(unsafe.SliceData(v.plain), len(v.plain)), int(prev.plainHi)+min(max(position, 0), gap)), true } } previous = piece @@ -238,90 +242,154 @@ func (v *MarkdownView) offsetAtIndexed(x, y float32) (int, bool) { dy = y - piece.y - piece.h } score := dy*1_000_000 + dx - if best < 0 || score < bestScore { + if best < 0 || score < bestScore || (score == bestScore && int(pi) < best) { best, bestScore = int(pi), score } } return 0, false } + spanDist := func(top, bottom float32) float32 { + if y < top { + return top - y + } + if y > bottom { + return y - bottom + } + return 0 + } + + spanCouldBeat := func(top, bottom float32) bool { + return best < 0 || spanDist(top, bottom)*1_000_000 <= bestScore + } + + // checkRowsNearY searches rows sorted by y around the pointer, widening + // within the slice before returning so empty rows (such as blank lines + // inside a code block) resolve against other rows of the same cell/block. checkRowsNearY := func(rows []mdRowSpan) (int, bool) { rn := len(rows) if rn == 0 { return 0, false } ri := sort.Search(rn, func(i int) bool { return rows[i].bottom >= y }) - rLo, rHi := ri, ri+1 - if ri >= rn { - rLo, rHi = rn-1, rn - } else if ri > 0 && y < rows[ri].y { - rLo = ri - 1 - } - for k := rLo; k < rHi; k++ { - if off, hit := checkRow(&rows[k]); hit { + up := ri - 1 + down := ri + if down < rn && y >= rows[down].y && y <= rows[down].bottom { + if off, hit := checkRow(&rows[down]); hit { return off, true } + down++ + } + for up >= 0 || down < rn { + upOK := up >= 0 && spanCouldBeat(rows[up].y, rows[up].bottom) + downOK := down < rn && spanCouldBeat(rows[down].y, rows[down].bottom) + if !upOK && !downOK { + break + } + if upOK && (!downOK || spanDist(rows[up].y, rows[up].bottom) <= spanDist(rows[down].y, rows[down].bottom)) { + if off, hit := checkRow(&rows[up]); hit { + return off, true + } + up-- + } else { + if off, hit := checkRow(&rows[down]); hit { + return off, true + } + down++ + } } return 0, false } - // Expand outward if the nearest block(s) had no selectable text (e.g. a Rule). - for expand := 0; expand < n; expand++ { - if expand > 0 { - foundAny := false - if loBlk > 0 { - loBlk-- - foundAny = true - } - if hiBlk < n { - hiBlk++ - foundAny = true - } - if !foundAny { - break + checkTableRow := func(tr *mdTableRowSpan) (int, bool) { + for ci := tr.cellLo; ci < tr.cellHi; ci++ { + cell := &v.cellSpans[ci] + if off, hit := checkRowsNearY(v.rowSpans[cell.rowLo:cell.rowHi]); hit { + return off, true } } - for idx := loBlk; idx < hiBlk; idx++ { - blk := &v.blockSpans[idx] - switch blk.kind { - case markdown.Table: - tRows := v.tableRows[blk.tableRowLo:blk.tableRowHi] - trn := len(tRows) - if trn == 0 { - continue + return 0, false + } + + checkBlock := func(blk *mdBlockSpan) (int, bool) { + switch blk.kind { + case markdown.Table: + tRows := v.tableRows[blk.tableRowLo:blk.tableRowHi] + trn := len(tRows) + if trn == 0 { + return 0, false + } + tri := sort.Search(trn, func(i int) bool { return tRows[i].bottom >= y }) + up := tri - 1 + down := tri + if down < trn && y >= tRows[down].y && y <= tRows[down].bottom { + if off, hit := checkTableRow(&tRows[down]); hit { + return off, true } - tri := sort.Search(trn, func(i int) bool { return tRows[i].bottom >= y }) - tLo, tHi := tri, tri+1 - if tri >= trn { - tLo, tHi = trn-1, trn - } else if tri > 0 && y < tRows[tri].y { - tLo = tri - 1 + down++ + } + for up >= 0 || down < trn { + upOK := up >= 0 && spanCouldBeat(tRows[up].y, tRows[up].bottom) + downOK := down < trn && spanCouldBeat(tRows[down].y, tRows[down].bottom) + if !upOK && !downOK { + break } - for k := tLo; k < tHi; k++ { - tr := &tRows[k] - for ci := tr.cellLo; ci < tr.cellHi; ci++ { - cell := &v.cellSpans[ci] - if off, hit := checkRowsNearY(v.rowSpans[cell.rowLo:cell.rowHi]); hit { - return off, true - } + if upOK && (!downOK || spanDist(tRows[up].y, tRows[up].bottom) <= spanDist(tRows[down].y, tRows[down].bottom)) { + if off, hit := checkTableRow(&tRows[up]); hit { + return off, true } - } - case markdown.Labeled: - for ci := blk.cellLo; ci < blk.cellHi; ci++ { - cell := &v.cellSpans[ci] - if off, hit := checkRowsNearY(v.rowSpans[cell.rowLo:cell.rowHi]); hit { + up-- + } else { + if off, hit := checkTableRow(&tRows[down]); hit { return off, true } + down++ } - default: - if off, hit := checkRowsNearY(v.rowSpans[blk.rowLo:blk.rowHi]); hit { + } + case markdown.Labeled: + for ci := blk.cellLo; ci < blk.cellHi; ci++ { + cell := &v.cellSpans[ci] + if off, hit := checkRowsNearY(v.rowSpans[cell.rowLo:cell.rowHi]); hit { return off, true } } + default: + if off, hit := checkRowsNearY(v.rowSpans[blk.rowLo:blk.rowHi]); hit { + return off, true + } + } + return 0, false + } + + // Search the block covering y first, then widen outward by increasing + // vertical distance while any neighbour block could still beat bestScore. + n := len(v.blockSpans) + bi := sort.Search(n, func(i int) bool { return v.blockSpans[i].bottom >= y }) + up := bi - 1 + down := bi + if down < n && y >= v.blockSpans[down].y && y <= v.blockSpans[down].bottom { + if off, hit := checkBlock(&v.blockSpans[down]); hit { + return off, true } - if best >= 0 { + down++ + } + for up >= 0 || down < n { + upOK := up >= 0 && spanCouldBeat(v.blockSpans[up].y, v.blockSpans[up].bottom) + downOK := down < n && spanCouldBeat(v.blockSpans[down].y, v.blockSpans[down].bottom) + if !upOK && !downOK { break } + if upOK && (!downOK || spanDist(v.blockSpans[up].y, v.blockSpans[up].bottom) <= spanDist(v.blockSpans[down].y, v.blockSpans[down].bottom)) { + if off, hit := checkBlock(&v.blockSpans[up]); hit { + return off, true + } + up-- + } else { + if off, hit := checkBlock(&v.blockSpans[down]); hit { + return off, true + } + down++ + } } if best < 0 { diff --git a/cmd/viva/templates/tree.go.txt b/cmd/viva/templates/tree.go.txt index 3537b04da..43dc35a84 100644 --- a/cmd/viva/templates/tree.go.txt +++ b/cmd/viva/templates/tree.go.txt @@ -102,6 +102,9 @@ func (tree *Tree) Item(item TreeItem) TreeRow { hovered := enabled && tree.canvas.Hovered() == item.ID focused := enabled && !item.Dragging && tree.canvas.FocusVisible() == item.ID radius := tree.theme.Metrics.RadiusControl + if item.Background.Alpha > 0 { + tree.canvas.Fill(row, item.Background) + } if item.Selected || hovered { background := tree.theme.Muted if item.Selected { diff --git a/components/markdown_index.go b/components/markdown_index.go index b294e4d5d..f442a48d9 100644 --- a/components/markdown_index.go +++ b/components/markdown_index.go @@ -51,9 +51,8 @@ type mdBlockSpan struct { markerPiece int32 // Item bullet/number piece, or -1 } -// AllocatedBytes reports a conservative estimate of retained heap memory held -// by v, including backing slice capacities so callers can enforce strict -// per-document and global memory budgets. +// AllocatedBytes reports a conservative estimate of the heap bytes retained by +// v's backing slices, including spare slice capacity. func (v *MarkdownView) AllocatedBytes() int { total := cap(v.pieces)*int(unsafe.Sizeof(mdPiece{})) + cap(v.runs)*int(unsafe.Sizeof(mdCodeRun{})) + @@ -191,24 +190,25 @@ func (v *MarkdownView) visitVisibleRows(firstBlk, lastBlk int, clipped bool, cli } // offsetAtIndexed locates the rendered byte offset nearest (x, y) in local -// coordinates using the hierarchical spatial index. +// coordinates using the hierarchical spatial index. Because every block, table +// row, and visual row strictly encloses its pieces vertically, widening outward +// by increasing vertical distance and pruning once minDy*1_000_000 > bestScore +// produces the exact same result as a full linear scan over v.pieces. func (v *MarkdownView) offsetAtIndexed(x, y float32) (int, bool) { if len(v.blockSpans) == 0 { return 0, false } - // Find the block containing y, or the closest vertical neighbor(s) when y - // sits in a gap between blocks. - n := len(v.blockSpans) - bi := sort.Search(n, func(i int) bool { return v.blockSpans[i].bottom >= y }) - loBlk, hiBlk := bi, bi+1 - if bi >= n { - loBlk, hiBlk = n-1, n - } else if bi > 0 && y < v.blockSpans[bi].y { - // y is in the vertical gap between block bi-1 and block bi; check both. - loBlk = bi - 1 + best, bestScore := -1, float32(0) + + prevPlainPiece := func(pi int32) *mdPiece { + for j := pi - 1; j >= 0; j-- { + if v.pieces[j].plainLo >= 0 { + return &v.pieces[j] + } + } + return nil } - best, bestScore := -1, float32(0) checkRow := func(row *mdRowSpan) (int, bool) { var previous *mdPiece for pi := row.pieceLo; pi < row.pieceHi; pi++ { @@ -216,13 +216,17 @@ func (v *MarkdownView) offsetAtIndexed(x, y float32) (int, bool) { if piece.plainLo < 0 { continue } - if previous != nil && previous.y == piece.y && previous.plainHi < piece.plainLo && y >= piece.y && y <= piece.y+piece.h { - start := previous.x + v.caretAdvance(previous, int(previous.plainHi-previous.plainLo)) + prev := previous + if prev == nil && y >= piece.y && y <= piece.y+piece.h { + prev = prevPlainPiece(pi) + } + if prev != nil && prev.y == piece.y && prev.plainHi < piece.plainLo && y >= piece.y && y <= piece.y+piece.h { + start := prev.x + v.caretAdvance(prev, int(prev.plainHi-prev.plainLo)) end := piece.x + v.caretAdvance(piece, 0) if end > start && x >= start && x <= end { - gap := int(piece.plainLo - previous.plainHi) + gap := int(piece.plainLo - prev.plainHi) position := int(float32(gap)*(x-start)/(end-start) + 0.5) - return gfx.GraphemeStart(unsafe.String(unsafe.SliceData(v.plain), len(v.plain)), int(previous.plainHi)+min(max(position, 0), gap)), true + return gfx.GraphemeStart(unsafe.String(unsafe.SliceData(v.plain), len(v.plain)), int(prev.plainHi)+min(max(position, 0), gap)), true } } previous = piece @@ -238,90 +242,154 @@ func (v *MarkdownView) offsetAtIndexed(x, y float32) (int, bool) { dy = y - piece.y - piece.h } score := dy*1_000_000 + dx - if best < 0 || score < bestScore { + if best < 0 || score < bestScore || (score == bestScore && int(pi) < best) { best, bestScore = int(pi), score } } return 0, false } + spanDist := func(top, bottom float32) float32 { + if y < top { + return top - y + } + if y > bottom { + return y - bottom + } + return 0 + } + + spanCouldBeat := func(top, bottom float32) bool { + return best < 0 || spanDist(top, bottom)*1_000_000 <= bestScore + } + + // checkRowsNearY searches rows sorted by y around the pointer, widening + // within the slice before returning so empty rows (such as blank lines + // inside a code block) resolve against other rows of the same cell/block. checkRowsNearY := func(rows []mdRowSpan) (int, bool) { rn := len(rows) if rn == 0 { return 0, false } ri := sort.Search(rn, func(i int) bool { return rows[i].bottom >= y }) - rLo, rHi := ri, ri+1 - if ri >= rn { - rLo, rHi = rn-1, rn - } else if ri > 0 && y < rows[ri].y { - rLo = ri - 1 - } - for k := rLo; k < rHi; k++ { - if off, hit := checkRow(&rows[k]); hit { + up := ri - 1 + down := ri + if down < rn && y >= rows[down].y && y <= rows[down].bottom { + if off, hit := checkRow(&rows[down]); hit { return off, true } + down++ + } + for up >= 0 || down < rn { + upOK := up >= 0 && spanCouldBeat(rows[up].y, rows[up].bottom) + downOK := down < rn && spanCouldBeat(rows[down].y, rows[down].bottom) + if !upOK && !downOK { + break + } + if upOK && (!downOK || spanDist(rows[up].y, rows[up].bottom) <= spanDist(rows[down].y, rows[down].bottom)) { + if off, hit := checkRow(&rows[up]); hit { + return off, true + } + up-- + } else { + if off, hit := checkRow(&rows[down]); hit { + return off, true + } + down++ + } } return 0, false } - // Expand outward if the nearest block(s) had no selectable text (e.g. a Rule). - for expand := 0; expand < n; expand++ { - if expand > 0 { - foundAny := false - if loBlk > 0 { - loBlk-- - foundAny = true - } - if hiBlk < n { - hiBlk++ - foundAny = true - } - if !foundAny { - break + checkTableRow := func(tr *mdTableRowSpan) (int, bool) { + for ci := tr.cellLo; ci < tr.cellHi; ci++ { + cell := &v.cellSpans[ci] + if off, hit := checkRowsNearY(v.rowSpans[cell.rowLo:cell.rowHi]); hit { + return off, true } } - for idx := loBlk; idx < hiBlk; idx++ { - blk := &v.blockSpans[idx] - switch blk.kind { - case markdown.Table: - tRows := v.tableRows[blk.tableRowLo:blk.tableRowHi] - trn := len(tRows) - if trn == 0 { - continue + return 0, false + } + + checkBlock := func(blk *mdBlockSpan) (int, bool) { + switch blk.kind { + case markdown.Table: + tRows := v.tableRows[blk.tableRowLo:blk.tableRowHi] + trn := len(tRows) + if trn == 0 { + return 0, false + } + tri := sort.Search(trn, func(i int) bool { return tRows[i].bottom >= y }) + up := tri - 1 + down := tri + if down < trn && y >= tRows[down].y && y <= tRows[down].bottom { + if off, hit := checkTableRow(&tRows[down]); hit { + return off, true } - tri := sort.Search(trn, func(i int) bool { return tRows[i].bottom >= y }) - tLo, tHi := tri, tri+1 - if tri >= trn { - tLo, tHi = trn-1, trn - } else if tri > 0 && y < tRows[tri].y { - tLo = tri - 1 + down++ + } + for up >= 0 || down < trn { + upOK := up >= 0 && spanCouldBeat(tRows[up].y, tRows[up].bottom) + downOK := down < trn && spanCouldBeat(tRows[down].y, tRows[down].bottom) + if !upOK && !downOK { + break } - for k := tLo; k < tHi; k++ { - tr := &tRows[k] - for ci := tr.cellLo; ci < tr.cellHi; ci++ { - cell := &v.cellSpans[ci] - if off, hit := checkRowsNearY(v.rowSpans[cell.rowLo:cell.rowHi]); hit { - return off, true - } + if upOK && (!downOK || spanDist(tRows[up].y, tRows[up].bottom) <= spanDist(tRows[down].y, tRows[down].bottom)) { + if off, hit := checkTableRow(&tRows[up]); hit { + return off, true } - } - case markdown.Labeled: - for ci := blk.cellLo; ci < blk.cellHi; ci++ { - cell := &v.cellSpans[ci] - if off, hit := checkRowsNearY(v.rowSpans[cell.rowLo:cell.rowHi]); hit { + up-- + } else { + if off, hit := checkTableRow(&tRows[down]); hit { return off, true } + down++ } - default: - if off, hit := checkRowsNearY(v.rowSpans[blk.rowLo:blk.rowHi]); hit { + } + case markdown.Labeled: + for ci := blk.cellLo; ci < blk.cellHi; ci++ { + cell := &v.cellSpans[ci] + if off, hit := checkRowsNearY(v.rowSpans[cell.rowLo:cell.rowHi]); hit { return off, true } } + default: + if off, hit := checkRowsNearY(v.rowSpans[blk.rowLo:blk.rowHi]); hit { + return off, true + } + } + return 0, false + } + + // Search the block covering y first, then widen outward by increasing + // vertical distance while any neighbour block could still beat bestScore. + n := len(v.blockSpans) + bi := sort.Search(n, func(i int) bool { return v.blockSpans[i].bottom >= y }) + up := bi - 1 + down := bi + if down < n && y >= v.blockSpans[down].y && y <= v.blockSpans[down].bottom { + if off, hit := checkBlock(&v.blockSpans[down]); hit { + return off, true } - if best >= 0 { + down++ + } + for up >= 0 || down < n { + upOK := up >= 0 && spanCouldBeat(v.blockSpans[up].y, v.blockSpans[up].bottom) + downOK := down < n && spanCouldBeat(v.blockSpans[down].y, v.blockSpans[down].bottom) + if !upOK && !downOK { break } + if upOK && (!downOK || spanDist(v.blockSpans[up].y, v.blockSpans[up].bottom) <= spanDist(v.blockSpans[down].y, v.blockSpans[down].bottom)) { + if off, hit := checkBlock(&v.blockSpans[up]); hit { + return off, true + } + up-- + } else { + if off, hit := checkBlock(&v.blockSpans[down]); hit { + return off, true + } + down++ + } } if best < 0 { diff --git a/components/markdown_index_test.go b/components/markdown_index_test.go index 736b24417..b1fb94d10 100644 --- a/components/markdown_index_test.go +++ b/components/markdown_index_test.go @@ -2,12 +2,266 @@ package components import ( "fmt" + "strings" "testing" + "unsafe" + "github.com/vivaui/viva/base" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/markdown" ) +// linearOffsetAtReference mirrors the pre-index linear scan over v.pieces so +// tests can verify exact equivalence across dense grids of pointer positions. +func linearOffsetAtReference(v *MarkdownView, point gfx.Point) (int, bool) { + if !v.painted || v.measure == nil || len(v.pieces) == 0 { + return 0, false + } + x, y := point.X-v.paintX, point.Y-v.paintY + best, bestScore := -1, float32(0) + var previous *mdPiece + for index := range v.pieces { + piece := &v.pieces[index] + if piece.plainLo < 0 { + continue + } + if previous != nil && previous.y == piece.y && previous.plainHi < piece.plainLo && y >= piece.y && y <= piece.y+piece.h { + start := previous.x + v.caretAdvance(previous, int(previous.plainHi-previous.plainLo)) + end := piece.x + v.caretAdvance(piece, 0) + if end > start && x >= start && x <= end { + gap := int(piece.plainLo - previous.plainHi) + position := int(float32(gap)*(x-start)/(end-start) + 0.5) + return gfx.GraphemeStart(unsafe.String(unsafe.SliceData(v.plain), len(v.plain)), int(previous.plainHi)+min(max(position, 0), gap)), true + } + } + previous = piece + dx, dy := float32(0), float32(0) + if x < piece.x { + dx = piece.x - x + } else if x > piece.x+piece.w { + dx = x - piece.x - piece.w + } + if y < piece.y { + dy = piece.y - y + } else if y > piece.y+piece.h { + dy = y - piece.y - piece.h + } + score := dy*1_000_000 + dx + if best < 0 || score < bestScore { + best, bestScore = index, score + } + } + if best < 0 { + return 0, false + } + piece := &v.pieces[best] + localX := min(max(x-piece.x, 0), piece.w) + var local int + if piece.mono { + local = v.codeOffsetAt(piece, localX) + } else { + local = v.measure.TextOffsetAtStyle(piece.text, gfx.TextStyle{Size: piece.size, Weight: piece.weight, Italic: piece.italic}, localX) + } + local = min(max(local, 0), int(piece.plainHi-piece.plainLo)) + return int(piece.plainLo) + local, true +} + +// linearCaretAtReference mirrors the pre-index linear scan over v.pieces so +// tests can verify exact equivalence for every byte offset. +func linearCaretAtReference(v *MarkdownView, offset int) (gfx.Rect, bool) { + if !v.painted || v.measure == nil || len(v.pieces) == 0 { + return gfx.Rect{}, false + } + value := unsafe.String(unsafe.SliceData(v.plain), len(v.plain)) + offset = gfx.GraphemeStart(value, offset) + var chosen, before, after *mdPiece + for index := range v.pieces { + piece := &v.pieces[index] + if piece.plainLo < 0 { + continue + } + switch { + case offset >= int(piece.plainLo) && offset <= int(piece.plainHi): + if chosen == nil || piece.plainLo == int32(offset) && chosen.plainLo < int32(offset) { + chosen = piece + } + case int(piece.plainHi) < offset: + if before == nil || piece.plainHi > before.plainHi { + before = piece + } + case int(piece.plainLo) > offset: + if after == nil || piece.plainLo < after.plainLo { + after = piece + } + } + } + if chosen == nil { + if before != nil && after != nil && before.y == after.y { + start := before.x + v.caretAdvance(before, int(before.plainHi-before.plainLo)) + end := after.x + v.caretAdvance(after, 0) + fraction := float32(offset-int(before.plainHi)) / float32(after.plainLo-before.plainHi) + return gfx.Rect{X: v.paintX + start + (end-start)*fraction, Y: v.paintY + before.y, Width: 1, Height: before.h}, true + } + if before == nil && after == nil { + return gfx.Rect{}, false + } + if before == nil || after != nil && int(after.plainLo)-offset <= offset-int(before.plainHi) { + chosen = after + offset = int(after.plainLo) + } else { + chosen = before + offset = int(before.plainHi) + } + } + local := min(max(offset-int(chosen.plainLo), 0), int(chosen.plainHi-chosen.plainLo)) + advance := v.caretAdvance(chosen, local) + return gfx.Rect{X: v.paintX + chosen.x + advance, Y: v.paintY + chosen.y, Width: 1, Height: chosen.h}, true +} + +func TestMarkdownIndexMatchesLinearReferenceOnGrid(t *testing.T) { + // Parse-built document combining blank lines inside code blocks, horizontal + // rules, tables (including empty and wrapped cells), nested quotes, lists, + // links, inline code, and multi-byte UTF-8. + parsedSrc := strings.Join([]string{ + "# Overview", + "", + "before text with [link](https://example.com) and `code` δΈ­ζ–‡", + "", + "```go", + "firstLine := 1", + "", + "", + "", + "lastLine := 2", + "```", + "", + "after text", + "", + "---", + "", + "```", + "", + "", + "", + "onlyTrailing()", + "```", + "", + "> outer quote line one", + ">> nested quote line two", + "", + "| Col A | Col B | Col C |", + "| --- | :---: | ---: |", + "| alpha | | gamma wrapped across multiple words in a narrow column |", + "| | | |", + "| delta | epsilon | zeta |", + "", + "1. First item", + "2. Second item with **bold** and *italic*", + }, "\n") + + var parsedDoc markdown.Document + parsedDoc.Parse(parsedSrc) + + // Programmatic document with Labeled blocks and mixed block kinds. + var labeledDoc markdown.Document + labeledDoc.Reset() + labeledDoc.AppendParagraph(0, 0, []markdown.Span{{Text: "Lead paragraph before labeled rows."}}) + labeledDoc.AppendCode(0, "java", "a();\n\n\n\nb();") + labeledDoc.AppendRule(0) + labeledDoc.AppendLabeled(0, []markdown.Span{{Text: "Since:"}}, []markdown.Span{{Text: "1.2"}}) + labeledDoc.AppendLabeled(0, []markdown.Span{{Text: "See also:"}}, []markdown.Span{ + {Text: "Collection", Style: markdown.Mono, Link: "symbol:Collection"}, + {Text: ", "}, + {Text: "List", Style: markdown.Mono, Link: "symbol:List"}, + }) + labeledDoc.AppendLabeled(0, []markdown.Span{{Text: "Type parameters:"}}, []markdown.Span{ + {Text: "", Style: markdown.Mono}, + {Text: " – the type of elements in this list wrapped onto another line"}, + }) + + cases := []struct { + name string + doc *markdown.Document + width float32 + }{ + {name: "parsed-full-features", doc: &parsedDoc, width: 320}, + {name: "programmatic-labeled", doc: &labeledDoc, width: 300}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + canvas := markdownCanvas() + var view MarkdownView + h := view.Layout(canvas, MarkdownStyle{Size: 13, LineHeight: 20}, tc.doc, tc.width) + if h <= 0 { + t.Fatalf("expected positive height, got %v", h) + } + const originX, originY float32 = 16, 24 + canvas.Reset() + view.Paint(canvas, MarkdownPaint{ + Look: MarkdownLookFor(gfx.Theme{}), + X: originX, + Y: originY, + }) + + // Verify OffsetAt on a dense grid covering margins, gaps, blank code + // lines, rules, table cell gaps, and boundaries. + for y := float32(-10); y <= h+20; y += 5 { + for x := float32(-10); x <= tc.width+20; x += 17 { + pt := gfx.Point{X: originX + x, Y: originY + y} + gotOff, gotOK := view.OffsetAt(pt) + wantOff, wantOK := linearOffsetAtReference(&view, pt) + if gotOff != wantOff || gotOK != wantOK { + t.Fatalf("OffsetAt(%v) = (%d, %v), want linear (%d, %v)", pt, gotOff, gotOK, wantOff, wantOK) + } + } + } + + // Verify CaretAt for every byte offset in [0, TextLen]. + n := view.TextLen() + for off := 0; off <= n; off++ { + gotRect, gotOK := view.CaretAt(off) + wantRect, wantOK := linearCaretAtReference(&view, off) + if gotRect != wantRect || gotOK != wantOK { + t.Fatalf("CaretAt(%d) = (%+v, %v), want linear (%+v, %v)", off, gotRect, gotOK, wantRect, wantOK) + } + } + }) + } +} + +func TestMarkdownEmptyCodeLinesStayInCodeBlock(t *testing.T) { + // Direct regression for blank lines inside a code block: clicking an empty + // line between code lines must resolve to the code block, not before/after text. + src := "before text\n\n```\nline1\n\n\n\nline5\n```\n\nafter text\n" + var doc markdown.Document + doc.Parse(src) + + canvas := markdownCanvas() + var view MarkdownView + h := view.Layout(canvas, MarkdownStyle{Size: 13, LineHeight: 20}, &doc, 400) + canvas.Reset() + view.Paint(canvas, MarkdownPaint{Look: MarkdownLookFor(gfx.Theme{})}) + + plain := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}) + codeLo := strings.Index(plain, "line1") + codeHi := strings.Index(plain, "line5") + len("line5") + if codeLo < 0 || codeHi <= codeLo { + t.Fatalf("expected code block text in plain %q", plain) + } + r1, ok1 := view.CaretAt(codeLo) + r5, ok5 := view.CaretAt(codeHi) + if !ok1 || !ok5 || r5.Y <= r1.Y+r1.Height { + t.Fatalf("expected empty lines between line1 (%+v) and line5 (%+v), height=%v", r1, r5, h) + } + for y := r1.Y + r1.Height + 2; y < r5.Y; y += 6 { + off, ok := view.OffsetAt(gfx.Point{X: 40, Y: y}) + if !ok || off < codeLo || off > codeHi { + t.Fatalf("empty code line at y=%v resolved to offset %d (plain=%q), want inside [%d,%d]", y, off, plain, codeLo, codeHi) + } + } +} + func TestMarkdownBuilderLabeledAndOpaqueLinks(t *testing.T) { var doc markdown.Document doc.Reset() @@ -28,6 +282,7 @@ func TestMarkdownBuilderLabeledAndOpaqueLinks(t *testing.T) { {Text: "", Style: markdown.Mono}, {Text: " – the type of elements"}, }) + doc.AppendLabeled(0, []markdown.Span{{Text: "Author:"}}, []markdown.Span{{Text: "Josh"}}) canvas := markdownCanvas() var view MarkdownView @@ -44,28 +299,35 @@ func TestMarkdownBuilderLabeledAndOpaqueLinks(t *testing.T) { if view.AllocatedBytes() <= 0 || doc.AllocatedBytes() <= 0 { t.Fatalf("expected positive AllocatedBytes: view=%d doc=%d", view.AllocatedBytes(), doc.AllocatedBytes()) } - // Verify aligned Labeled value columns start at the same X. - var labelEndX, valStartX []float32 - for _, blk := range view.blockSpans { - if blk.kind != markdown.Labeled { - continue + + // Verify aligned Labeled value columns start at the same X using public CaretAt + // (comparing plain-text rows with each other and inline-code rows with each other, + // since inline code pills include their internal horizontal padding). + canvas.Reset() + view.Paint(canvas, MarkdownPaint{Look: MarkdownLookFor(gfx.Theme{})}) + plain := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}) + caretX := func(needle string) float32 { + t.Helper() + off := strings.Index(plain, needle) + if off < 0 { + t.Fatalf("missing %q in rendered text %q", needle, plain) } - lCell := view.cellSpans[blk.cellLo] - vCell := view.cellSpans[blk.cellLo+1] - if lCell.rowLo < lCell.rowHi && vCell.rowLo < vCell.rowHi { - lp := view.pieces[view.rowSpans[lCell.rowLo].pieceLo] - vp := view.pieces[view.rowSpans[vCell.rowLo].pieceLo] - labelEndX = append(labelEndX, lp.x+lp.w) - valStartX = append(valStartX, vp.x) + rect, ok := view.CaretAt(off) + if !ok { + t.Fatalf("CaretAt(%q=%d) returned ok=false", needle, off) } + return rect.X } - if len(valStartX) != 3 { - t.Fatalf("expected 3 labeled rows, got %d", len(valStartX)) + plainA, plainB := caretX("1.2"), caretX("Josh") + monoA, monoB := caretX("Collection"), caretX("") + if plainA != plainB { + t.Fatalf("labeled plain value column misaligned: %v vs %v", plainA, plainB) } - for i := 1; i < len(valStartX); i++ { - if valStartX[i] != valStartX[0] { - t.Fatalf("labeled value column misaligned: %v (labels end at %v)", valStartX, labelEndX) - } + if monoA != monoB { + t.Fatalf("labeled mono value column misaligned: %v vs %v", monoA, monoB) + } + if monoA < plainA { + t.Fatalf("expected inline-code value X (%v) >= plain value X (%v)", monoA, plainA) } }