Implement click-to-move cursor in the editor

This commit is contained in:
gmp
2026-06-03 22:04:16 -04:00
parent 62d1f827e0
commit bab239a38a
5 changed files with 113 additions and 23 deletions
+30 -17
View File
@@ -431,6 +431,15 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
[]ui.Interaction{
{Gesture: ui.Scroll, Handler: HandleScroll},
{Gesture: ui.KeyDown, Handler: HandleKeyDown},
{Gesture: ui.Tap, Handler: func(data any) {
if pt, ok := data.(ui.Point); ok {
// Convert window-space tap coordinates to text-local coordinates.
// layout.X is relative to the text region left, and layout.Y is relative to the text region top.
localX := float64(pt.X - editorRegion.X)
localY := float64(pt.Y - editorRegion.Y + TheState.ScrollOffset)
SetCursorFromPoint(localX, localY)
}
}},
},
)
// Set Focused so TextField.Draw() issues key.FocusCmd, which is required
@@ -440,24 +449,28 @@ func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
return []ui.Element{statusBar, editorElem, bottomBar}
}
// byteOffsetToLineCol converts a byte offset in the buffer to (line, column).
// Both line and column are 0-indexed.
func byteOffsetToLineCol(buf string, offset int) (int, int) {
if offset < 0 {
return 0, 0
// SetCursorFromPoint updates the cursor position based on screen coordinates (Dp).
func SetCursorFromPoint(x, y float64) {
layout := TheState.Editor.GlyphLayout
if len(layout.ByteOffsets) == 0 {
return
}
if offset > len(buf) {
offset = len(buf)
}
line := 0
col := 0
for i := 0; i < offset; i++ {
if buf[i] == '\n' {
line++
col = 0
} else {
col++
// Simple heuristic: find the closest glyph by distance to (x, y)
bestIdx := 0
minDist := float64(1e9)
lineHeight := float64(EditorLineHeight())
for i := 0; i < len(layout.X); i++ {
dx := float64(layout.X[i]) - x
// layout.Y[i] is the baseline. Taps are generally near the middle of the line.
// Adjust to compare against the approximate vertical center of the line.
dy := float64(layout.Y[i] - ui.Dp(lineHeight/2)) - y
dist := dx*dx + dy*dy
if dist < minDist {
minDist = dist
bestIdx = i
}
}
return line, col
TheState.Editor.CursorPosition = layout.ByteOffsets[bestIdx]
}