diff --git a/README.md b/README.md index 862e3f9..d5a2b8f 100644 --- a/README.md +++ b/README.md @@ -188,6 +188,22 @@ than risking erasure of unrelated reflowed scrollback. Interactive prompts honor context cancellation; generic line readers can only check it before/after reads. See the executable `ExampleInline` and terminal tests in `deck/inline*_test.go`. +To keep completed actions in scrollback while editing the active prompt, set +`InlineSpec.AppendOnly: true`. For application-specific presentation, supply a +pure `Render func(deck.InlinePanel) string`: it receives sanitized text, the +bounded total panel width, and `InlineContent`, `InlineEditing`, +`InlineSubmitted`, `InlineCancelled`, or `InlineError`. For example, a renderer +can map these states to `outputbox` status colors. Normal `Panel` calls have no +implied success/failure status; applications own those semantics. Renderers must +fit within the supplied width, must not write terminal commands, and must omit +the trailing newline. Plain mode (and extremely narrow terminals) bypass custom +renderers. Scoped keys and prompt behavior are unchanged. + +ANSI styles are normally stripped from redirected or dumb output. Applications +with an explicit forced-color option may opt into `AllowANSI: true`; this does +**not** enable cursor movement or interactive input on redirected streams. +`Plain: true` still strips ANSI regardless of `AllowANSI`. + ## Status API may still shift before a published `v1`. diff --git a/deck/INTERFACE.md b/deck/INTERFACE.md index 6393a52..1250aba 100644 --- a/deck/INTERFACE.md +++ b/deck/INTERFACE.md @@ -64,6 +64,16 @@ secret redaction, and exit policy; `Report`/`ErrorReported` preserve error identity while avoiding duplicate error messages. The API is sequential, not concurrency-safe. Terminal-width changes preserve earlier reflowed output. +`InlineSpec.AppendOnly` retains completed panels even on interactive terminals; +it does not disable active-prompt editing. `Render` is an optional pure +presentation hook, receiving sanitized, wrapped `InlinePanel` text, bounded total +width, and a neutral `InlineState`. The host still owns input, hints, lifecycle, +newline accounting, and error reporting. Renderers own safe chrome/style only, +must fit the supplied width, and must not emit terminal control commands. +`Plain` and extremely narrow terminals bypass this hook. `AllowANSI` permits +styles on redirected output without changing interaction/clearing capability; +`Plain` takes precedence. Default behavior remains unchanged. + ## Chrome contract Apps inject branding via `WithChrome(Chrome{Brand, BrandGlyph, Subtitle, ClockGlyph})`. diff --git a/deck/inline.go b/deck/inline.go index e3d7aa6..9c1e058 100644 --- a/deck/inline.go +++ b/deck/inline.go @@ -26,6 +26,32 @@ import ( // it through InlineSpec.Keys. const InlineClear keys.Action = "inline.clear" +// InlineState identifies the lifecycle of a rendered workflow panel. +type InlineState uint8 + +const ( + // InlineContent is a caller-supplied panel, with no implied status. + InlineContent InlineState = iota + // InlineEditing is a text prompt awaiting a response. + InlineEditing + // InlineSubmitted is the final view of a submitted prompt. + InlineSubmitted + // InlineCancelled is the final view of a cancelled prompt. + InlineCancelled + // InlineError is an error displayed by Report. + InlineError +) + +// InlinePanel is the neutral input to a custom workflow renderer. Title and +// Lines contain sanitized text; Lines are wrapped to the preferred body width. +// Width includes the four columns reserved for default panel chrome. +type InlinePanel struct { + Title string + Lines []string + Width int + State InlineState +} + // InlineSpec configures a sequential, inline CLI workflow. Domain checks, // validation, persistence, and external commands belong to the caller. type InlineSpec struct { @@ -39,6 +65,19 @@ type InlineSpec struct { Width int // Plain disables panels, cursor movement, and interactive editing. Plain bool + // AppendOnly keeps completed panels in scrollback even on terminals. + // The active text prompt still edits and redraws interactively. + AppendOnly bool + // Render replaces the default panel presentation. It must be a pure + // renderer, fit within InlinePanel.Width, and return no trailing newline. + // It is not called in Plain mode or on terminals narrower than 5 cells. + // ANSI styles are allowed; terminal control commands are not. The host + // strips ANSI unless output supports it or AllowANSI is true. + Render func(InlinePanel) string + // AllowANSI preserves renderer styles even for redirected/dumb output + // (for example, an application's forced-color option). It never enables + // interaction or cursor movement, and Plain still strips all ANSI. + AllowANSI bool // Keys overrides the text editor map, including submit and cancel. Nil // uses text-safe scoped confirm/cancel/quit/erase and ctrl+u to clear. Keys *keys.Map @@ -60,6 +99,8 @@ type Inline struct { keyMap *keys.Map width int plain bool + appendOnly bool + renderPanel func(InlinePanel) string interactive bool ansi bool title string @@ -86,7 +127,8 @@ func NewInline(spec InlineSpec) *Inline { u := &Inline{ in: in, out: out, lines: bufio.NewReader(in), scope: scope, keyMap: spec.Keys, width: layout.NewFrame(spec.Width).Width, - plain: spec.Plain, ansi: caps.ANSI && !spec.Plain, + plain: spec.Plain, ansi: (caps.ANSI || spec.AllowANSI) && !spec.Plain, + appendOnly: spec.AppendOnly, renderPanel: spec.Render, interactive: inlineTerminal(in) && caps.ANSI && !spec.Plain, } u.size = func() (int, int) { @@ -127,7 +169,7 @@ func (u *Inline) frame(width int) layout.Frame { return layout.Frame{Width: bodyWidth + 4, UI: u.scope} } -func (u *Inline) render(title string, body []string, width int) string { +func (u *Inline) render(title string, body []string, width int, state InlineState) string { f := u.frame(width) bodyWidth := max(1, f.Width-4) if width > 0 && width < 5 { @@ -144,6 +186,8 @@ func (u *Inline) render(title string, body []string, width int) string { titleWidth = min(titleWidth, width) } text = inlineWrap(inlineText(title), titleWidth) + "\n" + strings.Join(lines, "\n") + } else if u.renderPanel != nil { + text = u.renderPanel(InlinePanel{Title: inlineText(title), Lines: lines, Width: f.Width, State: state}) } else { text = f.CellBox(inlineText(title), lines...) } @@ -165,7 +209,7 @@ func inlineWrap(text string, width int) string { } func (u *Inline) clear(width, height int) error { - if u.interactive && u.rows > 0 && width == u.lastWidth { + if u.interactive && !u.appendOnly && u.rows > 0 && width == u.lastWidth { rows := u.rows if height > 0 { rows = min(rows, height-1) @@ -186,8 +230,12 @@ func (u *Inline) clear(width, height int) error { // are untrusted text: terminal control sequences are stripped. A matching Ask // retains these instructions inside the same panel. func (u *Inline) Panel(title string, lines ...string) error { + return u.panel(InlineContent, title, lines...) +} + +func (u *Inline) panel(state InlineState, title string, lines ...string) error { width, height := u.size() - text := u.render(title, lines, width) + text := u.render(title, lines, width, state) if err := u.clear(width, height); err != nil { return err } @@ -241,7 +289,7 @@ func (u *Inline) Ask(ctx context.Context, title, label, value string) (string, e } // No Tea program or cursor escapes for transcripts. Reuse one buffered // reader across prompts so read-ahead remains available to the next step. - if err := u.Panel(title, append(body, inlineText(label)+" ["+value+"]:")...); err != nil { + if err := u.panel(InlineEditing, title, append(body, inlineText(label)+" ["+value+"]:")...); err != nil { return "", err } // A prompt is not an instruction for the following Ask/Report. @@ -304,7 +352,7 @@ func (u *Inline) Report(err error) error { title = "Error" } body := append(append([]string(nil), u.body...), err.Error()) - if renderErr := u.Panel(title, body...); renderErr != nil { + if renderErr := u.panel(InlineError, title, body...); renderErr != nil { return errors.Join(err, renderErr) } return inlineReportedError{err: err} @@ -381,7 +429,7 @@ func (m *inlineModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { func (m *inlineModel) View() string { if m.cancelled { - return m.owner.render(m.title, []string{"Cancelled."}, m.width) + "\n" + return m.owner.render(m.title, []string{"Cancelled."}, m.width, InlineCancelled) + "\n" } lines := append([]string(nil), m.body...) lines = append(lines, "", inlineText(m.label)+": "+m.form.Focused().Text, "") @@ -401,5 +449,9 @@ func (m *inlineModel) View() string { } lines = append(lines, strings.Join(hints, " ยท ")) } - return m.owner.render(m.title, lines, m.width) + "\n" + state := InlineEditing + if m.submitted { + state = InlineSubmitted + } + return m.owner.render(m.title, lines, m.width, state) + "\n" } diff --git a/deck/inline_test.go b/deck/inline_test.go index 55b54ca..5776082 100644 --- a/deck/inline_test.go +++ b/deck/inline_test.go @@ -270,6 +270,83 @@ func TestInlineScopedKeysAndHints(t *testing.T) { } } +func TestInlineCustomPresentation(t *testing.T) { + var out bytes.Buffer + var seen []InlinePanel + u := NewInline(InlineSpec{ + Input: strings.NewReader("answer\n"), Output: &out, AppendOnly: true, + Render: func(p InlinePanel) string { + seen = append(seen, p) + return "custom " + p.Title + "\n" + strings.Join(p.Lines, "\n") + }, + }) + u.size = func() (int, int) { return 50, 20 } + u.interactive = true // exercise terminal replacement independently of a PTY + if err := u.Panel("First\x1b[2J", "body\x1b[2J"); err != nil { + t.Fatal(err) + } + if err := u.Panel("Second", "instructions"); err != nil { + t.Fatal(err) + } + if seen[0].Title != "First" || seen[0].Lines[0] != "body" || seen[0].Width != 50 || seen[0].State != InlineContent { + t.Fatalf("renderer input not sanitized/sized: %#v", seen[0]) + } + if strings.Contains(out.String(), "\x1b") || !u.interactive { + t.Fatal("append-only must not clear panels or disable interactive editing", out.String()) + } + m := &inlineModel{owner: u, title: "Prompt", label: "Name", width: 50, + form: forms.NewForm(forms.Text("value", "Name"))} + m.View() + if seen[len(seen)-1].State != InlineEditing { + t.Fatal(seen) + } + m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m.View() + if seen[len(seen)-1].State != InlineSubmitted { + t.Fatal(seen) + } + m.cancelled = true + m.View() + if seen[len(seen)-1].State != InlineCancelled { + t.Fatal(seen) + } + if err := u.Report(errors.New("failed")); !ErrorReported(err) || seen[len(seen)-1].State != InlineError { + t.Fatal(err, seen) + } + u.interactive = false + if _, err := u.Ask(context.Background(), "Transcript", "Name", ""); err != nil || seen[len(seen)-1].State != InlineEditing { + t.Fatal(err, seen) + } +} + +func TestInlineCustomRendererColorAndPlain(t *testing.T) { + for _, tc := range []struct { + name string + plain, allowANSI bool + }{ + {name: "redirected"}, {name: "forced color", allowANSI: true}, + {name: "plain wins", plain: true, allowANSI: true}, + } { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + called := false + u := NewInline(InlineSpec{Input: strings.NewReader(""), Output: &out, + Plain: tc.plain, AllowANSI: tc.allowANSI, + Render: func(p InlinePanel) string { + called = true + return "\x1b[31m" + p.Title + "\x1b[0m" + }, + }) + if err := u.Panel("Title"); err != nil { + t.Fatal(err) + } + if called == tc.plain || strings.Contains(out.String(), "\x1b") != (tc.allowANSI && !tc.plain) || u.interactive { + t.Fatalf("called=%v interactive=%v output=%q", called, u.interactive, out.String()) + } + }) + } +} + func ExampleInline() { var transcript bytes.Buffer flow := NewInline(InlineSpec{ diff --git a/skills/viewkit/references/api.md b/skills/viewkit/references/api.md index 2cd1494..24d6e74 100644 --- a/skills/viewkit/references/api.md +++ b/skills/viewkit/references/api.md @@ -306,8 +306,19 @@ type InlineSpec struct { UI *ui.Scope // nil = ui.Default() Width int // preferred body width, zero = document width Plain bool // no panels, editing, or cursor movement + AppendOnly bool // retain completed panels; still edit active prompt + Render func(InlinePanel) string // pure bounded renderer; bypassed in plain mode + AllowANSI bool // permit forced-color styles, not cursor movement Keys *keys.Map // nil = text-safe scoped editor map } +type InlineState uint8 +const (InlineContent InlineState = iota; InlineEditing; InlineSubmitted; InlineCancelled; InlineError) +type InlinePanel struct { + Title string // sanitized + Lines []string // sanitized and wrapped + Width int // total width including chrome + State InlineState +} const InlineClear keys.Action = "inline.clear" // default ctrl+u func NewInline(spec InlineSpec) *Inline func (u *Inline) Panel(title string, lines ...string) error