♻️ Quality: internal/tui without smells (17 → 0)
- markdown: block layout as mdLayout steps, inline readers per marker, emphasis open/close/attr, wrapSpans cells, table grid/widths/rows; split into markdown_inline.go, markdown_wrap.go, markdown_table.go - initwin: windowKeys table, choiceKey/yesNoKey, drawQuestion as drawReady/drawField/drawOptions; split keys, field and drawing files - events: keyHandlers table; render: statusMarks map - question: formNumberKey/formListEnter, ticked and typeKey shared; runner side and drawing in their own files - draw, picker, turn split by theme (input, picker drawing, choices, compaction, permissions) Checked: Markdown rendering byte-identical on 18 texts x 5 widths and the init window screen-identical over 37 keys at 3 sizes (temporary golden tests, old vs new); live window against LFM3-1.7B: Markdown answer, ask_user choice/other/decline, / picker. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dddb66d parent: ff391e0 modified
internal/tui/draw.go +0 -111 | @@ -2,9 +2,6 @@ package tui | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "fmt" |
| 5 | - "strings" | |
| 6 | - | |
| 7 | - "github.com/gdamore/tcell/v2" | |
| 8 | 5 | ) |
| 9 | 6 | |
| 10 | 7 | // draw paints one frame: header, conversation, rule, input box (or the |
| @@ -112,71 +109,6 @@ func (v *View) ruleLabel() string { | ||
| 112 | 109 | } |
| 113 | 110 | } |
| 114 | 111 | |
| 115 | -// drawInput paints what has been typed, word-wrapped to the box's width | |
| 116 | -// (inputwrap.go), and the cursor. The box shows as many rows as it has and | |
| 117 | -// scrolls so the cursor's row is always one of them. A paste token is one | |
| 118 | -// rune in the input but a whole label on the screen, so rows are drawn rune | |
| 119 | -// by rune and the cursor column is measured the same way. | |
| 120 | -func (v *View) drawInput(p painter) { | |
| 121 | - height := p.height() | |
| 122 | - if height < 1 { | |
| 123 | - return | |
| 124 | - } | |
| 125 | - p.text(0, 0, ">", stPrompt) | |
| 126 | - width := max(p.width()-2, 1) | |
| 127 | - rows := v.inputRows(width) | |
| 128 | - cur, cx := v.cursorRow(rows) | |
| 129 | - top := max(cur-height+1, 0) | |
| 130 | - for row := 0; row < height; row++ { | |
| 131 | - at := top + row | |
| 132 | - if at >= len(rows) { | |
| 133 | - break | |
| 134 | - } | |
| 135 | - v.drawInputRow(p, row, rows[at]) | |
| 136 | - } | |
| 137 | - if v.onInput { | |
| 138 | - p.showCursor(2+min(cx, width-1), cur-top) | |
| 139 | - } else { | |
| 140 | - v.screen.HideCursor() | |
| 141 | - } | |
| 142 | -} | |
| 143 | - | |
| 144 | -// drawInputRow paints one row of the box from column 2: plain runes as | |
| 145 | -// they are, paste tokens as their label in the token style, clipped with an | |
| 146 | -// ellipsis at the right edge (a label wider than the row). | |
| 147 | -func (v *View) drawInputRow(p painter, row int, r inputRow) { | |
| 148 | - line := string([]rune(v.input[r.line])[r.from:r.to]) | |
| 149 | - x, limit := 2, p.width() | |
| 150 | - put := func(text string, style tcell.Style) { | |
| 151 | - for _, r := range text { | |
| 152 | - if x >= limit { | |
| 153 | - return | |
| 154 | - } | |
| 155 | - if x == limit-1 && len(text) > 1 { | |
| 156 | - p.set(x, row, '…', style) | |
| 157 | - x++ | |
| 158 | - return | |
| 159 | - } | |
| 160 | - p.set(x, row, r, style) | |
| 161 | - x++ | |
| 162 | - } | |
| 163 | - } | |
| 164 | - for _, r := range line { | |
| 165 | - if label, ok := v.pastes.labelOf(r); ok { | |
| 166 | - put(label, stPaste) | |
| 167 | - continue | |
| 168 | - } | |
| 169 | - put(string(r), stBody) | |
| 170 | - } | |
| 171 | -} | |
| 172 | - | |
| 173 | -// drawPermission replaces the box with the question a tool is waiting on. | |
| 174 | -func (v *View) drawPermission(p painter) { | |
| 175 | - v.screen.HideCursor() | |
| 176 | - p.textLimited(0, 0, p.width(), "? "+v.ask.title, stAsk) | |
| 177 | - p.textLimited(2, 1, max(p.width()-2, 0), "[a] allow once [s] allow "+v.ask.tool+" for this session [r] reject [n] never "+v.ask.tool, stBody) | |
| 178 | -} | |
| 179 | - | |
| 180 | 112 | // drawStatus is the bottom bar: key hints left, version and counters right |
| 181 | 113 | // — or, while the model struggles, the struggle badge in its colours in |
| 182 | 114 | // front of the counters. |
| @@ -213,49 +145,6 @@ func (v *View) rightBar(leftWidth, width int) string { | ||
| 213 | 145 | return v.status |
| 214 | 146 | } |
| 215 | 147 | |
| 216 | -// drawPicker paints the popup over the bottom of the conversation: one row | |
| 217 | -// per choice, the highlighted one in reverse, scrolled so that it is shown. | |
| 218 | -func (v *View) drawPicker(p painter) { | |
| 219 | - cs := v.choices() | |
| 220 | - if len(cs) == 0 { | |
| 221 | - return | |
| 222 | - } | |
| 223 | - rows := min(len(cs), pickerRows, p.height()) | |
| 224 | - top := p.height() - rows | |
| 225 | - // The label column is as wide as the widest label, so the details line | |
| 226 | - // up whichever trigger is open — commands, paths and skills all differ. | |
| 227 | - labels := 0 | |
| 228 | - width := 0 | |
| 229 | - for _, c := range cs { | |
| 230 | - labels = max(labels, len([]rune(c.label))) | |
| 231 | - } | |
| 232 | - labels = min(labels, p.width()/2) | |
| 233 | - for _, c := range cs { | |
| 234 | - width = max(width, labels+2+len([]rune(c.detail))) | |
| 235 | - } | |
| 236 | - width = min(width+4, p.width()) | |
| 237 | - first := pickerFirst(len(cs), rows, v.pick.selected) | |
| 238 | - for i := 0; i < rows; i++ { | |
| 239 | - c := cs[first+i] | |
| 240 | - style := stBody | |
| 241 | - if first+i == v.pick.selected { | |
| 242 | - style = stPick | |
| 243 | - } | |
| 244 | - text := " " + c.label + strings.Repeat(" ", max(labels-len([]rune(c.label))+2, 1)) + c.detail | |
| 245 | - p.hline(0, top+i, width, ' ', style) | |
| 246 | - p.textLimited(0, top+i, width, text, style) | |
| 247 | - } | |
| 248 | -} | |
| 249 | - | |
| 250 | -// pickerFirst is the first choice shown when only rows of n fit: 0 until the | |
| 251 | -// selection goes past the last row, then the window follows it — without | |
| 252 | -// it, the arrows selected choices nobody could see (/unload, the tenth | |
| 253 | -// command, was never shown). | |
| 254 | -func pickerFirst(n, rows, selected int) int { | |
| 255 | - selected = min(selected, n-1) | |
| 256 | - return max(0, selected-rows+1) | |
| 257 | -} | |
| 258 | - | |
| 259 | 148 | // drawSpans draws a rendered line run by run, each in its style, cut at |
| 260 | 149 | // width with an ellipsis as textLimited does. |
| 261 | 150 | func drawSpans(p painter, x, y, width int, spans []Span) { |
| @@ -2,9 +2,6 @@ package tui | |||
| 2 | 2 | ||
| 3 | import ( | 3 | import ( |
| 4 | "fmt" | 4 | "fmt" |
| 5 | - "strings" | ||
| 6 | - | ||
| 7 | - "github.com/gdamore/tcell/v2" | ||
| 8 | ) | 5 | ) |
| 9 | 6 | ||
| 10 | // draw paints one frame: header, conversation, rule, input box (or the | 7 | // draw paints one frame: header, conversation, rule, input box (or the |
| @@ -112,71 +109,6 @@ func (v *View) ruleLabel() string { | |||
| 112 | } | 109 | } |
| 113 | } | 110 | } |
| 114 | 111 | ||
| 115 | -// drawInput paints what has been typed, word-wrapped to the box's width | ||
| 116 | -// (inputwrap.go), and the cursor. The box shows as many rows as it has and | ||
| 117 | -// scrolls so the cursor's row is always one of them. A paste token is one | ||
| 118 | -// rune in the input but a whole label on the screen, so rows are drawn rune | ||
| 119 | -// by rune and the cursor column is measured the same way. | ||
| 120 | -func (v *View) drawInput(p painter) { | ||
| 121 | - height := p.height() | ||
| 122 | - if height < 1 { | ||
| 123 | - return | ||
| 124 | - } | ||
| 125 | - p.text(0, 0, ">", stPrompt) | ||
| 126 | - width := max(p.width()-2, 1) | ||
| 127 | - rows := v.inputRows(width) | ||
| 128 | - cur, cx := v.cursorRow(rows) | ||
| 129 | - top := max(cur-height+1, 0) | ||
| 130 | - for row := 0; row < height; row++ { | ||
| 131 | - at := top + row | ||
| 132 | - if at >= len(rows) { | ||
| 133 | - break | ||
| 134 | - } | ||
| 135 | - v.drawInputRow(p, row, rows[at]) | ||
| 136 | - } | ||
| 137 | - if v.onInput { | ||
| 138 | - p.showCursor(2+min(cx, width-1), cur-top) | ||
| 139 | - } else { | ||
| 140 | - v.screen.HideCursor() | ||
| 141 | - } | ||
| 142 | -} | ||
| 143 | - | ||
| 144 | -// drawInputRow paints one row of the box from column 2: plain runes as | ||
| 145 | -// they are, paste tokens as their label in the token style, clipped with an | ||
| 146 | -// ellipsis at the right edge (a label wider than the row). | ||
| 147 | -func (v *View) drawInputRow(p painter, row int, r inputRow) { | ||
| 148 | - line := string([]rune(v.input[r.line])[r.from:r.to]) | ||
| 149 | - x, limit := 2, p.width() | ||
| 150 | - put := func(text string, style tcell.Style) { | ||
| 151 | - for _, r := range text { | ||
| 152 | - if x >= limit { | ||
| 153 | - return | ||
| 154 | - } | ||
| 155 | - if x == limit-1 && len(text) > 1 { | ||
| 156 | - p.set(x, row, '…', style) | ||
| 157 | - x++ | ||
| 158 | - return | ||
| 159 | - } | ||
| 160 | - p.set(x, row, r, style) | ||
| 161 | - x++ | ||
| 162 | - } | ||
| 163 | - } | ||
| 164 | - for _, r := range line { | ||
| 165 | - if label, ok := v.pastes.labelOf(r); ok { | ||
| 166 | - put(label, stPaste) | ||
| 167 | - continue | ||
| 168 | - } | ||
| 169 | - put(string(r), stBody) | ||
| 170 | - } | ||
| 171 | -} | ||
| 172 | - | ||
| 173 | -// drawPermission replaces the box with the question a tool is waiting on. | ||
| 174 | -func (v *View) drawPermission(p painter) { | ||
| 175 | - v.screen.HideCursor() | ||
| 176 | - p.textLimited(0, 0, p.width(), "? "+v.ask.title, stAsk) | ||
| 177 | - p.textLimited(2, 1, max(p.width()-2, 0), "[a] allow once [s] allow "+v.ask.tool+" for this session [r] reject [n] never "+v.ask.tool, stBody) | ||
| 178 | -} | ||
| 179 | - | ||
| 180 | // drawStatus is the bottom bar: key hints left, version and counters right | 112 | // drawStatus is the bottom bar: key hints left, version and counters right |
| 181 | // — or, while the model struggles, the struggle badge in its colours in | 113 | // — or, while the model struggles, the struggle badge in its colours in |
| 182 | // front of the counters. | 114 | // front of the counters. |
| @@ -213,49 +145,6 @@ func (v *View) rightBar(leftWidth, width int) string { | |||
| 213 | return v.status | 145 | return v.status |
| 214 | } | 146 | } |
| 215 | 147 | ||
| 216 | -// drawPicker paints the popup over the bottom of the conversation: one row | ||
| 217 | -// per choice, the highlighted one in reverse, scrolled so that it is shown. | ||
| 218 | -func (v *View) drawPicker(p painter) { | ||
| 219 | - cs := v.choices() | ||
| 220 | - if len(cs) == 0 { | ||
| 221 | - return | ||
| 222 | - } | ||
| 223 | - rows := min(len(cs), pickerRows, p.height()) | ||
| 224 | - top := p.height() - rows | ||
| 225 | - // The label column is as wide as the widest label, so the details line | ||
| 226 | - // up whichever trigger is open — commands, paths and skills all differ. | ||
| 227 | - labels := 0 | ||
| 228 | - width := 0 | ||
| 229 | - for _, c := range cs { | ||
| 230 | - labels = max(labels, len([]rune(c.label))) | ||
| 231 | - } | ||
| 232 | - labels = min(labels, p.width()/2) | ||
| 233 | - for _, c := range cs { | ||
| 234 | - width = max(width, labels+2+len([]rune(c.detail))) | ||
| 235 | - } | ||
| 236 | - width = min(width+4, p.width()) | ||
| 237 | - first := pickerFirst(len(cs), rows, v.pick.selected) | ||
| 238 | - for i := 0; i < rows; i++ { | ||
| 239 | - c := cs[first+i] | ||
| 240 | - style := stBody | ||
| 241 | - if first+i == v.pick.selected { | ||
| 242 | - style = stPick | ||
| 243 | - } | ||
| 244 | - text := " " + c.label + strings.Repeat(" ", max(labels-len([]rune(c.label))+2, 1)) + c.detail | ||
| 245 | - p.hline(0, top+i, width, ' ', style) | ||
| 246 | - p.textLimited(0, top+i, width, text, style) | ||
| 247 | - } | ||
| 248 | -} | ||
| 249 | - | ||
| 250 | -// pickerFirst is the first choice shown when only rows of n fit: 0 until the | ||
| 251 | -// selection goes past the last row, then the window follows it — without | ||
| 252 | -// it, the arrows selected choices nobody could see (/unload, the tenth | ||
| 253 | -// command, was never shown). | ||
| 254 | -func pickerFirst(n, rows, selected int) int { | ||
| 255 | - selected = min(selected, n-1) | ||
| 256 | - return max(0, selected-rows+1) | ||
| 257 | -} | ||
| 258 | - | ||
| 259 | // drawSpans draws a rendered line run by run, each in its style, cut at | 148 | // drawSpans draws a rendered line run by run, each in its style, cut at |
| 260 | // width with an ellipsis as textLimited does. | 149 | // width with an ellipsis as textLimited does. |
| 261 | func drawSpans(p painter, x, y, width int, spans []Span) { | 150 | func drawSpans(p painter, x, y, width int, spans []Span) { |
added
internal/tui/draw_input.go +68 -0 | new file mode 100644 | ||
| @@ -0,0 +1,68 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import "github.com/gdamore/tcell/v2" | |
| 4 | + | |
| 5 | +// drawInput paints what has been typed, word-wrapped to the box's width | |
| 6 | +// (inputwrap.go), and the cursor. The box shows as many rows as it has and | |
| 7 | +// scrolls so the cursor's row is always one of them. A paste token is one | |
| 8 | +// rune in the input but a whole label on the screen, so rows are drawn rune | |
| 9 | +// by rune and the cursor column is measured the same way. | |
| 10 | +func (v *View) drawInput(p painter) { | |
| 11 | + height := p.height() | |
| 12 | + if height < 1 { | |
| 13 | + return | |
| 14 | + } | |
| 15 | + p.text(0, 0, ">", stPrompt) | |
| 16 | + width := max(p.width()-2, 1) | |
| 17 | + rows := v.inputRows(width) | |
| 18 | + cur, cx := v.cursorRow(rows) | |
| 19 | + top := max(cur-height+1, 0) | |
| 20 | + for row := 0; row < height; row++ { | |
| 21 | + at := top + row | |
| 22 | + if at >= len(rows) { | |
| 23 | + break | |
| 24 | + } | |
| 25 | + v.drawInputRow(p, row, rows[at]) | |
| 26 | + } | |
| 27 | + if v.onInput { | |
| 28 | + p.showCursor(2+min(cx, width-1), cur-top) | |
| 29 | + } else { | |
| 30 | + v.screen.HideCursor() | |
| 31 | + } | |
| 32 | +} | |
| 33 | + | |
| 34 | +// drawInputRow paints one row of the box from column 2: plain runes as | |
| 35 | +// they are, paste tokens as their label in the token style, clipped with an | |
| 36 | +// ellipsis at the right edge (a label wider than the row). | |
| 37 | +func (v *View) drawInputRow(p painter, row int, r inputRow) { | |
| 38 | + line := string([]rune(v.input[r.line])[r.from:r.to]) | |
| 39 | + x, limit := 2, p.width() | |
| 40 | + put := func(text string, style tcell.Style) { | |
| 41 | + for _, r := range text { | |
| 42 | + if x >= limit { | |
| 43 | + return | |
| 44 | + } | |
| 45 | + if x == limit-1 && len(text) > 1 { | |
| 46 | + p.set(x, row, '…', style) | |
| 47 | + x++ | |
| 48 | + return | |
| 49 | + } | |
| 50 | + p.set(x, row, r, style) | |
| 51 | + x++ | |
| 52 | + } | |
| 53 | + } | |
| 54 | + for _, r := range line { | |
| 55 | + if label, ok := v.pastes.labelOf(r); ok { | |
| 56 | + put(label, stPaste) | |
| 57 | + continue | |
| 58 | + } | |
| 59 | + put(string(r), stBody) | |
| 60 | + } | |
| 61 | +} | |
| 62 | + | |
| 63 | +// drawPermission replaces the box with the question a tool is waiting on. | |
| 64 | +func (v *View) drawPermission(p painter) { | |
| 65 | + v.screen.HideCursor() | |
| 66 | + p.textLimited(0, 0, p.width(), "? "+v.ask.title, stAsk) | |
| 67 | + p.textLimited(2, 1, max(p.width()-2, 0), "[a] allow once [s] allow "+v.ask.tool+" for this session [r] reject [n] never "+v.ask.tool, stBody) | |
| 68 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,68 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import "github.com/gdamore/tcell/v2" | ||
| 4 | + | ||
| 5 | +// drawInput paints what has been typed, word-wrapped to the box's width | ||
| 6 | +// (inputwrap.go), and the cursor. The box shows as many rows as it has and | ||
| 7 | +// scrolls so the cursor's row is always one of them. A paste token is one | ||
| 8 | +// rune in the input but a whole label on the screen, so rows are drawn rune | ||
| 9 | +// by rune and the cursor column is measured the same way. | ||
| 10 | +func (v *View) drawInput(p painter) { | ||
| 11 | + height := p.height() | ||
| 12 | + if height < 1 { | ||
| 13 | + return | ||
| 14 | + } | ||
| 15 | + p.text(0, 0, ">", stPrompt) | ||
| 16 | + width := max(p.width()-2, 1) | ||
| 17 | + rows := v.inputRows(width) | ||
| 18 | + cur, cx := v.cursorRow(rows) | ||
| 19 | + top := max(cur-height+1, 0) | ||
| 20 | + for row := 0; row < height; row++ { | ||
| 21 | + at := top + row | ||
| 22 | + if at >= len(rows) { | ||
| 23 | + break | ||
| 24 | + } | ||
| 25 | + v.drawInputRow(p, row, rows[at]) | ||
| 26 | + } | ||
| 27 | + if v.onInput { | ||
| 28 | + p.showCursor(2+min(cx, width-1), cur-top) | ||
| 29 | + } else { | ||
| 30 | + v.screen.HideCursor() | ||
| 31 | + } | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +// drawInputRow paints one row of the box from column 2: plain runes as | ||
| 35 | +// they are, paste tokens as their label in the token style, clipped with an | ||
| 36 | +// ellipsis at the right edge (a label wider than the row). | ||
| 37 | +func (v *View) drawInputRow(p painter, row int, r inputRow) { | ||
| 38 | + line := string([]rune(v.input[r.line])[r.from:r.to]) | ||
| 39 | + x, limit := 2, p.width() | ||
| 40 | + put := func(text string, style tcell.Style) { | ||
| 41 | + for _, r := range text { | ||
| 42 | + if x >= limit { | ||
| 43 | + return | ||
| 44 | + } | ||
| 45 | + if x == limit-1 && len(text) > 1 { | ||
| 46 | + p.set(x, row, '…', style) | ||
| 47 | + x++ | ||
| 48 | + return | ||
| 49 | + } | ||
| 50 | + p.set(x, row, r, style) | ||
| 51 | + x++ | ||
| 52 | + } | ||
| 53 | + } | ||
| 54 | + for _, r := range line { | ||
| 55 | + if label, ok := v.pastes.labelOf(r); ok { | ||
| 56 | + put(label, stPaste) | ||
| 57 | + continue | ||
| 58 | + } | ||
| 59 | + put(string(r), stBody) | ||
| 60 | + } | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +// drawPermission replaces the box with the question a tool is waiting on. | ||
| 64 | +func (v *View) drawPermission(p painter) { | ||
| 65 | + v.screen.HideCursor() | ||
| 66 | + p.textLimited(0, 0, p.width(), "? "+v.ask.title, stAsk) | ||
| 67 | + p.textLimited(2, 1, max(p.width()-2, 0), "[a] allow once [s] allow "+v.ask.tool+" for this session [r] reject [n] never "+v.ask.tool, stBody) | ||
| 68 | +} | ||
modified
internal/tui/events.go +45 -18 | @@ -32,28 +32,55 @@ func (v *View) handleKey(ev *tcell.EventKey) { | ||
| 32 | 32 | } |
| 33 | 33 | }() |
| 34 | 34 | |
| 35 | - if v.pasting { | |
| 36 | - v.bufferPasteKey(ev) | |
| 37 | - return | |
| 38 | - } | |
| 39 | - if v.ask != nil { | |
| 40 | - v.answerPermission(ev) | |
| 41 | - return | |
| 42 | - } | |
| 43 | - if v.form != nil { | |
| 44 | - v.handleFormKey(ev) | |
| 45 | - return | |
| 35 | + for _, handle := range keyHandlers { | |
| 36 | + if handle(v, ev) { | |
| 37 | + return | |
| 38 | + } | |
| 46 | 39 | } |
| 47 | - if v.handlePickerKey(ev) { | |
| 48 | - return | |
| 40 | + v.handleScrollKey(ev) | |
| 41 | +} | |
| 42 | + | |
| 43 | +// keyHandlers take a key in this order; the first that takes it ends the | |
| 44 | +// search, and a key none takes scrolls the transcript. | |
| 45 | +var keyHandlers = []func(*View, *tcell.EventKey) bool{ | |
| 46 | + (*View).pasteKey, | |
| 47 | + (*View).permissionKey, | |
| 48 | + (*View).formKey, | |
| 49 | + (*View).handlePickerKey, | |
| 50 | + (*View).handleWindowKey, | |
| 51 | + (*View).inputKey, | |
| 52 | +} | |
| 53 | + | |
| 54 | +// pasteKey buffers every key while a paste is coming in. | |
| 55 | +func (v *View) pasteKey(ev *tcell.EventKey) bool { | |
| 56 | + if !v.pasting { | |
| 57 | + return false | |
| 49 | 58 | } |
| 50 | - if v.handleWindowKey(ev) { | |
| 51 | - return | |
| 59 | + v.bufferPasteKey(ev) | |
| 60 | + return true | |
| 61 | +} | |
| 62 | + | |
| 63 | +// permissionKey gives every key to a pending permission. | |
| 64 | +func (v *View) permissionKey(ev *tcell.EventKey) bool { | |
| 65 | + if v.ask == nil { | |
| 66 | + return false | |
| 52 | 67 | } |
| 53 | - if v.onInput && v.handleInputKey(ev) { | |
| 54 | - return | |
| 68 | + v.answerPermission(ev) | |
| 69 | + return true | |
| 70 | +} | |
| 71 | + | |
| 72 | +// formKey gives every key to an open form. | |
| 73 | +func (v *View) formKey(ev *tcell.EventKey) bool { | |
| 74 | + if v.form == nil { | |
| 75 | + return false | |
| 55 | 76 | } |
| 56 | - v.handleScrollKey(ev) | |
| 77 | + v.handleFormKey(ev) | |
| 78 | + return true | |
| 79 | +} | |
| 80 | + | |
| 81 | +// inputKey gives a key to the input box when it has the focus. | |
| 82 | +func (v *View) inputKey(ev *tcell.EventKey) bool { | |
| 83 | + return v.onInput && v.handleInputKey(ev) | |
| 57 | 84 | } |
| 58 | 85 | |
| 59 | 86 | // answerPermission maps a key onto the pending permission: a once, s for |
| @@ -32,28 +32,55 @@ func (v *View) handleKey(ev *tcell.EventKey) { | |||
| 32 | } | 32 | } |
| 33 | }() | 33 | }() |
| 34 | 34 | ||
| 35 | - if v.pasting { | 35 | + for _, handle := range keyHandlers { |
| 36 | - v.bufferPasteKey(ev) | 36 | + if handle(v, ev) { |
| 37 | - return | 37 | + return |
| 38 | - } | 38 | + } |
| 39 | - if v.ask != nil { | ||
| 40 | - v.answerPermission(ev) | ||
| 41 | - return | ||
| 42 | - } | ||
| 43 | - if v.form != nil { | ||
| 44 | - v.handleFormKey(ev) | ||
| 45 | - return | ||
| 46 | } | 39 | } |
| 47 | - if v.handlePickerKey(ev) { | 40 | + v.handleScrollKey(ev) |
| 48 | - return | 41 | +} |
| 42 | + | ||
| 43 | +// keyHandlers take a key in this order; the first that takes it ends the | ||
| 44 | +// search, and a key none takes scrolls the transcript. | ||
| 45 | +var keyHandlers = []func(*View, *tcell.EventKey) bool{ | ||
| 46 | + (*View).pasteKey, | ||
| 47 | + (*View).permissionKey, | ||
| 48 | + (*View).formKey, | ||
| 49 | + (*View).handlePickerKey, | ||
| 50 | + (*View).handleWindowKey, | ||
| 51 | + (*View).inputKey, | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +// pasteKey buffers every key while a paste is coming in. | ||
| 55 | +func (v *View) pasteKey(ev *tcell.EventKey) bool { | ||
| 56 | + if !v.pasting { | ||
| 57 | + return false | ||
| 49 | } | 58 | } |
| 50 | - if v.handleWindowKey(ev) { | 59 | + v.bufferPasteKey(ev) |
| 51 | - return | 60 | + return true |
| 61 | +} | ||
| 62 | + | ||
| 63 | +// permissionKey gives every key to a pending permission. | ||
| 64 | +func (v *View) permissionKey(ev *tcell.EventKey) bool { | ||
| 65 | + if v.ask == nil { | ||
| 66 | + return false | ||
| 52 | } | 67 | } |
| 53 | - if v.onInput && v.handleInputKey(ev) { | 68 | + v.answerPermission(ev) |
| 54 | - return | 69 | + return true |
| 70 | +} | ||
| 71 | + | ||
| 72 | +// formKey gives every key to an open form. | ||
| 73 | +func (v *View) formKey(ev *tcell.EventKey) bool { | ||
| 74 | + if v.form == nil { | ||
| 75 | + return false | ||
| 55 | } | 76 | } |
| 56 | - v.handleScrollKey(ev) | 77 | + v.handleFormKey(ev) |
| 78 | + return true | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +// inputKey gives a key to the input box when it has the focus. | ||
| 82 | +func (v *View) inputKey(ev *tcell.EventKey) bool { | ||
| 83 | + return v.onInput && v.handleInputKey(ev) | ||
| 57 | } | 84 | } |
| 58 | 85 | ||
| 59 | // answerPermission maps a key onto the pending permission: a once, s for | 86 | // answerPermission maps a key onto the pending permission: a once, s for |
modified
internal/tui/initwin.go +0 -396 | @@ -2,7 +2,6 @@ package tui | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "context" |
| 5 | - "fmt" | |
| 6 | 5 | "strings" |
| 7 | 6 | |
| 8 | 7 | "mm/internal/agentinit" |
| @@ -192,398 +191,3 @@ func (w *initWin) candidate(st agentinit.Step) string { | ||
| 192 | 191 | } |
| 193 | 192 | return st.Options[min(w.sel[st.Key], len(st.Options)-1)].Value |
| 194 | 193 | } |
| 195 | - | |
| 196 | -func (w *initWin) handleKey(ev *tcell.EventKey) { | |
| 197 | - w.problem = "" | |
| 198 | - switch ev.Key() { | |
| 199 | - case tcell.KeyCtrlC: | |
| 200 | - w.result = -1 | |
| 201 | - return | |
| 202 | - case tcell.KeyTab: | |
| 203 | - w.preview = !w.preview | |
| 204 | - return | |
| 205 | - case tcell.KeyPgUp: | |
| 206 | - w.scroll = max(w.scroll-10, 0) | |
| 207 | - return | |
| 208 | - case tcell.KeyPgDn: | |
| 209 | - w.scroll += 10 | |
| 210 | - return | |
| 211 | - case tcell.KeyEscape: | |
| 212 | - w.back() | |
| 213 | - return | |
| 214 | - } | |
| 215 | - if w.confirm { | |
| 216 | - if ev.Key() == tcell.KeyEnter { | |
| 217 | - w.result = 1 | |
| 218 | - } | |
| 219 | - return | |
| 220 | - } | |
| 221 | - st := w.current() | |
| 222 | - if st.Kind == elicit.Text { | |
| 223 | - w.textKey(st, ev) | |
| 224 | - return | |
| 225 | - } | |
| 226 | - switch ev.Key() { | |
| 227 | - case tcell.KeyUp: | |
| 228 | - w.sel[st.Key] = (w.sel[st.Key] + len(st.Options) - 1) % len(st.Options) | |
| 229 | - case tcell.KeyDown: | |
| 230 | - w.sel[st.Key] = (w.sel[st.Key] + 1) % len(st.Options) | |
| 231 | - case tcell.KeyHome: | |
| 232 | - w.sel[st.Key] = 0 | |
| 233 | - case tcell.KeyEnd: | |
| 234 | - w.sel[st.Key] = len(st.Options) - 1 | |
| 235 | - case tcell.KeyEnter: | |
| 236 | - w.answer(st) | |
| 237 | - case tcell.KeyRune: | |
| 238 | - if st.Kind == elicit.Confirm && (ev.Rune() == 'y' || ev.Rune() == 'n') { | |
| 239 | - w.sel[st.Key] = map[rune]int{'y': 0, 'n': 1}[ev.Rune()] | |
| 240 | - w.answer(st) | |
| 241 | - } | |
| 242 | - } | |
| 243 | -} | |
| 244 | - | |
| 245 | -func (w *initWin) textKey(st agentinit.Step, ev *tcell.EventKey) { | |
| 246 | - f := w.text[st.Key] | |
| 247 | - if f == nil { | |
| 248 | - f = newField("") | |
| 249 | - w.text[st.Key] = f | |
| 250 | - } | |
| 251 | - switch { | |
| 252 | - case st.Multiline && ev.Key() == tcell.KeyCtrlD: | |
| 253 | - w.answer(st) | |
| 254 | - case st.Multiline && ev.Key() == tcell.KeyEnter: | |
| 255 | - f.insert('\n') | |
| 256 | - case st.Multiline && (ev.Key() == tcell.KeyUp || ev.Key() == tcell.KeyDown): | |
| 257 | - f.moveLine(map[tcell.Key]int{tcell.KeyUp: -1, tcell.KeyDown: 1}[ev.Key()]) | |
| 258 | - case ev.Key() == tcell.KeyEnter: | |
| 259 | - w.answer(st) | |
| 260 | - default: | |
| 261 | - f.key(ev) | |
| 262 | - } | |
| 263 | -} | |
| 264 | - | |
| 265 | -// field is a one-line text being typed — an endpoint, a variable name, a | |
| 266 | -// file name — with its caret, a rune index: the arrows move it, typing and | |
| 267 | -// deleting happen there (until ticket 177's questions, only appending and | |
| 268 | -// Backspace at the end were possible). | |
| 269 | -// | |
| 270 | -// f := newField("agent.yaml") // caret at the end | |
| 271 | -// f.key(tcell.NewEventKey(tcell.KeyHome, 0, tcell.ModNone)) | |
| 272 | -// f.key(tcell.NewEventKey(tcell.KeyRune, 'm', tcell.ModNone)) // "magent.yaml" | |
| 273 | -type field struct { | |
| 274 | - runes []rune | |
| 275 | - caret int | |
| 276 | -} | |
| 277 | - | |
| 278 | -func newField(s string) *field { | |
| 279 | - r := []rune(s) | |
| 280 | - return &field{runes: r, caret: len(r)} | |
| 281 | -} | |
| 282 | - | |
| 283 | -func (f *field) String() string { return string(f.runes) } | |
| 284 | - | |
| 285 | -// insert puts r at the caret. | |
| 286 | -func (f *field) insert(r rune) { | |
| 287 | - f.runes = append(f.runes[:f.caret], append([]rune{r}, f.runes[f.caret:]...)...) | |
| 288 | - f.caret++ | |
| 289 | -} | |
| 290 | - | |
| 291 | -// lineAt is the line of the caret (0-based) and the caret's column in it. | |
| 292 | -func (f *field) lineAt() (line, col int) { | |
| 293 | - for _, r := range f.runes[:f.caret] { | |
| 294 | - col++ | |
| 295 | - if r == '\n' { | |
| 296 | - line, col = line+1, 0 | |
| 297 | - } | |
| 298 | - } | |
| 299 | - return line, col | |
| 300 | -} | |
| 301 | - | |
| 302 | -// moveLine moves the caret to the line above (-1) or below (+1), at the | |
| 303 | -// same column or the end of that line when it is shorter. | |
| 304 | -func (f *field) moveLine(delta int) { | |
| 305 | - line, col := f.lineAt() | |
| 306 | - lines := strings.Split(string(f.runes), "\n") | |
| 307 | - target := line + delta | |
| 308 | - if target < 0 || target >= len(lines) { | |
| 309 | - return | |
| 310 | - } | |
| 311 | - caret := 0 | |
| 312 | - for i := range target { | |
| 313 | - caret += len([]rune(lines[i])) + 1 | |
| 314 | - } | |
| 315 | - f.caret = caret + min(col, len([]rune(lines[target]))) | |
| 316 | -} | |
| 317 | - | |
| 318 | -// key edits the text; it reports whether the key was an editing key. | |
| 319 | -func (f *field) key(ev *tcell.EventKey) bool { | |
| 320 | - switch ev.Key() { | |
| 321 | - case tcell.KeyRune: | |
| 322 | - f.insert(ev.Rune()) | |
| 323 | - case tcell.KeyBackspace, tcell.KeyBackspace2: | |
| 324 | - if f.caret > 0 { | |
| 325 | - f.runes = append(f.runes[:f.caret-1], f.runes[f.caret:]...) | |
| 326 | - f.caret-- | |
| 327 | - } | |
| 328 | - case tcell.KeyDelete: | |
| 329 | - if f.caret < len(f.runes) { | |
| 330 | - f.runes = append(f.runes[:f.caret], f.runes[f.caret+1:]...) | |
| 331 | - } | |
| 332 | - case tcell.KeyLeft: | |
| 333 | - f.caret = max(f.caret-1, 0) | |
| 334 | - case tcell.KeyRight: | |
| 335 | - f.caret = min(f.caret+1, len(f.runes)) | |
| 336 | - case tcell.KeyHome, tcell.KeyCtrlA: | |
| 337 | - f.caret = 0 | |
| 338 | - case tcell.KeyEnd, tcell.KeyCtrlE: | |
| 339 | - f.caret = len(f.runes) | |
| 340 | - case tcell.KeyCtrlU: | |
| 341 | - f.runes, f.caret = nil, 0 | |
| 342 | - default: | |
| 343 | - return false | |
| 344 | - } | |
| 345 | - return true | |
| 346 | -} | |
| 347 | - | |
| 348 | -// answer records the highlighted choice and moves to the next question. | |
| 349 | -func (w *initWin) answer(st agentinit.Step) { | |
| 350 | - value := w.candidate(st) | |
| 351 | - if value == "" { | |
| 352 | - value = st.Default | |
| 353 | - } | |
| 354 | - if err := w.flow.Set(st.Key, value); err != nil { | |
| 355 | - w.problem = err.Error() | |
| 356 | - return | |
| 357 | - } | |
| 358 | - w.scroll = 0 | |
| 359 | - w.toFirstPending() | |
| 360 | -} | |
| 361 | - | |
| 362 | -// back is Esc: the previous question the user answered becomes the current | |
| 363 | -// one again — its answer taken back; questions answered by flags are | |
| 364 | -// skipped. | |
| 365 | -func (w *initWin) back() { | |
| 366 | - steps := w.steps() | |
| 367 | - from := w.cursor | |
| 368 | - if w.confirm { | |
| 369 | - from = len(steps) | |
| 370 | - } | |
| 371 | - for i := from - 1; i >= 0; i-- { | |
| 372 | - if !steps[i].Given { | |
| 373 | - w.flow.Unset(steps[i].Key) | |
| 374 | - w.cursor, w.confirm = i, false | |
| 375 | - w.initSelection(w.flow.Step(steps[i].Key)) | |
| 376 | - return | |
| 377 | - } | |
| 378 | - } | |
| 379 | -} | |
| 380 | - | |
| 381 | -// --- drawing ---------------------------------------------------------------- | |
| 382 | - | |
| 383 | -func (w *initWin) draw() { | |
| 384 | - width, height := w.screen.Size() | |
| 385 | - if width < 1 || height < 4 { | |
| 386 | - return | |
| 387 | - } | |
| 388 | - w.screen.Clear() | |
| 389 | - p := painter{screen: w.screen, area: rect{w: width, h: height}} | |
| 390 | - w.drawHeader(p.sub(rect{x: 0, y: 0, w: width, h: 1})) | |
| 391 | - p.sub(rect{x: 0, y: 1, w: width, h: 1}).hline(0, 0, width, '─', stRule) | |
| 392 | - body := rect{x: 0, y: 2, w: width, h: height - 4} | |
| 393 | - w.drawBody(p.sub(body)) | |
| 394 | - rule := p.sub(rect{x: 0, y: height - 2, w: width, h: 1}) | |
| 395 | - rule.hline(0, 0, width, '─', stRule) | |
| 396 | - if w.problem != "" { | |
| 397 | - rule.textLimited(1, 0, width-2, " ⚠️ "+w.problem+" ", stError) | |
| 398 | - } | |
| 399 | - w.drawStatus(p.sub(rect{x: 0, y: height - 1, w: width, h: 1})) | |
| 400 | - w.screen.Show() | |
| 401 | -} | |
| 402 | - | |
| 403 | -func (w *initWin) drawHeader(p painter) { | |
| 404 | - p.fill(' ', stBar) | |
| 405 | - p.textLimited(0, 0, p.width(), w.heading(), stBar) | |
| 406 | -} | |
| 407 | - | |
| 408 | -func (w *initWin) drawStatus(p painter) { | |
| 409 | - p.fill(' ', stBar) | |
| 410 | - keys := " ↑↓ choose · Enter next · Esc back · PgUp/PgDn preview · Ctrl-C quit " | |
| 411 | - switch { | |
| 412 | - case w.confirm: | |
| 413 | - keys = " Enter write the file · Esc back · PgUp/PgDn preview · Ctrl-C quit " | |
| 414 | - case w.current().Multiline: | |
| 415 | - keys = " type · ←→↑↓ move · Enter new line · Ctrl-D done · Esc back · PgUp/PgDn preview · Ctrl-C quit " | |
| 416 | - case w.current().Kind == elicit.Text: | |
| 417 | - keys = " type · ←→ move · Enter next · Ctrl-U clear · Esc back · PgUp/PgDn preview · Ctrl-C quit " | |
| 418 | - } | |
| 419 | - if p.width() < previewMinWidth { | |
| 420 | - keys = strings.Replace(keys, " · Ctrl-C", " · Tab preview · Ctrl-C", 1) | |
| 421 | - } | |
| 422 | - p.textLimited(0, 0, p.width(), keys, stBar) | |
| 423 | -} | |
| 424 | - | |
| 425 | -// drawBody lays out the three panes: steps | question | preview. | |
| 426 | -func (w *initWin) drawBody(p painter) { | |
| 427 | - stepsW := 22 | |
| 428 | - w.drawSteps(p.sub(rect{x: 0, y: 0, w: stepsW, h: p.height()})) | |
| 429 | - for y := range p.height() { | |
| 430 | - p.set(stepsW, y, '│', stRule) | |
| 431 | - } | |
| 432 | - rest := rect{x: stepsW + 1, y: 0, w: p.width() - stepsW - 1, h: p.height()} | |
| 433 | - if p.width() < previewMinWidth { | |
| 434 | - if w.preview { | |
| 435 | - w.drawPreview(p.sub(rest)) | |
| 436 | - } else { | |
| 437 | - w.drawQuestion(p.sub(rest)) | |
| 438 | - } | |
| 439 | - return | |
| 440 | - } | |
| 441 | - qw := rest.w * 2 / 5 | |
| 442 | - w.drawQuestion(p.sub(rect{x: rest.x, y: 0, w: qw, h: rest.h})) | |
| 443 | - for y := range p.height() { | |
| 444 | - p.set(rest.x+qw, y, '│', stRule) | |
| 445 | - } | |
| 446 | - w.drawPreview(p.sub(rect{x: rest.x + qw + 1, y: 0, w: rest.w - qw - 1, h: rest.h})) | |
| 447 | -} | |
| 448 | - | |
| 449 | -func (w *initWin) drawSteps(p painter) { | |
| 450 | - for i, st := range w.steps() { | |
| 451 | - mark, style := "·", stNotice | |
| 452 | - switch { | |
| 453 | - case !w.confirm && i == w.cursor: | |
| 454 | - mark, style = "▸", stPrompt | |
| 455 | - case st.Value != "": | |
| 456 | - mark, style = "✓", stBody | |
| 457 | - } | |
| 458 | - line := fmt.Sprintf(" %s %-9s", mark, st.Title) | |
| 459 | - x := p.text(0, i, line, style) | |
| 460 | - if st.Value != "" && (w.confirm || i != w.cursor) { | |
| 461 | - p.textLimited(x+1, i, p.width()-x-1, shortModel(st.Value), stNotice) | |
| 462 | - } | |
| 463 | - } | |
| 464 | -} | |
| 465 | - | |
| 466 | -func (w *initWin) drawQuestion(p painter) { | |
| 467 | - if w.confirm { | |
| 468 | - p.textLimited(1, 0, p.width()-2, "Ready to write "+w.target(), stLabel) | |
| 469 | - p.textLimited(1, 2, p.width()-2, "Every question is answered: the file", stBody) | |
| 470 | - p.textLimited(1, 3, p.width()-2, "on the right is what will be written.", stBody) | |
| 471 | - p.textLimited(1, 5, p.width()-2, "Enter writes it; Esc goes back.", stNotice) | |
| 472 | - return | |
| 473 | - } | |
| 474 | - st := w.current() | |
| 475 | - p.textLimited(1, 0, p.width()-2, st.Prompt, stLabel) | |
| 476 | - if st.Multiline { | |
| 477 | - w.drawLines(p, st) | |
| 478 | - return | |
| 479 | - } | |
| 480 | - if st.Kind == elicit.Text { | |
| 481 | - f := w.text[st.Key] | |
| 482 | - if f == nil { | |
| 483 | - f = newField("") | |
| 484 | - } | |
| 485 | - // The text before the caret, then the rest: the cursor goes between. | |
| 486 | - x := p.text(1, 2, "› "+string(f.runes[:f.caret]), stBody) | |
| 487 | - p.text(x, 2, string(f.runes[f.caret:]), stBody) | |
| 488 | - p.showCursor(x, 2) | |
| 489 | - switch { | |
| 490 | - case st.Optional: | |
| 491 | - p.textLimited(1, 4, p.width()-2, "leave empty for none", stNotice) | |
| 492 | - case st.Default != "": | |
| 493 | - p.textLimited(1, 4, p.width()-2, "default: "+st.Default, stNotice) | |
| 494 | - } | |
| 495 | - return | |
| 496 | - } | |
| 497 | - p.showCursor(-1, -1) | |
| 498 | - listH := max(p.height()-6, 3) | |
| 499 | - sel := w.sel[st.Key] | |
| 500 | - top := min(max(sel-listH/2, 0), max(len(st.Options)-listH, 0)) | |
| 501 | - for row := 0; row < listH && top+row < len(st.Options); row++ { | |
| 502 | - o := st.Options[top+row] | |
| 503 | - label := " " + optionLabel(st, o) | |
| 504 | - if o.Value == st.Default { | |
| 505 | - label += " (default)" | |
| 506 | - } | |
| 507 | - style := stBody | |
| 508 | - if top+row == sel { | |
| 509 | - style = stPick | |
| 510 | - label = "▸" + label[1:] | |
| 511 | - } | |
| 512 | - p.textLimited(1, 2+row, p.width()-2, padTo(label, p.width()-2), style) | |
| 513 | - } | |
| 514 | - if d := optionDetail(st, st.Options[sel]); d != "" { | |
| 515 | - y := 3 + min(listH, len(st.Options)) | |
| 516 | - for i, line := range wrap(d, p.width()-2) { | |
| 517 | - if y+i < p.height() { | |
| 518 | - p.textLimited(1, y+i, p.width()-2, line, stNotice) | |
| 519 | - } | |
| 520 | - } | |
| 521 | - } | |
| 522 | -} | |
| 523 | - | |
| 524 | -// drawLines draws a multi-line answer (mm skillcreate's text), scrolled so | |
| 525 | -// the caret's line is visible; a line wider than the column is cut. | |
| 526 | -func (w *initWin) drawLines(p painter, st agentinit.Step) { | |
| 527 | - f := w.text[st.Key] | |
| 528 | - if f == nil { | |
| 529 | - f = newField("") | |
| 530 | - } | |
| 531 | - lines := strings.Split(f.String(), "\n") | |
| 532 | - line, col := f.lineAt() | |
| 533 | - height := max(p.height()-3, 1) | |
| 534 | - top := max(line-height+1, 0) | |
| 535 | - for i := 0; i < height && top+i < len(lines); i++ { | |
| 536 | - p.textLimited(1, 2+i, p.width()-2, "› "+lines[top+i], stBody) | |
| 537 | - } | |
| 538 | - p.showCursor(min(3+col, p.width()-2), 2+line-top) | |
| 539 | -} | |
| 540 | - | |
| 541 | -// optionLabel is how an option is listed. A model is listed by the | |
| 542 | -// header's short name: its identifier is an address of seventy characters, | |
| 543 | -// cut by the column before the part that tells two models apart. | |
| 544 | -func optionLabel(st agentinit.Step, o agentinit.Option) string { | |
| 545 | - if st.Key == "model" { | |
| 546 | - return shortModel(o.Label) | |
| 547 | - } | |
| 548 | - return o.Label | |
| 549 | -} | |
| 550 | - | |
| 551 | -// optionDetail is the line under the list for the highlighted option. For a | |
| 552 | -// model it is the full identifier: two short names can be the same, and the | |
| 553 | -// identifier is what the file will hold. | |
| 554 | -func optionDetail(st agentinit.Step, o agentinit.Option) string { | |
| 555 | - if st.Key == "model" { | |
| 556 | - if o.Detail == "" { | |
| 557 | - return o.Value | |
| 558 | - } | |
| 559 | - return o.Value + " — " + o.Detail | |
| 560 | - } | |
| 561 | - return o.Detail | |
| 562 | -} | |
| 563 | - | |
| 564 | -func padTo(s string, width int) string { | |
| 565 | - if n := len([]rune(s)); n < width { | |
| 566 | - return s + strings.Repeat(" ", width-n) | |
| 567 | - } | |
| 568 | - return s | |
| 569 | -} | |
| 570 | - | |
| 571 | -// drawPreview shows the file as it would be written with the highlighted | |
| 572 | -// choice; comments dim, keys plain. | |
| 573 | -func (w *initWin) drawPreview(p painter) { | |
| 574 | - key, candidate := "", "" | |
| 575 | - if !w.confirm { | |
| 576 | - st := w.current() | |
| 577 | - key, candidate = st.Key, w.candidate(st) | |
| 578 | - } | |
| 579 | - lines := strings.Split(w.flow.Preview(key, candidate), "\n") | |
| 580 | - w.scroll = min(w.scroll, max(len(lines)-p.height(), 0)) | |
| 581 | - for y := 0; y < p.height() && w.scroll+y < len(lines); y++ { | |
| 582 | - line := lines[w.scroll+y] | |
| 583 | - style := stBody | |
| 584 | - if strings.HasPrefix(strings.TrimSpace(line), "#") { | |
| 585 | - style = stNotice | |
| 586 | - } | |
| 587 | - p.textLimited(1, y, p.width()-1, line, style) | |
| 588 | - } | |
| 589 | -} | |
| @@ -2,7 +2,6 @@ package tui | |||
| 2 | 2 | ||
| 3 | import ( | 3 | import ( |
| 4 | "context" | 4 | "context" |
| 5 | - "fmt" | ||
| 6 | "strings" | 5 | "strings" |
| 7 | 6 | ||
| 8 | "mm/internal/agentinit" | 7 | "mm/internal/agentinit" |
| @@ -192,398 +191,3 @@ func (w *initWin) candidate(st agentinit.Step) string { | |||
| 192 | } | 191 | } |
| 193 | return st.Options[min(w.sel[st.Key], len(st.Options)-1)].Value | 192 | return st.Options[min(w.sel[st.Key], len(st.Options)-1)].Value |
| 194 | } | 193 | } |
| 195 | - | ||
| 196 | -func (w *initWin) handleKey(ev *tcell.EventKey) { | ||
| 197 | - w.problem = "" | ||
| 198 | - switch ev.Key() { | ||
| 199 | - case tcell.KeyCtrlC: | ||
| 200 | - w.result = -1 | ||
| 201 | - return | ||
| 202 | - case tcell.KeyTab: | ||
| 203 | - w.preview = !w.preview | ||
| 204 | - return | ||
| 205 | - case tcell.KeyPgUp: | ||
| 206 | - w.scroll = max(w.scroll-10, 0) | ||
| 207 | - return | ||
| 208 | - case tcell.KeyPgDn: | ||
| 209 | - w.scroll += 10 | ||
| 210 | - return | ||
| 211 | - case tcell.KeyEscape: | ||
| 212 | - w.back() | ||
| 213 | - return | ||
| 214 | - } | ||
| 215 | - if w.confirm { | ||
| 216 | - if ev.Key() == tcell.KeyEnter { | ||
| 217 | - w.result = 1 | ||
| 218 | - } | ||
| 219 | - return | ||
| 220 | - } | ||
| 221 | - st := w.current() | ||
| 222 | - if st.Kind == elicit.Text { | ||
| 223 | - w.textKey(st, ev) | ||
| 224 | - return | ||
| 225 | - } | ||
| 226 | - switch ev.Key() { | ||
| 227 | - case tcell.KeyUp: | ||
| 228 | - w.sel[st.Key] = (w.sel[st.Key] + len(st.Options) - 1) % len(st.Options) | ||
| 229 | - case tcell.KeyDown: | ||
| 230 | - w.sel[st.Key] = (w.sel[st.Key] + 1) % len(st.Options) | ||
| 231 | - case tcell.KeyHome: | ||
| 232 | - w.sel[st.Key] = 0 | ||
| 233 | - case tcell.KeyEnd: | ||
| 234 | - w.sel[st.Key] = len(st.Options) - 1 | ||
| 235 | - case tcell.KeyEnter: | ||
| 236 | - w.answer(st) | ||
| 237 | - case tcell.KeyRune: | ||
| 238 | - if st.Kind == elicit.Confirm && (ev.Rune() == 'y' || ev.Rune() == 'n') { | ||
| 239 | - w.sel[st.Key] = map[rune]int{'y': 0, 'n': 1}[ev.Rune()] | ||
| 240 | - w.answer(st) | ||
| 241 | - } | ||
| 242 | - } | ||
| 243 | -} | ||
| 244 | - | ||
| 245 | -func (w *initWin) textKey(st agentinit.Step, ev *tcell.EventKey) { | ||
| 246 | - f := w.text[st.Key] | ||
| 247 | - if f == nil { | ||
| 248 | - f = newField("") | ||
| 249 | - w.text[st.Key] = f | ||
| 250 | - } | ||
| 251 | - switch { | ||
| 252 | - case st.Multiline && ev.Key() == tcell.KeyCtrlD: | ||
| 253 | - w.answer(st) | ||
| 254 | - case st.Multiline && ev.Key() == tcell.KeyEnter: | ||
| 255 | - f.insert('\n') | ||
| 256 | - case st.Multiline && (ev.Key() == tcell.KeyUp || ev.Key() == tcell.KeyDown): | ||
| 257 | - f.moveLine(map[tcell.Key]int{tcell.KeyUp: -1, tcell.KeyDown: 1}[ev.Key()]) | ||
| 258 | - case ev.Key() == tcell.KeyEnter: | ||
| 259 | - w.answer(st) | ||
| 260 | - default: | ||
| 261 | - f.key(ev) | ||
| 262 | - } | ||
| 263 | -} | ||
| 264 | - | ||
| 265 | -// field is a one-line text being typed — an endpoint, a variable name, a | ||
| 266 | -// file name — with its caret, a rune index: the arrows move it, typing and | ||
| 267 | -// deleting happen there (until ticket 177's questions, only appending and | ||
| 268 | -// Backspace at the end were possible). | ||
| 269 | -// | ||
| 270 | -// f := newField("agent.yaml") // caret at the end | ||
| 271 | -// f.key(tcell.NewEventKey(tcell.KeyHome, 0, tcell.ModNone)) | ||
| 272 | -// f.key(tcell.NewEventKey(tcell.KeyRune, 'm', tcell.ModNone)) // "magent.yaml" | ||
| 273 | -type field struct { | ||
| 274 | - runes []rune | ||
| 275 | - caret int | ||
| 276 | -} | ||
| 277 | - | ||
| 278 | -func newField(s string) *field { | ||
| 279 | - r := []rune(s) | ||
| 280 | - return &field{runes: r, caret: len(r)} | ||
| 281 | -} | ||
| 282 | - | ||
| 283 | -func (f *field) String() string { return string(f.runes) } | ||
| 284 | - | ||
| 285 | -// insert puts r at the caret. | ||
| 286 | -func (f *field) insert(r rune) { | ||
| 287 | - f.runes = append(f.runes[:f.caret], append([]rune{r}, f.runes[f.caret:]...)...) | ||
| 288 | - f.caret++ | ||
| 289 | -} | ||
| 290 | - | ||
| 291 | -// lineAt is the line of the caret (0-based) and the caret's column in it. | ||
| 292 | -func (f *field) lineAt() (line, col int) { | ||
| 293 | - for _, r := range f.runes[:f.caret] { | ||
| 294 | - col++ | ||
| 295 | - if r == '\n' { | ||
| 296 | - line, col = line+1, 0 | ||
| 297 | - } | ||
| 298 | - } | ||
| 299 | - return line, col | ||
| 300 | -} | ||
| 301 | - | ||
| 302 | -// moveLine moves the caret to the line above (-1) or below (+1), at the | ||
| 303 | -// same column or the end of that line when it is shorter. | ||
| 304 | -func (f *field) moveLine(delta int) { | ||
| 305 | - line, col := f.lineAt() | ||
| 306 | - lines := strings.Split(string(f.runes), "\n") | ||
| 307 | - target := line + delta | ||
| 308 | - if target < 0 || target >= len(lines) { | ||
| 309 | - return | ||
| 310 | - } | ||
| 311 | - caret := 0 | ||
| 312 | - for i := range target { | ||
| 313 | - caret += len([]rune(lines[i])) + 1 | ||
| 314 | - } | ||
| 315 | - f.caret = caret + min(col, len([]rune(lines[target]))) | ||
| 316 | -} | ||
| 317 | - | ||
| 318 | -// key edits the text; it reports whether the key was an editing key. | ||
| 319 | -func (f *field) key(ev *tcell.EventKey) bool { | ||
| 320 | - switch ev.Key() { | ||
| 321 | - case tcell.KeyRune: | ||
| 322 | - f.insert(ev.Rune()) | ||
| 323 | - case tcell.KeyBackspace, tcell.KeyBackspace2: | ||
| 324 | - if f.caret > 0 { | ||
| 325 | - f.runes = append(f.runes[:f.caret-1], f.runes[f.caret:]...) | ||
| 326 | - f.caret-- | ||
| 327 | - } | ||
| 328 | - case tcell.KeyDelete: | ||
| 329 | - if f.caret < len(f.runes) { | ||
| 330 | - f.runes = append(f.runes[:f.caret], f.runes[f.caret+1:]...) | ||
| 331 | - } | ||
| 332 | - case tcell.KeyLeft: | ||
| 333 | - f.caret = max(f.caret-1, 0) | ||
| 334 | - case tcell.KeyRight: | ||
| 335 | - f.caret = min(f.caret+1, len(f.runes)) | ||
| 336 | - case tcell.KeyHome, tcell.KeyCtrlA: | ||
| 337 | - f.caret = 0 | ||
| 338 | - case tcell.KeyEnd, tcell.KeyCtrlE: | ||
| 339 | - f.caret = len(f.runes) | ||
| 340 | - case tcell.KeyCtrlU: | ||
| 341 | - f.runes, f.caret = nil, 0 | ||
| 342 | - default: | ||
| 343 | - return false | ||
| 344 | - } | ||
| 345 | - return true | ||
| 346 | -} | ||
| 347 | - | ||
| 348 | -// answer records the highlighted choice and moves to the next question. | ||
| 349 | -func (w *initWin) answer(st agentinit.Step) { | ||
| 350 | - value := w.candidate(st) | ||
| 351 | - if value == "" { | ||
| 352 | - value = st.Default | ||
| 353 | - } | ||
| 354 | - if err := w.flow.Set(st.Key, value); err != nil { | ||
| 355 | - w.problem = err.Error() | ||
| 356 | - return | ||
| 357 | - } | ||
| 358 | - w.scroll = 0 | ||
| 359 | - w.toFirstPending() | ||
| 360 | -} | ||
| 361 | - | ||
| 362 | -// back is Esc: the previous question the user answered becomes the current | ||
| 363 | -// one again — its answer taken back; questions answered by flags are | ||
| 364 | -// skipped. | ||
| 365 | -func (w *initWin) back() { | ||
| 366 | - steps := w.steps() | ||
| 367 | - from := w.cursor | ||
| 368 | - if w.confirm { | ||
| 369 | - from = len(steps) | ||
| 370 | - } | ||
| 371 | - for i := from - 1; i >= 0; i-- { | ||
| 372 | - if !steps[i].Given { | ||
| 373 | - w.flow.Unset(steps[i].Key) | ||
| 374 | - w.cursor, w.confirm = i, false | ||
| 375 | - w.initSelection(w.flow.Step(steps[i].Key)) | ||
| 376 | - return | ||
| 377 | - } | ||
| 378 | - } | ||
| 379 | -} | ||
| 380 | - | ||
| 381 | -// --- drawing ---------------------------------------------------------------- | ||
| 382 | - | ||
| 383 | -func (w *initWin) draw() { | ||
| 384 | - width, height := w.screen.Size() | ||
| 385 | - if width < 1 || height < 4 { | ||
| 386 | - return | ||
| 387 | - } | ||
| 388 | - w.screen.Clear() | ||
| 389 | - p := painter{screen: w.screen, area: rect{w: width, h: height}} | ||
| 390 | - w.drawHeader(p.sub(rect{x: 0, y: 0, w: width, h: 1})) | ||
| 391 | - p.sub(rect{x: 0, y: 1, w: width, h: 1}).hline(0, 0, width, '─', stRule) | ||
| 392 | - body := rect{x: 0, y: 2, w: width, h: height - 4} | ||
| 393 | - w.drawBody(p.sub(body)) | ||
| 394 | - rule := p.sub(rect{x: 0, y: height - 2, w: width, h: 1}) | ||
| 395 | - rule.hline(0, 0, width, '─', stRule) | ||
| 396 | - if w.problem != "" { | ||
| 397 | - rule.textLimited(1, 0, width-2, " ⚠️ "+w.problem+" ", stError) | ||
| 398 | - } | ||
| 399 | - w.drawStatus(p.sub(rect{x: 0, y: height - 1, w: width, h: 1})) | ||
| 400 | - w.screen.Show() | ||
| 401 | -} | ||
| 402 | - | ||
| 403 | -func (w *initWin) drawHeader(p painter) { | ||
| 404 | - p.fill(' ', stBar) | ||
| 405 | - p.textLimited(0, 0, p.width(), w.heading(), stBar) | ||
| 406 | -} | ||
| 407 | - | ||
| 408 | -func (w *initWin) drawStatus(p painter) { | ||
| 409 | - p.fill(' ', stBar) | ||
| 410 | - keys := " ↑↓ choose · Enter next · Esc back · PgUp/PgDn preview · Ctrl-C quit " | ||
| 411 | - switch { | ||
| 412 | - case w.confirm: | ||
| 413 | - keys = " Enter write the file · Esc back · PgUp/PgDn preview · Ctrl-C quit " | ||
| 414 | - case w.current().Multiline: | ||
| 415 | - keys = " type · ←→↑↓ move · Enter new line · Ctrl-D done · Esc back · PgUp/PgDn preview · Ctrl-C quit " | ||
| 416 | - case w.current().Kind == elicit.Text: | ||
| 417 | - keys = " type · ←→ move · Enter next · Ctrl-U clear · Esc back · PgUp/PgDn preview · Ctrl-C quit " | ||
| 418 | - } | ||
| 419 | - if p.width() < previewMinWidth { | ||
| 420 | - keys = strings.Replace(keys, " · Ctrl-C", " · Tab preview · Ctrl-C", 1) | ||
| 421 | - } | ||
| 422 | - p.textLimited(0, 0, p.width(), keys, stBar) | ||
| 423 | -} | ||
| 424 | - | ||
| 425 | -// drawBody lays out the three panes: steps | question | preview. | ||
| 426 | -func (w *initWin) drawBody(p painter) { | ||
| 427 | - stepsW := 22 | ||
| 428 | - w.drawSteps(p.sub(rect{x: 0, y: 0, w: stepsW, h: p.height()})) | ||
| 429 | - for y := range p.height() { | ||
| 430 | - p.set(stepsW, y, '│', stRule) | ||
| 431 | - } | ||
| 432 | - rest := rect{x: stepsW + 1, y: 0, w: p.width() - stepsW - 1, h: p.height()} | ||
| 433 | - if p.width() < previewMinWidth { | ||
| 434 | - if w.preview { | ||
| 435 | - w.drawPreview(p.sub(rest)) | ||
| 436 | - } else { | ||
| 437 | - w.drawQuestion(p.sub(rest)) | ||
| 438 | - } | ||
| 439 | - return | ||
| 440 | - } | ||
| 441 | - qw := rest.w * 2 / 5 | ||
| 442 | - w.drawQuestion(p.sub(rect{x: rest.x, y: 0, w: qw, h: rest.h})) | ||
| 443 | - for y := range p.height() { | ||
| 444 | - p.set(rest.x+qw, y, '│', stRule) | ||
| 445 | - } | ||
| 446 | - w.drawPreview(p.sub(rect{x: rest.x + qw + 1, y: 0, w: rest.w - qw - 1, h: rest.h})) | ||
| 447 | -} | ||
| 448 | - | ||
| 449 | -func (w *initWin) drawSteps(p painter) { | ||
| 450 | - for i, st := range w.steps() { | ||
| 451 | - mark, style := "·", stNotice | ||
| 452 | - switch { | ||
| 453 | - case !w.confirm && i == w.cursor: | ||
| 454 | - mark, style = "▸", stPrompt | ||
| 455 | - case st.Value != "": | ||
| 456 | - mark, style = "✓", stBody | ||
| 457 | - } | ||
| 458 | - line := fmt.Sprintf(" %s %-9s", mark, st.Title) | ||
| 459 | - x := p.text(0, i, line, style) | ||
| 460 | - if st.Value != "" && (w.confirm || i != w.cursor) { | ||
| 461 | - p.textLimited(x+1, i, p.width()-x-1, shortModel(st.Value), stNotice) | ||
| 462 | - } | ||
| 463 | - } | ||
| 464 | -} | ||
| 465 | - | ||
| 466 | -func (w *initWin) drawQuestion(p painter) { | ||
| 467 | - if w.confirm { | ||
| 468 | - p.textLimited(1, 0, p.width()-2, "Ready to write "+w.target(), stLabel) | ||
| 469 | - p.textLimited(1, 2, p.width()-2, "Every question is answered: the file", stBody) | ||
| 470 | - p.textLimited(1, 3, p.width()-2, "on the right is what will be written.", stBody) | ||
| 471 | - p.textLimited(1, 5, p.width()-2, "Enter writes it; Esc goes back.", stNotice) | ||
| 472 | - return | ||
| 473 | - } | ||
| 474 | - st := w.current() | ||
| 475 | - p.textLimited(1, 0, p.width()-2, st.Prompt, stLabel) | ||
| 476 | - if st.Multiline { | ||
| 477 | - w.drawLines(p, st) | ||
| 478 | - return | ||
| 479 | - } | ||
| 480 | - if st.Kind == elicit.Text { | ||
| 481 | - f := w.text[st.Key] | ||
| 482 | - if f == nil { | ||
| 483 | - f = newField("") | ||
| 484 | - } | ||
| 485 | - // The text before the caret, then the rest: the cursor goes between. | ||
| 486 | - x := p.text(1, 2, "› "+string(f.runes[:f.caret]), stBody) | ||
| 487 | - p.text(x, 2, string(f.runes[f.caret:]), stBody) | ||
| 488 | - p.showCursor(x, 2) | ||
| 489 | - switch { | ||
| 490 | - case st.Optional: | ||
| 491 | - p.textLimited(1, 4, p.width()-2, "leave empty for none", stNotice) | ||
| 492 | - case st.Default != "": | ||
| 493 | - p.textLimited(1, 4, p.width()-2, "default: "+st.Default, stNotice) | ||
| 494 | - } | ||
| 495 | - return | ||
| 496 | - } | ||
| 497 | - p.showCursor(-1, -1) | ||
| 498 | - listH := max(p.height()-6, 3) | ||
| 499 | - sel := w.sel[st.Key] | ||
| 500 | - top := min(max(sel-listH/2, 0), max(len(st.Options)-listH, 0)) | ||
| 501 | - for row := 0; row < listH && top+row < len(st.Options); row++ { | ||
| 502 | - o := st.Options[top+row] | ||
| 503 | - label := " " + optionLabel(st, o) | ||
| 504 | - if o.Value == st.Default { | ||
| 505 | - label += " (default)" | ||
| 506 | - } | ||
| 507 | - style := stBody | ||
| 508 | - if top+row == sel { | ||
| 509 | - style = stPick | ||
| 510 | - label = "▸" + label[1:] | ||
| 511 | - } | ||
| 512 | - p.textLimited(1, 2+row, p.width()-2, padTo(label, p.width()-2), style) | ||
| 513 | - } | ||
| 514 | - if d := optionDetail(st, st.Options[sel]); d != "" { | ||
| 515 | - y := 3 + min(listH, len(st.Options)) | ||
| 516 | - for i, line := range wrap(d, p.width()-2) { | ||
| 517 | - if y+i < p.height() { | ||
| 518 | - p.textLimited(1, y+i, p.width()-2, line, stNotice) | ||
| 519 | - } | ||
| 520 | - } | ||
| 521 | - } | ||
| 522 | -} | ||
| 523 | - | ||
| 524 | -// drawLines draws a multi-line answer (mm skillcreate's text), scrolled so | ||
| 525 | -// the caret's line is visible; a line wider than the column is cut. | ||
| 526 | -func (w *initWin) drawLines(p painter, st agentinit.Step) { | ||
| 527 | - f := w.text[st.Key] | ||
| 528 | - if f == nil { | ||
| 529 | - f = newField("") | ||
| 530 | - } | ||
| 531 | - lines := strings.Split(f.String(), "\n") | ||
| 532 | - line, col := f.lineAt() | ||
| 533 | - height := max(p.height()-3, 1) | ||
| 534 | - top := max(line-height+1, 0) | ||
| 535 | - for i := 0; i < height && top+i < len(lines); i++ { | ||
| 536 | - p.textLimited(1, 2+i, p.width()-2, "› "+lines[top+i], stBody) | ||
| 537 | - } | ||
| 538 | - p.showCursor(min(3+col, p.width()-2), 2+line-top) | ||
| 539 | -} | ||
| 540 | - | ||
| 541 | -// optionLabel is how an option is listed. A model is listed by the | ||
| 542 | -// header's short name: its identifier is an address of seventy characters, | ||
| 543 | -// cut by the column before the part that tells two models apart. | ||
| 544 | -func optionLabel(st agentinit.Step, o agentinit.Option) string { | ||
| 545 | - if st.Key == "model" { | ||
| 546 | - return shortModel(o.Label) | ||
| 547 | - } | ||
| 548 | - return o.Label | ||
| 549 | -} | ||
| 550 | - | ||
| 551 | -// optionDetail is the line under the list for the highlighted option. For a | ||
| 552 | -// model it is the full identifier: two short names can be the same, and the | ||
| 553 | -// identifier is what the file will hold. | ||
| 554 | -func optionDetail(st agentinit.Step, o agentinit.Option) string { | ||
| 555 | - if st.Key == "model" { | ||
| 556 | - if o.Detail == "" { | ||
| 557 | - return o.Value | ||
| 558 | - } | ||
| 559 | - return o.Value + " — " + o.Detail | ||
| 560 | - } | ||
| 561 | - return o.Detail | ||
| 562 | -} | ||
| 563 | - | ||
| 564 | -func padTo(s string, width int) string { | ||
| 565 | - if n := len([]rune(s)); n < width { | ||
| 566 | - return s + strings.Repeat(" ", width-n) | ||
| 567 | - } | ||
| 568 | - return s | ||
| 569 | -} | ||
| 570 | - | ||
| 571 | -// drawPreview shows the file as it would be written with the highlighted | ||
| 572 | -// choice; comments dim, keys plain. | ||
| 573 | -func (w *initWin) drawPreview(p painter) { | ||
| 574 | - key, candidate := "", "" | ||
| 575 | - if !w.confirm { | ||
| 576 | - st := w.current() | ||
| 577 | - key, candidate = st.Key, w.candidate(st) | ||
| 578 | - } | ||
| 579 | - lines := strings.Split(w.flow.Preview(key, candidate), "\n") | ||
| 580 | - w.scroll = min(w.scroll, max(len(lines)-p.height(), 0)) | ||
| 581 | - for y := 0; y < p.height() && w.scroll+y < len(lines); y++ { | ||
| 582 | - line := lines[w.scroll+y] | ||
| 583 | - style := stBody | ||
| 584 | - if strings.HasPrefix(strings.TrimSpace(line), "#") { | ||
| 585 | - style = stNotice | ||
| 586 | - } | ||
| 587 | - p.textLimited(1, y, p.width()-1, line, style) | ||
| 588 | - } | ||
| 589 | -} | ||
added
internal/tui/initwin_draw.go +250 -0 | new file mode 100644 | ||
| @@ -0,0 +1,250 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "fmt" | |
| 5 | + "mm/internal/agentinit" | |
| 6 | + "mm/internal/elicit" | |
| 7 | + "strings" | |
| 8 | + | |
| 9 | + "github.com/gdamore/tcell/v2" | |
| 10 | +) | |
| 11 | + | |
| 12 | +// draw paints the whole window: header, the three panes, the problem line | |
| 13 | +// and the keys. | |
| 14 | +func (w *initWin) draw() { | |
| 15 | + width, height := w.screen.Size() | |
| 16 | + if width < 1 || height < 4 { | |
| 17 | + return | |
| 18 | + } | |
| 19 | + w.screen.Clear() | |
| 20 | + p := painter{screen: w.screen, area: rect{w: width, h: height}} | |
| 21 | + w.drawHeader(p.sub(rect{x: 0, y: 0, w: width, h: 1})) | |
| 22 | + p.sub(rect{x: 0, y: 1, w: width, h: 1}).hline(0, 0, width, '─', stRule) | |
| 23 | + body := rect{x: 0, y: 2, w: width, h: height - 4} | |
| 24 | + w.drawBody(p.sub(body)) | |
| 25 | + rule := p.sub(rect{x: 0, y: height - 2, w: width, h: 1}) | |
| 26 | + rule.hline(0, 0, width, '─', stRule) | |
| 27 | + if w.problem != "" { | |
| 28 | + rule.textLimited(1, 0, width-2, " ⚠️ "+w.problem+" ", stError) | |
| 29 | + } | |
| 30 | + w.drawStatus(p.sub(rect{x: 0, y: height - 1, w: width, h: 1})) | |
| 31 | + w.screen.Show() | |
| 32 | +} | |
| 33 | + | |
| 34 | +func (w *initWin) drawHeader(p painter) { | |
| 35 | + p.fill(' ', stBar) | |
| 36 | + p.textLimited(0, 0, p.width(), w.heading(), stBar) | |
| 37 | +} | |
| 38 | + | |
| 39 | +func (w *initWin) drawStatus(p painter) { | |
| 40 | + p.fill(' ', stBar) | |
| 41 | + keys := " ↑↓ choose · Enter next · Esc back · PgUp/PgDn preview · Ctrl-C quit " | |
| 42 | + switch { | |
| 43 | + case w.confirm: | |
| 44 | + keys = " Enter write the file · Esc back · PgUp/PgDn preview · Ctrl-C quit " | |
| 45 | + case w.current().Multiline: | |
| 46 | + keys = " type · ←→↑↓ move · Enter new line · Ctrl-D done · Esc back · PgUp/PgDn preview · Ctrl-C quit " | |
| 47 | + case w.current().Kind == elicit.Text: | |
| 48 | + keys = " type · ←→ move · Enter next · Ctrl-U clear · Esc back · PgUp/PgDn preview · Ctrl-C quit " | |
| 49 | + } | |
| 50 | + if p.width() < previewMinWidth { | |
| 51 | + keys = strings.Replace(keys, " · Ctrl-C", " · Tab preview · Ctrl-C", 1) | |
| 52 | + } | |
| 53 | + p.textLimited(0, 0, p.width(), keys, stBar) | |
| 54 | +} | |
| 55 | + | |
| 56 | +// drawBody lays out the three panes: steps | question | preview. | |
| 57 | +func (w *initWin) drawBody(p painter) { | |
| 58 | + stepsW := 22 | |
| 59 | + w.drawSteps(p.sub(rect{x: 0, y: 0, w: stepsW, h: p.height()})) | |
| 60 | + for y := range p.height() { | |
| 61 | + p.set(stepsW, y, '│', stRule) | |
| 62 | + } | |
| 63 | + rest := rect{x: stepsW + 1, y: 0, w: p.width() - stepsW - 1, h: p.height()} | |
| 64 | + if p.width() < previewMinWidth { | |
| 65 | + if w.preview { | |
| 66 | + w.drawPreview(p.sub(rest)) | |
| 67 | + } else { | |
| 68 | + w.drawQuestion(p.sub(rest)) | |
| 69 | + } | |
| 70 | + return | |
| 71 | + } | |
| 72 | + qw := rest.w * 2 / 5 | |
| 73 | + w.drawQuestion(p.sub(rect{x: rest.x, y: 0, w: qw, h: rest.h})) | |
| 74 | + for y := range p.height() { | |
| 75 | + p.set(rest.x+qw, y, '│', stRule) | |
| 76 | + } | |
| 77 | + w.drawPreview(p.sub(rect{x: rest.x + qw + 1, y: 0, w: rest.w - qw - 1, h: rest.h})) | |
| 78 | +} | |
| 79 | + | |
| 80 | +func (w *initWin) drawSteps(p painter) { | |
| 81 | + for i, st := range w.steps() { | |
| 82 | + mark, style := "·", stNotice | |
| 83 | + switch { | |
| 84 | + case !w.confirm && i == w.cursor: | |
| 85 | + mark, style = "▸", stPrompt | |
| 86 | + case st.Value != "": | |
| 87 | + mark, style = "✓", stBody | |
| 88 | + } | |
| 89 | + line := fmt.Sprintf(" %s %-9s", mark, st.Title) | |
| 90 | + x := p.text(0, i, line, style) | |
| 91 | + if st.Value != "" && (w.confirm || i != w.cursor) { | |
| 92 | + p.textLimited(x+1, i, p.width()-x-1, shortModel(st.Value), stNotice) | |
| 93 | + } | |
| 94 | + } | |
| 95 | +} | |
| 96 | + | |
| 97 | +// drawQuestion draws the middle pane: the confirmation, or the current | |
| 98 | +// step's prompt and its answer being given. | |
| 99 | +func (w *initWin) drawQuestion(p painter) { | |
| 100 | + if w.confirm { | |
| 101 | + w.drawReady(p) | |
| 102 | + return | |
| 103 | + } | |
| 104 | + st := w.current() | |
| 105 | + p.textLimited(1, 0, p.width()-2, st.Prompt, stLabel) | |
| 106 | + switch { | |
| 107 | + case st.Multiline: | |
| 108 | + w.drawLines(p, st) | |
| 109 | + case st.Kind == elicit.Text: | |
| 110 | + w.drawField(p, st) | |
| 111 | + default: | |
| 112 | + w.drawOptions(p, st) | |
| 113 | + } | |
| 114 | +} | |
| 115 | + | |
| 116 | +// drawReady is the confirmation: every question answered, the file ready. | |
| 117 | +func (w *initWin) drawReady(p painter) { | |
| 118 | + p.textLimited(1, 0, p.width()-2, "Ready to write "+w.target(), stLabel) | |
| 119 | + p.textLimited(1, 2, p.width()-2, "Every question is answered: the file", stBody) | |
| 120 | + p.textLimited(1, 3, p.width()-2, "on the right is what will be written.", stBody) | |
| 121 | + p.textLimited(1, 5, p.width()-2, "Enter writes it; Esc goes back.", stNotice) | |
| 122 | +} | |
| 123 | + | |
| 124 | +// drawField draws a one-line text answer with its caret, and what leaving | |
| 125 | +// it empty gives. | |
| 126 | +func (w *initWin) drawField(p painter, st agentinit.Step) { | |
| 127 | + f := w.text[st.Key] | |
| 128 | + if f == nil { | |
| 129 | + f = newField("") | |
| 130 | + } | |
| 131 | + // The text before the caret, then the rest: the cursor goes between. | |
| 132 | + x := p.text(1, 2, "› "+string(f.runes[:f.caret]), stBody) | |
| 133 | + p.text(x, 2, string(f.runes[f.caret:]), stBody) | |
| 134 | + p.showCursor(x, 2) | |
| 135 | + switch { | |
| 136 | + case st.Optional: | |
| 137 | + p.textLimited(1, 4, p.width()-2, "leave empty for none", stNotice) | |
| 138 | + case st.Default != "": | |
| 139 | + p.textLimited(1, 4, p.width()-2, "default: "+st.Default, stNotice) | |
| 140 | + } | |
| 141 | +} | |
| 142 | + | |
| 143 | +// drawOptions draws a choice step's options, scrolled around the highlighted | |
| 144 | +// one, and that option's detail under the list. | |
| 145 | +func (w *initWin) drawOptions(p painter, st agentinit.Step) { | |
| 146 | + p.showCursor(-1, -1) | |
| 147 | + listH := max(p.height()-6, 3) | |
| 148 | + sel := w.sel[st.Key] | |
| 149 | + top := min(max(sel-listH/2, 0), max(len(st.Options)-listH, 0)) | |
| 150 | + for row := 0; row < listH && top+row < len(st.Options); row++ { | |
| 151 | + label, style := optionLine(st, top+row, sel) | |
| 152 | + p.textLimited(1, 2+row, p.width()-2, padTo(label, p.width()-2), style) | |
| 153 | + } | |
| 154 | + drawDetail(p, optionDetail(st, st.Options[sel]), 3+min(listH, len(st.Options))) | |
| 155 | +} | |
| 156 | + | |
| 157 | +// drawDetail draws the highlighted option's detail from line y, wrapped, cut | |
| 158 | +// at the bottom of the pane. | |
| 159 | +func drawDetail(p painter, detail string, y int) { | |
| 160 | + if detail == "" { | |
| 161 | + return | |
| 162 | + } | |
| 163 | + for i, line := range wrap(detail, p.width()-2) { | |
| 164 | + if y+i < p.height() { | |
| 165 | + p.textLimited(1, y+i, p.width()-2, line, stNotice) | |
| 166 | + } | |
| 167 | + } | |
| 168 | +} | |
| 169 | + | |
| 170 | +// optionLine is how option i is listed: its label, "(default)" after the | |
| 171 | +// default, and a ▸ in the highlight's style when it is the one selected. | |
| 172 | +func optionLine(st agentinit.Step, i, sel int) (string, tcell.Style) { | |
| 173 | + o := st.Options[i] | |
| 174 | + label := " " + optionLabel(st, o) | |
| 175 | + if o.Value == st.Default { | |
| 176 | + label += " (default)" | |
| 177 | + } | |
| 178 | + if i == sel { | |
| 179 | + return "▸" + label[1:], stPick | |
| 180 | + } | |
| 181 | + return label, stBody | |
| 182 | +} | |
| 183 | + | |
| 184 | +// drawLines draws a multi-line answer (mm skillcreate's text), scrolled so | |
| 185 | +// the caret's line is visible; a line wider than the column is cut. | |
| 186 | +func (w *initWin) drawLines(p painter, st agentinit.Step) { | |
| 187 | + f := w.text[st.Key] | |
| 188 | + if f == nil { | |
| 189 | + f = newField("") | |
| 190 | + } | |
| 191 | + lines := strings.Split(f.String(), "\n") | |
| 192 | + line, col := f.lineAt() | |
| 193 | + height := max(p.height()-3, 1) | |
| 194 | + top := max(line-height+1, 0) | |
| 195 | + for i := 0; i < height && top+i < len(lines); i++ { | |
| 196 | + p.textLimited(1, 2+i, p.width()-2, "› "+lines[top+i], stBody) | |
| 197 | + } | |
| 198 | + p.showCursor(min(3+col, p.width()-2), 2+line-top) | |
| 199 | +} | |
| 200 | + | |
| 201 | +// optionLabel is how an option is listed. A model is listed by the | |
| 202 | +// header's short name: its identifier is an address of seventy characters, | |
| 203 | +// cut by the column before the part that tells two models apart. | |
| 204 | +func optionLabel(st agentinit.Step, o agentinit.Option) string { | |
| 205 | + if st.Key == "model" { | |
| 206 | + return shortModel(o.Label) | |
| 207 | + } | |
| 208 | + return o.Label | |
| 209 | +} | |
| 210 | + | |
| 211 | +// optionDetail is the line under the list for the highlighted option. For a | |
| 212 | +// model it is the full identifier: two short names can be the same, and the | |
| 213 | +// identifier is what the file will hold. | |
| 214 | +func optionDetail(st agentinit.Step, o agentinit.Option) string { | |
| 215 | + if st.Key == "model" { | |
| 216 | + if o.Detail == "" { | |
| 217 | + return o.Value | |
| 218 | + } | |
| 219 | + return o.Value + " — " + o.Detail | |
| 220 | + } | |
| 221 | + return o.Detail | |
| 222 | +} | |
| 223 | + | |
| 224 | +// padTo pads s with spaces to width runes. | |
| 225 | +func padTo(s string, width int) string { | |
| 226 | + if n := len([]rune(s)); n < width { | |
| 227 | + return s + strings.Repeat(" ", width-n) | |
| 228 | + } | |
| 229 | + return s | |
| 230 | +} | |
| 231 | + | |
| 232 | +// drawPreview shows the file as it would be written with the highlighted | |
| 233 | +// choice; comments dim, keys plain. | |
| 234 | +func (w *initWin) drawPreview(p painter) { | |
| 235 | + key, candidate := "", "" | |
| 236 | + if !w.confirm { | |
| 237 | + st := w.current() | |
| 238 | + key, candidate = st.Key, w.candidate(st) | |
| 239 | + } | |
| 240 | + lines := strings.Split(w.flow.Preview(key, candidate), "\n") | |
| 241 | + w.scroll = min(w.scroll, max(len(lines)-p.height(), 0)) | |
| 242 | + for y := 0; y < p.height() && w.scroll+y < len(lines); y++ { | |
| 243 | + line := lines[w.scroll+y] | |
| 244 | + style := stBody | |
| 245 | + if strings.HasPrefix(strings.TrimSpace(line), "#") { | |
| 246 | + style = stNotice | |
| 247 | + } | |
| 248 | + p.textLimited(1, y, p.width()-1, line, style) | |
| 249 | + } | |
| 250 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,250 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "fmt" | ||
| 5 | + "mm/internal/agentinit" | ||
| 6 | + "mm/internal/elicit" | ||
| 7 | + "strings" | ||
| 8 | + | ||
| 9 | + "github.com/gdamore/tcell/v2" | ||
| 10 | +) | ||
| 11 | + | ||
| 12 | +// draw paints the whole window: header, the three panes, the problem line | ||
| 13 | +// and the keys. | ||
| 14 | +func (w *initWin) draw() { | ||
| 15 | + width, height := w.screen.Size() | ||
| 16 | + if width < 1 || height < 4 { | ||
| 17 | + return | ||
| 18 | + } | ||
| 19 | + w.screen.Clear() | ||
| 20 | + p := painter{screen: w.screen, area: rect{w: width, h: height}} | ||
| 21 | + w.drawHeader(p.sub(rect{x: 0, y: 0, w: width, h: 1})) | ||
| 22 | + p.sub(rect{x: 0, y: 1, w: width, h: 1}).hline(0, 0, width, '─', stRule) | ||
| 23 | + body := rect{x: 0, y: 2, w: width, h: height - 4} | ||
| 24 | + w.drawBody(p.sub(body)) | ||
| 25 | + rule := p.sub(rect{x: 0, y: height - 2, w: width, h: 1}) | ||
| 26 | + rule.hline(0, 0, width, '─', stRule) | ||
| 27 | + if w.problem != "" { | ||
| 28 | + rule.textLimited(1, 0, width-2, " ⚠️ "+w.problem+" ", stError) | ||
| 29 | + } | ||
| 30 | + w.drawStatus(p.sub(rect{x: 0, y: height - 1, w: width, h: 1})) | ||
| 31 | + w.screen.Show() | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +func (w *initWin) drawHeader(p painter) { | ||
| 35 | + p.fill(' ', stBar) | ||
| 36 | + p.textLimited(0, 0, p.width(), w.heading(), stBar) | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +func (w *initWin) drawStatus(p painter) { | ||
| 40 | + p.fill(' ', stBar) | ||
| 41 | + keys := " ↑↓ choose · Enter next · Esc back · PgUp/PgDn preview · Ctrl-C quit " | ||
| 42 | + switch { | ||
| 43 | + case w.confirm: | ||
| 44 | + keys = " Enter write the file · Esc back · PgUp/PgDn preview · Ctrl-C quit " | ||
| 45 | + case w.current().Multiline: | ||
| 46 | + keys = " type · ←→↑↓ move · Enter new line · Ctrl-D done · Esc back · PgUp/PgDn preview · Ctrl-C quit " | ||
| 47 | + case w.current().Kind == elicit.Text: | ||
| 48 | + keys = " type · ←→ move · Enter next · Ctrl-U clear · Esc back · PgUp/PgDn preview · Ctrl-C quit " | ||
| 49 | + } | ||
| 50 | + if p.width() < previewMinWidth { | ||
| 51 | + keys = strings.Replace(keys, " · Ctrl-C", " · Tab preview · Ctrl-C", 1) | ||
| 52 | + } | ||
| 53 | + p.textLimited(0, 0, p.width(), keys, stBar) | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +// drawBody lays out the three panes: steps | question | preview. | ||
| 57 | +func (w *initWin) drawBody(p painter) { | ||
| 58 | + stepsW := 22 | ||
| 59 | + w.drawSteps(p.sub(rect{x: 0, y: 0, w: stepsW, h: p.height()})) | ||
| 60 | + for y := range p.height() { | ||
| 61 | + p.set(stepsW, y, '│', stRule) | ||
| 62 | + } | ||
| 63 | + rest := rect{x: stepsW + 1, y: 0, w: p.width() - stepsW - 1, h: p.height()} | ||
| 64 | + if p.width() < previewMinWidth { | ||
| 65 | + if w.preview { | ||
| 66 | + w.drawPreview(p.sub(rest)) | ||
| 67 | + } else { | ||
| 68 | + w.drawQuestion(p.sub(rest)) | ||
| 69 | + } | ||
| 70 | + return | ||
| 71 | + } | ||
| 72 | + qw := rest.w * 2 / 5 | ||
| 73 | + w.drawQuestion(p.sub(rect{x: rest.x, y: 0, w: qw, h: rest.h})) | ||
| 74 | + for y := range p.height() { | ||
| 75 | + p.set(rest.x+qw, y, '│', stRule) | ||
| 76 | + } | ||
| 77 | + w.drawPreview(p.sub(rect{x: rest.x + qw + 1, y: 0, w: rest.w - qw - 1, h: rest.h})) | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +func (w *initWin) drawSteps(p painter) { | ||
| 81 | + for i, st := range w.steps() { | ||
| 82 | + mark, style := "·", stNotice | ||
| 83 | + switch { | ||
| 84 | + case !w.confirm && i == w.cursor: | ||
| 85 | + mark, style = "▸", stPrompt | ||
| 86 | + case st.Value != "": | ||
| 87 | + mark, style = "✓", stBody | ||
| 88 | + } | ||
| 89 | + line := fmt.Sprintf(" %s %-9s", mark, st.Title) | ||
| 90 | + x := p.text(0, i, line, style) | ||
| 91 | + if st.Value != "" && (w.confirm || i != w.cursor) { | ||
| 92 | + p.textLimited(x+1, i, p.width()-x-1, shortModel(st.Value), stNotice) | ||
| 93 | + } | ||
| 94 | + } | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +// drawQuestion draws the middle pane: the confirmation, or the current | ||
| 98 | +// step's prompt and its answer being given. | ||
| 99 | +func (w *initWin) drawQuestion(p painter) { | ||
| 100 | + if w.confirm { | ||
| 101 | + w.drawReady(p) | ||
| 102 | + return | ||
| 103 | + } | ||
| 104 | + st := w.current() | ||
| 105 | + p.textLimited(1, 0, p.width()-2, st.Prompt, stLabel) | ||
| 106 | + switch { | ||
| 107 | + case st.Multiline: | ||
| 108 | + w.drawLines(p, st) | ||
| 109 | + case st.Kind == elicit.Text: | ||
| 110 | + w.drawField(p, st) | ||
| 111 | + default: | ||
| 112 | + w.drawOptions(p, st) | ||
| 113 | + } | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +// drawReady is the confirmation: every question answered, the file ready. | ||
| 117 | +func (w *initWin) drawReady(p painter) { | ||
| 118 | + p.textLimited(1, 0, p.width()-2, "Ready to write "+w.target(), stLabel) | ||
| 119 | + p.textLimited(1, 2, p.width()-2, "Every question is answered: the file", stBody) | ||
| 120 | + p.textLimited(1, 3, p.width()-2, "on the right is what will be written.", stBody) | ||
| 121 | + p.textLimited(1, 5, p.width()-2, "Enter writes it; Esc goes back.", stNotice) | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +// drawField draws a one-line text answer with its caret, and what leaving | ||
| 125 | +// it empty gives. | ||
| 126 | +func (w *initWin) drawField(p painter, st agentinit.Step) { | ||
| 127 | + f := w.text[st.Key] | ||
| 128 | + if f == nil { | ||
| 129 | + f = newField("") | ||
| 130 | + } | ||
| 131 | + // The text before the caret, then the rest: the cursor goes between. | ||
| 132 | + x := p.text(1, 2, "› "+string(f.runes[:f.caret]), stBody) | ||
| 133 | + p.text(x, 2, string(f.runes[f.caret:]), stBody) | ||
| 134 | + p.showCursor(x, 2) | ||
| 135 | + switch { | ||
| 136 | + case st.Optional: | ||
| 137 | + p.textLimited(1, 4, p.width()-2, "leave empty for none", stNotice) | ||
| 138 | + case st.Default != "": | ||
| 139 | + p.textLimited(1, 4, p.width()-2, "default: "+st.Default, stNotice) | ||
| 140 | + } | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +// drawOptions draws a choice step's options, scrolled around the highlighted | ||
| 144 | +// one, and that option's detail under the list. | ||
| 145 | +func (w *initWin) drawOptions(p painter, st agentinit.Step) { | ||
| 146 | + p.showCursor(-1, -1) | ||
| 147 | + listH := max(p.height()-6, 3) | ||
| 148 | + sel := w.sel[st.Key] | ||
| 149 | + top := min(max(sel-listH/2, 0), max(len(st.Options)-listH, 0)) | ||
| 150 | + for row := 0; row < listH && top+row < len(st.Options); row++ { | ||
| 151 | + label, style := optionLine(st, top+row, sel) | ||
| 152 | + p.textLimited(1, 2+row, p.width()-2, padTo(label, p.width()-2), style) | ||
| 153 | + } | ||
| 154 | + drawDetail(p, optionDetail(st, st.Options[sel]), 3+min(listH, len(st.Options))) | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +// drawDetail draws the highlighted option's detail from line y, wrapped, cut | ||
| 158 | +// at the bottom of the pane. | ||
| 159 | +func drawDetail(p painter, detail string, y int) { | ||
| 160 | + if detail == "" { | ||
| 161 | + return | ||
| 162 | + } | ||
| 163 | + for i, line := range wrap(detail, p.width()-2) { | ||
| 164 | + if y+i < p.height() { | ||
| 165 | + p.textLimited(1, y+i, p.width()-2, line, stNotice) | ||
| 166 | + } | ||
| 167 | + } | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +// optionLine is how option i is listed: its label, "(default)" after the | ||
| 171 | +// default, and a ▸ in the highlight's style when it is the one selected. | ||
| 172 | +func optionLine(st agentinit.Step, i, sel int) (string, tcell.Style) { | ||
| 173 | + o := st.Options[i] | ||
| 174 | + label := " " + optionLabel(st, o) | ||
| 175 | + if o.Value == st.Default { | ||
| 176 | + label += " (default)" | ||
| 177 | + } | ||
| 178 | + if i == sel { | ||
| 179 | + return "▸" + label[1:], stPick | ||
| 180 | + } | ||
| 181 | + return label, stBody | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +// drawLines draws a multi-line answer (mm skillcreate's text), scrolled so | ||
| 185 | +// the caret's line is visible; a line wider than the column is cut. | ||
| 186 | +func (w *initWin) drawLines(p painter, st agentinit.Step) { | ||
| 187 | + f := w.text[st.Key] | ||
| 188 | + if f == nil { | ||
| 189 | + f = newField("") | ||
| 190 | + } | ||
| 191 | + lines := strings.Split(f.String(), "\n") | ||
| 192 | + line, col := f.lineAt() | ||
| 193 | + height := max(p.height()-3, 1) | ||
| 194 | + top := max(line-height+1, 0) | ||
| 195 | + for i := 0; i < height && top+i < len(lines); i++ { | ||
| 196 | + p.textLimited(1, 2+i, p.width()-2, "› "+lines[top+i], stBody) | ||
| 197 | + } | ||
| 198 | + p.showCursor(min(3+col, p.width()-2), 2+line-top) | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +// optionLabel is how an option is listed. A model is listed by the | ||
| 202 | +// header's short name: its identifier is an address of seventy characters, | ||
| 203 | +// cut by the column before the part that tells two models apart. | ||
| 204 | +func optionLabel(st agentinit.Step, o agentinit.Option) string { | ||
| 205 | + if st.Key == "model" { | ||
| 206 | + return shortModel(o.Label) | ||
| 207 | + } | ||
| 208 | + return o.Label | ||
| 209 | +} | ||
| 210 | + | ||
| 211 | +// optionDetail is the line under the list for the highlighted option. For a | ||
| 212 | +// model it is the full identifier: two short names can be the same, and the | ||
| 213 | +// identifier is what the file will hold. | ||
| 214 | +func optionDetail(st agentinit.Step, o agentinit.Option) string { | ||
| 215 | + if st.Key == "model" { | ||
| 216 | + if o.Detail == "" { | ||
| 217 | + return o.Value | ||
| 218 | + } | ||
| 219 | + return o.Value + " — " + o.Detail | ||
| 220 | + } | ||
| 221 | + return o.Detail | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +// padTo pads s with spaces to width runes. | ||
| 225 | +func padTo(s string, width int) string { | ||
| 226 | + if n := len([]rune(s)); n < width { | ||
| 227 | + return s + strings.Repeat(" ", width-n) | ||
| 228 | + } | ||
| 229 | + return s | ||
| 230 | +} | ||
| 231 | + | ||
| 232 | +// drawPreview shows the file as it would be written with the highlighted | ||
| 233 | +// choice; comments dim, keys plain. | ||
| 234 | +func (w *initWin) drawPreview(p painter) { | ||
| 235 | + key, candidate := "", "" | ||
| 236 | + if !w.confirm { | ||
| 237 | + st := w.current() | ||
| 238 | + key, candidate = st.Key, w.candidate(st) | ||
| 239 | + } | ||
| 240 | + lines := strings.Split(w.flow.Preview(key, candidate), "\n") | ||
| 241 | + w.scroll = min(w.scroll, max(len(lines)-p.height(), 0)) | ||
| 242 | + for y := 0; y < p.height() && w.scroll+y < len(lines); y++ { | ||
| 243 | + line := lines[w.scroll+y] | ||
| 244 | + style := stBody | ||
| 245 | + if strings.HasPrefix(strings.TrimSpace(line), "#") { | ||
| 246 | + style = stNotice | ||
| 247 | + } | ||
| 248 | + p.textLimited(1, y, p.width()-1, line, style) | ||
| 249 | + } | ||
| 250 | +} | ||
added
internal/tui/initwin_field.go +90 -0 | new file mode 100644 | ||
| @@ -0,0 +1,90 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "strings" | |
| 5 | + | |
| 6 | + "github.com/gdamore/tcell/v2" | |
| 7 | +) | |
| 8 | + | |
| 9 | +// field is a one-line text being typed — an endpoint, a variable name, a | |
| 10 | +// file name — with its caret, a rune index: the arrows move it, typing and | |
| 11 | +// deleting happen there (until ticket 177's questions, only appending and | |
| 12 | +// Backspace at the end were possible). | |
| 13 | +// | |
| 14 | +// f := newField("agent.yaml") // caret at the end | |
| 15 | +// f.key(tcell.NewEventKey(tcell.KeyHome, 0, tcell.ModNone)) | |
| 16 | +// f.key(tcell.NewEventKey(tcell.KeyRune, 'm', tcell.ModNone)) // "magent.yaml" | |
| 17 | +type field struct { | |
| 18 | + runes []rune | |
| 19 | + caret int | |
| 20 | +} | |
| 21 | + | |
| 22 | +func newField(s string) *field { | |
| 23 | + r := []rune(s) | |
| 24 | + return &field{runes: r, caret: len(r)} | |
| 25 | +} | |
| 26 | + | |
| 27 | +func (f *field) String() string { return string(f.runes) } | |
| 28 | + | |
| 29 | +// insert puts r at the caret. | |
| 30 | +func (f *field) insert(r rune) { | |
| 31 | + f.runes = append(f.runes[:f.caret], append([]rune{r}, f.runes[f.caret:]...)...) | |
| 32 | + f.caret++ | |
| 33 | +} | |
| 34 | + | |
| 35 | +// lineAt is the line of the caret (0-based) and the caret's column in it. | |
| 36 | +func (f *field) lineAt() (line, col int) { | |
| 37 | + for _, r := range f.runes[:f.caret] { | |
| 38 | + col++ | |
| 39 | + if r == '\n' { | |
| 40 | + line, col = line+1, 0 | |
| 41 | + } | |
| 42 | + } | |
| 43 | + return line, col | |
| 44 | +} | |
| 45 | + | |
| 46 | +// moveLine moves the caret to the line above (-1) or below (+1), at the | |
| 47 | +// same column or the end of that line when it is shorter. | |
| 48 | +func (f *field) moveLine(delta int) { | |
| 49 | + line, col := f.lineAt() | |
| 50 | + lines := strings.Split(string(f.runes), "\n") | |
| 51 | + target := line + delta | |
| 52 | + if target < 0 || target >= len(lines) { | |
| 53 | + return | |
| 54 | + } | |
| 55 | + caret := 0 | |
| 56 | + for i := range target { | |
| 57 | + caret += len([]rune(lines[i])) + 1 | |
| 58 | + } | |
| 59 | + f.caret = caret + min(col, len([]rune(lines[target]))) | |
| 60 | +} | |
| 61 | + | |
| 62 | +// key edits the text; it reports whether the key was an editing key. | |
| 63 | +func (f *field) key(ev *tcell.EventKey) bool { | |
| 64 | + switch ev.Key() { | |
| 65 | + case tcell.KeyRune: | |
| 66 | + f.insert(ev.Rune()) | |
| 67 | + case tcell.KeyBackspace, tcell.KeyBackspace2: | |
| 68 | + if f.caret > 0 { | |
| 69 | + f.runes = append(f.runes[:f.caret-1], f.runes[f.caret:]...) | |
| 70 | + f.caret-- | |
| 71 | + } | |
| 72 | + case tcell.KeyDelete: | |
| 73 | + if f.caret < len(f.runes) { | |
| 74 | + f.runes = append(f.runes[:f.caret], f.runes[f.caret+1:]...) | |
| 75 | + } | |
| 76 | + case tcell.KeyLeft: | |
| 77 | + f.caret = max(f.caret-1, 0) | |
| 78 | + case tcell.KeyRight: | |
| 79 | + f.caret = min(f.caret+1, len(f.runes)) | |
| 80 | + case tcell.KeyHome, tcell.KeyCtrlA: | |
| 81 | + f.caret = 0 | |
| 82 | + case tcell.KeyEnd, tcell.KeyCtrlE: | |
| 83 | + f.caret = len(f.runes) | |
| 84 | + case tcell.KeyCtrlU: | |
| 85 | + f.runes, f.caret = nil, 0 | |
| 86 | + default: | |
| 87 | + return false | |
| 88 | + } | |
| 89 | + return true | |
| 90 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,90 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "strings" | ||
| 5 | + | ||
| 6 | + "github.com/gdamore/tcell/v2" | ||
| 7 | +) | ||
| 8 | + | ||
| 9 | +// field is a one-line text being typed — an endpoint, a variable name, a | ||
| 10 | +// file name — with its caret, a rune index: the arrows move it, typing and | ||
| 11 | +// deleting happen there (until ticket 177's questions, only appending and | ||
| 12 | +// Backspace at the end were possible). | ||
| 13 | +// | ||
| 14 | +// f := newField("agent.yaml") // caret at the end | ||
| 15 | +// f.key(tcell.NewEventKey(tcell.KeyHome, 0, tcell.ModNone)) | ||
| 16 | +// f.key(tcell.NewEventKey(tcell.KeyRune, 'm', tcell.ModNone)) // "magent.yaml" | ||
| 17 | +type field struct { | ||
| 18 | + runes []rune | ||
| 19 | + caret int | ||
| 20 | +} | ||
| 21 | + | ||
| 22 | +func newField(s string) *field { | ||
| 23 | + r := []rune(s) | ||
| 24 | + return &field{runes: r, caret: len(r)} | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +func (f *field) String() string { return string(f.runes) } | ||
| 28 | + | ||
| 29 | +// insert puts r at the caret. | ||
| 30 | +func (f *field) insert(r rune) { | ||
| 31 | + f.runes = append(f.runes[:f.caret], append([]rune{r}, f.runes[f.caret:]...)...) | ||
| 32 | + f.caret++ | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +// lineAt is the line of the caret (0-based) and the caret's column in it. | ||
| 36 | +func (f *field) lineAt() (line, col int) { | ||
| 37 | + for _, r := range f.runes[:f.caret] { | ||
| 38 | + col++ | ||
| 39 | + if r == '\n' { | ||
| 40 | + line, col = line+1, 0 | ||
| 41 | + } | ||
| 42 | + } | ||
| 43 | + return line, col | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +// moveLine moves the caret to the line above (-1) or below (+1), at the | ||
| 47 | +// same column or the end of that line when it is shorter. | ||
| 48 | +func (f *field) moveLine(delta int) { | ||
| 49 | + line, col := f.lineAt() | ||
| 50 | + lines := strings.Split(string(f.runes), "\n") | ||
| 51 | + target := line + delta | ||
| 52 | + if target < 0 || target >= len(lines) { | ||
| 53 | + return | ||
| 54 | + } | ||
| 55 | + caret := 0 | ||
| 56 | + for i := range target { | ||
| 57 | + caret += len([]rune(lines[i])) + 1 | ||
| 58 | + } | ||
| 59 | + f.caret = caret + min(col, len([]rune(lines[target]))) | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +// key edits the text; it reports whether the key was an editing key. | ||
| 63 | +func (f *field) key(ev *tcell.EventKey) bool { | ||
| 64 | + switch ev.Key() { | ||
| 65 | + case tcell.KeyRune: | ||
| 66 | + f.insert(ev.Rune()) | ||
| 67 | + case tcell.KeyBackspace, tcell.KeyBackspace2: | ||
| 68 | + if f.caret > 0 { | ||
| 69 | + f.runes = append(f.runes[:f.caret-1], f.runes[f.caret:]...) | ||
| 70 | + f.caret-- | ||
| 71 | + } | ||
| 72 | + case tcell.KeyDelete: | ||
| 73 | + if f.caret < len(f.runes) { | ||
| 74 | + f.runes = append(f.runes[:f.caret], f.runes[f.caret+1:]...) | ||
| 75 | + } | ||
| 76 | + case tcell.KeyLeft: | ||
| 77 | + f.caret = max(f.caret-1, 0) | ||
| 78 | + case tcell.KeyRight: | ||
| 79 | + f.caret = min(f.caret+1, len(f.runes)) | ||
| 80 | + case tcell.KeyHome, tcell.KeyCtrlA: | ||
| 81 | + f.caret = 0 | ||
| 82 | + case tcell.KeyEnd, tcell.KeyCtrlE: | ||
| 83 | + f.caret = len(f.runes) | ||
| 84 | + case tcell.KeyCtrlU: | ||
| 85 | + f.runes, f.caret = nil, 0 | ||
| 86 | + default: | ||
| 87 | + return false | ||
| 88 | + } | ||
| 89 | + return true | ||
| 90 | +} | ||
added
internal/tui/initwin_keys.go +121 -0 | new file mode 100644 | ||
| @@ -0,0 +1,121 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "mm/internal/agentinit" | |
| 5 | + "mm/internal/elicit" | |
| 6 | + | |
| 7 | + "github.com/gdamore/tcell/v2" | |
| 8 | +) | |
| 9 | + | |
| 10 | +// handleKey is the window's keymap: the keys that mean the same thing on | |
| 11 | +// every step first, then the confirmation's Enter, then the step's own keys. | |
| 12 | +func (w *initWin) handleKey(ev *tcell.EventKey) { | |
| 13 | + w.problem = "" | |
| 14 | + if act, ok := windowKeys[ev.Key()]; ok { | |
| 15 | + act(w) | |
| 16 | + return | |
| 17 | + } | |
| 18 | + switch { | |
| 19 | + case w.confirm: | |
| 20 | + if ev.Key() == tcell.KeyEnter { | |
| 21 | + w.result = 1 | |
| 22 | + } | |
| 23 | + case w.current().Kind == elicit.Text: | |
| 24 | + w.textKey(w.current(), ev) | |
| 25 | + default: | |
| 26 | + w.choiceKey(w.current(), ev) | |
| 27 | + } | |
| 28 | +} | |
| 29 | + | |
| 30 | +// windowKeys are the keys that do the same thing whatever the step: quit, | |
| 31 | +// the preview pane on a narrow screen, its scrolling, and going back. | |
| 32 | +var windowKeys = map[tcell.Key]func(*initWin){ | |
| 33 | + tcell.KeyCtrlC: func(w *initWin) { w.result = -1 }, | |
| 34 | + tcell.KeyTab: func(w *initWin) { w.preview = !w.preview }, | |
| 35 | + tcell.KeyPgUp: func(w *initWin) { w.scroll = max(w.scroll-10, 0) }, | |
| 36 | + tcell.KeyPgDn: func(w *initWin) { w.scroll += 10 }, | |
| 37 | + tcell.KeyEscape: (*initWin).back, | |
| 38 | +} | |
| 39 | + | |
| 40 | +// choiceKey moves through a choice step's options, answers it with Enter, | |
| 41 | +// and a yes/no step with y or n. | |
| 42 | +func (w *initWin) choiceKey(st agentinit.Step, ev *tcell.EventKey) { | |
| 43 | + n := len(st.Options) | |
| 44 | + switch ev.Key() { | |
| 45 | + case tcell.KeyUp: | |
| 46 | + w.sel[st.Key] = (w.sel[st.Key] + n - 1) % n | |
| 47 | + case tcell.KeyDown: | |
| 48 | + w.sel[st.Key] = (w.sel[st.Key] + 1) % n | |
| 49 | + case tcell.KeyHome: | |
| 50 | + w.sel[st.Key] = 0 | |
| 51 | + case tcell.KeyEnd: | |
| 52 | + w.sel[st.Key] = n - 1 | |
| 53 | + case tcell.KeyEnter: | |
| 54 | + w.answer(st) | |
| 55 | + case tcell.KeyRune: | |
| 56 | + w.yesNoKey(st, ev.Rune()) | |
| 57 | + } | |
| 58 | +} | |
| 59 | + | |
| 60 | +// yesNoKey answers a yes/no step with y or n. | |
| 61 | +func (w *initWin) yesNoKey(st agentinit.Step, r rune) { | |
| 62 | + if st.Kind == elicit.Confirm && (r == 'y' || r == 'n') { | |
| 63 | + w.sel[st.Key] = map[rune]int{'y': 0, 'n': 1}[r] | |
| 64 | + w.answer(st) | |
| 65 | + } | |
| 66 | +} | |
| 67 | + | |
| 68 | +// textKey edits a text step's answer; Enter answers a one-line step, and | |
| 69 | +// Ctrl-D a multi-line one, where Enter is a new line. | |
| 70 | +func (w *initWin) textKey(st agentinit.Step, ev *tcell.EventKey) { | |
| 71 | + f := w.text[st.Key] | |
| 72 | + if f == nil { | |
| 73 | + f = newField("") | |
| 74 | + w.text[st.Key] = f | |
| 75 | + } | |
| 76 | + switch { | |
| 77 | + case st.Multiline && ev.Key() == tcell.KeyCtrlD: | |
| 78 | + w.answer(st) | |
| 79 | + case st.Multiline && ev.Key() == tcell.KeyEnter: | |
| 80 | + f.insert('\n') | |
| 81 | + case st.Multiline && (ev.Key() == tcell.KeyUp || ev.Key() == tcell.KeyDown): | |
| 82 | + f.moveLine(map[tcell.Key]int{tcell.KeyUp: -1, tcell.KeyDown: 1}[ev.Key()]) | |
| 83 | + case ev.Key() == tcell.KeyEnter: | |
| 84 | + w.answer(st) | |
| 85 | + default: | |
| 86 | + f.key(ev) | |
| 87 | + } | |
| 88 | +} | |
| 89 | + | |
| 90 | +// answer records the highlighted choice and moves to the next question. | |
| 91 | +func (w *initWin) answer(st agentinit.Step) { | |
| 92 | + value := w.candidate(st) | |
| 93 | + if value == "" { | |
| 94 | + value = st.Default | |
| 95 | + } | |
| 96 | + if err := w.flow.Set(st.Key, value); err != nil { | |
| 97 | + w.problem = err.Error() | |
| 98 | + return | |
| 99 | + } | |
| 100 | + w.scroll = 0 | |
| 101 | + w.toFirstPending() | |
| 102 | +} | |
| 103 | + | |
| 104 | +// back is Esc: the previous question the user answered becomes the current | |
| 105 | +// one again — its answer taken back; questions answered by flags are | |
| 106 | +// skipped. | |
| 107 | +func (w *initWin) back() { | |
| 108 | + steps := w.steps() | |
| 109 | + from := w.cursor | |
| 110 | + if w.confirm { | |
| 111 | + from = len(steps) | |
| 112 | + } | |
| 113 | + for i := from - 1; i >= 0; i-- { | |
| 114 | + if !steps[i].Given { | |
| 115 | + w.flow.Unset(steps[i].Key) | |
| 116 | + w.cursor, w.confirm = i, false | |
| 117 | + w.initSelection(w.flow.Step(steps[i].Key)) | |
| 118 | + return | |
| 119 | + } | |
| 120 | + } | |
| 121 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,121 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "mm/internal/agentinit" | ||
| 5 | + "mm/internal/elicit" | ||
| 6 | + | ||
| 7 | + "github.com/gdamore/tcell/v2" | ||
| 8 | +) | ||
| 9 | + | ||
| 10 | +// handleKey is the window's keymap: the keys that mean the same thing on | ||
| 11 | +// every step first, then the confirmation's Enter, then the step's own keys. | ||
| 12 | +func (w *initWin) handleKey(ev *tcell.EventKey) { | ||
| 13 | + w.problem = "" | ||
| 14 | + if act, ok := windowKeys[ev.Key()]; ok { | ||
| 15 | + act(w) | ||
| 16 | + return | ||
| 17 | + } | ||
| 18 | + switch { | ||
| 19 | + case w.confirm: | ||
| 20 | + if ev.Key() == tcell.KeyEnter { | ||
| 21 | + w.result = 1 | ||
| 22 | + } | ||
| 23 | + case w.current().Kind == elicit.Text: | ||
| 24 | + w.textKey(w.current(), ev) | ||
| 25 | + default: | ||
| 26 | + w.choiceKey(w.current(), ev) | ||
| 27 | + } | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +// windowKeys are the keys that do the same thing whatever the step: quit, | ||
| 31 | +// the preview pane on a narrow screen, its scrolling, and going back. | ||
| 32 | +var windowKeys = map[tcell.Key]func(*initWin){ | ||
| 33 | + tcell.KeyCtrlC: func(w *initWin) { w.result = -1 }, | ||
| 34 | + tcell.KeyTab: func(w *initWin) { w.preview = !w.preview }, | ||
| 35 | + tcell.KeyPgUp: func(w *initWin) { w.scroll = max(w.scroll-10, 0) }, | ||
| 36 | + tcell.KeyPgDn: func(w *initWin) { w.scroll += 10 }, | ||
| 37 | + tcell.KeyEscape: (*initWin).back, | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +// choiceKey moves through a choice step's options, answers it with Enter, | ||
| 41 | +// and a yes/no step with y or n. | ||
| 42 | +func (w *initWin) choiceKey(st agentinit.Step, ev *tcell.EventKey) { | ||
| 43 | + n := len(st.Options) | ||
| 44 | + switch ev.Key() { | ||
| 45 | + case tcell.KeyUp: | ||
| 46 | + w.sel[st.Key] = (w.sel[st.Key] + n - 1) % n | ||
| 47 | + case tcell.KeyDown: | ||
| 48 | + w.sel[st.Key] = (w.sel[st.Key] + 1) % n | ||
| 49 | + case tcell.KeyHome: | ||
| 50 | + w.sel[st.Key] = 0 | ||
| 51 | + case tcell.KeyEnd: | ||
| 52 | + w.sel[st.Key] = n - 1 | ||
| 53 | + case tcell.KeyEnter: | ||
| 54 | + w.answer(st) | ||
| 55 | + case tcell.KeyRune: | ||
| 56 | + w.yesNoKey(st, ev.Rune()) | ||
| 57 | + } | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +// yesNoKey answers a yes/no step with y or n. | ||
| 61 | +func (w *initWin) yesNoKey(st agentinit.Step, r rune) { | ||
| 62 | + if st.Kind == elicit.Confirm && (r == 'y' || r == 'n') { | ||
| 63 | + w.sel[st.Key] = map[rune]int{'y': 0, 'n': 1}[r] | ||
| 64 | + w.answer(st) | ||
| 65 | + } | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +// textKey edits a text step's answer; Enter answers a one-line step, and | ||
| 69 | +// Ctrl-D a multi-line one, where Enter is a new line. | ||
| 70 | +func (w *initWin) textKey(st agentinit.Step, ev *tcell.EventKey) { | ||
| 71 | + f := w.text[st.Key] | ||
| 72 | + if f == nil { | ||
| 73 | + f = newField("") | ||
| 74 | + w.text[st.Key] = f | ||
| 75 | + } | ||
| 76 | + switch { | ||
| 77 | + case st.Multiline && ev.Key() == tcell.KeyCtrlD: | ||
| 78 | + w.answer(st) | ||
| 79 | + case st.Multiline && ev.Key() == tcell.KeyEnter: | ||
| 80 | + f.insert('\n') | ||
| 81 | + case st.Multiline && (ev.Key() == tcell.KeyUp || ev.Key() == tcell.KeyDown): | ||
| 82 | + f.moveLine(map[tcell.Key]int{tcell.KeyUp: -1, tcell.KeyDown: 1}[ev.Key()]) | ||
| 83 | + case ev.Key() == tcell.KeyEnter: | ||
| 84 | + w.answer(st) | ||
| 85 | + default: | ||
| 86 | + f.key(ev) | ||
| 87 | + } | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +// answer records the highlighted choice and moves to the next question. | ||
| 91 | +func (w *initWin) answer(st agentinit.Step) { | ||
| 92 | + value := w.candidate(st) | ||
| 93 | + if value == "" { | ||
| 94 | + value = st.Default | ||
| 95 | + } | ||
| 96 | + if err := w.flow.Set(st.Key, value); err != nil { | ||
| 97 | + w.problem = err.Error() | ||
| 98 | + return | ||
| 99 | + } | ||
| 100 | + w.scroll = 0 | ||
| 101 | + w.toFirstPending() | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +// back is Esc: the previous question the user answered becomes the current | ||
| 105 | +// one again — its answer taken back; questions answered by flags are | ||
| 106 | +// skipped. | ||
| 107 | +func (w *initWin) back() { | ||
| 108 | + steps := w.steps() | ||
| 109 | + from := w.cursor | ||
| 110 | + if w.confirm { | ||
| 111 | + from = len(steps) | ||
| 112 | + } | ||
| 113 | + for i := from - 1; i >= 0; i-- { | ||
| 114 | + if !steps[i].Given { | ||
| 115 | + w.flow.Unset(steps[i].Key) | ||
| 116 | + w.cursor, w.confirm = i, false | ||
| 117 | + w.initSelection(w.flow.Step(steps[i].Key)) | ||
| 118 | + return | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | +} | ||
modified
internal/tui/markdown.go +112 -420 | @@ -3,7 +3,6 @@ package tui | ||
| 3 | 3 | import ( |
| 4 | 4 | "strconv" |
| 5 | 5 | "strings" |
| 6 | - "unicode" | |
| 7 | 6 | ) |
| 8 | 7 | |
| 9 | 8 | // Markdown in the window (experiment, branch experiment/tui-markdown): an |
| @@ -56,327 +55,142 @@ func spanLine(spans []Span) Line { | ||
| 56 | 55 | return Line{Text: spansText(spans), Spans: spans} |
| 57 | 56 | } |
| 58 | 57 | |
| 59 | -// --- inline ------------------------------------------------------------------ | |
| 58 | +// --- blocks ------------------------------------------------------------------ | |
| 60 | 59 | |
| 61 | -// inline parses one line of Markdown text into spans, all at base style. | |
| 60 | +// markdown lays a closed answer out at width: blocks, then inline spans, | |
| 61 | +// wrapped. Every line is indented like the raw body. | |
| 62 | 62 | // |
| 63 | -// inline("a **b** `c`", styleBody) // "a " · "b" bold · " " · "c" code | |
| 64 | -func inline(text string, base styleKind) []Span { | |
| 65 | - var out []Span | |
| 66 | - var plain strings.Builder | |
| 67 | - flush := func() { | |
| 68 | - if plain.Len() > 0 { | |
| 69 | - out = append(out, Span{Text: plain.String(), Style: base}) | |
| 70 | - plain.Reset() | |
| 71 | - } | |
| 72 | - } | |
| 73 | - add := func(spans ...Span) { | |
| 74 | - flush() | |
| 75 | - out = append(out, spans...) | |
| 76 | - } | |
| 77 | - r := []rune(text) | |
| 78 | - for i := 0; i < len(r); { | |
| 79 | - c := r[i] | |
| 80 | - switch { | |
| 81 | - case c == '\\' && i+1 < len(r) && isMarkdownPunct(r[i+1]): | |
| 82 | - plain.WriteRune(r[i+1]) | |
| 83 | - i += 2 | |
| 84 | - continue | |
| 85 | - case c == '`': | |
| 86 | - if end, n := closingTicks(r, i); end > 0 { | |
| 87 | - code := strings.TrimSpace(string(r[i+n : end])) | |
| 88 | - add(Span{Text: code, Style: styleCode}) | |
| 89 | - i = end + n | |
| 90 | - continue | |
| 91 | - } | |
| 92 | - case c == '[': | |
| 93 | - if label, url, next, ok := link(r, i); ok { | |
| 94 | - spans := inline(label, base) | |
| 95 | - for k := range spans { | |
| 96 | - spans[k].Attr |= attrUnderline | |
| 97 | - } | |
| 98 | - if url != "" && url != label { | |
| 99 | - spans = append(spans, Span{Text: " (" + url + ")", Style: base, Attr: attrDim}) | |
| 100 | - } | |
| 101 | - add(spans...) | |
| 102 | - i = next | |
| 103 | - continue | |
| 104 | - } | |
| 105 | - case c == '<': | |
| 106 | - if end := strings.IndexRune(string(r[i+1:]), '>'); end > 0 { | |
| 107 | - inner := string(r[i+1 : i+1+end]) | |
| 108 | - if strings.HasPrefix(inner, "http://") || strings.HasPrefix(inner, "https://") { | |
| 109 | - add(Span{Text: inner, Style: base, Attr: attrUnderline}) | |
| 110 | - i += end + 2 | |
| 111 | - continue | |
| 112 | - } | |
| 113 | - } | |
| 114 | - case c == '*' || c == '_' || c == '~': | |
| 115 | - if spans, next, ok := emphasis(r, i, base); ok { | |
| 116 | - add(spans...) | |
| 117 | - i = next | |
| 118 | - continue | |
| 119 | - } | |
| 120 | - } | |
| 121 | - plain.WriteRune(c) | |
| 122 | - i++ | |
| 63 | +// markdown("# Title\n\n- a **b**", 80) // the title, a blank line, "• a b" | |
| 64 | +func markdown(text string, width int) []Line { | |
| 65 | + l := &mdLayout{src: strings.Split(strings.TrimRight(text, "\n"), "\n"), width: width} | |
| 66 | + for i := 0; i < len(l.src); i++ { | |
| 67 | + i = l.block(i) | |
| 123 | 68 | } |
| 124 | - flush() | |
| 125 | - return out | |
| 69 | + return l.out | |
| 126 | 70 | } |
| 127 | 71 | |
| 128 | -// isMarkdownPunct is what a backslash may escape. | |
| 129 | -func isMarkdownPunct(r rune) bool { return strings.ContainsRune("\\`*_{}[]()#+-.!|~<>", r) } | |
| 72 | +// mdLayout is one answer being laid out: its source lines, the width, the | |
| 73 | +// lines drawn so far, and whether the last source line was blank. | |
| 74 | +type mdLayout struct { | |
| 75 | + src []string | |
| 76 | + width int | |
| 77 | + out []Line | |
| 78 | + blank bool | |
| 79 | +} | |
| 130 | 80 | |
| 131 | -// closingTicks finds the run of backticks closing the one at i: the index of | |
| 132 | -// the closing run and the run's length, or 0 when there is none. | |
| 133 | -func closingTicks(r []rune, i int) (int, int) { | |
| 134 | - n := 0 | |
| 135 | - for i+n < len(r) && r[i+n] == '`' { | |
| 136 | - n++ | |
| 81 | +// block lays out the block that starts at source line i and returns the | |
| 82 | +// index of its last line — more than i for a fence or a table. | |
| 83 | +func (l *mdLayout) block(i int) int { | |
| 84 | + trim := strings.TrimSpace(l.src[i]) | |
| 85 | + if trim == "" { | |
| 86 | + l.blankLine() | |
| 87 | + return i | |
| 137 | 88 | } |
| 138 | - for j := i + n; j < len(r); j++ { | |
| 139 | - if r[j] != '`' { | |
| 140 | - continue | |
| 141 | - } | |
| 142 | - m := 0 | |
| 143 | - for j+m < len(r) && r[j+m] == '`' { | |
| 144 | - m++ | |
| 145 | - } | |
| 146 | - if m == n { | |
| 147 | - return j, n | |
| 148 | - } | |
| 149 | - j += m - 1 | |
| 89 | + l.blank = false | |
| 90 | + switch { | |
| 91 | + case isFence(trim): | |
| 92 | + return l.fenceBlock(i, trim) | |
| 93 | + case heading(trim) > 0: | |
| 94 | + l.headingBlock(trim) | |
| 95 | + case isRule(trim): | |
| 96 | + l.emit([]Span{{Text: strings.Repeat("─", max(min(l.width-indent, 60), 1)), Style: styleRule}}) | |
| 97 | + case strings.HasPrefix(trim, ">"): | |
| 98 | + l.quoteBlock(trim) | |
| 99 | + case isTableStart(l.src, i): | |
| 100 | + return l.tableBlock(i) | |
| 101 | + default: | |
| 102 | + l.paragraph(l.src[i]) | |
| 150 | 103 | } |
| 151 | - return 0, n | |
| 104 | + return i | |
| 152 | 105 | } |
| 153 | 106 | |
| 154 | -// link reads [label](url) at i. | |
| 155 | -func link(r []rune, i int) (label, url string, next int, ok bool) { | |
| 156 | - depth := 0 | |
| 157 | - for j := i; j < len(r); j++ { | |
| 158 | - switch r[j] { | |
| 159 | - case '[': | |
| 160 | - depth++ | |
| 161 | - case ']': | |
| 162 | - depth-- | |
| 163 | - if depth == 0 { | |
| 164 | - if j+1 >= len(r) || r[j+1] != '(' { | |
| 165 | - return "", "", 0, false | |
| 166 | - } | |
| 167 | - end := strings.IndexRune(string(r[j+2:]), ')') | |
| 168 | - if end < 0 { | |
| 169 | - return "", "", 0, false | |
| 170 | - } | |
| 171 | - url = strings.TrimSpace(string(r[j+2 : j+2+end])) | |
| 172 | - if k := strings.IndexAny(url, " \t"); k >= 0 { // [x](url "title") | |
| 173 | - url = url[:k] | |
| 174 | - } | |
| 175 | - return string(r[i+1 : j]), url, j + 3 + end, true | |
| 176 | - } | |
| 177 | - } | |
| 178 | - } | |
| 179 | - return "", "", 0, false | |
| 107 | +// emit draws one line of spans, indented like the raw body. | |
| 108 | +func (l *mdLayout) emit(spans []Span) { | |
| 109 | + l.out = append(l.out, spanLine(append([]Span{{Text: pad}}, spans...))) | |
| 180 | 110 | } |
| 181 | 111 | |
| 182 | -// emphasis reads **bold**, *italic*, ***both***, __bold__, _italic_ or | |
| 183 | -// ~~struck~~ at i. An underscore inside a word (snake_case) is not one, and | |
| 184 | -// neither is a marker followed by a space ("2 * 3"). | |
| 185 | -func emphasis(r []rune, i int, base styleKind) ([]Span, int, bool) { | |
| 186 | - c := r[i] | |
| 187 | - n := 0 | |
| 188 | - for i+n < len(r) && r[i+n] == c && n < 3 { | |
| 189 | - n++ | |
| 190 | - } | |
| 191 | - if c == '~' && n != 2 { | |
| 192 | - return nil, 0, false | |
| 193 | - } | |
| 194 | - if c == '_' && i > 0 && isWordRune(r[i-1]) { | |
| 195 | - return nil, 0, false | |
| 196 | - } | |
| 197 | - open := i + n | |
| 198 | - if open >= len(r) || unicode.IsSpace(r[open]) { | |
| 199 | - return nil, 0, false | |
| 200 | - } | |
| 201 | - marker := strings.Repeat(string(c), n) | |
| 202 | - rest := string(r[open:]) | |
| 203 | - for from := 0; ; { | |
| 204 | - at := strings.Index(rest[from:], marker) | |
| 205 | - if at < 0 { | |
| 206 | - return nil, 0, false | |
| 207 | - } | |
| 208 | - at += from | |
| 209 | - inner := []rune(rest[:at]) | |
| 210 | - after := open + len(inner) + n | |
| 211 | - closes := len(inner) > 0 && !unicode.IsSpace(inner[len(inner)-1]) && | |
| 212 | - (after >= len(r) || r[after] != c) && | |
| 213 | - (c != '_' || after >= len(r) || !isWordRune(r[after])) | |
| 214 | - if closes { | |
| 215 | - var a attr | |
| 216 | - switch { | |
| 217 | - case c == '~': | |
| 218 | - a = attrStrike | |
| 219 | - case n == 1: | |
| 220 | - a = attrItalic | |
| 221 | - case n == 2: | |
| 222 | - a = attrBold | |
| 223 | - default: | |
| 224 | - a = attrBold | attrItalic | |
| 225 | - } | |
| 226 | - spans := inline(string(inner), base) | |
| 227 | - for k := range spans { | |
| 228 | - spans[k].Attr |= a | |
| 229 | - } | |
| 230 | - return spans, after, true | |
| 231 | - } | |
| 232 | - from = at + len(marker) | |
| 112 | +// wrapped draws spans wrapped to the width, first before the first line and | |
| 113 | +// rest before the others. | |
| 114 | +func (l *mdLayout) wrapped(spans []Span, first, rest []Span) { | |
| 115 | + for _, line := range wrapSpans(spans, max(l.width-indent, 1), first, rest) { | |
| 116 | + l.emit(line) | |
| 233 | 117 | } |
| 234 | 118 | } |
| 235 | 119 | |
| 236 | -func isWordRune(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) } | |
| 120 | +// blankLine keeps one blank line between blocks: never two in a row, never | |
| 121 | +// one at the top. | |
| 122 | +func (l *mdLayout) blankLine() { | |
| 123 | + if !l.blank && len(l.out) > 0 { | |
| 124 | + l.out = append(l.out, Line{}) | |
| 125 | + } | |
| 126 | + l.blank = true | |
| 127 | +} | |
| 237 | 128 | |
| 238 | -// --- wrapping spans -------------------------------------------------------------- | |
| 129 | +// isFence reports the opening of a fenced code block. | |
| 130 | +func isFence(trim string) bool { | |
| 131 | + return strings.HasPrefix(trim, "```") || strings.HasPrefix(trim, "~~~") | |
| 132 | +} | |
| 239 | 133 | |
| 240 | -// wrapSpans wraps spans to width runes, at spaces where it can, the way wrap | |
| 241 | -// does for plain text. first goes before the first line, rest before the | |
| 242 | -// others — a list item's bullet, then its hanging indent. | |
| 243 | -func wrapSpans(spans []Span, width int, first, rest []Span) [][]Span { | |
| 244 | - type cell struct { | |
| 245 | - r rune | |
| 246 | - at int // index of the span it came from | |
| 134 | +// fenceBlock draws a fenced code block as written, its language dimmed above | |
| 135 | +// it, and returns the index of its closing fence (or the end of the text). | |
| 136 | +func (l *mdLayout) fenceBlock(i int, trim string) int { | |
| 137 | + fence := trim[:3] | |
| 138 | + if lang := strings.TrimSpace(strings.TrimLeft(trim, fence[:1])); lang != "" { | |
| 139 | + l.emit([]Span{{Text: lang, Style: styleCode, Attr: attrDim}}) | |
| 247 | 140 | } |
| 248 | - var cells []cell | |
| 249 | - for k, s := range spans { | |
| 250 | - for _, r := range s.Text { | |
| 251 | - cells = append(cells, cell{r, k}) | |
| 252 | - } | |
| 253 | - } | |
| 254 | - build := func(prefix []Span, part []cell) []Span { | |
| 255 | - line := append([]Span(nil), prefix...) | |
| 256 | - for i := 0; i < len(part); { | |
| 257 | - j := i | |
| 258 | - for j < len(part) && part[j].at == part[i].at { | |
| 259 | - j++ | |
| 260 | - } | |
| 261 | - var b strings.Builder | |
| 262 | - for _, c := range part[i:j] { | |
| 263 | - b.WriteRune(c.r) | |
| 264 | - } | |
| 265 | - src := spans[part[i].at] | |
| 266 | - line = append(line, Span{Text: b.String(), Style: src.Style, Attr: src.Attr}) | |
| 267 | - i = j | |
| 268 | - } | |
| 269 | - return line | |
| 141 | + for i++; i < len(l.src) && !strings.HasPrefix(strings.TrimSpace(l.src[i]), fence); i++ { | |
| 142 | + l.out = append(l.out, Line{Text: pad + " " + l.src[i], Style: styleCode}) | |
| 270 | 143 | } |
| 271 | - var out [][]Span | |
| 272 | - prefix := first | |
| 273 | - for { | |
| 274 | - room := max(width-len([]rune(spansText(prefix))), 1) | |
| 275 | - if len(cells) <= room { | |
| 276 | - return append(out, build(prefix, cells)) | |
| 277 | - } | |
| 278 | - runes := make([]rune, len(cells)) | |
| 279 | - for i, c := range cells { | |
| 280 | - runes[i] = c.r | |
| 281 | - } | |
| 282 | - at := breakPoint(runes, room) | |
| 283 | - end := at | |
| 284 | - for end > 0 && cells[end-1].r == ' ' { | |
| 285 | - end-- | |
| 286 | - } | |
| 287 | - out = append(out, build(prefix, cells[:end])) | |
| 288 | - cells = cells[at:] | |
| 289 | - for len(cells) > 0 && cells[0].r == ' ' { | |
| 290 | - cells = cells[1:] | |
| 291 | - } | |
| 292 | - prefix = rest | |
| 293 | - if len(cells) == 0 { | |
| 294 | - return out | |
| 295 | - } | |
| 144 | + return i | |
| 145 | +} | |
| 146 | + | |
| 147 | +// headingBlock draws a heading bold, underlined too at level 1. | |
| 148 | +func (l *mdLayout) headingBlock(trim string) { | |
| 149 | + level := heading(trim) | |
| 150 | + a := attrBold | |
| 151 | + if level == 1 { | |
| 152 | + a |= attrUnderline | |
| 296 | 153 | } |
| 154 | + l.wrapped(withAttr(inline(strings.TrimSpace(strings.TrimRight(trim[level:], "# ")), styleHeading), a), nil, nil) | |
| 297 | 155 | } |
| 298 | 156 | |
| 299 | -// --- blocks ------------------------------------------------------------------ | |
| 157 | +// quoteBlock draws a quote behind a bar on every line. | |
| 158 | +func (l *mdLayout) quoteBlock(trim string) { | |
| 159 | + bar := []Span{{Text: "│ ", Style: styleQuote}} | |
| 160 | + l.wrapped(inline(strings.TrimSpace(strings.TrimPrefix(trim, ">")), styleQuote), bar, bar) | |
| 161 | +} | |
| 300 | 162 | |
| 301 | -// markdown lays a closed answer out at width: blocks, then inline spans, | |
| 302 | -// wrapped. Every line is indented like the raw body. | |
| 303 | -func markdown(text string, width int) []Line { | |
| 304 | - src := strings.Split(strings.TrimRight(text, "\n"), "\n") | |
| 305 | - var out []Line | |
| 306 | - emit := func(spans []Span) { out = append(out, spanLine(append([]Span{{Text: pad}}, spans...))) } | |
| 307 | - wrapped := func(spans []Span, first, rest []Span) { | |
| 308 | - for _, l := range wrapSpans(spans, max(width-indent, 1), first, rest) { | |
| 309 | - emit(l) | |
| 310 | - } | |
| 163 | +// tableBlock draws the table that starts at line i and returns the index of | |
| 164 | +// its last row. | |
| 165 | +func (l *mdLayout) tableBlock(i int) int { | |
| 166 | + var rows []string | |
| 167 | + for ; i < len(l.src) && strings.HasPrefix(strings.TrimSpace(l.src[i]), "|"); i++ { | |
| 168 | + rows = append(rows, strings.TrimSpace(l.src[i])) | |
| 311 | 169 | } |
| 312 | - blank := false | |
| 313 | - for i := 0; i < len(src); i++ { | |
| 314 | - line := src[i] | |
| 315 | - trim := strings.TrimSpace(line) | |
| 316 | - if trim == "" { | |
| 317 | - if !blank && len(out) > 0 { | |
| 318 | - out = append(out, Line{}) | |
| 319 | - } | |
| 320 | - blank = true | |
| 321 | - continue | |
| 322 | - } | |
| 323 | - blank = false | |
| 324 | - switch { | |
| 325 | - case strings.HasPrefix(trim, "```") || strings.HasPrefix(trim, "~~~"): | |
| 326 | - fence := trim[:3] | |
| 327 | - lang := strings.TrimSpace(strings.TrimLeft(trim, fence[:1])) | |
| 328 | - if lang != "" { | |
| 329 | - emit([]Span{{Text: lang, Style: styleCode, Attr: attrDim}}) | |
| 330 | - } | |
| 331 | - for i++; i < len(src) && !strings.HasPrefix(strings.TrimSpace(src[i]), fence); i++ { | |
| 332 | - out = append(out, Line{Text: pad + " " + src[i], Style: styleCode}) | |
| 333 | - } | |
| 334 | - case heading(trim) > 0: | |
| 335 | - level := heading(trim) | |
| 336 | - spans := inline(strings.TrimSpace(strings.TrimRight(trim[level:], "# ")), styleHeading) | |
| 337 | - for k := range spans { | |
| 338 | - spans[k].Attr |= attrBold | |
| 339 | - if level == 1 { | |
| 340 | - spans[k].Attr |= attrUnderline | |
| 341 | - } | |
| 342 | - } | |
| 343 | - wrapped(spans, nil, nil) | |
| 344 | - case isRule(trim): | |
| 345 | - emit([]Span{{Text: strings.Repeat("─", max(min(width-indent, 60), 1)), Style: styleRule}}) | |
| 346 | - case strings.HasPrefix(trim, ">"): | |
| 347 | - quote := strings.TrimSpace(strings.TrimPrefix(trim, ">")) | |
| 348 | - bar := []Span{{Text: "│ ", Style: styleQuote}} | |
| 349 | - wrapped(inline(quote, styleQuote), bar, bar) | |
| 350 | - case isTableStart(src, i): | |
| 351 | - var rows []string | |
| 352 | - for ; i < len(src) && strings.HasPrefix(strings.TrimSpace(src[i]), "|"); i++ { | |
| 353 | - rows = append(rows, strings.TrimSpace(src[i])) | |
| 354 | - } | |
| 355 | - i-- | |
| 356 | - for _, l := range table(rows, max(width-indent, 1)) { | |
| 357 | - emit(l) | |
| 358 | - } | |
| 359 | - default: | |
| 360 | - if bullet, body, depth, ok := listItem(line); ok { | |
| 361 | - lead := strings.Repeat(" ", depth) | |
| 362 | - first := []Span{{Text: lead + bullet, Style: styleBullet}} | |
| 363 | - rest := []Span{{Text: lead + strings.Repeat(" ", len([]rune(bullet)))}} | |
| 364 | - wrapped(inline(body, styleBody), first, rest) | |
| 365 | - continue | |
| 366 | - } | |
| 367 | - wrapped(inline(line, styleBody), nil, nil) | |
| 368 | - } | |
| 170 | + for _, line := range table(rows, max(l.width-indent, 1)) { | |
| 171 | + l.emit(line) | |
| 172 | + } | |
| 173 | + return i - 1 | |
| 174 | +} | |
| 175 | + | |
| 176 | +// paragraph draws a list item behind its bullet and hanging indent, or a | |
| 177 | +// plain line of text. | |
| 178 | +func (l *mdLayout) paragraph(line string) { | |
| 179 | + bullet, body, depth, ok := listItem(line) | |
| 180 | + if !ok { | |
| 181 | + l.wrapped(inline(line, styleBody), nil, nil) | |
| 182 | + return | |
| 369 | 183 | } |
| 370 | - return out | |
| 184 | + lead := strings.Repeat(" ", depth) | |
| 185 | + first := []Span{{Text: lead + bullet, Style: styleBullet}} | |
| 186 | + rest := []Span{{Text: lead + strings.Repeat(" ", len([]rune(bullet)))}} | |
| 187 | + l.wrapped(inline(body, styleBody), first, rest) | |
| 371 | 188 | } |
| 372 | 189 | |
| 373 | 190 | // heading is the level of an ATX heading line ("## Title" → 2), 0 if none. |
| 374 | 191 | func heading(trim string) int { |
| 375 | - n := 0 | |
| 376 | - for n < len(trim) && trim[n] == '#' { | |
| 377 | - n++ | |
| 378 | - } | |
| 379 | - if n == 0 || n > 6 || (n < len(trim) && trim[n] != ' ') || n == len(trim) { | |
| 192 | + n := len(trim) - len(strings.TrimLeft(trim, "#")) | |
| 193 | + if n == 0 || n > 6 || !strings.HasPrefix(trim[n:], " ") { | |
| 380 | 194 | return 0 |
| 381 | 195 | } |
| 382 | 196 | return n |
| @@ -409,134 +223,12 @@ func listItem(line string) (bullet, body string, depth int, ok bool) { | ||
| 409 | 223 | } |
| 410 | 224 | return "• ", body, depth, true |
| 411 | 225 | } |
| 412 | - n := 0 | |
| 413 | - for n < len(trim) && trim[n] >= '0' && trim[n] <= '9' { | |
| 414 | - n++ | |
| 415 | - } | |
| 416 | - if n > 0 && n <= 9 && n+1 < len(trim) && (trim[n] == '.' || trim[n] == ')') && trim[n+1] == ' ' { | |
| 417 | - num, _ := strconv.Atoi(trim[:n]) | |
| 418 | - return strconv.Itoa(num) + ". ", trim[n+2:], depth, true | |
| 419 | - } | |
| 420 | - return "", "", 0, false | |
| 421 | -} | |
| 422 | - | |
| 423 | -// isTableStart reports a table: a `|` row followed by a |---|---| line. | |
| 424 | -func isTableStart(src []string, i int) bool { | |
| 425 | - if i+1 >= len(src) || !strings.HasPrefix(strings.TrimSpace(src[i]), "|") { | |
| 426 | - return false | |
| 427 | - } | |
| 428 | - sep := strings.TrimSpace(src[i+1]) | |
| 429 | - return strings.HasPrefix(sep, "|") && strings.Trim(sep, "|-: ") == "" && strings.Contains(sep, "-") | |
| 430 | -} | |
| 431 | - | |
| 432 | -// cells splits a table row: "| a | b |" → ["a", "b"]. An escaped \| stays. | |
| 433 | -func cells(row string) []string { | |
| 434 | - row = strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(row), "|"), "|") | |
| 435 | - row = strings.ReplaceAll(row, `\|`, "\x00") | |
| 436 | - var out []string | |
| 437 | - for _, c := range strings.Split(row, "|") { | |
| 438 | - out = append(out, strings.ReplaceAll(strings.TrimSpace(c), "\x00", "|")) | |
| 439 | - } | |
| 440 | - return out | |
| 441 | -} | |
| 442 | - | |
| 443 | -// table lays a table out: columns as wide as their widest cell, the header | |
| 444 | -// bold, a ─┼─ line under it. A table wider than width has its widest columns | |
| 445 | -// narrowed and their cells cut with "…" — a table is read across, wrapping | |
| 446 | -// its cells would break that. | |
| 447 | -func table(rows []string, width int) [][]Span { | |
| 448 | - var grid [][][]Span | |
| 449 | - cols := 0 | |
| 450 | - for k, r := range rows { | |
| 451 | - if k == 1 { // the |---| line | |
| 452 | - continue | |
| 453 | - } | |
| 454 | - var row [][]Span | |
| 455 | - for _, c := range cells(r) { | |
| 456 | - row = append(row, inline(c, styleBody)) | |
| 457 | - } | |
| 458 | - cols = max(cols, len(row)) | |
| 459 | - grid = append(grid, row) | |
| 460 | - } | |
| 461 | - widths := make([]int, cols) | |
| 462 | - for _, row := range grid { | |
| 463 | - for c, cell := range row { | |
| 464 | - widths[c] = max(widths[c], len([]rune(spansText(cell)))) | |
| 465 | - } | |
| 466 | - } | |
| 467 | - for total(widths) > width { | |
| 468 | - widest := 0 | |
| 469 | - for c := range widths { | |
| 470 | - if widths[c] > widths[widest] { | |
| 471 | - widest = c | |
| 472 | - } | |
| 473 | - } | |
| 474 | - if widths[widest] <= 3 { | |
| 475 | - break | |
| 476 | - } | |
| 477 | - widths[widest]-- | |
| 478 | - } | |
| 479 | - var out [][]Span | |
| 480 | - for r, row := range grid { | |
| 481 | - var line []Span | |
| 482 | - for c := 0; c < cols; c++ { | |
| 483 | - if c > 0 { | |
| 484 | - line = append(line, Span{Text: " │ ", Style: styleRule}) | |
| 485 | - } | |
| 486 | - var cell []Span | |
| 487 | - if c < len(row) { | |
| 488 | - cell = row[c] | |
| 489 | - } | |
| 490 | - cell = clipSpans(cell, widths[c]) | |
| 491 | - if r == 0 { | |
| 492 | - for k := range cell { | |
| 493 | - cell[k].Attr |= attrBold | |
| 494 | - } | |
| 495 | - } | |
| 496 | - line = append(line, cell...) | |
| 497 | - if fill := widths[c] - len([]rune(spansText(cell))); fill > 0 { | |
| 498 | - line = append(line, Span{Text: strings.Repeat(" ", fill)}) | |
| 499 | - } | |
| 500 | - } | |
| 501 | - out = append(out, line) | |
| 502 | - if r == 0 { | |
| 503 | - var sep []string | |
| 504 | - for _, w := range widths { | |
| 505 | - sep = append(sep, strings.Repeat("─", w)) | |
| 506 | - } | |
| 507 | - out = append(out, []Span{{Text: strings.Join(sep, "─┼─"), Style: styleRule}}) | |
| 508 | - } | |
| 509 | - } | |
| 510 | - return out | |
| 511 | -} | |
| 512 | - | |
| 513 | -// total is the drawn width of a table's columns, separators included. | |
| 514 | -func total(widths []int) int { | |
| 515 | - n := 3 * max(len(widths)-1, 0) | |
| 516 | - for _, w := range widths { | |
| 517 | - n += w | |
| 518 | - } | |
| 519 | - return n | |
| 520 | -} | |
| 521 | - | |
| 522 | -// clipSpans cuts spans to width runes, the last one ending with "…". | |
| 523 | -func clipSpans(spans []Span, width int) []Span { | |
| 524 | - if len([]rune(spansText(spans))) <= width { | |
| 525 | - return append([]Span(nil), spans...) | |
| 526 | - } | |
| 527 | - var out []Span | |
| 528 | - left := width - 1 | |
| 529 | - for _, s := range spans { | |
| 530 | - r := []rune(s.Text) | |
| 531 | - if len(r) > left { | |
| 532 | - s.Text = string(r[:max(left, 0)]) | |
| 533 | - out = append(out, s, Span{Text: "…", Style: s.Style, Attr: s.Attr}) | |
| 534 | - return out | |
| 535 | - } | |
| 536 | - out = append(out, s) | |
| 537 | - left -= len(r) | |
| 226 | + n := len(trim) - len(strings.TrimLeft(trim, "0123456789")) | |
| 227 | + if n == 0 || n > 9 || !(strings.HasPrefix(trim[n:], ". ") || strings.HasPrefix(trim[n:], ") ")) { | |
| 228 | + return "", "", 0, false | |
| 538 | 229 | } |
| 539 | - return out | |
| 230 | + num, _ := strconv.Atoi(trim[:n]) | |
| 231 | + return strconv.Itoa(num) + ". ", trim[n+2:], depth, true | |
| 540 | 232 | } |
| 541 | 233 | |
| 542 | 234 | // --- cache ------------------------------------------------------------------- |
| @@ -3,7 +3,6 @@ package tui | |||
| 3 | import ( | 3 | import ( |
| 4 | "strconv" | 4 | "strconv" |
| 5 | "strings" | 5 | "strings" |
| 6 | - "unicode" | ||
| 7 | ) | 6 | ) |
| 8 | 7 | ||
| 9 | // Markdown in the window (experiment, branch experiment/tui-markdown): an | 8 | // Markdown in the window (experiment, branch experiment/tui-markdown): an |
| @@ -56,327 +55,142 @@ func spanLine(spans []Span) Line { | |||
| 56 | return Line{Text: spansText(spans), Spans: spans} | 55 | return Line{Text: spansText(spans), Spans: spans} |
| 57 | } | 56 | } |
| 58 | 57 | ||
| 59 | -// --- inline ------------------------------------------------------------------ | 58 | +// --- blocks ------------------------------------------------------------------ |
| 60 | 59 | ||
| 61 | -// inline parses one line of Markdown text into spans, all at base style. | 60 | +// markdown lays a closed answer out at width: blocks, then inline spans, |
| 61 | +// wrapped. Every line is indented like the raw body. | ||
| 62 | // | 62 | // |
| 63 | -// inline("a **b** `c`", styleBody) // "a " · "b" bold · " " · "c" code | 63 | +// markdown("# Title\n\n- a **b**", 80) // the title, a blank line, "• a b" |
| 64 | -func inline(text string, base styleKind) []Span { | 64 | +func markdown(text string, width int) []Line { |
| 65 | - var out []Span | 65 | + l := &mdLayout{src: strings.Split(strings.TrimRight(text, "\n"), "\n"), width: width} |
| 66 | - var plain strings.Builder | 66 | + for i := 0; i < len(l.src); i++ { |
| 67 | - flush := func() { | 67 | + i = l.block(i) |
| 68 | - if plain.Len() > 0 { | ||
| 69 | - out = append(out, Span{Text: plain.String(), Style: base}) | ||
| 70 | - plain.Reset() | ||
| 71 | - } | ||
| 72 | - } | ||
| 73 | - add := func(spans ...Span) { | ||
| 74 | - flush() | ||
| 75 | - out = append(out, spans...) | ||
| 76 | - } | ||
| 77 | - r := []rune(text) | ||
| 78 | - for i := 0; i < len(r); { | ||
| 79 | - c := r[i] | ||
| 80 | - switch { | ||
| 81 | - case c == '\\' && i+1 < len(r) && isMarkdownPunct(r[i+1]): | ||
| 82 | - plain.WriteRune(r[i+1]) | ||
| 83 | - i += 2 | ||
| 84 | - continue | ||
| 85 | - case c == '`': | ||
| 86 | - if end, n := closingTicks(r, i); end > 0 { | ||
| 87 | - code := strings.TrimSpace(string(r[i+n : end])) | ||
| 88 | - add(Span{Text: code, Style: styleCode}) | ||
| 89 | - i = end + n | ||
| 90 | - continue | ||
| 91 | - } | ||
| 92 | - case c == '[': | ||
| 93 | - if label, url, next, ok := link(r, i); ok { | ||
| 94 | - spans := inline(label, base) | ||
| 95 | - for k := range spans { | ||
| 96 | - spans[k].Attr |= attrUnderline | ||
| 97 | - } | ||
| 98 | - if url != "" && url != label { | ||
| 99 | - spans = append(spans, Span{Text: " (" + url + ")", Style: base, Attr: attrDim}) | ||
| 100 | - } | ||
| 101 | - add(spans...) | ||
| 102 | - i = next | ||
| 103 | - continue | ||
| 104 | - } | ||
| 105 | - case c == '<': | ||
| 106 | - if end := strings.IndexRune(string(r[i+1:]), '>'); end > 0 { | ||
| 107 | - inner := string(r[i+1 : i+1+end]) | ||
| 108 | - if strings.HasPrefix(inner, "http://") || strings.HasPrefix(inner, "https://") { | ||
| 109 | - add(Span{Text: inner, Style: base, Attr: attrUnderline}) | ||
| 110 | - i += end + 2 | ||
| 111 | - continue | ||
| 112 | - } | ||
| 113 | - } | ||
| 114 | - case c == '*' || c == '_' || c == '~': | ||
| 115 | - if spans, next, ok := emphasis(r, i, base); ok { | ||
| 116 | - add(spans...) | ||
| 117 | - i = next | ||
| 118 | - continue | ||
| 119 | - } | ||
| 120 | - } | ||
| 121 | - plain.WriteRune(c) | ||
| 122 | - i++ | ||
| 123 | } | 68 | } |
| 124 | - flush() | 69 | + return l.out |
| 125 | - return out | ||
| 126 | } | 70 | } |
| 127 | 71 | ||
| 128 | -// isMarkdownPunct is what a backslash may escape. | 72 | +// mdLayout is one answer being laid out: its source lines, the width, the |
| 129 | -func isMarkdownPunct(r rune) bool { return strings.ContainsRune("\\`*_{}[]()#+-.!|~<>", r) } | 73 | +// lines drawn so far, and whether the last source line was blank. |
| 74 | +type mdLayout struct { | ||
| 75 | + src []string | ||
| 76 | + width int | ||
| 77 | + out []Line | ||
| 78 | + blank bool | ||
| 79 | +} | ||
| 130 | 80 | ||
| 131 | -// closingTicks finds the run of backticks closing the one at i: the index of | 81 | +// block lays out the block that starts at source line i and returns the |
| 132 | -// the closing run and the run's length, or 0 when there is none. | 82 | +// index of its last line — more than i for a fence or a table. |
| 133 | -func closingTicks(r []rune, i int) (int, int) { | 83 | +func (l *mdLayout) block(i int) int { |
| 134 | - n := 0 | 84 | + trim := strings.TrimSpace(l.src[i]) |
| 135 | - for i+n < len(r) && r[i+n] == '`' { | 85 | + if trim == "" { |
| 136 | - n++ | 86 | + l.blankLine() |
| 87 | + return i | ||
| 137 | } | 88 | } |
| 138 | - for j := i + n; j < len(r); j++ { | 89 | + l.blank = false |
| 139 | - if r[j] != '`' { | 90 | + switch { |
| 140 | - continue | 91 | + case isFence(trim): |
| 141 | - } | 92 | + return l.fenceBlock(i, trim) |
| 142 | - m := 0 | 93 | + case heading(trim) > 0: |
| 143 | - for j+m < len(r) && r[j+m] == '`' { | 94 | + l.headingBlock(trim) |
| 144 | - m++ | 95 | + case isRule(trim): |
| 145 | - } | 96 | + l.emit([]Span{{Text: strings.Repeat("─", max(min(l.width-indent, 60), 1)), Style: styleRule}}) |
| 146 | - if m == n { | 97 | + case strings.HasPrefix(trim, ">"): |
| 147 | - return j, n | 98 | + l.quoteBlock(trim) |
| 148 | - } | 99 | + case isTableStart(l.src, i): |
| 149 | - j += m - 1 | 100 | + return l.tableBlock(i) |
| 101 | + default: | ||
| 102 | + l.paragraph(l.src[i]) | ||
| 150 | } | 103 | } |
| 151 | - return 0, n | 104 | + return i |
| 152 | } | 105 | } |
| 153 | 106 | ||
| 154 | -// link reads [label](url) at i. | 107 | +// emit draws one line of spans, indented like the raw body. |
| 155 | -func link(r []rune, i int) (label, url string, next int, ok bool) { | 108 | +func (l *mdLayout) emit(spans []Span) { |
| 156 | - depth := 0 | 109 | + l.out = append(l.out, spanLine(append([]Span{{Text: pad}}, spans...))) |
| 157 | - for j := i; j < len(r); j++ { | ||
| 158 | - switch r[j] { | ||
| 159 | - case '[': | ||
| 160 | - depth++ | ||
| 161 | - case ']': | ||
| 162 | - depth-- | ||
| 163 | - if depth == 0 { | ||
| 164 | - if j+1 >= len(r) || r[j+1] != '(' { | ||
| 165 | - return "", "", 0, false | ||
| 166 | - } | ||
| 167 | - end := strings.IndexRune(string(r[j+2:]), ')') | ||
| 168 | - if end < 0 { | ||
| 169 | - return "", "", 0, false | ||
| 170 | - } | ||
| 171 | - url = strings.TrimSpace(string(r[j+2 : j+2+end])) | ||
| 172 | - if k := strings.IndexAny(url, " \t"); k >= 0 { // [x](url "title") | ||
| 173 | - url = url[:k] | ||
| 174 | - } | ||
| 175 | - return string(r[i+1 : j]), url, j + 3 + end, true | ||
| 176 | - } | ||
| 177 | - } | ||
| 178 | - } | ||
| 179 | - return "", "", 0, false | ||
| 180 | } | 110 | } |
| 181 | 111 | ||
| 182 | -// emphasis reads **bold**, *italic*, ***both***, __bold__, _italic_ or | 112 | +// wrapped draws spans wrapped to the width, first before the first line and |
| 183 | -// ~~struck~~ at i. An underscore inside a word (snake_case) is not one, and | 113 | +// rest before the others. |
| 184 | -// neither is a marker followed by a space ("2 * 3"). | 114 | +func (l *mdLayout) wrapped(spans []Span, first, rest []Span) { |
| 185 | -func emphasis(r []rune, i int, base styleKind) ([]Span, int, bool) { | 115 | + for _, line := range wrapSpans(spans, max(l.width-indent, 1), first, rest) { |
| 186 | - c := r[i] | 116 | + l.emit(line) |
| 187 | - n := 0 | ||
| 188 | - for i+n < len(r) && r[i+n] == c && n < 3 { | ||
| 189 | - n++ | ||
| 190 | - } | ||
| 191 | - if c == '~' && n != 2 { | ||
| 192 | - return nil, 0, false | ||
| 193 | - } | ||
| 194 | - if c == '_' && i > 0 && isWordRune(r[i-1]) { | ||
| 195 | - return nil, 0, false | ||
| 196 | - } | ||
| 197 | - open := i + n | ||
| 198 | - if open >= len(r) || unicode.IsSpace(r[open]) { | ||
| 199 | - return nil, 0, false | ||
| 200 | - } | ||
| 201 | - marker := strings.Repeat(string(c), n) | ||
| 202 | - rest := string(r[open:]) | ||
| 203 | - for from := 0; ; { | ||
| 204 | - at := strings.Index(rest[from:], marker) | ||
| 205 | - if at < 0 { | ||
| 206 | - return nil, 0, false | ||
| 207 | - } | ||
| 208 | - at += from | ||
| 209 | - inner := []rune(rest[:at]) | ||
| 210 | - after := open + len(inner) + n | ||
| 211 | - closes := len(inner) > 0 && !unicode.IsSpace(inner[len(inner)-1]) && | ||
| 212 | - (after >= len(r) || r[after] != c) && | ||
| 213 | - (c != '_' || after >= len(r) || !isWordRune(r[after])) | ||
| 214 | - if closes { | ||
| 215 | - var a attr | ||
| 216 | - switch { | ||
| 217 | - case c == '~': | ||
| 218 | - a = attrStrike | ||
| 219 | - case n == 1: | ||
| 220 | - a = attrItalic | ||
| 221 | - case n == 2: | ||
| 222 | - a = attrBold | ||
| 223 | - default: | ||
| 224 | - a = attrBold | attrItalic | ||
| 225 | - } | ||
| 226 | - spans := inline(string(inner), base) | ||
| 227 | - for k := range spans { | ||
| 228 | - spans[k].Attr |= a | ||
| 229 | - } | ||
| 230 | - return spans, after, true | ||
| 231 | - } | ||
| 232 | - from = at + len(marker) | ||
| 233 | } | 117 | } |
| 234 | } | 118 | } |
| 235 | 119 | ||
| 236 | -func isWordRune(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) } | 120 | +// blankLine keeps one blank line between blocks: never two in a row, never |
| 121 | +// one at the top. | ||
| 122 | +func (l *mdLayout) blankLine() { | ||
| 123 | + if !l.blank && len(l.out) > 0 { | ||
| 124 | + l.out = append(l.out, Line{}) | ||
| 125 | + } | ||
| 126 | + l.blank = true | ||
| 127 | +} | ||
| 237 | 128 | ||
| 238 | -// --- wrapping spans -------------------------------------------------------------- | 129 | +// isFence reports the opening of a fenced code block. |
| 130 | +func isFence(trim string) bool { | ||
| 131 | + return strings.HasPrefix(trim, "```") || strings.HasPrefix(trim, "~~~") | ||
| 132 | +} | ||
| 239 | 133 | ||
| 240 | -// wrapSpans wraps spans to width runes, at spaces where it can, the way wrap | 134 | +// fenceBlock draws a fenced code block as written, its language dimmed above |
| 241 | -// does for plain text. first goes before the first line, rest before the | 135 | +// it, and returns the index of its closing fence (or the end of the text). |
| 242 | -// others — a list item's bullet, then its hanging indent. | 136 | +func (l *mdLayout) fenceBlock(i int, trim string) int { |
| 243 | -func wrapSpans(spans []Span, width int, first, rest []Span) [][]Span { | 137 | + fence := trim[:3] |
| 244 | - type cell struct { | 138 | + if lang := strings.TrimSpace(strings.TrimLeft(trim, fence[:1])); lang != "" { |
| 245 | - r rune | 139 | + l.emit([]Span{{Text: lang, Style: styleCode, Attr: attrDim}}) |
| 246 | - at int // index of the span it came from | ||
| 247 | } | 140 | } |
| 248 | - var cells []cell | 141 | + for i++; i < len(l.src) && !strings.HasPrefix(strings.TrimSpace(l.src[i]), fence); i++ { |
| 249 | - for k, s := range spans { | 142 | + l.out = append(l.out, Line{Text: pad + " " + l.src[i], Style: styleCode}) |
| 250 | - for _, r := range s.Text { | ||
| 251 | - cells = append(cells, cell{r, k}) | ||
| 252 | - } | ||
| 253 | - } | ||
| 254 | - build := func(prefix []Span, part []cell) []Span { | ||
| 255 | - line := append([]Span(nil), prefix...) | ||
| 256 | - for i := 0; i < len(part); { | ||
| 257 | - j := i | ||
| 258 | - for j < len(part) && part[j].at == part[i].at { | ||
| 259 | - j++ | ||
| 260 | - } | ||
| 261 | - var b strings.Builder | ||
| 262 | - for _, c := range part[i:j] { | ||
| 263 | - b.WriteRune(c.r) | ||
| 264 | - } | ||
| 265 | - src := spans[part[i].at] | ||
| 266 | - line = append(line, Span{Text: b.String(), Style: src.Style, Attr: src.Attr}) | ||
| 267 | - i = j | ||
| 268 | - } | ||
| 269 | - return line | ||
| 270 | } | 143 | } |
| 271 | - var out [][]Span | 144 | + return i |
| 272 | - prefix := first | 145 | +} |
| 273 | - for { | 146 | + |
| 274 | - room := max(width-len([]rune(spansText(prefix))), 1) | 147 | +// headingBlock draws a heading bold, underlined too at level 1. |
| 275 | - if len(cells) <= room { | 148 | +func (l *mdLayout) headingBlock(trim string) { |
| 276 | - return append(out, build(prefix, cells)) | 149 | + level := heading(trim) |
| 277 | - } | 150 | + a := attrBold |
| 278 | - runes := make([]rune, len(cells)) | 151 | + if level == 1 { |
| 279 | - for i, c := range cells { | 152 | + a |= attrUnderline |
| 280 | - runes[i] = c.r | ||
| 281 | - } | ||
| 282 | - at := breakPoint(runes, room) | ||
| 283 | - end := at | ||
| 284 | - for end > 0 && cells[end-1].r == ' ' { | ||
| 285 | - end-- | ||
| 286 | - } | ||
| 287 | - out = append(out, build(prefix, cells[:end])) | ||
| 288 | - cells = cells[at:] | ||
| 289 | - for len(cells) > 0 && cells[0].r == ' ' { | ||
| 290 | - cells = cells[1:] | ||
| 291 | - } | ||
| 292 | - prefix = rest | ||
| 293 | - if len(cells) == 0 { | ||
| 294 | - return out | ||
| 295 | - } | ||
| 296 | } | 153 | } |
| 154 | + l.wrapped(withAttr(inline(strings.TrimSpace(strings.TrimRight(trim[level:], "# ")), styleHeading), a), nil, nil) | ||
| 297 | } | 155 | } |
| 298 | 156 | ||
| 299 | -// --- blocks ------------------------------------------------------------------ | 157 | +// quoteBlock draws a quote behind a bar on every line. |
| 158 | +func (l *mdLayout) quoteBlock(trim string) { | ||
| 159 | + bar := []Span{{Text: "│ ", Style: styleQuote}} | ||
| 160 | + l.wrapped(inline(strings.TrimSpace(strings.TrimPrefix(trim, ">")), styleQuote), bar, bar) | ||
| 161 | +} | ||
| 300 | 162 | ||
| 301 | -// markdown lays a closed answer out at width: blocks, then inline spans, | 163 | +// tableBlock draws the table that starts at line i and returns the index of |
| 302 | -// wrapped. Every line is indented like the raw body. | 164 | +// its last row. |
| 303 | -func markdown(text string, width int) []Line { | 165 | +func (l *mdLayout) tableBlock(i int) int { |
| 304 | - src := strings.Split(strings.TrimRight(text, "\n"), "\n") | 166 | + var rows []string |
| 305 | - var out []Line | 167 | + for ; i < len(l.src) && strings.HasPrefix(strings.TrimSpace(l.src[i]), "|"); i++ { |
| 306 | - emit := func(spans []Span) { out = append(out, spanLine(append([]Span{{Text: pad}}, spans...))) } | 168 | + rows = append(rows, strings.TrimSpace(l.src[i])) |
| 307 | - wrapped := func(spans []Span, first, rest []Span) { | ||
| 308 | - for _, l := range wrapSpans(spans, max(width-indent, 1), first, rest) { | ||
| 309 | - emit(l) | ||
| 310 | - } | ||
| 311 | } | 169 | } |
| 312 | - blank := false | 170 | + for _, line := range table(rows, max(l.width-indent, 1)) { |
| 313 | - for i := 0; i < len(src); i++ { | 171 | + l.emit(line) |
| 314 | - line := src[i] | 172 | + } |
| 315 | - trim := strings.TrimSpace(line) | 173 | + return i - 1 |
| 316 | - if trim == "" { | 174 | +} |
| 317 | - if !blank && len(out) > 0 { | 175 | + |
| 318 | - out = append(out, Line{}) | 176 | +// paragraph draws a list item behind its bullet and hanging indent, or a |
| 319 | - } | 177 | +// plain line of text. |
| 320 | - blank = true | 178 | +func (l *mdLayout) paragraph(line string) { |
| 321 | - continue | 179 | + bullet, body, depth, ok := listItem(line) |
| 322 | - } | 180 | + if !ok { |
| 323 | - blank = false | 181 | + l.wrapped(inline(line, styleBody), nil, nil) |
| 324 | - switch { | 182 | + return |
| 325 | - case strings.HasPrefix(trim, "```") || strings.HasPrefix(trim, "~~~"): | ||
| 326 | - fence := trim[:3] | ||
| 327 | - lang := strings.TrimSpace(strings.TrimLeft(trim, fence[:1])) | ||
| 328 | - if lang != "" { | ||
| 329 | - emit([]Span{{Text: lang, Style: styleCode, Attr: attrDim}}) | ||
| 330 | - } | ||
| 331 | - for i++; i < len(src) && !strings.HasPrefix(strings.TrimSpace(src[i]), fence); i++ { | ||
| 332 | - out = append(out, Line{Text: pad + " " + src[i], Style: styleCode}) | ||
| 333 | - } | ||
| 334 | - case heading(trim) > 0: | ||
| 335 | - level := heading(trim) | ||
| 336 | - spans := inline(strings.TrimSpace(strings.TrimRight(trim[level:], "# ")), styleHeading) | ||
| 337 | - for k := range spans { | ||
| 338 | - spans[k].Attr |= attrBold | ||
| 339 | - if level == 1 { | ||
| 340 | - spans[k].Attr |= attrUnderline | ||
| 341 | - } | ||
| 342 | - } | ||
| 343 | - wrapped(spans, nil, nil) | ||
| 344 | - case isRule(trim): | ||
| 345 | - emit([]Span{{Text: strings.Repeat("─", max(min(width-indent, 60), 1)), Style: styleRule}}) | ||
| 346 | - case strings.HasPrefix(trim, ">"): | ||
| 347 | - quote := strings.TrimSpace(strings.TrimPrefix(trim, ">")) | ||
| 348 | - bar := []Span{{Text: "│ ", Style: styleQuote}} | ||
| 349 | - wrapped(inline(quote, styleQuote), bar, bar) | ||
| 350 | - case isTableStart(src, i): | ||
| 351 | - var rows []string | ||
| 352 | - for ; i < len(src) && strings.HasPrefix(strings.TrimSpace(src[i]), "|"); i++ { | ||
| 353 | - rows = append(rows, strings.TrimSpace(src[i])) | ||
| 354 | - } | ||
| 355 | - i-- | ||
| 356 | - for _, l := range table(rows, max(width-indent, 1)) { | ||
| 357 | - emit(l) | ||
| 358 | - } | ||
| 359 | - default: | ||
| 360 | - if bullet, body, depth, ok := listItem(line); ok { | ||
| 361 | - lead := strings.Repeat(" ", depth) | ||
| 362 | - first := []Span{{Text: lead + bullet, Style: styleBullet}} | ||
| 363 | - rest := []Span{{Text: lead + strings.Repeat(" ", len([]rune(bullet)))}} | ||
| 364 | - wrapped(inline(body, styleBody), first, rest) | ||
| 365 | - continue | ||
| 366 | - } | ||
| 367 | - wrapped(inline(line, styleBody), nil, nil) | ||
| 368 | - } | ||
| 369 | } | 183 | } |
| 370 | - return out | 184 | + lead := strings.Repeat(" ", depth) |
| 185 | + first := []Span{{Text: lead + bullet, Style: styleBullet}} | ||
| 186 | + rest := []Span{{Text: lead + strings.Repeat(" ", len([]rune(bullet)))}} | ||
| 187 | + l.wrapped(inline(body, styleBody), first, rest) | ||
| 371 | } | 188 | } |
| 372 | 189 | ||
| 373 | // heading is the level of an ATX heading line ("## Title" → 2), 0 if none. | 190 | // heading is the level of an ATX heading line ("## Title" → 2), 0 if none. |
| 374 | func heading(trim string) int { | 191 | func heading(trim string) int { |
| 375 | - n := 0 | 192 | + n := len(trim) - len(strings.TrimLeft(trim, "#")) |
| 376 | - for n < len(trim) && trim[n] == '#' { | 193 | + if n == 0 || n > 6 || !strings.HasPrefix(trim[n:], " ") { |
| 377 | - n++ | ||
| 378 | - } | ||
| 379 | - if n == 0 || n > 6 || (n < len(trim) && trim[n] != ' ') || n == len(trim) { | ||
| 380 | return 0 | 194 | return 0 |
| 381 | } | 195 | } |
| 382 | return n | 196 | return n |
| @@ -409,134 +223,12 @@ func listItem(line string) (bullet, body string, depth int, ok bool) { | |||
| 409 | } | 223 | } |
| 410 | return "• ", body, depth, true | 224 | return "• ", body, depth, true |
| 411 | } | 225 | } |
| 412 | - n := 0 | 226 | + n := len(trim) - len(strings.TrimLeft(trim, "0123456789")) |
| 413 | - for n < len(trim) && trim[n] >= '0' && trim[n] <= '9' { | 227 | + if n == 0 || n > 9 || !(strings.HasPrefix(trim[n:], ". ") || strings.HasPrefix(trim[n:], ") ")) { |
| 414 | - n++ | 228 | + return "", "", 0, false |
| 415 | - } | ||
| 416 | - if n > 0 && n <= 9 && n+1 < len(trim) && (trim[n] == '.' || trim[n] == ')') && trim[n+1] == ' ' { | ||
| 417 | - num, _ := strconv.Atoi(trim[:n]) | ||
| 418 | - return strconv.Itoa(num) + ". ", trim[n+2:], depth, true | ||
| 419 | - } | ||
| 420 | - return "", "", 0, false | ||
| 421 | -} | ||
| 422 | - | ||
| 423 | -// isTableStart reports a table: a `|` row followed by a |---|---| line. | ||
| 424 | -func isTableStart(src []string, i int) bool { | ||
| 425 | - if i+1 >= len(src) || !strings.HasPrefix(strings.TrimSpace(src[i]), "|") { | ||
| 426 | - return false | ||
| 427 | - } | ||
| 428 | - sep := strings.TrimSpace(src[i+1]) | ||
| 429 | - return strings.HasPrefix(sep, "|") && strings.Trim(sep, "|-: ") == "" && strings.Contains(sep, "-") | ||
| 430 | -} | ||
| 431 | - | ||
| 432 | -// cells splits a table row: "| a | b |" → ["a", "b"]. An escaped \| stays. | ||
| 433 | -func cells(row string) []string { | ||
| 434 | - row = strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(row), "|"), "|") | ||
| 435 | - row = strings.ReplaceAll(row, `\|`, "\x00") | ||
| 436 | - var out []string | ||
| 437 | - for _, c := range strings.Split(row, "|") { | ||
| 438 | - out = append(out, strings.ReplaceAll(strings.TrimSpace(c), "\x00", "|")) | ||
| 439 | - } | ||
| 440 | - return out | ||
| 441 | -} | ||
| 442 | - | ||
| 443 | -// table lays a table out: columns as wide as their widest cell, the header | ||
| 444 | -// bold, a ─┼─ line under it. A table wider than width has its widest columns | ||
| 445 | -// narrowed and their cells cut with "…" — a table is read across, wrapping | ||
| 446 | -// its cells would break that. | ||
| 447 | -func table(rows []string, width int) [][]Span { | ||
| 448 | - var grid [][][]Span | ||
| 449 | - cols := 0 | ||
| 450 | - for k, r := range rows { | ||
| 451 | - if k == 1 { // the |---| line | ||
| 452 | - continue | ||
| 453 | - } | ||
| 454 | - var row [][]Span | ||
| 455 | - for _, c := range cells(r) { | ||
| 456 | - row = append(row, inline(c, styleBody)) | ||
| 457 | - } | ||
| 458 | - cols = max(cols, len(row)) | ||
| 459 | - grid = append(grid, row) | ||
| 460 | - } | ||
| 461 | - widths := make([]int, cols) | ||
| 462 | - for _, row := range grid { | ||
| 463 | - for c, cell := range row { | ||
| 464 | - widths[c] = max(widths[c], len([]rune(spansText(cell)))) | ||
| 465 | - } | ||
| 466 | - } | ||
| 467 | - for total(widths) > width { | ||
| 468 | - widest := 0 | ||
| 469 | - for c := range widths { | ||
| 470 | - if widths[c] > widths[widest] { | ||
| 471 | - widest = c | ||
| 472 | - } | ||
| 473 | - } | ||
| 474 | - if widths[widest] <= 3 { | ||
| 475 | - break | ||
| 476 | - } | ||
| 477 | - widths[widest]-- | ||
| 478 | - } | ||
| 479 | - var out [][]Span | ||
| 480 | - for r, row := range grid { | ||
| 481 | - var line []Span | ||
| 482 | - for c := 0; c < cols; c++ { | ||
| 483 | - if c > 0 { | ||
| 484 | - line = append(line, Span{Text: " │ ", Style: styleRule}) | ||
| 485 | - } | ||
| 486 | - var cell []Span | ||
| 487 | - if c < len(row) { | ||
| 488 | - cell = row[c] | ||
| 489 | - } | ||
| 490 | - cell = clipSpans(cell, widths[c]) | ||
| 491 | - if r == 0 { | ||
| 492 | - for k := range cell { | ||
| 493 | - cell[k].Attr |= attrBold | ||
| 494 | - } | ||
| 495 | - } | ||
| 496 | - line = append(line, cell...) | ||
| 497 | - if fill := widths[c] - len([]rune(spansText(cell))); fill > 0 { | ||
| 498 | - line = append(line, Span{Text: strings.Repeat(" ", fill)}) | ||
| 499 | - } | ||
| 500 | - } | ||
| 501 | - out = append(out, line) | ||
| 502 | - if r == 0 { | ||
| 503 | - var sep []string | ||
| 504 | - for _, w := range widths { | ||
| 505 | - sep = append(sep, strings.Repeat("─", w)) | ||
| 506 | - } | ||
| 507 | - out = append(out, []Span{{Text: strings.Join(sep, "─┼─"), Style: styleRule}}) | ||
| 508 | - } | ||
| 509 | - } | ||
| 510 | - return out | ||
| 511 | -} | ||
| 512 | - | ||
| 513 | -// total is the drawn width of a table's columns, separators included. | ||
| 514 | -func total(widths []int) int { | ||
| 515 | - n := 3 * max(len(widths)-1, 0) | ||
| 516 | - for _, w := range widths { | ||
| 517 | - n += w | ||
| 518 | - } | ||
| 519 | - return n | ||
| 520 | -} | ||
| 521 | - | ||
| 522 | -// clipSpans cuts spans to width runes, the last one ending with "…". | ||
| 523 | -func clipSpans(spans []Span, width int) []Span { | ||
| 524 | - if len([]rune(spansText(spans))) <= width { | ||
| 525 | - return append([]Span(nil), spans...) | ||
| 526 | - } | ||
| 527 | - var out []Span | ||
| 528 | - left := width - 1 | ||
| 529 | - for _, s := range spans { | ||
| 530 | - r := []rune(s.Text) | ||
| 531 | - if len(r) > left { | ||
| 532 | - s.Text = string(r[:max(left, 0)]) | ||
| 533 | - out = append(out, s, Span{Text: "…", Style: s.Style, Attr: s.Attr}) | ||
| 534 | - return out | ||
| 535 | - } | ||
| 536 | - out = append(out, s) | ||
| 537 | - left -= len(r) | ||
| 538 | } | 229 | } |
| 539 | - return out | 230 | + num, _ := strconv.Atoi(trim[:n]) |
| 231 | + return strconv.Itoa(num) + ". ", trim[n+2:], depth, true | ||
| 540 | } | 232 | } |
| 541 | 233 | ||
| 542 | // --- cache ------------------------------------------------------------------- | 234 | // --- cache ------------------------------------------------------------------- |
added
internal/tui/markdown_inline.go +262 -0 | new file mode 100644 | ||
| @@ -0,0 +1,262 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "strings" | |
| 5 | + "unicode" | |
| 6 | +) | |
| 7 | + | |
| 8 | +// The inline half of the Markdown subset (markdown.go): one line of text | |
| 9 | +// into spans — **bold**, *italic*, ~~struck~~, `code`, [text](url), | |
| 10 | +// <https://…> and \ escapes. | |
| 11 | + | |
| 12 | +// inline parses one line of Markdown text into spans, all at base style. | |
| 13 | +// | |
| 14 | +// inline("a **b** `c`", styleBody) // "a " · "b" bold · " " · "c" code | |
| 15 | +func inline(text string, base styleKind) []Span { | |
| 16 | + p := plainRun{base: base} | |
| 17 | + r := []rune(text) | |
| 18 | + for i := 0; i < len(r); { | |
| 19 | + if i+1 < len(r) && r[i] == '\\' && isMarkdownPunct(r[i+1]) { | |
| 20 | + p.text.WriteRune(r[i+1]) | |
| 21 | + i += 2 | |
| 22 | + continue | |
| 23 | + } | |
| 24 | + if spans, next, ok := inlineSpan(r, i, base); ok { | |
| 25 | + p.add(spans...) | |
| 26 | + i = next | |
| 27 | + continue | |
| 28 | + } | |
| 29 | + p.text.WriteRune(r[i]) | |
| 30 | + i++ | |
| 31 | + } | |
| 32 | + p.flush() | |
| 33 | + return p.out | |
| 34 | +} | |
| 35 | + | |
| 36 | +// plainRun gathers the plain text between marked-up spans, so that a run of | |
| 37 | +// plain characters stays one span. | |
| 38 | +type plainRun struct { | |
| 39 | + base styleKind | |
| 40 | + text strings.Builder | |
| 41 | + out []Span | |
| 42 | +} | |
| 43 | + | |
| 44 | +// flush closes the pending plain text into a span. | |
| 45 | +func (p *plainRun) flush() { | |
| 46 | + if p.text.Len() > 0 { | |
| 47 | + p.out = append(p.out, Span{Text: p.text.String(), Style: p.base}) | |
| 48 | + p.text.Reset() | |
| 49 | + } | |
| 50 | +} | |
| 51 | + | |
| 52 | +// add closes the pending plain text, then appends spans. | |
| 53 | +func (p *plainRun) add(spans ...Span) { | |
| 54 | + p.flush() | |
| 55 | + p.out = append(p.out, spans...) | |
| 56 | +} | |
| 57 | + | |
| 58 | +// inlineSpan reads the marked-up span that starts at i, if the character | |
| 59 | +// there opens one that is closed: its spans and the index after it. | |
| 60 | +func inlineSpan(r []rune, i int, base styleKind) ([]Span, int, bool) { | |
| 61 | + switch r[i] { | |
| 62 | + case '`': | |
| 63 | + return codeSpan(r, i) | |
| 64 | + case '[': | |
| 65 | + return linkSpans(r, i, base) | |
| 66 | + case '<': | |
| 67 | + return autoLink(r, i, base) | |
| 68 | + case '*', '_', '~': | |
| 69 | + return emphasis(r, i, base) | |
| 70 | + } | |
| 71 | + return nil, 0, false | |
| 72 | +} | |
| 73 | + | |
| 74 | +// isMarkdownPunct is what a backslash may escape. | |
| 75 | +func isMarkdownPunct(r rune) bool { return strings.ContainsRune("\\`*_{}[]()#+-.!|~<>", r) } | |
| 76 | + | |
| 77 | +// withAttr adds a to every span, in place, and returns them. | |
| 78 | +func withAttr(spans []Span, a attr) []Span { | |
| 79 | + for k := range spans { | |
| 80 | + spans[k].Attr |= a | |
| 81 | + } | |
| 82 | + return spans | |
| 83 | +} | |
| 84 | + | |
| 85 | +// codeSpan reads `code` (or “co`de“) at i. | |
| 86 | +func codeSpan(r []rune, i int) ([]Span, int, bool) { | |
| 87 | + end, n := closingTicks(r, i) | |
| 88 | + if end == 0 { | |
| 89 | + return nil, 0, false | |
| 90 | + } | |
| 91 | + return []Span{{Text: strings.TrimSpace(string(r[i+n : end])), Style: styleCode}}, end + n, true | |
| 92 | +} | |
| 93 | + | |
| 94 | +// closingTicks finds the run of backticks closing the one at i: the index of | |
| 95 | +// the closing run and the run's length, or 0 when there is none. | |
| 96 | +func closingTicks(r []rune, i int) (int, int) { | |
| 97 | + n := tickRun(r, i) | |
| 98 | + for j := i + n; j < len(r); j++ { | |
| 99 | + if r[j] != '`' { | |
| 100 | + continue | |
| 101 | + } | |
| 102 | + m := tickRun(r, j) | |
| 103 | + if m == n { | |
| 104 | + return j, n | |
| 105 | + } | |
| 106 | + j += m - 1 | |
| 107 | + } | |
| 108 | + return 0, n | |
| 109 | +} | |
| 110 | + | |
| 111 | +// tickRun is the number of backticks in a row from i. | |
| 112 | +func tickRun(r []rune, i int) int { | |
| 113 | + n := 0 | |
| 114 | + for i+n < len(r) && r[i+n] == '`' { | |
| 115 | + n++ | |
| 116 | + } | |
| 117 | + return n | |
| 118 | +} | |
| 119 | + | |
| 120 | +// linkSpans reads [label](url) at i: the label underlined, the url dimmed | |
| 121 | +// after it unless it says the same. | |
| 122 | +func linkSpans(r []rune, i int, base styleKind) ([]Span, int, bool) { | |
| 123 | + label, url, next, ok := link(r, i) | |
| 124 | + if !ok { | |
| 125 | + return nil, 0, false | |
| 126 | + } | |
| 127 | + spans := withAttr(inline(label, base), attrUnderline) | |
| 128 | + if url != "" && url != label { | |
| 129 | + spans = append(spans, Span{Text: " (" + url + ")", Style: base, Attr: attrDim}) | |
| 130 | + } | |
| 131 | + return spans, next, true | |
| 132 | +} | |
| 133 | + | |
| 134 | +// autoLink reads <https://…> or <http://…> at i, drawn underlined. | |
| 135 | +func autoLink(r []rune, i int, base styleKind) ([]Span, int, bool) { | |
| 136 | + end := strings.IndexRune(string(r[i+1:]), '>') | |
| 137 | + if end <= 0 { | |
| 138 | + return nil, 0, false | |
| 139 | + } | |
| 140 | + inner := string(r[i+1 : i+1+end]) | |
| 141 | + if !strings.HasPrefix(inner, "http://") && !strings.HasPrefix(inner, "https://") { | |
| 142 | + return nil, 0, false | |
| 143 | + } | |
| 144 | + return []Span{{Text: inner, Style: base, Attr: attrUnderline}}, i + end + 2, true | |
| 145 | +} | |
| 146 | + | |
| 147 | +// link reads [label](url) at i. | |
| 148 | +func link(r []rune, i int) (label, url string, next int, ok bool) { | |
| 149 | + j := closingBracket(r, i) | |
| 150 | + if j < 0 || j+1 >= len(r) || r[j+1] != '(' { | |
| 151 | + return "", "", 0, false | |
| 152 | + } | |
| 153 | + end := strings.IndexRune(string(r[j+2:]), ')') | |
| 154 | + if end < 0 { | |
| 155 | + return "", "", 0, false | |
| 156 | + } | |
| 157 | + url = strings.TrimSpace(string(r[j+2 : j+2+end])) | |
| 158 | + if k := strings.IndexAny(url, " \t"); k >= 0 { // [x](url "title") | |
| 159 | + url = url[:k] | |
| 160 | + } | |
| 161 | + return string(r[i+1 : j]), url, j + 3 + end, true | |
| 162 | +} | |
| 163 | + | |
| 164 | +// closingBracket is the index of the ] closing the [ at i, nested brackets | |
| 165 | +// counted, or -1. | |
| 166 | +func closingBracket(r []rune, i int) int { | |
| 167 | + depth := 0 | |
| 168 | + for j := i; j < len(r); j++ { | |
| 169 | + switch r[j] { | |
| 170 | + case '[': | |
| 171 | + depth++ | |
| 172 | + case ']': | |
| 173 | + depth-- | |
| 174 | + if depth == 0 { | |
| 175 | + return j | |
| 176 | + } | |
| 177 | + } | |
| 178 | + } | |
| 179 | + return -1 | |
| 180 | +} | |
| 181 | + | |
| 182 | +// emphasis reads **bold**, *italic*, ***both***, __bold__, _italic_ or | |
| 183 | +// ~~struck~~ at i. An underscore inside a word (snake_case) is not one, and | |
| 184 | +// neither is a marker followed by a space ("2 * 3"). | |
| 185 | +func emphasis(r []rune, i int, base styleKind) ([]Span, int, bool) { | |
| 186 | + c := r[i] | |
| 187 | + n, ok := emphasisOpens(r, i) | |
| 188 | + if !ok { | |
| 189 | + return nil, 0, false | |
| 190 | + } | |
| 191 | + inner, after, ok := emphasisCloses(r, i+n, c, n) | |
| 192 | + if !ok { | |
| 193 | + return nil, 0, false | |
| 194 | + } | |
| 195 | + return withAttr(inline(inner, base), emphasisAttr(c, n)), after, true | |
| 196 | +} | |
| 197 | + | |
| 198 | +// emphasisOpens reports whether the marker at i opens an emphasis, and the | |
| 199 | +// length of its run (three at most). | |
| 200 | +func emphasisOpens(r []rune, i int) (int, bool) { | |
| 201 | + c := r[i] | |
| 202 | + n := 0 | |
| 203 | + for i+n < len(r) && r[i+n] == c && n < 3 { | |
| 204 | + n++ | |
| 205 | + } | |
| 206 | + if c == '~' && n != 2 { | |
| 207 | + return 0, false | |
| 208 | + } | |
| 209 | + if c == '_' && i > 0 && isWordRune(r[i-1]) { | |
| 210 | + return 0, false | |
| 211 | + } | |
| 212 | + open := i + n | |
| 213 | + return n, open < len(r) && !unicode.IsSpace(r[open]) | |
| 214 | +} | |
| 215 | + | |
| 216 | +// emphasisCloses finds the run of n markers c closing an emphasis opened just | |
| 217 | +// before open: the text between, and the index after the closing run. | |
| 218 | +func emphasisCloses(r []rune, open int, c rune, n int) (string, int, bool) { | |
| 219 | + marker := strings.Repeat(string(c), n) | |
| 220 | + rest := string(r[open:]) | |
| 221 | + for from := 0; ; { | |
| 222 | + at := strings.Index(rest[from:], marker) | |
| 223 | + if at < 0 { | |
| 224 | + return "", 0, false | |
| 225 | + } | |
| 226 | + at += from | |
| 227 | + inner := []rune(rest[:at]) | |
| 228 | + after := open + len(inner) + n | |
| 229 | + if closesEmphasis(r, inner, after, c) { | |
| 230 | + return string(inner), after, true | |
| 231 | + } | |
| 232 | + from = at + len(marker) | |
| 233 | + } | |
| 234 | +} | |
| 235 | + | |
| 236 | +// closesEmphasis reports whether a run of markers c ending just before after | |
| 237 | +// closes the emphasis around inner: inner not empty nor ending with a space, | |
| 238 | +// and the run neither longer nor (for _) followed by a word. | |
| 239 | +func closesEmphasis(r, inner []rune, after int, c rune) bool { | |
| 240 | + if len(inner) == 0 || unicode.IsSpace(inner[len(inner)-1]) { | |
| 241 | + return false | |
| 242 | + } | |
| 243 | + if after >= len(r) { | |
| 244 | + return true | |
| 245 | + } | |
| 246 | + return r[after] != c && (c != '_' || !isWordRune(r[after])) | |
| 247 | +} | |
| 248 | + | |
| 249 | +// emphasisAttr is what a run of n markers c adds. | |
| 250 | +func emphasisAttr(c rune, n int) attr { | |
| 251 | + switch { | |
| 252 | + case c == '~': | |
| 253 | + return attrStrike | |
| 254 | + case n == 1: | |
| 255 | + return attrItalic | |
| 256 | + case n == 2: | |
| 257 | + return attrBold | |
| 258 | + } | |
| 259 | + return attrBold | attrItalic | |
| 260 | +} | |
| 261 | + | |
| 262 | +func isWordRune(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) } | |
| new file mode 100644 | |||
| @@ -0,0 +1,262 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "strings" | ||
| 5 | + "unicode" | ||
| 6 | +) | ||
| 7 | + | ||
| 8 | +// The inline half of the Markdown subset (markdown.go): one line of text | ||
| 9 | +// into spans — **bold**, *italic*, ~~struck~~, `code`, [text](url), | ||
| 10 | +// <https://…> and \ escapes. | ||
| 11 | + | ||
| 12 | +// inline parses one line of Markdown text into spans, all at base style. | ||
| 13 | +// | ||
| 14 | +// inline("a **b** `c`", styleBody) // "a " · "b" bold · " " · "c" code | ||
| 15 | +func inline(text string, base styleKind) []Span { | ||
| 16 | + p := plainRun{base: base} | ||
| 17 | + r := []rune(text) | ||
| 18 | + for i := 0; i < len(r); { | ||
| 19 | + if i+1 < len(r) && r[i] == '\\' && isMarkdownPunct(r[i+1]) { | ||
| 20 | + p.text.WriteRune(r[i+1]) | ||
| 21 | + i += 2 | ||
| 22 | + continue | ||
| 23 | + } | ||
| 24 | + if spans, next, ok := inlineSpan(r, i, base); ok { | ||
| 25 | + p.add(spans...) | ||
| 26 | + i = next | ||
| 27 | + continue | ||
| 28 | + } | ||
| 29 | + p.text.WriteRune(r[i]) | ||
| 30 | + i++ | ||
| 31 | + } | ||
| 32 | + p.flush() | ||
| 33 | + return p.out | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +// plainRun gathers the plain text between marked-up spans, so that a run of | ||
| 37 | +// plain characters stays one span. | ||
| 38 | +type plainRun struct { | ||
| 39 | + base styleKind | ||
| 40 | + text strings.Builder | ||
| 41 | + out []Span | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +// flush closes the pending plain text into a span. | ||
| 45 | +func (p *plainRun) flush() { | ||
| 46 | + if p.text.Len() > 0 { | ||
| 47 | + p.out = append(p.out, Span{Text: p.text.String(), Style: p.base}) | ||
| 48 | + p.text.Reset() | ||
| 49 | + } | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +// add closes the pending plain text, then appends spans. | ||
| 53 | +func (p *plainRun) add(spans ...Span) { | ||
| 54 | + p.flush() | ||
| 55 | + p.out = append(p.out, spans...) | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +// inlineSpan reads the marked-up span that starts at i, if the character | ||
| 59 | +// there opens one that is closed: its spans and the index after it. | ||
| 60 | +func inlineSpan(r []rune, i int, base styleKind) ([]Span, int, bool) { | ||
| 61 | + switch r[i] { | ||
| 62 | + case '`': | ||
| 63 | + return codeSpan(r, i) | ||
| 64 | + case '[': | ||
| 65 | + return linkSpans(r, i, base) | ||
| 66 | + case '<': | ||
| 67 | + return autoLink(r, i, base) | ||
| 68 | + case '*', '_', '~': | ||
| 69 | + return emphasis(r, i, base) | ||
| 70 | + } | ||
| 71 | + return nil, 0, false | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +// isMarkdownPunct is what a backslash may escape. | ||
| 75 | +func isMarkdownPunct(r rune) bool { return strings.ContainsRune("\\`*_{}[]()#+-.!|~<>", r) } | ||
| 76 | + | ||
| 77 | +// withAttr adds a to every span, in place, and returns them. | ||
| 78 | +func withAttr(spans []Span, a attr) []Span { | ||
| 79 | + for k := range spans { | ||
| 80 | + spans[k].Attr |= a | ||
| 81 | + } | ||
| 82 | + return spans | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +// codeSpan reads `code` (or “co`de“) at i. | ||
| 86 | +func codeSpan(r []rune, i int) ([]Span, int, bool) { | ||
| 87 | + end, n := closingTicks(r, i) | ||
| 88 | + if end == 0 { | ||
| 89 | + return nil, 0, false | ||
| 90 | + } | ||
| 91 | + return []Span{{Text: strings.TrimSpace(string(r[i+n : end])), Style: styleCode}}, end + n, true | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +// closingTicks finds the run of backticks closing the one at i: the index of | ||
| 95 | +// the closing run and the run's length, or 0 when there is none. | ||
| 96 | +func closingTicks(r []rune, i int) (int, int) { | ||
| 97 | + n := tickRun(r, i) | ||
| 98 | + for j := i + n; j < len(r); j++ { | ||
| 99 | + if r[j] != '`' { | ||
| 100 | + continue | ||
| 101 | + } | ||
| 102 | + m := tickRun(r, j) | ||
| 103 | + if m == n { | ||
| 104 | + return j, n | ||
| 105 | + } | ||
| 106 | + j += m - 1 | ||
| 107 | + } | ||
| 108 | + return 0, n | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +// tickRun is the number of backticks in a row from i. | ||
| 112 | +func tickRun(r []rune, i int) int { | ||
| 113 | + n := 0 | ||
| 114 | + for i+n < len(r) && r[i+n] == '`' { | ||
| 115 | + n++ | ||
| 116 | + } | ||
| 117 | + return n | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +// linkSpans reads [label](url) at i: the label underlined, the url dimmed | ||
| 121 | +// after it unless it says the same. | ||
| 122 | +func linkSpans(r []rune, i int, base styleKind) ([]Span, int, bool) { | ||
| 123 | + label, url, next, ok := link(r, i) | ||
| 124 | + if !ok { | ||
| 125 | + return nil, 0, false | ||
| 126 | + } | ||
| 127 | + spans := withAttr(inline(label, base), attrUnderline) | ||
| 128 | + if url != "" && url != label { | ||
| 129 | + spans = append(spans, Span{Text: " (" + url + ")", Style: base, Attr: attrDim}) | ||
| 130 | + } | ||
| 131 | + return spans, next, true | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +// autoLink reads <https://…> or <http://…> at i, drawn underlined. | ||
| 135 | +func autoLink(r []rune, i int, base styleKind) ([]Span, int, bool) { | ||
| 136 | + end := strings.IndexRune(string(r[i+1:]), '>') | ||
| 137 | + if end <= 0 { | ||
| 138 | + return nil, 0, false | ||
| 139 | + } | ||
| 140 | + inner := string(r[i+1 : i+1+end]) | ||
| 141 | + if !strings.HasPrefix(inner, "http://") && !strings.HasPrefix(inner, "https://") { | ||
| 142 | + return nil, 0, false | ||
| 143 | + } | ||
| 144 | + return []Span{{Text: inner, Style: base, Attr: attrUnderline}}, i + end + 2, true | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +// link reads [label](url) at i. | ||
| 148 | +func link(r []rune, i int) (label, url string, next int, ok bool) { | ||
| 149 | + j := closingBracket(r, i) | ||
| 150 | + if j < 0 || j+1 >= len(r) || r[j+1] != '(' { | ||
| 151 | + return "", "", 0, false | ||
| 152 | + } | ||
| 153 | + end := strings.IndexRune(string(r[j+2:]), ')') | ||
| 154 | + if end < 0 { | ||
| 155 | + return "", "", 0, false | ||
| 156 | + } | ||
| 157 | + url = strings.TrimSpace(string(r[j+2 : j+2+end])) | ||
| 158 | + if k := strings.IndexAny(url, " \t"); k >= 0 { // [x](url "title") | ||
| 159 | + url = url[:k] | ||
| 160 | + } | ||
| 161 | + return string(r[i+1 : j]), url, j + 3 + end, true | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +// closingBracket is the index of the ] closing the [ at i, nested brackets | ||
| 165 | +// counted, or -1. | ||
| 166 | +func closingBracket(r []rune, i int) int { | ||
| 167 | + depth := 0 | ||
| 168 | + for j := i; j < len(r); j++ { | ||
| 169 | + switch r[j] { | ||
| 170 | + case '[': | ||
| 171 | + depth++ | ||
| 172 | + case ']': | ||
| 173 | + depth-- | ||
| 174 | + if depth == 0 { | ||
| 175 | + return j | ||
| 176 | + } | ||
| 177 | + } | ||
| 178 | + } | ||
| 179 | + return -1 | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +// emphasis reads **bold**, *italic*, ***both***, __bold__, _italic_ or | ||
| 183 | +// ~~struck~~ at i. An underscore inside a word (snake_case) is not one, and | ||
| 184 | +// neither is a marker followed by a space ("2 * 3"). | ||
| 185 | +func emphasis(r []rune, i int, base styleKind) ([]Span, int, bool) { | ||
| 186 | + c := r[i] | ||
| 187 | + n, ok := emphasisOpens(r, i) | ||
| 188 | + if !ok { | ||
| 189 | + return nil, 0, false | ||
| 190 | + } | ||
| 191 | + inner, after, ok := emphasisCloses(r, i+n, c, n) | ||
| 192 | + if !ok { | ||
| 193 | + return nil, 0, false | ||
| 194 | + } | ||
| 195 | + return withAttr(inline(inner, base), emphasisAttr(c, n)), after, true | ||
| 196 | +} | ||
| 197 | + | ||
| 198 | +// emphasisOpens reports whether the marker at i opens an emphasis, and the | ||
| 199 | +// length of its run (three at most). | ||
| 200 | +func emphasisOpens(r []rune, i int) (int, bool) { | ||
| 201 | + c := r[i] | ||
| 202 | + n := 0 | ||
| 203 | + for i+n < len(r) && r[i+n] == c && n < 3 { | ||
| 204 | + n++ | ||
| 205 | + } | ||
| 206 | + if c == '~' && n != 2 { | ||
| 207 | + return 0, false | ||
| 208 | + } | ||
| 209 | + if c == '_' && i > 0 && isWordRune(r[i-1]) { | ||
| 210 | + return 0, false | ||
| 211 | + } | ||
| 212 | + open := i + n | ||
| 213 | + return n, open < len(r) && !unicode.IsSpace(r[open]) | ||
| 214 | +} | ||
| 215 | + | ||
| 216 | +// emphasisCloses finds the run of n markers c closing an emphasis opened just | ||
| 217 | +// before open: the text between, and the index after the closing run. | ||
| 218 | +func emphasisCloses(r []rune, open int, c rune, n int) (string, int, bool) { | ||
| 219 | + marker := strings.Repeat(string(c), n) | ||
| 220 | + rest := string(r[open:]) | ||
| 221 | + for from := 0; ; { | ||
| 222 | + at := strings.Index(rest[from:], marker) | ||
| 223 | + if at < 0 { | ||
| 224 | + return "", 0, false | ||
| 225 | + } | ||
| 226 | + at += from | ||
| 227 | + inner := []rune(rest[:at]) | ||
| 228 | + after := open + len(inner) + n | ||
| 229 | + if closesEmphasis(r, inner, after, c) { | ||
| 230 | + return string(inner), after, true | ||
| 231 | + } | ||
| 232 | + from = at + len(marker) | ||
| 233 | + } | ||
| 234 | +} | ||
| 235 | + | ||
| 236 | +// closesEmphasis reports whether a run of markers c ending just before after | ||
| 237 | +// closes the emphasis around inner: inner not empty nor ending with a space, | ||
| 238 | +// and the run neither longer nor (for _) followed by a word. | ||
| 239 | +func closesEmphasis(r, inner []rune, after int, c rune) bool { | ||
| 240 | + if len(inner) == 0 || unicode.IsSpace(inner[len(inner)-1]) { | ||
| 241 | + return false | ||
| 242 | + } | ||
| 243 | + if after >= len(r) { | ||
| 244 | + return true | ||
| 245 | + } | ||
| 246 | + return r[after] != c && (c != '_' || !isWordRune(r[after])) | ||
| 247 | +} | ||
| 248 | + | ||
| 249 | +// emphasisAttr is what a run of n markers c adds. | ||
| 250 | +func emphasisAttr(c rune, n int) attr { | ||
| 251 | + switch { | ||
| 252 | + case c == '~': | ||
| 253 | + return attrStrike | ||
| 254 | + case n == 1: | ||
| 255 | + return attrItalic | ||
| 256 | + case n == 2: | ||
| 257 | + return attrBold | ||
| 258 | + } | ||
| 259 | + return attrBold | attrItalic | ||
| 260 | +} | ||
| 261 | + | ||
| 262 | +func isWordRune(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) } | ||
added
internal/tui/markdown_table.go +156 -0 | new file mode 100644 | ||
| @@ -0,0 +1,156 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import "strings" | |
| 4 | + | |
| 5 | +// isTableStart reports a table: a `|` row followed by a |---|---| line. | |
| 6 | +func isTableStart(src []string, i int) bool { | |
| 7 | + if i+1 >= len(src) || !strings.HasPrefix(strings.TrimSpace(src[i]), "|") { | |
| 8 | + return false | |
| 9 | + } | |
| 10 | + sep := strings.TrimSpace(src[i+1]) | |
| 11 | + return strings.HasPrefix(sep, "|") && strings.Trim(sep, "|-: ") == "" && strings.Contains(sep, "-") | |
| 12 | +} | |
| 13 | + | |
| 14 | +// cells splits a table row: "| a | b |" → ["a", "b"]. An escaped \| stays. | |
| 15 | +func cells(row string) []string { | |
| 16 | + row = strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(row), "|"), "|") | |
| 17 | + row = strings.ReplaceAll(row, `\|`, "\x00") | |
| 18 | + var out []string | |
| 19 | + for _, c := range strings.Split(row, "|") { | |
| 20 | + out = append(out, strings.ReplaceAll(strings.TrimSpace(c), "\x00", "|")) | |
| 21 | + } | |
| 22 | + return out | |
| 23 | +} | |
| 24 | + | |
| 25 | +// table lays a table out: columns as wide as their widest cell, the header | |
| 26 | +// bold, a ─┼─ line under it. A table wider than width has its widest columns | |
| 27 | +// narrowed and their cells cut with "…" — a table is read across, wrapping | |
| 28 | +// its cells would break that. | |
| 29 | +// | |
| 30 | +// table([]string{"| a | b |", "|---|---|", "| 1 | 2 |"}, 80) // "a │ b" · "──┼──" · "1 │ 2" | |
| 31 | +func table(rows []string, width int) [][]Span { | |
| 32 | + grid, cols := tableGrid(rows) | |
| 33 | + widths := fitWidths(columnWidths(grid, cols), width) | |
| 34 | + var out [][]Span | |
| 35 | + for r, row := range grid { | |
| 36 | + out = append(out, tableRow(row, widths, r == 0)) | |
| 37 | + if r == 0 { | |
| 38 | + out = append(out, tableRule(widths)) | |
| 39 | + } | |
| 40 | + } | |
| 41 | + return out | |
| 42 | +} | |
| 43 | + | |
| 44 | +// tableGrid parses the rows but the |---| line into cells of spans, and | |
| 45 | +// counts the columns of the widest row. | |
| 46 | +func tableGrid(rows []string) ([][][]Span, int) { | |
| 47 | + var grid [][][]Span | |
| 48 | + cols := 0 | |
| 49 | + for k, r := range rows { | |
| 50 | + if k == 1 { // the |---| line | |
| 51 | + continue | |
| 52 | + } | |
| 53 | + var row [][]Span | |
| 54 | + for _, c := range cells(r) { | |
| 55 | + row = append(row, inline(c, styleBody)) | |
| 56 | + } | |
| 57 | + cols = max(cols, len(row)) | |
| 58 | + grid = append(grid, row) | |
| 59 | + } | |
| 60 | + return grid, cols | |
| 61 | +} | |
| 62 | + | |
| 63 | +// columnWidths is the width of each column's widest cell. | |
| 64 | +func columnWidths(grid [][][]Span, cols int) []int { | |
| 65 | + widths := make([]int, cols) | |
| 66 | + for _, row := range grid { | |
| 67 | + for c, cell := range row { | |
| 68 | + widths[c] = max(widths[c], len([]rune(spansText(cell)))) | |
| 69 | + } | |
| 70 | + } | |
| 71 | + return widths | |
| 72 | +} | |
| 73 | + | |
| 74 | +// fitWidths narrows the widest column, one rune at a time, until the table | |
| 75 | +// fits width or every column is down to three runes. | |
| 76 | +func fitWidths(widths []int, width int) []int { | |
| 77 | + for total(widths) > width { | |
| 78 | + widest := 0 | |
| 79 | + for c := range widths { | |
| 80 | + if widths[c] > widths[widest] { | |
| 81 | + widest = c | |
| 82 | + } | |
| 83 | + } | |
| 84 | + if widths[widest] <= 3 { | |
| 85 | + break | |
| 86 | + } | |
| 87 | + widths[widest]-- | |
| 88 | + } | |
| 89 | + return widths | |
| 90 | +} | |
| 91 | + | |
| 92 | +// tableRow draws one row, its cells padded to their column's width. | |
| 93 | +func tableRow(row [][]Span, widths []int, header bool) []Span { | |
| 94 | + var line []Span | |
| 95 | + for c, w := range widths { | |
| 96 | + if c > 0 { | |
| 97 | + line = append(line, Span{Text: " │ ", Style: styleRule}) | |
| 98 | + } | |
| 99 | + line = append(line, tableCell(row, c, w, header)...) | |
| 100 | + } | |
| 101 | + return line | |
| 102 | +} | |
| 103 | + | |
| 104 | +// tableCell draws cell c of row cut or padded to w runes, bold in the header. | |
| 105 | +func tableCell(row [][]Span, c, w int, header bool) []Span { | |
| 106 | + var cell []Span | |
| 107 | + if c < len(row) { | |
| 108 | + cell = row[c] | |
| 109 | + } | |
| 110 | + cell = clipSpans(cell, w) | |
| 111 | + if header { | |
| 112 | + withAttr(cell, attrBold) | |
| 113 | + } | |
| 114 | + if fill := w - len([]rune(spansText(cell))); fill > 0 { | |
| 115 | + cell = append(cell, Span{Text: strings.Repeat(" ", fill)}) | |
| 116 | + } | |
| 117 | + return cell | |
| 118 | +} | |
| 119 | + | |
| 120 | +// tableRule is the ─┼─ line under the header. | |
| 121 | +func tableRule(widths []int) []Span { | |
| 122 | + var sep []string | |
| 123 | + for _, w := range widths { | |
| 124 | + sep = append(sep, strings.Repeat("─", w)) | |
| 125 | + } | |
| 126 | + return []Span{{Text: strings.Join(sep, "─┼─"), Style: styleRule}} | |
| 127 | +} | |
| 128 | + | |
| 129 | +// total is the drawn width of a table's columns, separators included. | |
| 130 | +func total(widths []int) int { | |
| 131 | + n := 3 * max(len(widths)-1, 0) | |
| 132 | + for _, w := range widths { | |
| 133 | + n += w | |
| 134 | + } | |
| 135 | + return n | |
| 136 | +} | |
| 137 | + | |
| 138 | +// clipSpans cuts spans to width runes, the last one ending with "…". | |
| 139 | +func clipSpans(spans []Span, width int) []Span { | |
| 140 | + if len([]rune(spansText(spans))) <= width { | |
| 141 | + return append([]Span(nil), spans...) | |
| 142 | + } | |
| 143 | + var out []Span | |
| 144 | + left := width - 1 | |
| 145 | + for _, s := range spans { | |
| 146 | + r := []rune(s.Text) | |
| 147 | + if len(r) > left { | |
| 148 | + s.Text = string(r[:max(left, 0)]) | |
| 149 | + out = append(out, s, Span{Text: "…", Style: s.Style, Attr: s.Attr}) | |
| 150 | + return out | |
| 151 | + } | |
| 152 | + out = append(out, s) | |
| 153 | + left -= len(r) | |
| 154 | + } | |
| 155 | + return out | |
| 156 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,156 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import "strings" | ||
| 4 | + | ||
| 5 | +// isTableStart reports a table: a `|` row followed by a |---|---| line. | ||
| 6 | +func isTableStart(src []string, i int) bool { | ||
| 7 | + if i+1 >= len(src) || !strings.HasPrefix(strings.TrimSpace(src[i]), "|") { | ||
| 8 | + return false | ||
| 9 | + } | ||
| 10 | + sep := strings.TrimSpace(src[i+1]) | ||
| 11 | + return strings.HasPrefix(sep, "|") && strings.Trim(sep, "|-: ") == "" && strings.Contains(sep, "-") | ||
| 12 | +} | ||
| 13 | + | ||
| 14 | +// cells splits a table row: "| a | b |" → ["a", "b"]. An escaped \| stays. | ||
| 15 | +func cells(row string) []string { | ||
| 16 | + row = strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(row), "|"), "|") | ||
| 17 | + row = strings.ReplaceAll(row, `\|`, "\x00") | ||
| 18 | + var out []string | ||
| 19 | + for _, c := range strings.Split(row, "|") { | ||
| 20 | + out = append(out, strings.ReplaceAll(strings.TrimSpace(c), "\x00", "|")) | ||
| 21 | + } | ||
| 22 | + return out | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +// table lays a table out: columns as wide as their widest cell, the header | ||
| 26 | +// bold, a ─┼─ line under it. A table wider than width has its widest columns | ||
| 27 | +// narrowed and their cells cut with "…" — a table is read across, wrapping | ||
| 28 | +// its cells would break that. | ||
| 29 | +// | ||
| 30 | +// table([]string{"| a | b |", "|---|---|", "| 1 | 2 |"}, 80) // "a │ b" · "──┼──" · "1 │ 2" | ||
| 31 | +func table(rows []string, width int) [][]Span { | ||
| 32 | + grid, cols := tableGrid(rows) | ||
| 33 | + widths := fitWidths(columnWidths(grid, cols), width) | ||
| 34 | + var out [][]Span | ||
| 35 | + for r, row := range grid { | ||
| 36 | + out = append(out, tableRow(row, widths, r == 0)) | ||
| 37 | + if r == 0 { | ||
| 38 | + out = append(out, tableRule(widths)) | ||
| 39 | + } | ||
| 40 | + } | ||
| 41 | + return out | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +// tableGrid parses the rows but the |---| line into cells of spans, and | ||
| 45 | +// counts the columns of the widest row. | ||
| 46 | +func tableGrid(rows []string) ([][][]Span, int) { | ||
| 47 | + var grid [][][]Span | ||
| 48 | + cols := 0 | ||
| 49 | + for k, r := range rows { | ||
| 50 | + if k == 1 { // the |---| line | ||
| 51 | + continue | ||
| 52 | + } | ||
| 53 | + var row [][]Span | ||
| 54 | + for _, c := range cells(r) { | ||
| 55 | + row = append(row, inline(c, styleBody)) | ||
| 56 | + } | ||
| 57 | + cols = max(cols, len(row)) | ||
| 58 | + grid = append(grid, row) | ||
| 59 | + } | ||
| 60 | + return grid, cols | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +// columnWidths is the width of each column's widest cell. | ||
| 64 | +func columnWidths(grid [][][]Span, cols int) []int { | ||
| 65 | + widths := make([]int, cols) | ||
| 66 | + for _, row := range grid { | ||
| 67 | + for c, cell := range row { | ||
| 68 | + widths[c] = max(widths[c], len([]rune(spansText(cell)))) | ||
| 69 | + } | ||
| 70 | + } | ||
| 71 | + return widths | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +// fitWidths narrows the widest column, one rune at a time, until the table | ||
| 75 | +// fits width or every column is down to three runes. | ||
| 76 | +func fitWidths(widths []int, width int) []int { | ||
| 77 | + for total(widths) > width { | ||
| 78 | + widest := 0 | ||
| 79 | + for c := range widths { | ||
| 80 | + if widths[c] > widths[widest] { | ||
| 81 | + widest = c | ||
| 82 | + } | ||
| 83 | + } | ||
| 84 | + if widths[widest] <= 3 { | ||
| 85 | + break | ||
| 86 | + } | ||
| 87 | + widths[widest]-- | ||
| 88 | + } | ||
| 89 | + return widths | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +// tableRow draws one row, its cells padded to their column's width. | ||
| 93 | +func tableRow(row [][]Span, widths []int, header bool) []Span { | ||
| 94 | + var line []Span | ||
| 95 | + for c, w := range widths { | ||
| 96 | + if c > 0 { | ||
| 97 | + line = append(line, Span{Text: " │ ", Style: styleRule}) | ||
| 98 | + } | ||
| 99 | + line = append(line, tableCell(row, c, w, header)...) | ||
| 100 | + } | ||
| 101 | + return line | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +// tableCell draws cell c of row cut or padded to w runes, bold in the header. | ||
| 105 | +func tableCell(row [][]Span, c, w int, header bool) []Span { | ||
| 106 | + var cell []Span | ||
| 107 | + if c < len(row) { | ||
| 108 | + cell = row[c] | ||
| 109 | + } | ||
| 110 | + cell = clipSpans(cell, w) | ||
| 111 | + if header { | ||
| 112 | + withAttr(cell, attrBold) | ||
| 113 | + } | ||
| 114 | + if fill := w - len([]rune(spansText(cell))); fill > 0 { | ||
| 115 | + cell = append(cell, Span{Text: strings.Repeat(" ", fill)}) | ||
| 116 | + } | ||
| 117 | + return cell | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +// tableRule is the ─┼─ line under the header. | ||
| 121 | +func tableRule(widths []int) []Span { | ||
| 122 | + var sep []string | ||
| 123 | + for _, w := range widths { | ||
| 124 | + sep = append(sep, strings.Repeat("─", w)) | ||
| 125 | + } | ||
| 126 | + return []Span{{Text: strings.Join(sep, "─┼─"), Style: styleRule}} | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +// total is the drawn width of a table's columns, separators included. | ||
| 130 | +func total(widths []int) int { | ||
| 131 | + n := 3 * max(len(widths)-1, 0) | ||
| 132 | + for _, w := range widths { | ||
| 133 | + n += w | ||
| 134 | + } | ||
| 135 | + return n | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +// clipSpans cuts spans to width runes, the last one ending with "…". | ||
| 139 | +func clipSpans(spans []Span, width int) []Span { | ||
| 140 | + if len([]rune(spansText(spans))) <= width { | ||
| 141 | + return append([]Span(nil), spans...) | ||
| 142 | + } | ||
| 143 | + var out []Span | ||
| 144 | + left := width - 1 | ||
| 145 | + for _, s := range spans { | ||
| 146 | + r := []rune(s.Text) | ||
| 147 | + if len(r) > left { | ||
| 148 | + s.Text = string(r[:max(left, 0)]) | ||
| 149 | + out = append(out, s, Span{Text: "…", Style: s.Style, Attr: s.Attr}) | ||
| 150 | + return out | ||
| 151 | + } | ||
| 152 | + out = append(out, s) | ||
| 153 | + left -= len(r) | ||
| 154 | + } | ||
| 155 | + return out | ||
| 156 | +} | ||
added
internal/tui/markdown_wrap.go +88 -0 | new file mode 100644 | ||
| @@ -0,0 +1,88 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import "strings" | |
| 4 | + | |
| 5 | +// spanCell is one rune of a wrapped text and the span it came from. | |
| 6 | +type spanCell struct { | |
| 7 | + r rune | |
| 8 | + at int // index of the span it came from | |
| 9 | +} | |
| 10 | + | |
| 11 | +// wrapSpans wraps spans to width runes, at spaces where it can, the way wrap | |
| 12 | +// does for plain text. first goes before the first line, rest before the | |
| 13 | +// others — a list item's bullet, then its hanging indent. | |
| 14 | +// | |
| 15 | +// wrapSpans(inline("a b c", styleBody), 3, nil, nil) // "a b" · "c" | |
| 16 | +func wrapSpans(spans []Span, width int, first, rest []Span) [][]Span { | |
| 17 | + cells := spanCells(spans) | |
| 18 | + var out [][]Span | |
| 19 | + prefix := first | |
| 20 | + for { | |
| 21 | + room := max(width-len([]rune(spansText(prefix))), 1) | |
| 22 | + if len(cells) <= room { | |
| 23 | + return append(out, cellLine(spans, prefix, cells)) | |
| 24 | + } | |
| 25 | + var line []spanCell | |
| 26 | + line, cells = cutCells(cells, room) | |
| 27 | + out = append(out, cellLine(spans, prefix, line)) | |
| 28 | + prefix = rest | |
| 29 | + if len(cells) == 0 { | |
| 30 | + return out | |
| 31 | + } | |
| 32 | + } | |
| 33 | +} | |
| 34 | + | |
| 35 | +// spanCells is the runes of spans, each with the index of its span. | |
| 36 | +func spanCells(spans []Span) []spanCell { | |
| 37 | + var cells []spanCell | |
| 38 | + for k, s := range spans { | |
| 39 | + for _, r := range s.Text { | |
| 40 | + cells = append(cells, spanCell{r, k}) | |
| 41 | + } | |
| 42 | + } | |
| 43 | + return cells | |
| 44 | +} | |
| 45 | + | |
| 46 | +// cutCells cuts the first line of at most room runes off cells, at a space | |
| 47 | +// where it can: the line without its trailing spaces, and what is left | |
| 48 | +// without its leading ones. | |
| 49 | +func cutCells(cells []spanCell, room int) (line, left []spanCell) { | |
| 50 | + runes := make([]rune, len(cells)) | |
| 51 | + for i, c := range cells { | |
| 52 | + runes[i] = c.r | |
| 53 | + } | |
| 54 | + at := breakPoint(runes, room) | |
| 55 | + end := at | |
| 56 | + for end > 0 && cells[end-1].r == ' ' { | |
| 57 | + end-- | |
| 58 | + } | |
| 59 | + left = cells[at:] | |
| 60 | + for len(left) > 0 && left[0].r == ' ' { | |
| 61 | + left = left[1:] | |
| 62 | + } | |
| 63 | + return cells[:end], left | |
| 64 | +} | |
| 65 | + | |
| 66 | +// cellLine turns cells back into spans behind prefix, one span per run of | |
| 67 | +// cells from the same source span, in that span's style. | |
| 68 | +func cellLine(spans, prefix []Span, part []spanCell) []Span { | |
| 69 | + line := append([]Span(nil), prefix...) | |
| 70 | + for i := 0; i < len(part); { | |
| 71 | + j := i | |
| 72 | + for j < len(part) && part[j].at == part[i].at { | |
| 73 | + j++ | |
| 74 | + } | |
| 75 | + line = append(line, cellSpan(spans[part[i].at], part[i:j])) | |
| 76 | + i = j | |
| 77 | + } | |
| 78 | + return line | |
| 79 | +} | |
| 80 | + | |
| 81 | +// cellSpan is cells drawn in the style of src. | |
| 82 | +func cellSpan(src Span, cells []spanCell) Span { | |
| 83 | + var b strings.Builder | |
| 84 | + for _, c := range cells { | |
| 85 | + b.WriteRune(c.r) | |
| 86 | + } | |
| 87 | + return Span{Text: b.String(), Style: src.Style, Attr: src.Attr} | |
| 88 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,88 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import "strings" | ||
| 4 | + | ||
| 5 | +// spanCell is one rune of a wrapped text and the span it came from. | ||
| 6 | +type spanCell struct { | ||
| 7 | + r rune | ||
| 8 | + at int // index of the span it came from | ||
| 9 | +} | ||
| 10 | + | ||
| 11 | +// wrapSpans wraps spans to width runes, at spaces where it can, the way wrap | ||
| 12 | +// does for plain text. first goes before the first line, rest before the | ||
| 13 | +// others — a list item's bullet, then its hanging indent. | ||
| 14 | +// | ||
| 15 | +// wrapSpans(inline("a b c", styleBody), 3, nil, nil) // "a b" · "c" | ||
| 16 | +func wrapSpans(spans []Span, width int, first, rest []Span) [][]Span { | ||
| 17 | + cells := spanCells(spans) | ||
| 18 | + var out [][]Span | ||
| 19 | + prefix := first | ||
| 20 | + for { | ||
| 21 | + room := max(width-len([]rune(spansText(prefix))), 1) | ||
| 22 | + if len(cells) <= room { | ||
| 23 | + return append(out, cellLine(spans, prefix, cells)) | ||
| 24 | + } | ||
| 25 | + var line []spanCell | ||
| 26 | + line, cells = cutCells(cells, room) | ||
| 27 | + out = append(out, cellLine(spans, prefix, line)) | ||
| 28 | + prefix = rest | ||
| 29 | + if len(cells) == 0 { | ||
| 30 | + return out | ||
| 31 | + } | ||
| 32 | + } | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +// spanCells is the runes of spans, each with the index of its span. | ||
| 36 | +func spanCells(spans []Span) []spanCell { | ||
| 37 | + var cells []spanCell | ||
| 38 | + for k, s := range spans { | ||
| 39 | + for _, r := range s.Text { | ||
| 40 | + cells = append(cells, spanCell{r, k}) | ||
| 41 | + } | ||
| 42 | + } | ||
| 43 | + return cells | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +// cutCells cuts the first line of at most room runes off cells, at a space | ||
| 47 | +// where it can: the line without its trailing spaces, and what is left | ||
| 48 | +// without its leading ones. | ||
| 49 | +func cutCells(cells []spanCell, room int) (line, left []spanCell) { | ||
| 50 | + runes := make([]rune, len(cells)) | ||
| 51 | + for i, c := range cells { | ||
| 52 | + runes[i] = c.r | ||
| 53 | + } | ||
| 54 | + at := breakPoint(runes, room) | ||
| 55 | + end := at | ||
| 56 | + for end > 0 && cells[end-1].r == ' ' { | ||
| 57 | + end-- | ||
| 58 | + } | ||
| 59 | + left = cells[at:] | ||
| 60 | + for len(left) > 0 && left[0].r == ' ' { | ||
| 61 | + left = left[1:] | ||
| 62 | + } | ||
| 63 | + return cells[:end], left | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +// cellLine turns cells back into spans behind prefix, one span per run of | ||
| 67 | +// cells from the same source span, in that span's style. | ||
| 68 | +func cellLine(spans, prefix []Span, part []spanCell) []Span { | ||
| 69 | + line := append([]Span(nil), prefix...) | ||
| 70 | + for i := 0; i < len(part); { | ||
| 71 | + j := i | ||
| 72 | + for j < len(part) && part[j].at == part[i].at { | ||
| 73 | + j++ | ||
| 74 | + } | ||
| 75 | + line = append(line, cellSpan(spans[part[i].at], part[i:j])) | ||
| 76 | + i = j | ||
| 77 | + } | ||
| 78 | + return line | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +// cellSpan is cells drawn in the style of src. | ||
| 82 | +func cellSpan(src Span, cells []spanCell) Span { | ||
| 83 | + var b strings.Builder | ||
| 84 | + for _, c := range cells { | ||
| 85 | + b.WriteRune(c.r) | ||
| 86 | + } | ||
| 87 | + return Span{Text: b.String(), Style: src.Style, Attr: src.Attr} | ||
| 88 | +} | ||
modified
internal/tui/picker.go +0 -145 | @@ -1,14 +1,9 @@ | ||
| 1 | 1 | package tui |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | - "os" | |
| 5 | - "path/filepath" | |
| 6 | - "sort" | |
| 7 | 4 | "strings" |
| 8 | 5 | |
| 9 | 6 | "mm/internal/command" |
| 10 | - "mm/internal/metaprompt" | |
| 11 | - "mm/internal/skills" | |
| 12 | 7 | ) |
| 13 | 8 | |
| 14 | 9 | // pickerRows is how many choices the popup shows at most. |
| @@ -95,146 +90,6 @@ func (v *View) tokenAtCursor() (token, bool) { | ||
| 95 | 90 | |
| 96 | 91 | func isSpaceRune(r rune) bool { return r == ' ' || r == '\t' } |
| 97 | 92 | |
| 98 | -// choices returns what the popup offers, or nothing when it must stay shut. | |
| 99 | -func (v *View) choices() []choice { | |
| 100 | - if typed, ok := v.bracketPartial(); ok { | |
| 101 | - if v.pick.dismissed && v.pick.dismissedFor == v.Input() { | |
| 102 | - return nil | |
| 103 | - } | |
| 104 | - return metaChoices(v.metaPrompts(), typed) | |
| 105 | - } | |
| 106 | - tok, ok := v.tokenAtCursor() | |
| 107 | - if !ok || (v.pick.dismissed && v.pick.dismissedFor == v.Input()) { | |
| 108 | - return nil | |
| 109 | - } | |
| 110 | - var out []choice | |
| 111 | - switch tok.trigger { | |
| 112 | - case '/': | |
| 113 | - // A command is the whole message: only offered as the first word of | |
| 114 | - // a one-line box, exactly as before. | |
| 115 | - if len(v.input) == 1 && tok.from == 0 { | |
| 116 | - out = commandChoices(tok.partial) | |
| 117 | - } | |
| 118 | - case '$': | |
| 119 | - out = skillChoices(v.skills, tok.partial) | |
| 120 | - case '@': | |
| 121 | - out = pathChoices(v.cwd, tok.partial) | |
| 122 | - } | |
| 123 | - return out | |
| 124 | -} | |
| 125 | - | |
| 126 | -// bracketPartial is what follows the `[` when the `[` picker may open: the | |
| 127 | -// box is one line that starts with `[`, has no `]` yet, and the cursor is at | |
| 128 | -// its end. Spaces are part of it — "[As a" narrows to the three "As a …". | |
| 129 | -func (v *View) bracketPartial() (string, bool) { | |
| 130 | - if len(v.input) != 1 { | |
| 131 | - return "", false | |
| 132 | - } | |
| 133 | - line := []rune(v.input[0]) | |
| 134 | - if len(line) == 0 || line[0] != '[' || v.column != len(line) { | |
| 135 | - return "", false | |
| 136 | - } | |
| 137 | - rest := string(line[1:]) | |
| 138 | - if strings.ContainsRune(rest, ']') { | |
| 139 | - return "", false | |
| 140 | - } | |
| 141 | - return rest, true | |
| 142 | -} | |
| 143 | - | |
| 144 | -// metaPrompts is the catalogue the `[` picker offers: the built-ins and the | |
| 145 | -// agent's own (Options.MetaPrompts); the built-ins alone when none was given. | |
| 146 | -func (v *View) metaPrompts() []metaprompt.MetaPrompt { | |
| 147 | - if v.metas == nil { | |
| 148 | - return metaprompt.All() | |
| 149 | - } | |
| 150 | - return v.metas | |
| 151 | -} | |
| 152 | - | |
| 153 | -// metaChoices narrows the meta-prompts by what follows the `[`. | |
| 154 | -func metaChoices(list []metaprompt.MetaPrompt, typed string) []choice { | |
| 155 | - var out []choice | |
| 156 | - for _, m := range metaprompt.Matching(list, typed) { | |
| 157 | - out = append(out, choice{insert: m.Prefix, label: m.Label(), detail: m.Description}) | |
| 158 | - } | |
| 159 | - return out | |
| 160 | -} | |
| 161 | - | |
| 162 | -func commandChoices(partial string) []choice { | |
| 163 | - var out []choice | |
| 164 | - for _, c := range command.For(command.Window) { | |
| 165 | - if strings.HasPrefix(c.Name, partial) { | |
| 166 | - out = append(out, choice{insert: c.Slash(), label: c.Slash(), detail: c.Description}) | |
| 167 | - } | |
| 168 | - } | |
| 169 | - return out | |
| 170 | -} | |
| 171 | - | |
| 172 | -// skillChoices narrows the catalogue by what follows the `$`. The `$` is kept | |
| 173 | -// in the inserted text: it is what tells the turn this skill is to be carried | |
| 174 | -// out, and it leaves the cursor in front of the parameters. | |
| 175 | -func skillChoices(list []skills.Skill, partial string) []choice { | |
| 176 | - var out []choice | |
| 177 | - for _, s := range list { | |
| 178 | - if !strings.HasPrefix(strings.ToLower(s.Name), strings.ToLower(partial)) { | |
| 179 | - continue | |
| 180 | - } | |
| 181 | - out = append(out, choice{insert: "$" + s.Name, label: "$" + s.Name, detail: s.Description}) | |
| 182 | - } | |
| 183 | - return out | |
| 184 | -} | |
| 185 | - | |
| 186 | -// pathChoices lists what is on disk under the directory the partial path | |
| 187 | -// names, narrowed by its last segment. A directory is offered with a | |
| 188 | -// trailing "/" so the next keystroke walks into it. | |
| 189 | -// | |
| 190 | -// It reads ONE directory per keystroke and stops at pickerRows*4 entries: | |
| 191 | -// the popup shows eight, and a node_modules must not stall the window. | |
| 192 | -func pathChoices(cwd, partial string) []choice { | |
| 193 | - dir, prefix := filepath.Split(partial) | |
| 194 | - base := filepath.Join(cwd, dir) | |
| 195 | - if strings.HasPrefix(dir, "~/") { | |
| 196 | - home, err := os.UserHomeDir() | |
| 197 | - if err != nil { | |
| 198 | - return nil | |
| 199 | - } | |
| 200 | - base = filepath.Join(home, strings.TrimPrefix(dir, "~/")) | |
| 201 | - } else if filepath.IsAbs(dir) { | |
| 202 | - base = dir | |
| 203 | - } | |
| 204 | - | |
| 205 | - entries, err := os.ReadDir(base) | |
| 206 | - if err != nil { | |
| 207 | - return nil | |
| 208 | - } | |
| 209 | - var out []choice | |
| 210 | - for _, e := range entries { | |
| 211 | - name := e.Name() | |
| 212 | - if strings.HasPrefix(name, ".") && !strings.HasPrefix(prefix, ".") { | |
| 213 | - continue // hidden files only once the user asks for them | |
| 214 | - } | |
| 215 | - if !strings.HasPrefix(strings.ToLower(name), strings.ToLower(prefix)) { | |
| 216 | - continue | |
| 217 | - } | |
| 218 | - shown, detail := name, "file" | |
| 219 | - if e.IsDir() { | |
| 220 | - shown, detail = name+"/", "directory" | |
| 221 | - } | |
| 222 | - out = append(out, choice{insert: "@" + dir + shown, label: shown, detail: detail}) | |
| 223 | - if len(out) >= pickerRows*4 { | |
| 224 | - break | |
| 225 | - } | |
| 226 | - } | |
| 227 | - // Directories first, then names: walking a tree is the common case. | |
| 228 | - sort.SliceStable(out, func(i, j int) bool { | |
| 229 | - di, dj := strings.HasSuffix(out[i].label, "/"), strings.HasSuffix(out[j].label, "/") | |
| 230 | - if di != dj { | |
| 231 | - return di | |
| 232 | - } | |
| 233 | - return out[i].label < out[j].label | |
| 234 | - }) | |
| 235 | - return out | |
| 236 | -} | |
| 237 | - | |
| 238 | 93 | // pickerOpen reports whether the popup is showing. |
| 239 | 94 | func (v *View) pickerOpen() bool { return len(v.choices()) > 0 } |
| 240 | 95 | |
| @@ -1,14 +1,9 @@ | |||
| 1 | package tui | 1 | package tui |
| 2 | 2 | ||
| 3 | import ( | 3 | import ( |
| 4 | - "os" | ||
| 5 | - "path/filepath" | ||
| 6 | - "sort" | ||
| 7 | "strings" | 4 | "strings" |
| 8 | 5 | ||
| 9 | "mm/internal/command" | 6 | "mm/internal/command" |
| 10 | - "mm/internal/metaprompt" | ||
| 11 | - "mm/internal/skills" | ||
| 12 | ) | 7 | ) |
| 13 | 8 | ||
| 14 | // pickerRows is how many choices the popup shows at most. | 9 | // pickerRows is how many choices the popup shows at most. |
| @@ -95,146 +90,6 @@ func (v *View) tokenAtCursor() (token, bool) { | |||
| 95 | 90 | ||
| 96 | func isSpaceRune(r rune) bool { return r == ' ' || r == '\t' } | 91 | func isSpaceRune(r rune) bool { return r == ' ' || r == '\t' } |
| 97 | 92 | ||
| 98 | -// choices returns what the popup offers, or nothing when it must stay shut. | ||
| 99 | -func (v *View) choices() []choice { | ||
| 100 | - if typed, ok := v.bracketPartial(); ok { | ||
| 101 | - if v.pick.dismissed && v.pick.dismissedFor == v.Input() { | ||
| 102 | - return nil | ||
| 103 | - } | ||
| 104 | - return metaChoices(v.metaPrompts(), typed) | ||
| 105 | - } | ||
| 106 | - tok, ok := v.tokenAtCursor() | ||
| 107 | - if !ok || (v.pick.dismissed && v.pick.dismissedFor == v.Input()) { | ||
| 108 | - return nil | ||
| 109 | - } | ||
| 110 | - var out []choice | ||
| 111 | - switch tok.trigger { | ||
| 112 | - case '/': | ||
| 113 | - // A command is the whole message: only offered as the first word of | ||
| 114 | - // a one-line box, exactly as before. | ||
| 115 | - if len(v.input) == 1 && tok.from == 0 { | ||
| 116 | - out = commandChoices(tok.partial) | ||
| 117 | - } | ||
| 118 | - case '$': | ||
| 119 | - out = skillChoices(v.skills, tok.partial) | ||
| 120 | - case '@': | ||
| 121 | - out = pathChoices(v.cwd, tok.partial) | ||
| 122 | - } | ||
| 123 | - return out | ||
| 124 | -} | ||
| 125 | - | ||
| 126 | -// bracketPartial is what follows the `[` when the `[` picker may open: the | ||
| 127 | -// box is one line that starts with `[`, has no `]` yet, and the cursor is at | ||
| 128 | -// its end. Spaces are part of it — "[As a" narrows to the three "As a …". | ||
| 129 | -func (v *View) bracketPartial() (string, bool) { | ||
| 130 | - if len(v.input) != 1 { | ||
| 131 | - return "", false | ||
| 132 | - } | ||
| 133 | - line := []rune(v.input[0]) | ||
| 134 | - if len(line) == 0 || line[0] != '[' || v.column != len(line) { | ||
| 135 | - return "", false | ||
| 136 | - } | ||
| 137 | - rest := string(line[1:]) | ||
| 138 | - if strings.ContainsRune(rest, ']') { | ||
| 139 | - return "", false | ||
| 140 | - } | ||
| 141 | - return rest, true | ||
| 142 | -} | ||
| 143 | - | ||
| 144 | -// metaPrompts is the catalogue the `[` picker offers: the built-ins and the | ||
| 145 | -// agent's own (Options.MetaPrompts); the built-ins alone when none was given. | ||
| 146 | -func (v *View) metaPrompts() []metaprompt.MetaPrompt { | ||
| 147 | - if v.metas == nil { | ||
| 148 | - return metaprompt.All() | ||
| 149 | - } | ||
| 150 | - return v.metas | ||
| 151 | -} | ||
| 152 | - | ||
| 153 | -// metaChoices narrows the meta-prompts by what follows the `[`. | ||
| 154 | -func metaChoices(list []metaprompt.MetaPrompt, typed string) []choice { | ||
| 155 | - var out []choice | ||
| 156 | - for _, m := range metaprompt.Matching(list, typed) { | ||
| 157 | - out = append(out, choice{insert: m.Prefix, label: m.Label(), detail: m.Description}) | ||
| 158 | - } | ||
| 159 | - return out | ||
| 160 | -} | ||
| 161 | - | ||
| 162 | -func commandChoices(partial string) []choice { | ||
| 163 | - var out []choice | ||
| 164 | - for _, c := range command.For(command.Window) { | ||
| 165 | - if strings.HasPrefix(c.Name, partial) { | ||
| 166 | - out = append(out, choice{insert: c.Slash(), label: c.Slash(), detail: c.Description}) | ||
| 167 | - } | ||
| 168 | - } | ||
| 169 | - return out | ||
| 170 | -} | ||
| 171 | - | ||
| 172 | -// skillChoices narrows the catalogue by what follows the `$`. The `$` is kept | ||
| 173 | -// in the inserted text: it is what tells the turn this skill is to be carried | ||
| 174 | -// out, and it leaves the cursor in front of the parameters. | ||
| 175 | -func skillChoices(list []skills.Skill, partial string) []choice { | ||
| 176 | - var out []choice | ||
| 177 | - for _, s := range list { | ||
| 178 | - if !strings.HasPrefix(strings.ToLower(s.Name), strings.ToLower(partial)) { | ||
| 179 | - continue | ||
| 180 | - } | ||
| 181 | - out = append(out, choice{insert: "$" + s.Name, label: "$" + s.Name, detail: s.Description}) | ||
| 182 | - } | ||
| 183 | - return out | ||
| 184 | -} | ||
| 185 | - | ||
| 186 | -// pathChoices lists what is on disk under the directory the partial path | ||
| 187 | -// names, narrowed by its last segment. A directory is offered with a | ||
| 188 | -// trailing "/" so the next keystroke walks into it. | ||
| 189 | -// | ||
| 190 | -// It reads ONE directory per keystroke and stops at pickerRows*4 entries: | ||
| 191 | -// the popup shows eight, and a node_modules must not stall the window. | ||
| 192 | -func pathChoices(cwd, partial string) []choice { | ||
| 193 | - dir, prefix := filepath.Split(partial) | ||
| 194 | - base := filepath.Join(cwd, dir) | ||
| 195 | - if strings.HasPrefix(dir, "~/") { | ||
| 196 | - home, err := os.UserHomeDir() | ||
| 197 | - if err != nil { | ||
| 198 | - return nil | ||
| 199 | - } | ||
| 200 | - base = filepath.Join(home, strings.TrimPrefix(dir, "~/")) | ||
| 201 | - } else if filepath.IsAbs(dir) { | ||
| 202 | - base = dir | ||
| 203 | - } | ||
| 204 | - | ||
| 205 | - entries, err := os.ReadDir(base) | ||
| 206 | - if err != nil { | ||
| 207 | - return nil | ||
| 208 | - } | ||
| 209 | - var out []choice | ||
| 210 | - for _, e := range entries { | ||
| 211 | - name := e.Name() | ||
| 212 | - if strings.HasPrefix(name, ".") && !strings.HasPrefix(prefix, ".") { | ||
| 213 | - continue // hidden files only once the user asks for them | ||
| 214 | - } | ||
| 215 | - if !strings.HasPrefix(strings.ToLower(name), strings.ToLower(prefix)) { | ||
| 216 | - continue | ||
| 217 | - } | ||
| 218 | - shown, detail := name, "file" | ||
| 219 | - if e.IsDir() { | ||
| 220 | - shown, detail = name+"/", "directory" | ||
| 221 | - } | ||
| 222 | - out = append(out, choice{insert: "@" + dir + shown, label: shown, detail: detail}) | ||
| 223 | - if len(out) >= pickerRows*4 { | ||
| 224 | - break | ||
| 225 | - } | ||
| 226 | - } | ||
| 227 | - // Directories first, then names: walking a tree is the common case. | ||
| 228 | - sort.SliceStable(out, func(i, j int) bool { | ||
| 229 | - di, dj := strings.HasSuffix(out[i].label, "/"), strings.HasSuffix(out[j].label, "/") | ||
| 230 | - if di != dj { | ||
| 231 | - return di | ||
| 232 | - } | ||
| 233 | - return out[i].label < out[j].label | ||
| 234 | - }) | ||
| 235 | - return out | ||
| 236 | -} | ||
| 237 | - | ||
| 238 | // pickerOpen reports whether the popup is showing. | 93 | // pickerOpen reports whether the popup is showing. |
| 239 | func (v *View) pickerOpen() bool { return len(v.choices()) > 0 } | 94 | func (v *View) pickerOpen() bool { return len(v.choices()) > 0 } |
| 240 | 95 | ||
added
internal/tui/picker_choices.go +151 -0 | new file mode 100644 | ||
| @@ -0,0 +1,151 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "mm/internal/command" | |
| 5 | + "mm/internal/metaprompt" | |
| 6 | + "mm/internal/skills" | |
| 7 | + "os" | |
| 8 | + "path/filepath" | |
| 9 | + "sort" | |
| 10 | + "strings" | |
| 11 | +) | |
| 12 | + | |
| 13 | +// choices returns what the popup offers, or nothing when it must stay shut. | |
| 14 | +func (v *View) choices() []choice { | |
| 15 | + if typed, ok := v.bracketPartial(); ok { | |
| 16 | + if v.pick.dismissed && v.pick.dismissedFor == v.Input() { | |
| 17 | + return nil | |
| 18 | + } | |
| 19 | + return metaChoices(v.metaPrompts(), typed) | |
| 20 | + } | |
| 21 | + tok, ok := v.tokenAtCursor() | |
| 22 | + if !ok || (v.pick.dismissed && v.pick.dismissedFor == v.Input()) { | |
| 23 | + return nil | |
| 24 | + } | |
| 25 | + var out []choice | |
| 26 | + switch tok.trigger { | |
| 27 | + case '/': | |
| 28 | + // A command is the whole message: only offered as the first word of | |
| 29 | + // a one-line box, exactly as before. | |
| 30 | + if len(v.input) == 1 && tok.from == 0 { | |
| 31 | + out = commandChoices(tok.partial) | |
| 32 | + } | |
| 33 | + case '$': | |
| 34 | + out = skillChoices(v.skills, tok.partial) | |
| 35 | + case '@': | |
| 36 | + out = pathChoices(v.cwd, tok.partial) | |
| 37 | + } | |
| 38 | + return out | |
| 39 | +} | |
| 40 | + | |
| 41 | +// bracketPartial is what follows the `[` when the `[` picker may open: the | |
| 42 | +// box is one line that starts with `[`, has no `]` yet, and the cursor is at | |
| 43 | +// its end. Spaces are part of it — "[As a" narrows to the three "As a …". | |
| 44 | +func (v *View) bracketPartial() (string, bool) { | |
| 45 | + if len(v.input) != 1 { | |
| 46 | + return "", false | |
| 47 | + } | |
| 48 | + line := []rune(v.input[0]) | |
| 49 | + if len(line) == 0 || line[0] != '[' || v.column != len(line) { | |
| 50 | + return "", false | |
| 51 | + } | |
| 52 | + rest := string(line[1:]) | |
| 53 | + if strings.ContainsRune(rest, ']') { | |
| 54 | + return "", false | |
| 55 | + } | |
| 56 | + return rest, true | |
| 57 | +} | |
| 58 | + | |
| 59 | +// metaPrompts is the catalogue the `[` picker offers: the built-ins and the | |
| 60 | +// agent's own (Options.MetaPrompts); the built-ins alone when none was given. | |
| 61 | +func (v *View) metaPrompts() []metaprompt.MetaPrompt { | |
| 62 | + if v.metas == nil { | |
| 63 | + return metaprompt.All() | |
| 64 | + } | |
| 65 | + return v.metas | |
| 66 | +} | |
| 67 | + | |
| 68 | +// metaChoices narrows the meta-prompts by what follows the `[`. | |
| 69 | +func metaChoices(list []metaprompt.MetaPrompt, typed string) []choice { | |
| 70 | + var out []choice | |
| 71 | + for _, m := range metaprompt.Matching(list, typed) { | |
| 72 | + out = append(out, choice{insert: m.Prefix, label: m.Label(), detail: m.Description}) | |
| 73 | + } | |
| 74 | + return out | |
| 75 | +} | |
| 76 | + | |
| 77 | +func commandChoices(partial string) []choice { | |
| 78 | + var out []choice | |
| 79 | + for _, c := range command.For(command.Window) { | |
| 80 | + if strings.HasPrefix(c.Name, partial) { | |
| 81 | + out = append(out, choice{insert: c.Slash(), label: c.Slash(), detail: c.Description}) | |
| 82 | + } | |
| 83 | + } | |
| 84 | + return out | |
| 85 | +} | |
| 86 | + | |
| 87 | +// skillChoices narrows the catalogue by what follows the `$`. The `$` is kept | |
| 88 | +// in the inserted text: it is what tells the turn this skill is to be carried | |
| 89 | +// out, and it leaves the cursor in front of the parameters. | |
| 90 | +func skillChoices(list []skills.Skill, partial string) []choice { | |
| 91 | + var out []choice | |
| 92 | + for _, s := range list { | |
| 93 | + if !strings.HasPrefix(strings.ToLower(s.Name), strings.ToLower(partial)) { | |
| 94 | + continue | |
| 95 | + } | |
| 96 | + out = append(out, choice{insert: "$" + s.Name, label: "$" + s.Name, detail: s.Description}) | |
| 97 | + } | |
| 98 | + return out | |
| 99 | +} | |
| 100 | + | |
| 101 | +// pathChoices lists what is on disk under the directory the partial path | |
| 102 | +// names, narrowed by its last segment. A directory is offered with a | |
| 103 | +// trailing "/" so the next keystroke walks into it. | |
| 104 | +// | |
| 105 | +// It reads ONE directory per keystroke and stops at pickerRows*4 entries: | |
| 106 | +// the popup shows eight, and a node_modules must not stall the window. | |
| 107 | +func pathChoices(cwd, partial string) []choice { | |
| 108 | + dir, prefix := filepath.Split(partial) | |
| 109 | + base := filepath.Join(cwd, dir) | |
| 110 | + if strings.HasPrefix(dir, "~/") { | |
| 111 | + home, err := os.UserHomeDir() | |
| 112 | + if err != nil { | |
| 113 | + return nil | |
| 114 | + } | |
| 115 | + base = filepath.Join(home, strings.TrimPrefix(dir, "~/")) | |
| 116 | + } else if filepath.IsAbs(dir) { | |
| 117 | + base = dir | |
| 118 | + } | |
| 119 | + | |
| 120 | + entries, err := os.ReadDir(base) | |
| 121 | + if err != nil { | |
| 122 | + return nil | |
| 123 | + } | |
| 124 | + var out []choice | |
| 125 | + for _, e := range entries { | |
| 126 | + name := e.Name() | |
| 127 | + if strings.HasPrefix(name, ".") && !strings.HasPrefix(prefix, ".") { | |
| 128 | + continue // hidden files only once the user asks for them | |
| 129 | + } | |
| 130 | + if !strings.HasPrefix(strings.ToLower(name), strings.ToLower(prefix)) { | |
| 131 | + continue | |
| 132 | + } | |
| 133 | + shown, detail := name, "file" | |
| 134 | + if e.IsDir() { | |
| 135 | + shown, detail = name+"/", "directory" | |
| 136 | + } | |
| 137 | + out = append(out, choice{insert: "@" + dir + shown, label: shown, detail: detail}) | |
| 138 | + if len(out) >= pickerRows*4 { | |
| 139 | + break | |
| 140 | + } | |
| 141 | + } | |
| 142 | + // Directories first, then names: walking a tree is the common case. | |
| 143 | + sort.SliceStable(out, func(i, j int) bool { | |
| 144 | + di, dj := strings.HasSuffix(out[i].label, "/"), strings.HasSuffix(out[j].label, "/") | |
| 145 | + if di != dj { | |
| 146 | + return di | |
| 147 | + } | |
| 148 | + return out[i].label < out[j].label | |
| 149 | + }) | |
| 150 | + return out | |
| 151 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,151 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "mm/internal/command" | ||
| 5 | + "mm/internal/metaprompt" | ||
| 6 | + "mm/internal/skills" | ||
| 7 | + "os" | ||
| 8 | + "path/filepath" | ||
| 9 | + "sort" | ||
| 10 | + "strings" | ||
| 11 | +) | ||
| 12 | + | ||
| 13 | +// choices returns what the popup offers, or nothing when it must stay shut. | ||
| 14 | +func (v *View) choices() []choice { | ||
| 15 | + if typed, ok := v.bracketPartial(); ok { | ||
| 16 | + if v.pick.dismissed && v.pick.dismissedFor == v.Input() { | ||
| 17 | + return nil | ||
| 18 | + } | ||
| 19 | + return metaChoices(v.metaPrompts(), typed) | ||
| 20 | + } | ||
| 21 | + tok, ok := v.tokenAtCursor() | ||
| 22 | + if !ok || (v.pick.dismissed && v.pick.dismissedFor == v.Input()) { | ||
| 23 | + return nil | ||
| 24 | + } | ||
| 25 | + var out []choice | ||
| 26 | + switch tok.trigger { | ||
| 27 | + case '/': | ||
| 28 | + // A command is the whole message: only offered as the first word of | ||
| 29 | + // a one-line box, exactly as before. | ||
| 30 | + if len(v.input) == 1 && tok.from == 0 { | ||
| 31 | + out = commandChoices(tok.partial) | ||
| 32 | + } | ||
| 33 | + case '$': | ||
| 34 | + out = skillChoices(v.skills, tok.partial) | ||
| 35 | + case '@': | ||
| 36 | + out = pathChoices(v.cwd, tok.partial) | ||
| 37 | + } | ||
| 38 | + return out | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +// bracketPartial is what follows the `[` when the `[` picker may open: the | ||
| 42 | +// box is one line that starts with `[`, has no `]` yet, and the cursor is at | ||
| 43 | +// its end. Spaces are part of it — "[As a" narrows to the three "As a …". | ||
| 44 | +func (v *View) bracketPartial() (string, bool) { | ||
| 45 | + if len(v.input) != 1 { | ||
| 46 | + return "", false | ||
| 47 | + } | ||
| 48 | + line := []rune(v.input[0]) | ||
| 49 | + if len(line) == 0 || line[0] != '[' || v.column != len(line) { | ||
| 50 | + return "", false | ||
| 51 | + } | ||
| 52 | + rest := string(line[1:]) | ||
| 53 | + if strings.ContainsRune(rest, ']') { | ||
| 54 | + return "", false | ||
| 55 | + } | ||
| 56 | + return rest, true | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +// metaPrompts is the catalogue the `[` picker offers: the built-ins and the | ||
| 60 | +// agent's own (Options.MetaPrompts); the built-ins alone when none was given. | ||
| 61 | +func (v *View) metaPrompts() []metaprompt.MetaPrompt { | ||
| 62 | + if v.metas == nil { | ||
| 63 | + return metaprompt.All() | ||
| 64 | + } | ||
| 65 | + return v.metas | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +// metaChoices narrows the meta-prompts by what follows the `[`. | ||
| 69 | +func metaChoices(list []metaprompt.MetaPrompt, typed string) []choice { | ||
| 70 | + var out []choice | ||
| 71 | + for _, m := range metaprompt.Matching(list, typed) { | ||
| 72 | + out = append(out, choice{insert: m.Prefix, label: m.Label(), detail: m.Description}) | ||
| 73 | + } | ||
| 74 | + return out | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +func commandChoices(partial string) []choice { | ||
| 78 | + var out []choice | ||
| 79 | + for _, c := range command.For(command.Window) { | ||
| 80 | + if strings.HasPrefix(c.Name, partial) { | ||
| 81 | + out = append(out, choice{insert: c.Slash(), label: c.Slash(), detail: c.Description}) | ||
| 82 | + } | ||
| 83 | + } | ||
| 84 | + return out | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +// skillChoices narrows the catalogue by what follows the `$`. The `$` is kept | ||
| 88 | +// in the inserted text: it is what tells the turn this skill is to be carried | ||
| 89 | +// out, and it leaves the cursor in front of the parameters. | ||
| 90 | +func skillChoices(list []skills.Skill, partial string) []choice { | ||
| 91 | + var out []choice | ||
| 92 | + for _, s := range list { | ||
| 93 | + if !strings.HasPrefix(strings.ToLower(s.Name), strings.ToLower(partial)) { | ||
| 94 | + continue | ||
| 95 | + } | ||
| 96 | + out = append(out, choice{insert: "$" + s.Name, label: "$" + s.Name, detail: s.Description}) | ||
| 97 | + } | ||
| 98 | + return out | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +// pathChoices lists what is on disk under the directory the partial path | ||
| 102 | +// names, narrowed by its last segment. A directory is offered with a | ||
| 103 | +// trailing "/" so the next keystroke walks into it. | ||
| 104 | +// | ||
| 105 | +// It reads ONE directory per keystroke and stops at pickerRows*4 entries: | ||
| 106 | +// the popup shows eight, and a node_modules must not stall the window. | ||
| 107 | +func pathChoices(cwd, partial string) []choice { | ||
| 108 | + dir, prefix := filepath.Split(partial) | ||
| 109 | + base := filepath.Join(cwd, dir) | ||
| 110 | + if strings.HasPrefix(dir, "~/") { | ||
| 111 | + home, err := os.UserHomeDir() | ||
| 112 | + if err != nil { | ||
| 113 | + return nil | ||
| 114 | + } | ||
| 115 | + base = filepath.Join(home, strings.TrimPrefix(dir, "~/")) | ||
| 116 | + } else if filepath.IsAbs(dir) { | ||
| 117 | + base = dir | ||
| 118 | + } | ||
| 119 | + | ||
| 120 | + entries, err := os.ReadDir(base) | ||
| 121 | + if err != nil { | ||
| 122 | + return nil | ||
| 123 | + } | ||
| 124 | + var out []choice | ||
| 125 | + for _, e := range entries { | ||
| 126 | + name := e.Name() | ||
| 127 | + if strings.HasPrefix(name, ".") && !strings.HasPrefix(prefix, ".") { | ||
| 128 | + continue // hidden files only once the user asks for them | ||
| 129 | + } | ||
| 130 | + if !strings.HasPrefix(strings.ToLower(name), strings.ToLower(prefix)) { | ||
| 131 | + continue | ||
| 132 | + } | ||
| 133 | + shown, detail := name, "file" | ||
| 134 | + if e.IsDir() { | ||
| 135 | + shown, detail = name+"/", "directory" | ||
| 136 | + } | ||
| 137 | + out = append(out, choice{insert: "@" + dir + shown, label: shown, detail: detail}) | ||
| 138 | + if len(out) >= pickerRows*4 { | ||
| 139 | + break | ||
| 140 | + } | ||
| 141 | + } | ||
| 142 | + // Directories first, then names: walking a tree is the common case. | ||
| 143 | + sort.SliceStable(out, func(i, j int) bool { | ||
| 144 | + di, dj := strings.HasSuffix(out[i].label, "/"), strings.HasSuffix(out[j].label, "/") | ||
| 145 | + if di != dj { | ||
| 146 | + return di | ||
| 147 | + } | ||
| 148 | + return out[i].label < out[j].label | ||
| 149 | + }) | ||
| 150 | + return out | ||
| 151 | +} | ||
added
internal/tui/picker_draw.go +46 -0 | new file mode 100644 | ||
| @@ -0,0 +1,46 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import "strings" | |
| 4 | + | |
| 5 | +// drawPicker paints the popup over the bottom of the conversation: one row | |
| 6 | +// per choice, the highlighted one in reverse, scrolled so that it is shown. | |
| 7 | +func (v *View) drawPicker(p painter) { | |
| 8 | + cs := v.choices() | |
| 9 | + if len(cs) == 0 { | |
| 10 | + return | |
| 11 | + } | |
| 12 | + rows := min(len(cs), pickerRows, p.height()) | |
| 13 | + top := p.height() - rows | |
| 14 | + // The label column is as wide as the widest label, so the details line | |
| 15 | + // up whichever trigger is open — commands, paths and skills all differ. | |
| 16 | + labels := 0 | |
| 17 | + width := 0 | |
| 18 | + for _, c := range cs { | |
| 19 | + labels = max(labels, len([]rune(c.label))) | |
| 20 | + } | |
| 21 | + labels = min(labels, p.width()/2) | |
| 22 | + for _, c := range cs { | |
| 23 | + width = max(width, labels+2+len([]rune(c.detail))) | |
| 24 | + } | |
| 25 | + width = min(width+4, p.width()) | |
| 26 | + first := pickerFirst(len(cs), rows, v.pick.selected) | |
| 27 | + for i := 0; i < rows; i++ { | |
| 28 | + c := cs[first+i] | |
| 29 | + style := stBody | |
| 30 | + if first+i == v.pick.selected { | |
| 31 | + style = stPick | |
| 32 | + } | |
| 33 | + text := " " + c.label + strings.Repeat(" ", max(labels-len([]rune(c.label))+2, 1)) + c.detail | |
| 34 | + p.hline(0, top+i, width, ' ', style) | |
| 35 | + p.textLimited(0, top+i, width, text, style) | |
| 36 | + } | |
| 37 | +} | |
| 38 | + | |
| 39 | +// pickerFirst is the first choice shown when only rows of n fit: 0 until the | |
| 40 | +// selection goes past the last row, then the window follows it — without | |
| 41 | +// it, the arrows selected choices nobody could see (/unload, the tenth | |
| 42 | +// command, was never shown). | |
| 43 | +func pickerFirst(n, rows, selected int) int { | |
| 44 | + selected = min(selected, n-1) | |
| 45 | + return max(0, selected-rows+1) | |
| 46 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,46 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import "strings" | ||
| 4 | + | ||
| 5 | +// drawPicker paints the popup over the bottom of the conversation: one row | ||
| 6 | +// per choice, the highlighted one in reverse, scrolled so that it is shown. | ||
| 7 | +func (v *View) drawPicker(p painter) { | ||
| 8 | + cs := v.choices() | ||
| 9 | + if len(cs) == 0 { | ||
| 10 | + return | ||
| 11 | + } | ||
| 12 | + rows := min(len(cs), pickerRows, p.height()) | ||
| 13 | + top := p.height() - rows | ||
| 14 | + // The label column is as wide as the widest label, so the details line | ||
| 15 | + // up whichever trigger is open — commands, paths and skills all differ. | ||
| 16 | + labels := 0 | ||
| 17 | + width := 0 | ||
| 18 | + for _, c := range cs { | ||
| 19 | + labels = max(labels, len([]rune(c.label))) | ||
| 20 | + } | ||
| 21 | + labels = min(labels, p.width()/2) | ||
| 22 | + for _, c := range cs { | ||
| 23 | + width = max(width, labels+2+len([]rune(c.detail))) | ||
| 24 | + } | ||
| 25 | + width = min(width+4, p.width()) | ||
| 26 | + first := pickerFirst(len(cs), rows, v.pick.selected) | ||
| 27 | + for i := 0; i < rows; i++ { | ||
| 28 | + c := cs[first+i] | ||
| 29 | + style := stBody | ||
| 30 | + if first+i == v.pick.selected { | ||
| 31 | + style = stPick | ||
| 32 | + } | ||
| 33 | + text := " " + c.label + strings.Repeat(" ", max(labels-len([]rune(c.label))+2, 1)) + c.detail | ||
| 34 | + p.hline(0, top+i, width, ' ', style) | ||
| 35 | + p.textLimited(0, top+i, width, text, style) | ||
| 36 | + } | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +// pickerFirst is the first choice shown when only rows of n fit: 0 until the | ||
| 40 | +// selection goes past the last row, then the window follows it — without | ||
| 41 | +// it, the arrows selected choices nobody could see (/unload, the tenth | ||
| 42 | +// command, was never shown). | ||
| 43 | +func pickerFirst(n, rows, selected int) int { | ||
| 44 | + selected = min(selected, n-1) | ||
| 45 | + return max(0, selected-rows+1) | ||
| 46 | +} | ||
modified
internal/tui/question.go +65 -181 | @@ -1,8 +1,6 @@ | ||
| 1 | 1 | package tui |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | - "context" | |
| 5 | - "fmt" | |
| 6 | 4 | "strings" |
| 7 | 5 | |
| 8 | 6 | "github.com/gdamore/tcell/v2" |
| @@ -29,55 +27,8 @@ import ( | ||
| 29 | 27 | // Several questions are asked one after the other; the answers go back |
| 30 | 28 | // together when the last one is answered. |
| 31 | 29 | |
| 32 | -// formAsk is a form waiting for the user. | |
| 33 | -type formAsk struct { | |
| 34 | - form elicit.Form | |
| 35 | - reply chan elicit.Result // the runner's, buffered; the view never writes it | |
| 36 | -} | |
| 37 | - | |
| 38 | -// --- runner side ------------------------------------------------------------------ | |
| 39 | - | |
| 40 | -// currentForm is the form waiting for answers, nil when none. | |
| 41 | -func (r *runner) currentForm() *formAsk { | |
| 42 | - r.askMu.Lock() | |
| 43 | - defer r.askMu.Unlock() | |
| 44 | - return r.form | |
| 45 | -} | |
| 46 | - | |
| 47 | -// answerForm settles the pending form from the loop goroutine. | |
| 48 | -func (r *runner) answerForm(res elicit.Result) { | |
| 49 | - r.askMu.Lock() | |
| 50 | - defer r.askMu.Unlock() | |
| 51 | - if r.form == nil { | |
| 52 | - return | |
| 53 | - } | |
| 54 | - r.form.reply <- res | |
| 55 | - r.form = nil | |
| 56 | -} | |
| 57 | - | |
| 58 | -// elicit posts a form for the view to show and waits for the answers, or for | |
| 59 | -// the turn to end (Cancelled). Called on the tool's goroutine. | |
| 60 | -func (r *runner) elicit(ctx context.Context, f elicit.Form) elicit.Result { | |
| 61 | - ask := &formAsk{form: f, reply: make(chan elicit.Result, 1)} | |
| 62 | - r.askMu.Lock() | |
| 63 | - r.form = ask | |
| 64 | - r.askMu.Unlock() | |
| 65 | - r.wake() | |
| 66 | - select { | |
| 67 | - case res := <-ask.reply: | |
| 68 | - return res | |
| 69 | - case <-ctx.Done(): | |
| 70 | - r.askMu.Lock() | |
| 71 | - if r.form == ask { | |
| 72 | - r.form = nil | |
| 73 | - } | |
| 74 | - r.askMu.Unlock() | |
| 75 | - r.wake() | |
| 76 | - return elicit.Result{Status: elicit.Cancelled} | |
| 77 | - } | |
| 78 | -} | |
| 79 | - | |
| 80 | -// --- view side -------------------------------------------------------------------- | |
| 30 | +// The runner side — the form waiting for answers — is in question_runner.go, | |
| 31 | +// the drawing in question_draw.go; this file is the view's keys. | |
| 81 | 32 | |
| 82 | 33 | // formView is what the view keeps while a form is shown: which question, |
| 83 | 34 | // where the highlight is, what is ticked or typed, the answers so far. |
| @@ -169,34 +120,66 @@ func (v *View) formListKey(ev *tcell.EventKey) { | ||
| 169 | 120 | f, q := v.form, v.form.question() |
| 170 | 121 | rows := f.rows() |
| 171 | 122 | onOther := q.AllowOther && f.cursor == len(q.Options) |
| 123 | + space := ev.Key() == tcell.KeyRune && ev.Rune() == ' ' | |
| 172 | 124 | switch { |
| 173 | 125 | case ev.Key() == tcell.KeyUp: |
| 174 | 126 | f.cursor = (f.cursor + rows - 1) % rows |
| 175 | 127 | case ev.Key() == tcell.KeyDown, ev.Key() == tcell.KeyTab: |
| 176 | 128 | f.cursor = (f.cursor + 1) % rows |
| 177 | - case onOther && (ev.Key() == tcell.KeyEnter || ev.Key() == tcell.KeyRune && ev.Rune() == ' '): | |
| 129 | + case onOther && (ev.Key() == tcell.KeyEnter || space): | |
| 178 | 130 | f.typingOther, f.text = true, nil |
| 179 | - case q.Kind == elicit.Multi && ev.Key() == tcell.KeyRune && ev.Rune() == ' ': | |
| 131 | + case q.Kind == elicit.Multi && space: | |
| 180 | 132 | f.checked[f.cursor] = !f.checked[f.cursor] |
| 181 | 133 | case q.Kind == elicit.Choice && ev.Key() == tcell.KeyRune && ev.Rune() >= '1' && ev.Rune() <= '9': |
| 182 | - n := int(ev.Rune() - '0') | |
| 183 | - switch { | |
| 184 | - case n <= len(q.Options): | |
| 185 | - v.submitAnswer(elicit.Answer{Values: []string{q.Options[n-1]}}) | |
| 186 | - case q.AllowOther && n == len(q.Options)+1: | |
| 187 | - f.cursor, f.typingOther, f.text = n-1, true, nil | |
| 188 | - } | |
| 189 | - case ev.Key() == tcell.KeyEnter && q.Kind == elicit.Choice: | |
| 190 | - v.submitAnswer(elicit.Answer{Values: []string{q.Options[f.cursor]}}) | |
| 134 | + v.formNumberKey(q, int(ev.Rune()-'0')) | |
| 191 | 135 | case ev.Key() == tcell.KeyEnter: |
| 192 | - var a elicit.Answer | |
| 193 | - for i, on := range f.checked { | |
| 194 | - if on { | |
| 195 | - a.Values = append(a.Values, q.Options[i]) | |
| 196 | - } | |
| 136 | + v.formListEnter(q) | |
| 137 | + } | |
| 138 | +} | |
| 139 | + | |
| 140 | +// formNumberKey answers a choice with its option number n, or opens the | |
| 141 | +// field for the user's own answer when n is the row after the options. | |
| 142 | +func (v *View) formNumberKey(q elicit.Question, n int) { | |
| 143 | + f := v.form | |
| 144 | + switch { | |
| 145 | + case n <= len(q.Options): | |
| 146 | + v.submitAnswer(elicit.Answer{Values: []string{q.Options[n-1]}}) | |
| 147 | + case q.AllowOther && n == len(q.Options)+1: | |
| 148 | + f.cursor, f.typingOther, f.text = n-1, true, nil | |
| 149 | + } | |
| 150 | +} | |
| 151 | + | |
| 152 | +// formListEnter answers a choice with the highlighted option, and a multi | |
| 153 | +// with the ticked ones — nothing ticked is not an answer yet. | |
| 154 | +func (v *View) formListEnter(q elicit.Question) { | |
| 155 | + if q.Kind == elicit.Choice { | |
| 156 | + v.submitAnswer(elicit.Answer{Values: []string{q.Options[v.form.cursor]}}) | |
| 157 | + return | |
| 158 | + } | |
| 159 | + if ticked := v.form.ticked(q); len(ticked) > 0 { | |
| 160 | + v.submitAnswer(elicit.Answer{Values: ticked}) | |
| 161 | + } | |
| 162 | +} | |
| 163 | + | |
| 164 | +// ticked is the options of q ticked so far. | |
| 165 | +func (f *formView) ticked(q elicit.Question) []string { | |
| 166 | + var values []string | |
| 167 | + for i, on := range f.checked { | |
| 168 | + if on { | |
| 169 | + values = append(values, q.Options[i]) | |
| 197 | 170 | } |
| 198 | - if len(a.Values) > 0 { // nothing ticked: not an answer yet | |
| 199 | - v.submitAnswer(a) | |
| 171 | + } | |
| 172 | + return values | |
| 173 | +} | |
| 174 | + | |
| 175 | +// typeKey edits the typed text: a rune is added, Backspace removes the last. | |
| 176 | +func (f *formView) typeKey(ev *tcell.EventKey) { | |
| 177 | + switch ev.Key() { | |
| 178 | + case tcell.KeyRune: | |
| 179 | + f.text = append(f.text, ev.Rune()) | |
| 180 | + case tcell.KeyBackspace, tcell.KeyBackspace2: | |
| 181 | + if len(f.text) > 0 { | |
| 182 | + f.text = f.text[:len(f.text)-1] | |
| 200 | 183 | } |
| 201 | 184 | } |
| 202 | 185 | } |
| @@ -209,12 +192,6 @@ func (v *View) formOtherKey(ev *tcell.EventKey) { | ||
| 209 | 192 | switch ev.Key() { |
| 210 | 193 | case tcell.KeyEscape: |
| 211 | 194 | f.typingOther, f.text = false, nil |
| 212 | - case tcell.KeyRune: | |
| 213 | - f.text = append(f.text, ev.Rune()) | |
| 214 | - case tcell.KeyBackspace, tcell.KeyBackspace2: | |
| 215 | - if len(f.text) > 0 { | |
| 216 | - f.text = f.text[:len(f.text)-1] | |
| 217 | - } | |
| 218 | 195 | case tcell.KeyEnter: |
| 219 | 196 | other := strings.TrimSpace(string(f.text)) |
| 220 | 197 | if other == "" { |
| @@ -222,16 +199,15 @@ func (v *View) formOtherKey(ev *tcell.EventKey) { | ||
| 222 | 199 | } |
| 223 | 200 | a := elicit.Answer{Other: other} |
| 224 | 201 | if q.Kind == elicit.Multi { |
| 225 | - for i, on := range f.checked { | |
| 226 | - if on { | |
| 227 | - a.Values = append(a.Values, q.Options[i]) | |
| 228 | - } | |
| 229 | - } | |
| 202 | + a.Values = f.ticked(q) | |
| 230 | 203 | } |
| 231 | 204 | v.submitAnswer(a) |
| 205 | + default: | |
| 206 | + f.typeKey(ev) | |
| 232 | 207 | } |
| 233 | 208 | } |
| 234 | 209 | |
| 210 | +// formConfirmKey: a yes/no question — y/o or n, or the arrows then Enter. | |
| 235 | 211 | func (v *View) formConfirmKey(ev *tcell.EventKey) { |
| 236 | 212 | f := v.form |
| 237 | 213 | switch { |
| @@ -246,19 +222,16 @@ func (v *View) formConfirmKey(ev *tcell.EventKey) { | ||
| 246 | 222 | } |
| 247 | 223 | } |
| 248 | 224 | |
| 225 | +// formTextKey: a text question; Enter sends the line (an empty one takes | |
| 226 | +// the default). | |
| 249 | 227 | func (v *View) formTextKey(ev *tcell.EventKey) { |
| 250 | 228 | f := v.form |
| 251 | - switch ev.Key() { | |
| 252 | - case tcell.KeyRune: | |
| 253 | - f.text = append(f.text, ev.Rune()) | |
| 254 | - case tcell.KeyBackspace, tcell.KeyBackspace2: | |
| 255 | - if len(f.text) > 0 { | |
| 256 | - f.text = f.text[:len(f.text)-1] | |
| 257 | - } | |
| 258 | - case tcell.KeyEnter: | |
| 259 | - if a, ok := elicit.ParseLine(f.question(), string(f.text)); ok { | |
| 260 | - v.submitAnswer(a) | |
| 261 | - } | |
| 229 | + if ev.Key() != tcell.KeyEnter { | |
| 230 | + f.typeKey(ev) | |
| 231 | + return | |
| 232 | + } | |
| 233 | + if a, ok := elicit.ParseLine(f.question(), string(f.text)); ok { | |
| 234 | + v.submitAnswer(a) | |
| 262 | 235 | } |
| 263 | 236 | } |
| 264 | 237 | |
| @@ -275,99 +248,10 @@ func (v *View) submitAnswer(a elicit.Answer) { | ||
| 275 | 248 | v.finishForm(elicit.Result{Status: elicit.Answered, Answers: f.answers}) |
| 276 | 249 | } |
| 277 | 250 | |
| 251 | +// finishForm closes the form and sends its result back to the runner. | |
| 278 | 252 | func (v *View) finishForm(res elicit.Result) { |
| 279 | 253 | v.form = nil |
| 280 | 254 | if v.on.answerForm != nil { |
| 281 | 255 | v.on.answerForm(res) |
| 282 | 256 | } |
| 283 | 257 | } |
| 284 | - | |
| 285 | -// drawFormBox replaces the input box: the question, then what is typed (a | |
| 286 | -// text question) or the keys that answer it. | |
| 287 | -func (v *View) drawFormBox(p painter) { | |
| 288 | - f, q := v.form, v.form.question() | |
| 289 | - title := "? " + q.Prompt | |
| 290 | - if n := len(f.ask.form.Questions); n > 1 { | |
| 291 | - title += fmt.Sprintf(" (%d/%d)", f.index+1, n) | |
| 292 | - } | |
| 293 | - p.textLimited(0, 0, p.width(), title, stAsk) | |
| 294 | - if f.typingOther { | |
| 295 | - p.text(0, 1, ">", stPrompt) | |
| 296 | - p.textLimited(2, 1, max(p.width()-2, 0), string(f.text), stBody) | |
| 297 | - p.showCursor(2+min(len(f.text), max(p.width()-3, 0)), 1) | |
| 298 | - p.textLimited(2, 2, max(p.width()-2, 0), "your own answer · Enter send · Esc back to the options", stNotice) | |
| 299 | - return | |
| 300 | - } | |
| 301 | - if q.Kind == elicit.Text { | |
| 302 | - p.text(0, 1, ">", stPrompt) | |
| 303 | - text := string(f.text) | |
| 304 | - p.textLimited(2, 1, max(p.width()-2, 0), text, stBody) | |
| 305 | - p.showCursor(2+min(len(f.text), max(p.width()-3, 0)), 1) | |
| 306 | - p.textLimited(2, 2, max(p.width()-2, 0), "Enter send · Esc decline", stNotice) | |
| 307 | - return | |
| 308 | - } | |
| 309 | - v.screen.HideCursor() | |
| 310 | - p.textLimited(2, 1, max(p.width()-2, 0), formKeys(q.Kind), stNotice) | |
| 311 | -} | |
| 312 | - | |
| 313 | -func formKeys(kind elicit.Kind) string { | |
| 314 | - switch kind { | |
| 315 | - case elicit.Multi: | |
| 316 | - return "↑↓ move · Space tick · Enter send · Esc decline" | |
| 317 | - case elicit.Confirm: | |
| 318 | - return "y yes · n no · ←→ Enter · Esc decline" | |
| 319 | - } | |
| 320 | - return "↑↓ move · Enter or 1-9 choose · Esc decline" | |
| 321 | -} | |
| 322 | - | |
| 323 | -// drawFormChoices paints the current question's choices over the bottom of | |
| 324 | -// the conversation, the highlighted one in reverse. | |
| 325 | -func (v *View) drawFormChoices(p painter) { | |
| 326 | - f, q := v.form, v.form.question() | |
| 327 | - rows := f.rows() | |
| 328 | - if rows == 0 || p.height() < 1 { | |
| 329 | - return | |
| 330 | - } | |
| 331 | - labels := q.Options | |
| 332 | - if q.Kind == elicit.Confirm { | |
| 333 | - labels = []string{"Yes", "No"} | |
| 334 | - } | |
| 335 | - if q.AllowOther && q.Kind != elicit.Confirm { | |
| 336 | - labels = append(append([]string(nil), labels...), elicit.OtherLabel+" (type your own answer)") | |
| 337 | - } | |
| 338 | - shown := min(rows, p.height()) | |
| 339 | - first := max(f.cursor-shown+1, 0) // keep the highlight visible | |
| 340 | - width := 0 | |
| 341 | - for _, l := range labels { | |
| 342 | - width = max(width, len([]rune(l))+8) | |
| 343 | - } | |
| 344 | - width = min(width, p.width()) | |
| 345 | - top := p.height() - shown | |
| 346 | - for i := 0; i < shown; i++ { | |
| 347 | - at := first + i | |
| 348 | - mark := " " | |
| 349 | - if at == f.cursor { | |
| 350 | - mark = "❯ " | |
| 351 | - } | |
| 352 | - other := at == len(q.Options) // the Other row, when there is one | |
| 353 | - switch q.Kind { | |
| 354 | - case elicit.Multi: | |
| 355 | - box := "[ ] " | |
| 356 | - switch { | |
| 357 | - case other: | |
| 358 | - box = "[+] " | |
| 359 | - case f.checked[at]: | |
| 360 | - box = "[x] " | |
| 361 | - } | |
| 362 | - mark += box | |
| 363 | - case elicit.Choice: | |
| 364 | - mark += fmt.Sprintf("%d. ", at+1) | |
| 365 | - } | |
| 366 | - style := stBody | |
| 367 | - if at == f.cursor { | |
| 368 | - style = stPick | |
| 369 | - } | |
| 370 | - p.hline(0, top+i, width, ' ', style) | |
| 371 | - p.textLimited(0, top+i, width, " "+mark+labels[at], style) | |
| 372 | - } | |
| 373 | -} | |
| @@ -1,8 +1,6 @@ | |||
| 1 | package tui | 1 | package tui |
| 2 | 2 | ||
| 3 | import ( | 3 | import ( |
| 4 | - "context" | ||
| 5 | - "fmt" | ||
| 6 | "strings" | 4 | "strings" |
| 7 | 5 | ||
| 8 | "github.com/gdamore/tcell/v2" | 6 | "github.com/gdamore/tcell/v2" |
| @@ -29,55 +27,8 @@ import ( | |||
| 29 | // Several questions are asked one after the other; the answers go back | 27 | // Several questions are asked one after the other; the answers go back |
| 30 | // together when the last one is answered. | 28 | // together when the last one is answered. |
| 31 | 29 | ||
| 32 | -// formAsk is a form waiting for the user. | 30 | +// The runner side — the form waiting for answers — is in question_runner.go, |
| 33 | -type formAsk struct { | 31 | +// the drawing in question_draw.go; this file is the view's keys. |
| 34 | - form elicit.Form | ||
| 35 | - reply chan elicit.Result // the runner's, buffered; the view never writes it | ||
| 36 | -} | ||
| 37 | - | ||
| 38 | -// --- runner side ------------------------------------------------------------------ | ||
| 39 | - | ||
| 40 | -// currentForm is the form waiting for answers, nil when none. | ||
| 41 | -func (r *runner) currentForm() *formAsk { | ||
| 42 | - r.askMu.Lock() | ||
| 43 | - defer r.askMu.Unlock() | ||
| 44 | - return r.form | ||
| 45 | -} | ||
| 46 | - | ||
| 47 | -// answerForm settles the pending form from the loop goroutine. | ||
| 48 | -func (r *runner) answerForm(res elicit.Result) { | ||
| 49 | - r.askMu.Lock() | ||
| 50 | - defer r.askMu.Unlock() | ||
| 51 | - if r.form == nil { | ||
| 52 | - return | ||
| 53 | - } | ||
| 54 | - r.form.reply <- res | ||
| 55 | - r.form = nil | ||
| 56 | -} | ||
| 57 | - | ||
| 58 | -// elicit posts a form for the view to show and waits for the answers, or for | ||
| 59 | -// the turn to end (Cancelled). Called on the tool's goroutine. | ||
| 60 | -func (r *runner) elicit(ctx context.Context, f elicit.Form) elicit.Result { | ||
| 61 | - ask := &formAsk{form: f, reply: make(chan elicit.Result, 1)} | ||
| 62 | - r.askMu.Lock() | ||
| 63 | - r.form = ask | ||
| 64 | - r.askMu.Unlock() | ||
| 65 | - r.wake() | ||
| 66 | - select { | ||
| 67 | - case res := <-ask.reply: | ||
| 68 | - return res | ||
| 69 | - case <-ctx.Done(): | ||
| 70 | - r.askMu.Lock() | ||
| 71 | - if r.form == ask { | ||
| 72 | - r.form = nil | ||
| 73 | - } | ||
| 74 | - r.askMu.Unlock() | ||
| 75 | - r.wake() | ||
| 76 | - return elicit.Result{Status: elicit.Cancelled} | ||
| 77 | - } | ||
| 78 | -} | ||
| 79 | - | ||
| 80 | -// --- view side -------------------------------------------------------------------- | ||
| 81 | 32 | ||
| 82 | // formView is what the view keeps while a form is shown: which question, | 33 | // formView is what the view keeps while a form is shown: which question, |
| 83 | // where the highlight is, what is ticked or typed, the answers so far. | 34 | // where the highlight is, what is ticked or typed, the answers so far. |
| @@ -169,34 +120,66 @@ func (v *View) formListKey(ev *tcell.EventKey) { | |||
| 169 | f, q := v.form, v.form.question() | 120 | f, q := v.form, v.form.question() |
| 170 | rows := f.rows() | 121 | rows := f.rows() |
| 171 | onOther := q.AllowOther && f.cursor == len(q.Options) | 122 | onOther := q.AllowOther && f.cursor == len(q.Options) |
| 123 | + space := ev.Key() == tcell.KeyRune && ev.Rune() == ' ' | ||
| 172 | switch { | 124 | switch { |
| 173 | case ev.Key() == tcell.KeyUp: | 125 | case ev.Key() == tcell.KeyUp: |
| 174 | f.cursor = (f.cursor + rows - 1) % rows | 126 | f.cursor = (f.cursor + rows - 1) % rows |
| 175 | case ev.Key() == tcell.KeyDown, ev.Key() == tcell.KeyTab: | 127 | case ev.Key() == tcell.KeyDown, ev.Key() == tcell.KeyTab: |
| 176 | f.cursor = (f.cursor + 1) % rows | 128 | f.cursor = (f.cursor + 1) % rows |
| 177 | - case onOther && (ev.Key() == tcell.KeyEnter || ev.Key() == tcell.KeyRune && ev.Rune() == ' '): | 129 | + case onOther && (ev.Key() == tcell.KeyEnter || space): |
| 178 | f.typingOther, f.text = true, nil | 130 | f.typingOther, f.text = true, nil |
| 179 | - case q.Kind == elicit.Multi && ev.Key() == tcell.KeyRune && ev.Rune() == ' ': | 131 | + case q.Kind == elicit.Multi && space: |
| 180 | f.checked[f.cursor] = !f.checked[f.cursor] | 132 | f.checked[f.cursor] = !f.checked[f.cursor] |
| 181 | case q.Kind == elicit.Choice && ev.Key() == tcell.KeyRune && ev.Rune() >= '1' && ev.Rune() <= '9': | 133 | case q.Kind == elicit.Choice && ev.Key() == tcell.KeyRune && ev.Rune() >= '1' && ev.Rune() <= '9': |
| 182 | - n := int(ev.Rune() - '0') | 134 | + v.formNumberKey(q, int(ev.Rune()-'0')) |
| 183 | - switch { | ||
| 184 | - case n <= len(q.Options): | ||
| 185 | - v.submitAnswer(elicit.Answer{Values: []string{q.Options[n-1]}}) | ||
| 186 | - case q.AllowOther && n == len(q.Options)+1: | ||
| 187 | - f.cursor, f.typingOther, f.text = n-1, true, nil | ||
| 188 | - } | ||
| 189 | - case ev.Key() == tcell.KeyEnter && q.Kind == elicit.Choice: | ||
| 190 | - v.submitAnswer(elicit.Answer{Values: []string{q.Options[f.cursor]}}) | ||
| 191 | case ev.Key() == tcell.KeyEnter: | 135 | case ev.Key() == tcell.KeyEnter: |
| 192 | - var a elicit.Answer | 136 | + v.formListEnter(q) |
| 193 | - for i, on := range f.checked { | 137 | + } |
| 194 | - if on { | 138 | +} |
| 195 | - a.Values = append(a.Values, q.Options[i]) | 139 | + |
| 196 | - } | 140 | +// formNumberKey answers a choice with its option number n, or opens the |
| 141 | +// field for the user's own answer when n is the row after the options. | ||
| 142 | +func (v *View) formNumberKey(q elicit.Question, n int) { | ||
| 143 | + f := v.form | ||
| 144 | + switch { | ||
| 145 | + case n <= len(q.Options): | ||
| 146 | + v.submitAnswer(elicit.Answer{Values: []string{q.Options[n-1]}}) | ||
| 147 | + case q.AllowOther && n == len(q.Options)+1: | ||
| 148 | + f.cursor, f.typingOther, f.text = n-1, true, nil | ||
| 149 | + } | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +// formListEnter answers a choice with the highlighted option, and a multi | ||
| 153 | +// with the ticked ones — nothing ticked is not an answer yet. | ||
| 154 | +func (v *View) formListEnter(q elicit.Question) { | ||
| 155 | + if q.Kind == elicit.Choice { | ||
| 156 | + v.submitAnswer(elicit.Answer{Values: []string{q.Options[v.form.cursor]}}) | ||
| 157 | + return | ||
| 158 | + } | ||
| 159 | + if ticked := v.form.ticked(q); len(ticked) > 0 { | ||
| 160 | + v.submitAnswer(elicit.Answer{Values: ticked}) | ||
| 161 | + } | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +// ticked is the options of q ticked so far. | ||
| 165 | +func (f *formView) ticked(q elicit.Question) []string { | ||
| 166 | + var values []string | ||
| 167 | + for i, on := range f.checked { | ||
| 168 | + if on { | ||
| 169 | + values = append(values, q.Options[i]) | ||
| 197 | } | 170 | } |
| 198 | - if len(a.Values) > 0 { // nothing ticked: not an answer yet | 171 | + } |
| 199 | - v.submitAnswer(a) | 172 | + return values |
| 173 | +} | ||
| 174 | + | ||
| 175 | +// typeKey edits the typed text: a rune is added, Backspace removes the last. | ||
| 176 | +func (f *formView) typeKey(ev *tcell.EventKey) { | ||
| 177 | + switch ev.Key() { | ||
| 178 | + case tcell.KeyRune: | ||
| 179 | + f.text = append(f.text, ev.Rune()) | ||
| 180 | + case tcell.KeyBackspace, tcell.KeyBackspace2: | ||
| 181 | + if len(f.text) > 0 { | ||
| 182 | + f.text = f.text[:len(f.text)-1] | ||
| 200 | } | 183 | } |
| 201 | } | 184 | } |
| 202 | } | 185 | } |
| @@ -209,12 +192,6 @@ func (v *View) formOtherKey(ev *tcell.EventKey) { | |||
| 209 | switch ev.Key() { | 192 | switch ev.Key() { |
| 210 | case tcell.KeyEscape: | 193 | case tcell.KeyEscape: |
| 211 | f.typingOther, f.text = false, nil | 194 | f.typingOther, f.text = false, nil |
| 212 | - case tcell.KeyRune: | ||
| 213 | - f.text = append(f.text, ev.Rune()) | ||
| 214 | - case tcell.KeyBackspace, tcell.KeyBackspace2: | ||
| 215 | - if len(f.text) > 0 { | ||
| 216 | - f.text = f.text[:len(f.text)-1] | ||
| 217 | - } | ||
| 218 | case tcell.KeyEnter: | 195 | case tcell.KeyEnter: |
| 219 | other := strings.TrimSpace(string(f.text)) | 196 | other := strings.TrimSpace(string(f.text)) |
| 220 | if other == "" { | 197 | if other == "" { |
| @@ -222,16 +199,15 @@ func (v *View) formOtherKey(ev *tcell.EventKey) { | |||
| 222 | } | 199 | } |
| 223 | a := elicit.Answer{Other: other} | 200 | a := elicit.Answer{Other: other} |
| 224 | if q.Kind == elicit.Multi { | 201 | if q.Kind == elicit.Multi { |
| 225 | - for i, on := range f.checked { | 202 | + a.Values = f.ticked(q) |
| 226 | - if on { | ||
| 227 | - a.Values = append(a.Values, q.Options[i]) | ||
| 228 | - } | ||
| 229 | - } | ||
| 230 | } | 203 | } |
| 231 | v.submitAnswer(a) | 204 | v.submitAnswer(a) |
| 205 | + default: | ||
| 206 | + f.typeKey(ev) | ||
| 232 | } | 207 | } |
| 233 | } | 208 | } |
| 234 | 209 | ||
| 210 | +// formConfirmKey: a yes/no question — y/o or n, or the arrows then Enter. | ||
| 235 | func (v *View) formConfirmKey(ev *tcell.EventKey) { | 211 | func (v *View) formConfirmKey(ev *tcell.EventKey) { |
| 236 | f := v.form | 212 | f := v.form |
| 237 | switch { | 213 | switch { |
| @@ -246,19 +222,16 @@ func (v *View) formConfirmKey(ev *tcell.EventKey) { | |||
| 246 | } | 222 | } |
| 247 | } | 223 | } |
| 248 | 224 | ||
| 225 | +// formTextKey: a text question; Enter sends the line (an empty one takes | ||
| 226 | +// the default). | ||
| 249 | func (v *View) formTextKey(ev *tcell.EventKey) { | 227 | func (v *View) formTextKey(ev *tcell.EventKey) { |
| 250 | f := v.form | 228 | f := v.form |
| 251 | - switch ev.Key() { | 229 | + if ev.Key() != tcell.KeyEnter { |
| 252 | - case tcell.KeyRune: | 230 | + f.typeKey(ev) |
| 253 | - f.text = append(f.text, ev.Rune()) | 231 | + return |
| 254 | - case tcell.KeyBackspace, tcell.KeyBackspace2: | 232 | + } |
| 255 | - if len(f.text) > 0 { | 233 | + if a, ok := elicit.ParseLine(f.question(), string(f.text)); ok { |
| 256 | - f.text = f.text[:len(f.text)-1] | 234 | + v.submitAnswer(a) |
| 257 | - } | ||
| 258 | - case tcell.KeyEnter: | ||
| 259 | - if a, ok := elicit.ParseLine(f.question(), string(f.text)); ok { | ||
| 260 | - v.submitAnswer(a) | ||
| 261 | - } | ||
| 262 | } | 235 | } |
| 263 | } | 236 | } |
| 264 | 237 | ||
| @@ -275,99 +248,10 @@ func (v *View) submitAnswer(a elicit.Answer) { | |||
| 275 | v.finishForm(elicit.Result{Status: elicit.Answered, Answers: f.answers}) | 248 | v.finishForm(elicit.Result{Status: elicit.Answered, Answers: f.answers}) |
| 276 | } | 249 | } |
| 277 | 250 | ||
| 251 | +// finishForm closes the form and sends its result back to the runner. | ||
| 278 | func (v *View) finishForm(res elicit.Result) { | 252 | func (v *View) finishForm(res elicit.Result) { |
| 279 | v.form = nil | 253 | v.form = nil |
| 280 | if v.on.answerForm != nil { | 254 | if v.on.answerForm != nil { |
| 281 | v.on.answerForm(res) | 255 | v.on.answerForm(res) |
| 282 | } | 256 | } |
| 283 | } | 257 | } |
| 284 | - | ||
| 285 | -// drawFormBox replaces the input box: the question, then what is typed (a | ||
| 286 | -// text question) or the keys that answer it. | ||
| 287 | -func (v *View) drawFormBox(p painter) { | ||
| 288 | - f, q := v.form, v.form.question() | ||
| 289 | - title := "? " + q.Prompt | ||
| 290 | - if n := len(f.ask.form.Questions); n > 1 { | ||
| 291 | - title += fmt.Sprintf(" (%d/%d)", f.index+1, n) | ||
| 292 | - } | ||
| 293 | - p.textLimited(0, 0, p.width(), title, stAsk) | ||
| 294 | - if f.typingOther { | ||
| 295 | - p.text(0, 1, ">", stPrompt) | ||
| 296 | - p.textLimited(2, 1, max(p.width()-2, 0), string(f.text), stBody) | ||
| 297 | - p.showCursor(2+min(len(f.text), max(p.width()-3, 0)), 1) | ||
| 298 | - p.textLimited(2, 2, max(p.width()-2, 0), "your own answer · Enter send · Esc back to the options", stNotice) | ||
| 299 | - return | ||
| 300 | - } | ||
| 301 | - if q.Kind == elicit.Text { | ||
| 302 | - p.text(0, 1, ">", stPrompt) | ||
| 303 | - text := string(f.text) | ||
| 304 | - p.textLimited(2, 1, max(p.width()-2, 0), text, stBody) | ||
| 305 | - p.showCursor(2+min(len(f.text), max(p.width()-3, 0)), 1) | ||
| 306 | - p.textLimited(2, 2, max(p.width()-2, 0), "Enter send · Esc decline", stNotice) | ||
| 307 | - return | ||
| 308 | - } | ||
| 309 | - v.screen.HideCursor() | ||
| 310 | - p.textLimited(2, 1, max(p.width()-2, 0), formKeys(q.Kind), stNotice) | ||
| 311 | -} | ||
| 312 | - | ||
| 313 | -func formKeys(kind elicit.Kind) string { | ||
| 314 | - switch kind { | ||
| 315 | - case elicit.Multi: | ||
| 316 | - return "↑↓ move · Space tick · Enter send · Esc decline" | ||
| 317 | - case elicit.Confirm: | ||
| 318 | - return "y yes · n no · ←→ Enter · Esc decline" | ||
| 319 | - } | ||
| 320 | - return "↑↓ move · Enter or 1-9 choose · Esc decline" | ||
| 321 | -} | ||
| 322 | - | ||
| 323 | -// drawFormChoices paints the current question's choices over the bottom of | ||
| 324 | -// the conversation, the highlighted one in reverse. | ||
| 325 | -func (v *View) drawFormChoices(p painter) { | ||
| 326 | - f, q := v.form, v.form.question() | ||
| 327 | - rows := f.rows() | ||
| 328 | - if rows == 0 || p.height() < 1 { | ||
| 329 | - return | ||
| 330 | - } | ||
| 331 | - labels := q.Options | ||
| 332 | - if q.Kind == elicit.Confirm { | ||
| 333 | - labels = []string{"Yes", "No"} | ||
| 334 | - } | ||
| 335 | - if q.AllowOther && q.Kind != elicit.Confirm { | ||
| 336 | - labels = append(append([]string(nil), labels...), elicit.OtherLabel+" (type your own answer)") | ||
| 337 | - } | ||
| 338 | - shown := min(rows, p.height()) | ||
| 339 | - first := max(f.cursor-shown+1, 0) // keep the highlight visible | ||
| 340 | - width := 0 | ||
| 341 | - for _, l := range labels { | ||
| 342 | - width = max(width, len([]rune(l))+8) | ||
| 343 | - } | ||
| 344 | - width = min(width, p.width()) | ||
| 345 | - top := p.height() - shown | ||
| 346 | - for i := 0; i < shown; i++ { | ||
| 347 | - at := first + i | ||
| 348 | - mark := " " | ||
| 349 | - if at == f.cursor { | ||
| 350 | - mark = "❯ " | ||
| 351 | - } | ||
| 352 | - other := at == len(q.Options) // the Other row, when there is one | ||
| 353 | - switch q.Kind { | ||
| 354 | - case elicit.Multi: | ||
| 355 | - box := "[ ] " | ||
| 356 | - switch { | ||
| 357 | - case other: | ||
| 358 | - box = "[+] " | ||
| 359 | - case f.checked[at]: | ||
| 360 | - box = "[x] " | ||
| 361 | - } | ||
| 362 | - mark += box | ||
| 363 | - case elicit.Choice: | ||
| 364 | - mark += fmt.Sprintf("%d. ", at+1) | ||
| 365 | - } | ||
| 366 | - style := stBody | ||
| 367 | - if at == f.cursor { | ||
| 368 | - style = stPick | ||
| 369 | - } | ||
| 370 | - p.hline(0, top+i, width, ' ', style) | ||
| 371 | - p.textLimited(0, top+i, width, " "+mark+labels[at], style) | ||
| 372 | - } | ||
| 373 | -} | ||
added
internal/tui/question_draw.go +96 -0 | new file mode 100644 | ||
| @@ -0,0 +1,96 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "fmt" | |
| 5 | + "mm/internal/elicit" | |
| 6 | +) | |
| 7 | + | |
| 8 | +// drawFormBox replaces the input box: the question, then what is typed (a | |
| 9 | +// text question) or the keys that answer it. | |
| 10 | +func (v *View) drawFormBox(p painter) { | |
| 11 | + f, q := v.form, v.form.question() | |
| 12 | + title := "? " + q.Prompt | |
| 13 | + if n := len(f.ask.form.Questions); n > 1 { | |
| 14 | + title += fmt.Sprintf(" (%d/%d)", f.index+1, n) | |
| 15 | + } | |
| 16 | + p.textLimited(0, 0, p.width(), title, stAsk) | |
| 17 | + if f.typingOther { | |
| 18 | + p.text(0, 1, ">", stPrompt) | |
| 19 | + p.textLimited(2, 1, max(p.width()-2, 0), string(f.text), stBody) | |
| 20 | + p.showCursor(2+min(len(f.text), max(p.width()-3, 0)), 1) | |
| 21 | + p.textLimited(2, 2, max(p.width()-2, 0), "your own answer · Enter send · Esc back to the options", stNotice) | |
| 22 | + return | |
| 23 | + } | |
| 24 | + if q.Kind == elicit.Text { | |
| 25 | + p.text(0, 1, ">", stPrompt) | |
| 26 | + text := string(f.text) | |
| 27 | + p.textLimited(2, 1, max(p.width()-2, 0), text, stBody) | |
| 28 | + p.showCursor(2+min(len(f.text), max(p.width()-3, 0)), 1) | |
| 29 | + p.textLimited(2, 2, max(p.width()-2, 0), "Enter send · Esc decline", stNotice) | |
| 30 | + return | |
| 31 | + } | |
| 32 | + v.screen.HideCursor() | |
| 33 | + p.textLimited(2, 1, max(p.width()-2, 0), formKeys(q.Kind), stNotice) | |
| 34 | +} | |
| 35 | + | |
| 36 | +func formKeys(kind elicit.Kind) string { | |
| 37 | + switch kind { | |
| 38 | + case elicit.Multi: | |
| 39 | + return "↑↓ move · Space tick · Enter send · Esc decline" | |
| 40 | + case elicit.Confirm: | |
| 41 | + return "y yes · n no · ←→ Enter · Esc decline" | |
| 42 | + } | |
| 43 | + return "↑↓ move · Enter or 1-9 choose · Esc decline" | |
| 44 | +} | |
| 45 | + | |
| 46 | +// drawFormChoices paints the current question's choices over the bottom of | |
| 47 | +// the conversation, the highlighted one in reverse. | |
| 48 | +func (v *View) drawFormChoices(p painter) { | |
| 49 | + f, q := v.form, v.form.question() | |
| 50 | + rows := f.rows() | |
| 51 | + if rows == 0 || p.height() < 1 { | |
| 52 | + return | |
| 53 | + } | |
| 54 | + labels := q.Options | |
| 55 | + if q.Kind == elicit.Confirm { | |
| 56 | + labels = []string{"Yes", "No"} | |
| 57 | + } | |
| 58 | + if q.AllowOther && q.Kind != elicit.Confirm { | |
| 59 | + labels = append(append([]string(nil), labels...), elicit.OtherLabel+" (type your own answer)") | |
| 60 | + } | |
| 61 | + shown := min(rows, p.height()) | |
| 62 | + first := max(f.cursor-shown+1, 0) // keep the highlight visible | |
| 63 | + width := 0 | |
| 64 | + for _, l := range labels { | |
| 65 | + width = max(width, len([]rune(l))+8) | |
| 66 | + } | |
| 67 | + width = min(width, p.width()) | |
| 68 | + top := p.height() - shown | |
| 69 | + for i := 0; i < shown; i++ { | |
| 70 | + at := first + i | |
| 71 | + mark := " " | |
| 72 | + if at == f.cursor { | |
| 73 | + mark = "❯ " | |
| 74 | + } | |
| 75 | + other := at == len(q.Options) // the Other row, when there is one | |
| 76 | + switch q.Kind { | |
| 77 | + case elicit.Multi: | |
| 78 | + box := "[ ] " | |
| 79 | + switch { | |
| 80 | + case other: | |
| 81 | + box = "[+] " | |
| 82 | + case f.checked[at]: | |
| 83 | + box = "[x] " | |
| 84 | + } | |
| 85 | + mark += box | |
| 86 | + case elicit.Choice: | |
| 87 | + mark += fmt.Sprintf("%d. ", at+1) | |
| 88 | + } | |
| 89 | + style := stBody | |
| 90 | + if at == f.cursor { | |
| 91 | + style = stPick | |
| 92 | + } | |
| 93 | + p.hline(0, top+i, width, ' ', style) | |
| 94 | + p.textLimited(0, top+i, width, " "+mark+labels[at], style) | |
| 95 | + } | |
| 96 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,96 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "fmt" | ||
| 5 | + "mm/internal/elicit" | ||
| 6 | +) | ||
| 7 | + | ||
| 8 | +// drawFormBox replaces the input box: the question, then what is typed (a | ||
| 9 | +// text question) or the keys that answer it. | ||
| 10 | +func (v *View) drawFormBox(p painter) { | ||
| 11 | + f, q := v.form, v.form.question() | ||
| 12 | + title := "? " + q.Prompt | ||
| 13 | + if n := len(f.ask.form.Questions); n > 1 { | ||
| 14 | + title += fmt.Sprintf(" (%d/%d)", f.index+1, n) | ||
| 15 | + } | ||
| 16 | + p.textLimited(0, 0, p.width(), title, stAsk) | ||
| 17 | + if f.typingOther { | ||
| 18 | + p.text(0, 1, ">", stPrompt) | ||
| 19 | + p.textLimited(2, 1, max(p.width()-2, 0), string(f.text), stBody) | ||
| 20 | + p.showCursor(2+min(len(f.text), max(p.width()-3, 0)), 1) | ||
| 21 | + p.textLimited(2, 2, max(p.width()-2, 0), "your own answer · Enter send · Esc back to the options", stNotice) | ||
| 22 | + return | ||
| 23 | + } | ||
| 24 | + if q.Kind == elicit.Text { | ||
| 25 | + p.text(0, 1, ">", stPrompt) | ||
| 26 | + text := string(f.text) | ||
| 27 | + p.textLimited(2, 1, max(p.width()-2, 0), text, stBody) | ||
| 28 | + p.showCursor(2+min(len(f.text), max(p.width()-3, 0)), 1) | ||
| 29 | + p.textLimited(2, 2, max(p.width()-2, 0), "Enter send · Esc decline", stNotice) | ||
| 30 | + return | ||
| 31 | + } | ||
| 32 | + v.screen.HideCursor() | ||
| 33 | + p.textLimited(2, 1, max(p.width()-2, 0), formKeys(q.Kind), stNotice) | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +func formKeys(kind elicit.Kind) string { | ||
| 37 | + switch kind { | ||
| 38 | + case elicit.Multi: | ||
| 39 | + return "↑↓ move · Space tick · Enter send · Esc decline" | ||
| 40 | + case elicit.Confirm: | ||
| 41 | + return "y yes · n no · ←→ Enter · Esc decline" | ||
| 42 | + } | ||
| 43 | + return "↑↓ move · Enter or 1-9 choose · Esc decline" | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +// drawFormChoices paints the current question's choices over the bottom of | ||
| 47 | +// the conversation, the highlighted one in reverse. | ||
| 48 | +func (v *View) drawFormChoices(p painter) { | ||
| 49 | + f, q := v.form, v.form.question() | ||
| 50 | + rows := f.rows() | ||
| 51 | + if rows == 0 || p.height() < 1 { | ||
| 52 | + return | ||
| 53 | + } | ||
| 54 | + labels := q.Options | ||
| 55 | + if q.Kind == elicit.Confirm { | ||
| 56 | + labels = []string{"Yes", "No"} | ||
| 57 | + } | ||
| 58 | + if q.AllowOther && q.Kind != elicit.Confirm { | ||
| 59 | + labels = append(append([]string(nil), labels...), elicit.OtherLabel+" (type your own answer)") | ||
| 60 | + } | ||
| 61 | + shown := min(rows, p.height()) | ||
| 62 | + first := max(f.cursor-shown+1, 0) // keep the highlight visible | ||
| 63 | + width := 0 | ||
| 64 | + for _, l := range labels { | ||
| 65 | + width = max(width, len([]rune(l))+8) | ||
| 66 | + } | ||
| 67 | + width = min(width, p.width()) | ||
| 68 | + top := p.height() - shown | ||
| 69 | + for i := 0; i < shown; i++ { | ||
| 70 | + at := first + i | ||
| 71 | + mark := " " | ||
| 72 | + if at == f.cursor { | ||
| 73 | + mark = "❯ " | ||
| 74 | + } | ||
| 75 | + other := at == len(q.Options) // the Other row, when there is one | ||
| 76 | + switch q.Kind { | ||
| 77 | + case elicit.Multi: | ||
| 78 | + box := "[ ] " | ||
| 79 | + switch { | ||
| 80 | + case other: | ||
| 81 | + box = "[+] " | ||
| 82 | + case f.checked[at]: | ||
| 83 | + box = "[x] " | ||
| 84 | + } | ||
| 85 | + mark += box | ||
| 86 | + case elicit.Choice: | ||
| 87 | + mark += fmt.Sprintf("%d. ", at+1) | ||
| 88 | + } | ||
| 89 | + style := stBody | ||
| 90 | + if at == f.cursor { | ||
| 91 | + style = stPick | ||
| 92 | + } | ||
| 93 | + p.hline(0, top+i, width, ' ', style) | ||
| 94 | + p.textLimited(0, top+i, width, " "+mark+labels[at], style) | ||
| 95 | + } | ||
| 96 | +} | ||
added
internal/tui/question_runner.go +55 -0 | new file mode 100644 | ||
| @@ -0,0 +1,55 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "context" | |
| 5 | + "mm/internal/elicit" | |
| 6 | +) | |
| 7 | + | |
| 8 | +// The runner side of the ask_user forms (question.go): the tool's goroutine | |
| 9 | +// posts a form and waits; the loop reads it before each frame. | |
| 10 | + | |
| 11 | +// formAsk is a form waiting for the user. | |
| 12 | +type formAsk struct { | |
| 13 | + form elicit.Form | |
| 14 | + reply chan elicit.Result // the runner's, buffered; the view never writes it | |
| 15 | +} | |
| 16 | + | |
| 17 | +// currentForm is the form waiting for answers, nil when none. | |
| 18 | +func (r *runner) currentForm() *formAsk { | |
| 19 | + r.askMu.Lock() | |
| 20 | + defer r.askMu.Unlock() | |
| 21 | + return r.form | |
| 22 | +} | |
| 23 | + | |
| 24 | +// answerForm settles the pending form from the loop goroutine. | |
| 25 | +func (r *runner) answerForm(res elicit.Result) { | |
| 26 | + r.askMu.Lock() | |
| 27 | + defer r.askMu.Unlock() | |
| 28 | + if r.form == nil { | |
| 29 | + return | |
| 30 | + } | |
| 31 | + r.form.reply <- res | |
| 32 | + r.form = nil | |
| 33 | +} | |
| 34 | + | |
| 35 | +// elicit posts a form for the view to show and waits for the answers, or for | |
| 36 | +// the turn to end (Cancelled). Called on the tool's goroutine. | |
| 37 | +func (r *runner) elicit(ctx context.Context, f elicit.Form) elicit.Result { | |
| 38 | + ask := &formAsk{form: f, reply: make(chan elicit.Result, 1)} | |
| 39 | + r.askMu.Lock() | |
| 40 | + r.form = ask | |
| 41 | + r.askMu.Unlock() | |
| 42 | + r.wake() | |
| 43 | + select { | |
| 44 | + case res := <-ask.reply: | |
| 45 | + return res | |
| 46 | + case <-ctx.Done(): | |
| 47 | + r.askMu.Lock() | |
| 48 | + if r.form == ask { | |
| 49 | + r.form = nil | |
| 50 | + } | |
| 51 | + r.askMu.Unlock() | |
| 52 | + r.wake() | |
| 53 | + return elicit.Result{Status: elicit.Cancelled} | |
| 54 | + } | |
| 55 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,55 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "mm/internal/elicit" | ||
| 6 | +) | ||
| 7 | + | ||
| 8 | +// The runner side of the ask_user forms (question.go): the tool's goroutine | ||
| 9 | +// posts a form and waits; the loop reads it before each frame. | ||
| 10 | + | ||
| 11 | +// formAsk is a form waiting for the user. | ||
| 12 | +type formAsk struct { | ||
| 13 | + form elicit.Form | ||
| 14 | + reply chan elicit.Result // the runner's, buffered; the view never writes it | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +// currentForm is the form waiting for answers, nil when none. | ||
| 18 | +func (r *runner) currentForm() *formAsk { | ||
| 19 | + r.askMu.Lock() | ||
| 20 | + defer r.askMu.Unlock() | ||
| 21 | + return r.form | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +// answerForm settles the pending form from the loop goroutine. | ||
| 25 | +func (r *runner) answerForm(res elicit.Result) { | ||
| 26 | + r.askMu.Lock() | ||
| 27 | + defer r.askMu.Unlock() | ||
| 28 | + if r.form == nil { | ||
| 29 | + return | ||
| 30 | + } | ||
| 31 | + r.form.reply <- res | ||
| 32 | + r.form = nil | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +// elicit posts a form for the view to show and waits for the answers, or for | ||
| 36 | +// the turn to end (Cancelled). Called on the tool's goroutine. | ||
| 37 | +func (r *runner) elicit(ctx context.Context, f elicit.Form) elicit.Result { | ||
| 38 | + ask := &formAsk{form: f, reply: make(chan elicit.Result, 1)} | ||
| 39 | + r.askMu.Lock() | ||
| 40 | + r.form = ask | ||
| 41 | + r.askMu.Unlock() | ||
| 42 | + r.wake() | ||
| 43 | + select { | ||
| 44 | + case res := <-ask.reply: | ||
| 45 | + return res | ||
| 46 | + case <-ctx.Done(): | ||
| 47 | + r.askMu.Lock() | ||
| 48 | + if r.form == ask { | ||
| 49 | + r.form = nil | ||
| 50 | + } | ||
| 51 | + r.askMu.Unlock() | ||
| 52 | + r.wake() | ||
| 53 | + return elicit.Result{Status: elicit.Cancelled} | ||
| 54 | + } | ||
| 55 | +} | ||
modified
internal/tui/render.go +12 -13 | @@ -209,20 +209,19 @@ func outputStyle(e Entry, line string) styleKind { | ||
| 209 | 209 | // statusMark is the short sign of how a tool call is going — a word beside |
| 210 | 210 | // the symbol, because ✓ and ✗ are one cell apart at a glance. |
| 211 | 211 | func statusMark(status string) string { |
| 212 | - switch status { | |
| 213 | - case StatusDone: | |
| 214 | - return "✓ done" | |
| 215 | - case StatusFailed: | |
| 216 | - return "✗ failed" | |
| 217 | - case StatusRunning: | |
| 218 | - return "… running" | |
| 219 | - case StatusWaiting: | |
| 220 | - return "… waiting for permission" | |
| 221 | - case StatusAsking: | |
| 222 | - return "… waiting for your answer" | |
| 223 | - default: | |
| 224 | - return "… pending" | |
| 212 | + if mark, ok := statusMarks[status]; ok { | |
| 213 | + return mark | |
| 225 | 214 | } |
| 215 | + return "… pending" | |
| 216 | +} | |
| 217 | + | |
| 218 | +// statusMarks are the signs of the known statuses; any other is pending. | |
| 219 | +var statusMarks = map[string]string{ | |
| 220 | + StatusDone: "✓ done", | |
| 221 | + StatusFailed: "✗ failed", | |
| 222 | + StatusRunning: "… running", | |
| 223 | + StatusWaiting: "… waiting for permission", | |
| 224 | + StatusAsking: "… waiting for your answer", | |
| 226 | 225 | } |
| 227 | 226 | |
| 228 | 227 | // elapsed prints a duration the way the spinner does: tenths under ten |
| @@ -209,20 +209,19 @@ func outputStyle(e Entry, line string) styleKind { | |||
| 209 | // statusMark is the short sign of how a tool call is going — a word beside | 209 | // statusMark is the short sign of how a tool call is going — a word beside |
| 210 | // the symbol, because ✓ and ✗ are one cell apart at a glance. | 210 | // the symbol, because ✓ and ✗ are one cell apart at a glance. |
| 211 | func statusMark(status string) string { | 211 | func statusMark(status string) string { |
| 212 | - switch status { | 212 | + if mark, ok := statusMarks[status]; ok { |
| 213 | - case StatusDone: | 213 | + return mark |
| 214 | - return "✓ done" | ||
| 215 | - case StatusFailed: | ||
| 216 | - return "✗ failed" | ||
| 217 | - case StatusRunning: | ||
| 218 | - return "… running" | ||
| 219 | - case StatusWaiting: | ||
| 220 | - return "… waiting for permission" | ||
| 221 | - case StatusAsking: | ||
| 222 | - return "… waiting for your answer" | ||
| 223 | - default: | ||
| 224 | - return "… pending" | ||
| 225 | } | 214 | } |
| 215 | + return "… pending" | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +// statusMarks are the signs of the known statuses; any other is pending. | ||
| 219 | +var statusMarks = map[string]string{ | ||
| 220 | + StatusDone: "✓ done", | ||
| 221 | + StatusFailed: "✗ failed", | ||
| 222 | + StatusRunning: "… running", | ||
| 223 | + StatusWaiting: "… waiting for permission", | ||
| 224 | + StatusAsking: "… waiting for your answer", | ||
| 226 | } | 225 | } |
| 227 | 226 | ||
| 228 | // elapsed prints a duration the way the spinner does: tenths under ten | 227 | // elapsed prints a duration the way the spinner does: tenths under ten |
modified
internal/tui/turn.go +0 -98 | @@ -253,63 +253,6 @@ func (r *runner) startTurn(p Prompt) { | ||
| 253 | 253 | }() |
| 254 | 254 | } |
| 255 | 255 | |
| 256 | -// compactIfDue is the automatic compaction, the REPL's rule verbatim: the | |
| 257 | -// server's own count of the last context beats the estimate, the window is | |
| 258 | -// re-probed while unknown, and a failure keeps the history. The second | |
| 259 | -// result is the failure line when the summary failed, for the session file. | |
| 260 | -func (r *runner) compactIfDue(ctx context.Context, msgs []*ai.Message) ([]*ai.Message, string) { | |
| 261 | - cfg := config.Cfg.Context | |
| 262 | - if !cfg.Enabled { | |
| 263 | - return msgs, "" | |
| 264 | - } | |
| 265 | - if r.opts.Window() == 0 && r.opts.Ensure != nil { | |
| 266 | - if w, src := r.opts.Ensure(ctx); w > 0 { | |
| 267 | - r.t.Notice(fmt.Sprintf("ctx: %d (%s)", w, src)) | |
| 268 | - } | |
| 269 | - } | |
| 270 | - dec := compact.Decide(msgs, r.opts.Model.LastInputTokens(), r.opts.Window(), cfg) | |
| 271 | - if !dec.Compact { | |
| 272 | - return msgs, "" | |
| 273 | - } | |
| 274 | - out, line, outcome := compact.Apply(ctx, msgs, cfg, r.summarize, r.opts.Model.Explain) | |
| 275 | - switch outcome { | |
| 276 | - case compact.Compressed: | |
| 277 | - r.opts.Model.ForgetInputTokens() | |
| 278 | - if cfg.ShowStats { | |
| 279 | - r.t.Notice(line) | |
| 280 | - } | |
| 281 | - case compact.Failed: | |
| 282 | - r.t.Error(line) | |
| 283 | - return out, line | |
| 284 | - } | |
| 285 | - return out, "" | |
| 286 | -} | |
| 287 | - | |
| 288 | -func (r *runner) summarize(ctx context.Context, request []*ai.Message) (string, error) { | |
| 289 | - return r.opts.Model.Summarize(ctx, request, config.Cfg.Context.SummaryMaxTokens) | |
| 290 | -} | |
| 291 | - | |
| 292 | -// startCompact is /compact: forced, on a goroutine, reported as a notice. | |
| 293 | -func (r *runner) startCompact() { | |
| 294 | - ctx, cancel := context.WithCancel(context.Background()) | |
| 295 | - r.cancel = cancel | |
| 296 | - r.cancelled.Store(false) | |
| 297 | - r.busy.Store("compressing") | |
| 298 | - msgs := append([]*ai.Message(nil), r.messages...) | |
| 299 | - go func() { | |
| 300 | - out, line, oc := compact.Apply(ctx, msgs, config.Cfg.Context, r.summarize, r.opts.Model.Explain) | |
| 301 | - r.results <- outcome{kind: "compact", messages: out, line: line, changed: oc == compact.Compressed, err: errIf(oc == compact.Failed)} | |
| 302 | - r.wake() | |
| 303 | - }() | |
| 304 | -} | |
| 305 | - | |
| 306 | -func errIf(failed bool) error { | |
| 307 | - if failed { | |
| 308 | - return fmt.Errorf("compaction failed") | |
| 309 | - } | |
| 310 | - return nil | |
| 311 | -} | |
| 312 | - | |
| 313 | 256 | // settle takes a finished job, if any, and applies it to the session. Called |
| 314 | 257 | // by the loop before every frame — the one goroutine that touches messages. |
| 315 | 258 | func (r *runner) settle() { |
| @@ -534,44 +477,3 @@ func (r *runner) status() string { | ||
| 534 | 477 | } |
| 535 | 478 | return counters |
| 536 | 479 | } |
| 537 | - | |
| 538 | -// --- permissions ------------------------------------------------------------------ | |
| 539 | - | |
| 540 | -// currentAsk is the permission waiting for an answer, nil when none. | |
| 541 | -func (r *runner) currentAsk() *permission { | |
| 542 | - r.askMu.Lock() | |
| 543 | - defer r.askMu.Unlock() | |
| 544 | - return r.ask | |
| 545 | -} | |
| 546 | - | |
| 547 | -// answer settles the pending permission from the loop goroutine. | |
| 548 | -func (r *runner) answer(a permissionAnswer) { | |
| 549 | - r.askMu.Lock() | |
| 550 | - defer r.askMu.Unlock() | |
| 551 | - if r.ask == nil { | |
| 552 | - return | |
| 553 | - } | |
| 554 | - r.ask.reply <- a | |
| 555 | - r.ask = nil | |
| 556 | -} | |
| 557 | - | |
| 558 | -// request posts a permission for the view to show and waits for the answer, | |
| 559 | -// or for the turn to end. Called on the tool's goroutine. | |
| 560 | -func (r *runner) request(ctx context.Context, ev ui.ToolEvent) permissionAnswer { | |
| 561 | - p := &permission{tool: ev.Tool, title: ev.Title, reply: make(chan permissionAnswer, 1)} | |
| 562 | - r.askMu.Lock() | |
| 563 | - r.ask = p | |
| 564 | - r.askMu.Unlock() | |
| 565 | - r.wake() | |
| 566 | - select { | |
| 567 | - case a := <-p.reply: | |
| 568 | - return a | |
| 569 | - case <-ctx.Done(): | |
| 570 | - r.askMu.Lock() | |
| 571 | - if r.ask == p { | |
| 572 | - r.ask = nil | |
| 573 | - } | |
| 574 | - r.askMu.Unlock() | |
| 575 | - return permReject | |
| 576 | - } | |
| 577 | -} | |
| @@ -253,63 +253,6 @@ func (r *runner) startTurn(p Prompt) { | |||
| 253 | }() | 253 | }() |
| 254 | } | 254 | } |
| 255 | 255 | ||
| 256 | -// compactIfDue is the automatic compaction, the REPL's rule verbatim: the | ||
| 257 | -// server's own count of the last context beats the estimate, the window is | ||
| 258 | -// re-probed while unknown, and a failure keeps the history. The second | ||
| 259 | -// result is the failure line when the summary failed, for the session file. | ||
| 260 | -func (r *runner) compactIfDue(ctx context.Context, msgs []*ai.Message) ([]*ai.Message, string) { | ||
| 261 | - cfg := config.Cfg.Context | ||
| 262 | - if !cfg.Enabled { | ||
| 263 | - return msgs, "" | ||
| 264 | - } | ||
| 265 | - if r.opts.Window() == 0 && r.opts.Ensure != nil { | ||
| 266 | - if w, src := r.opts.Ensure(ctx); w > 0 { | ||
| 267 | - r.t.Notice(fmt.Sprintf("ctx: %d (%s)", w, src)) | ||
| 268 | - } | ||
| 269 | - } | ||
| 270 | - dec := compact.Decide(msgs, r.opts.Model.LastInputTokens(), r.opts.Window(), cfg) | ||
| 271 | - if !dec.Compact { | ||
| 272 | - return msgs, "" | ||
| 273 | - } | ||
| 274 | - out, line, outcome := compact.Apply(ctx, msgs, cfg, r.summarize, r.opts.Model.Explain) | ||
| 275 | - switch outcome { | ||
| 276 | - case compact.Compressed: | ||
| 277 | - r.opts.Model.ForgetInputTokens() | ||
| 278 | - if cfg.ShowStats { | ||
| 279 | - r.t.Notice(line) | ||
| 280 | - } | ||
| 281 | - case compact.Failed: | ||
| 282 | - r.t.Error(line) | ||
| 283 | - return out, line | ||
| 284 | - } | ||
| 285 | - return out, "" | ||
| 286 | -} | ||
| 287 | - | ||
| 288 | -func (r *runner) summarize(ctx context.Context, request []*ai.Message) (string, error) { | ||
| 289 | - return r.opts.Model.Summarize(ctx, request, config.Cfg.Context.SummaryMaxTokens) | ||
| 290 | -} | ||
| 291 | - | ||
| 292 | -// startCompact is /compact: forced, on a goroutine, reported as a notice. | ||
| 293 | -func (r *runner) startCompact() { | ||
| 294 | - ctx, cancel := context.WithCancel(context.Background()) | ||
| 295 | - r.cancel = cancel | ||
| 296 | - r.cancelled.Store(false) | ||
| 297 | - r.busy.Store("compressing") | ||
| 298 | - msgs := append([]*ai.Message(nil), r.messages...) | ||
| 299 | - go func() { | ||
| 300 | - out, line, oc := compact.Apply(ctx, msgs, config.Cfg.Context, r.summarize, r.opts.Model.Explain) | ||
| 301 | - r.results <- outcome{kind: "compact", messages: out, line: line, changed: oc == compact.Compressed, err: errIf(oc == compact.Failed)} | ||
| 302 | - r.wake() | ||
| 303 | - }() | ||
| 304 | -} | ||
| 305 | - | ||
| 306 | -func errIf(failed bool) error { | ||
| 307 | - if failed { | ||
| 308 | - return fmt.Errorf("compaction failed") | ||
| 309 | - } | ||
| 310 | - return nil | ||
| 311 | -} | ||
| 312 | - | ||
| 313 | // settle takes a finished job, if any, and applies it to the session. Called | 256 | // settle takes a finished job, if any, and applies it to the session. Called |
| 314 | // by the loop before every frame — the one goroutine that touches messages. | 257 | // by the loop before every frame — the one goroutine that touches messages. |
| 315 | func (r *runner) settle() { | 258 | func (r *runner) settle() { |
| @@ -534,44 +477,3 @@ func (r *runner) status() string { | |||
| 534 | } | 477 | } |
| 535 | return counters | 478 | return counters |
| 536 | } | 479 | } |
| 537 | - | ||
| 538 | -// --- permissions ------------------------------------------------------------------ | ||
| 539 | - | ||
| 540 | -// currentAsk is the permission waiting for an answer, nil when none. | ||
| 541 | -func (r *runner) currentAsk() *permission { | ||
| 542 | - r.askMu.Lock() | ||
| 543 | - defer r.askMu.Unlock() | ||
| 544 | - return r.ask | ||
| 545 | -} | ||
| 546 | - | ||
| 547 | -// answer settles the pending permission from the loop goroutine. | ||
| 548 | -func (r *runner) answer(a permissionAnswer) { | ||
| 549 | - r.askMu.Lock() | ||
| 550 | - defer r.askMu.Unlock() | ||
| 551 | - if r.ask == nil { | ||
| 552 | - return | ||
| 553 | - } | ||
| 554 | - r.ask.reply <- a | ||
| 555 | - r.ask = nil | ||
| 556 | -} | ||
| 557 | - | ||
| 558 | -// request posts a permission for the view to show and waits for the answer, | ||
| 559 | -// or for the turn to end. Called on the tool's goroutine. | ||
| 560 | -func (r *runner) request(ctx context.Context, ev ui.ToolEvent) permissionAnswer { | ||
| 561 | - p := &permission{tool: ev.Tool, title: ev.Title, reply: make(chan permissionAnswer, 1)} | ||
| 562 | - r.askMu.Lock() | ||
| 563 | - r.ask = p | ||
| 564 | - r.askMu.Unlock() | ||
| 565 | - r.wake() | ||
| 566 | - select { | ||
| 567 | - case a := <-p.reply: | ||
| 568 | - return a | ||
| 569 | - case <-ctx.Done(): | ||
| 570 | - r.askMu.Lock() | ||
| 571 | - if r.ask == p { | ||
| 572 | - r.ask = nil | ||
| 573 | - } | ||
| 574 | - r.askMu.Unlock() | ||
| 575 | - return permReject | ||
| 576 | - } | ||
| 577 | -} | ||
added
internal/tui/turn_compact.go +70 -0 | new file mode 100644 | ||
| @@ -0,0 +1,70 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "context" | |
| 5 | + "fmt" | |
| 6 | + "mm/internal/compact" | |
| 7 | + "mm/internal/config" | |
| 8 | + | |
| 9 | + "github.com/firebase/genkit/go/ai" | |
| 10 | +) | |
| 11 | + | |
| 12 | +// The context compression of the window's conversation: before a turn when | |
| 13 | +// it is due, and on /compact. | |
| 14 | + | |
| 15 | +// compactIfDue is the automatic compaction, the REPL's rule verbatim: the | |
| 16 | +// server's own count of the last context beats the estimate, the window is | |
| 17 | +// re-probed while unknown, and a failure keeps the history. The second | |
| 18 | +// result is the failure line when the summary failed, for the session file. | |
| 19 | +func (r *runner) compactIfDue(ctx context.Context, msgs []*ai.Message) ([]*ai.Message, string) { | |
| 20 | + cfg := config.Cfg.Context | |
| 21 | + if !cfg.Enabled { | |
| 22 | + return msgs, "" | |
| 23 | + } | |
| 24 | + if r.opts.Window() == 0 && r.opts.Ensure != nil { | |
| 25 | + if w, src := r.opts.Ensure(ctx); w > 0 { | |
| 26 | + r.t.Notice(fmt.Sprintf("ctx: %d (%s)", w, src)) | |
| 27 | + } | |
| 28 | + } | |
| 29 | + dec := compact.Decide(msgs, r.opts.Model.LastInputTokens(), r.opts.Window(), cfg) | |
| 30 | + if !dec.Compact { | |
| 31 | + return msgs, "" | |
| 32 | + } | |
| 33 | + out, line, outcome := compact.Apply(ctx, msgs, cfg, r.summarize, r.opts.Model.Explain) | |
| 34 | + switch outcome { | |
| 35 | + case compact.Compressed: | |
| 36 | + r.opts.Model.ForgetInputTokens() | |
| 37 | + if cfg.ShowStats { | |
| 38 | + r.t.Notice(line) | |
| 39 | + } | |
| 40 | + case compact.Failed: | |
| 41 | + r.t.Error(line) | |
| 42 | + return out, line | |
| 43 | + } | |
| 44 | + return out, "" | |
| 45 | +} | |
| 46 | + | |
| 47 | +func (r *runner) summarize(ctx context.Context, request []*ai.Message) (string, error) { | |
| 48 | + return r.opts.Model.Summarize(ctx, request, config.Cfg.Context.SummaryMaxTokens) | |
| 49 | +} | |
| 50 | + | |
| 51 | +// startCompact is /compact: forced, on a goroutine, reported as a notice. | |
| 52 | +func (r *runner) startCompact() { | |
| 53 | + ctx, cancel := context.WithCancel(context.Background()) | |
| 54 | + r.cancel = cancel | |
| 55 | + r.cancelled.Store(false) | |
| 56 | + r.busy.Store("compressing") | |
| 57 | + msgs := append([]*ai.Message(nil), r.messages...) | |
| 58 | + go func() { | |
| 59 | + out, line, oc := compact.Apply(ctx, msgs, config.Cfg.Context, r.summarize, r.opts.Model.Explain) | |
| 60 | + r.results <- outcome{kind: "compact", messages: out, line: line, changed: oc == compact.Compressed, err: errIf(oc == compact.Failed)} | |
| 61 | + r.wake() | |
| 62 | + }() | |
| 63 | +} | |
| 64 | + | |
| 65 | +func errIf(failed bool) error { | |
| 66 | + if failed { | |
| 67 | + return fmt.Errorf("compaction failed") | |
| 68 | + } | |
| 69 | + return nil | |
| 70 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,70 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "fmt" | ||
| 6 | + "mm/internal/compact" | ||
| 7 | + "mm/internal/config" | ||
| 8 | + | ||
| 9 | + "github.com/firebase/genkit/go/ai" | ||
| 10 | +) | ||
| 11 | + | ||
| 12 | +// The context compression of the window's conversation: before a turn when | ||
| 13 | +// it is due, and on /compact. | ||
| 14 | + | ||
| 15 | +// compactIfDue is the automatic compaction, the REPL's rule verbatim: the | ||
| 16 | +// server's own count of the last context beats the estimate, the window is | ||
| 17 | +// re-probed while unknown, and a failure keeps the history. The second | ||
| 18 | +// result is the failure line when the summary failed, for the session file. | ||
| 19 | +func (r *runner) compactIfDue(ctx context.Context, msgs []*ai.Message) ([]*ai.Message, string) { | ||
| 20 | + cfg := config.Cfg.Context | ||
| 21 | + if !cfg.Enabled { | ||
| 22 | + return msgs, "" | ||
| 23 | + } | ||
| 24 | + if r.opts.Window() == 0 && r.opts.Ensure != nil { | ||
| 25 | + if w, src := r.opts.Ensure(ctx); w > 0 { | ||
| 26 | + r.t.Notice(fmt.Sprintf("ctx: %d (%s)", w, src)) | ||
| 27 | + } | ||
| 28 | + } | ||
| 29 | + dec := compact.Decide(msgs, r.opts.Model.LastInputTokens(), r.opts.Window(), cfg) | ||
| 30 | + if !dec.Compact { | ||
| 31 | + return msgs, "" | ||
| 32 | + } | ||
| 33 | + out, line, outcome := compact.Apply(ctx, msgs, cfg, r.summarize, r.opts.Model.Explain) | ||
| 34 | + switch outcome { | ||
| 35 | + case compact.Compressed: | ||
| 36 | + r.opts.Model.ForgetInputTokens() | ||
| 37 | + if cfg.ShowStats { | ||
| 38 | + r.t.Notice(line) | ||
| 39 | + } | ||
| 40 | + case compact.Failed: | ||
| 41 | + r.t.Error(line) | ||
| 42 | + return out, line | ||
| 43 | + } | ||
| 44 | + return out, "" | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +func (r *runner) summarize(ctx context.Context, request []*ai.Message) (string, error) { | ||
| 48 | + return r.opts.Model.Summarize(ctx, request, config.Cfg.Context.SummaryMaxTokens) | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +// startCompact is /compact: forced, on a goroutine, reported as a notice. | ||
| 52 | +func (r *runner) startCompact() { | ||
| 53 | + ctx, cancel := context.WithCancel(context.Background()) | ||
| 54 | + r.cancel = cancel | ||
| 55 | + r.cancelled.Store(false) | ||
| 56 | + r.busy.Store("compressing") | ||
| 57 | + msgs := append([]*ai.Message(nil), r.messages...) | ||
| 58 | + go func() { | ||
| 59 | + out, line, oc := compact.Apply(ctx, msgs, config.Cfg.Context, r.summarize, r.opts.Model.Explain) | ||
| 60 | + r.results <- outcome{kind: "compact", messages: out, line: line, changed: oc == compact.Compressed, err: errIf(oc == compact.Failed)} | ||
| 61 | + r.wake() | ||
| 62 | + }() | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +func errIf(failed bool) error { | ||
| 66 | + if failed { | ||
| 67 | + return fmt.Errorf("compaction failed") | ||
| 68 | + } | ||
| 69 | + return nil | ||
| 70 | +} | ||
added
internal/tui/turn_permissions.go +49 -0 | new file mode 100644 | ||
| @@ -0,0 +1,49 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "context" | |
| 5 | + "mm/internal/ui" | |
| 6 | +) | |
| 7 | + | |
| 8 | +// The permissions of the turn's tool calls: the tool's goroutine posts a | |
| 9 | +// request and waits; the loop reads it before each frame and the view | |
| 10 | +// answers it (events.go's answerPermission). | |
| 11 | + | |
| 12 | +// currentAsk is the permission waiting for an answer, nil when none. | |
| 13 | +func (r *runner) currentAsk() *permission { | |
| 14 | + r.askMu.Lock() | |
| 15 | + defer r.askMu.Unlock() | |
| 16 | + return r.ask | |
| 17 | +} | |
| 18 | + | |
| 19 | +// answer settles the pending permission from the loop goroutine. | |
| 20 | +func (r *runner) answer(a permissionAnswer) { | |
| 21 | + r.askMu.Lock() | |
| 22 | + defer r.askMu.Unlock() | |
| 23 | + if r.ask == nil { | |
| 24 | + return | |
| 25 | + } | |
| 26 | + r.ask.reply <- a | |
| 27 | + r.ask = nil | |
| 28 | +} | |
| 29 | + | |
| 30 | +// request posts a permission for the view to show and waits for the answer, | |
| 31 | +// or for the turn to end. Called on the tool's goroutine. | |
| 32 | +func (r *runner) request(ctx context.Context, ev ui.ToolEvent) permissionAnswer { | |
| 33 | + p := &permission{tool: ev.Tool, title: ev.Title, reply: make(chan permissionAnswer, 1)} | |
| 34 | + r.askMu.Lock() | |
| 35 | + r.ask = p | |
| 36 | + r.askMu.Unlock() | |
| 37 | + r.wake() | |
| 38 | + select { | |
| 39 | + case a := <-p.reply: | |
| 40 | + return a | |
| 41 | + case <-ctx.Done(): | |
| 42 | + r.askMu.Lock() | |
| 43 | + if r.ask == p { | |
| 44 | + r.ask = nil | |
| 45 | + } | |
| 46 | + r.askMu.Unlock() | |
| 47 | + return permReject | |
| 48 | + } | |
| 49 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,49 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "mm/internal/ui" | ||
| 6 | +) | ||
| 7 | + | ||
| 8 | +// The permissions of the turn's tool calls: the tool's goroutine posts a | ||
| 9 | +// request and waits; the loop reads it before each frame and the view | ||
| 10 | +// answers it (events.go's answerPermission). | ||
| 11 | + | ||
| 12 | +// currentAsk is the permission waiting for an answer, nil when none. | ||
| 13 | +func (r *runner) currentAsk() *permission { | ||
| 14 | + r.askMu.Lock() | ||
| 15 | + defer r.askMu.Unlock() | ||
| 16 | + return r.ask | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +// answer settles the pending permission from the loop goroutine. | ||
| 20 | +func (r *runner) answer(a permissionAnswer) { | ||
| 21 | + r.askMu.Lock() | ||
| 22 | + defer r.askMu.Unlock() | ||
| 23 | + if r.ask == nil { | ||
| 24 | + return | ||
| 25 | + } | ||
| 26 | + r.ask.reply <- a | ||
| 27 | + r.ask = nil | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +// request posts a permission for the view to show and waits for the answer, | ||
| 31 | +// or for the turn to end. Called on the tool's goroutine. | ||
| 32 | +func (r *runner) request(ctx context.Context, ev ui.ToolEvent) permissionAnswer { | ||
| 33 | + p := &permission{tool: ev.Tool, title: ev.Title, reply: make(chan permissionAnswer, 1)} | ||
| 34 | + r.askMu.Lock() | ||
| 35 | + r.ask = p | ||
| 36 | + r.askMu.Unlock() | ||
| 37 | + r.wake() | ||
| 38 | + select { | ||
| 39 | + case a := <-p.reply: | ||
| 40 | + return a | ||
| 41 | + case <-ctx.Done(): | ||
| 42 | + r.askMu.Lock() | ||
| 43 | + if r.ask == p { | ||
| 44 | + r.ask = nil | ||
| 45 | + } | ||
| 46 | + r.askMu.Unlock() | ||
| 47 | + return permReject | ||
| 48 | + } | ||
| 49 | +} | ||