Terminal
Example sourceGo · Copyable
This is the complete source for the gallery example above.examples/components/terminal.go
Reuse the component construction and Render methods in a scaffolded project. The example’s registerSection and shared helpers are provided by the component gallery.
package main
import (
"fmt"
"strings"
"time"
"unicode/utf8"
"github.com/dyike/keel/ui/core"
"github.com/dyike/keel/ui/el"
"github.com/dyike/keel/ui/kit"
)
func init() {
registerSection("terminal", "data", func() core.Widget {
term := kit.Terminal().Name(demoText("Terminal session", "终端会话")).Height(380)
prompt := "\x1b[32mkeel\x1b[0m:\x1b[34m~\x1b[0m$ "
line := ""
welcomed := false
running := false
generation := 0
write := func(s string) { term.WriteString(s) }
help := func() { write("help · colors · progress · echo <text> · clear\r\n") }
var tick func(int, int)
tick = func(token, done int) {
time.AfterFunc(60*time.Millisecond, func() {
core.UpdateIf(func() bool {
if generation != token || !running {
return false
}
next := done + 5
write(fmt.Sprintf("\r\x1b[36m%s\x1b[2m%s\x1b[0m %d%%", strings.Repeat("█", next/5), strings.Repeat("░", 20-next/5), next))
if next == 100 {
running = false
write("\r\n" + prompt)
} else {
tick(token, next)
}
return true
})
})
}
term.OnResize(func(cols, rows int) {
if !welcomed {
welcomed = true
write("Keel terminal · pure Go\r\n")
help()
write(prompt)
}
}).OnData(func(data string) {
if strings.ContainsRune(data, 3) {
generation++
running = false
line = ""
write("^C\r\n" + prompt)
return
}
if running {
return
}
if strings.HasPrefix(data, "\x1b") {
return
}
for _, r := range data {
switch r {
case '\r':
write("\r\n")
command := strings.TrimSpace(line)
line = ""
name, rest, _ := strings.Cut(command, " ")
switch name {
case "help":
help()
case "clear":
write("\x1b[3J\x1b[2J\x1b[H")
case "echo":
write(rest + "\r\n")
case "colors":
for i := 0; i < 16; i++ {
write(fmt.Sprintf("\x1b[48;5;%dm \x1b[0m", i))
}
write("\r\n")
for i := 0; i < 32; i++ {
write(fmt.Sprintf("\x1b[48;2;%d;96;%dm \x1b[0m", 255-i*8, i*8))
}
write("\r\n")
case "progress":
running = true
generation++
tick(generation, 0)
case "":
default:
write("\x1b[31mUnknown command: " + name + "\x1b[0m\r\n")
}
if !running {
write(prompt)
}
case 0x7f:
if line != "" {
_, n := utf8.DecodeLastRuneInString(line)
line = line[:len(line)-n]
write("\b \b")
}
default:
if r >= ' ' {
line += string(r)
write(string(r))
}
}
}
})
return el.Root(el.ViewFunc(func(cx *el.Context) el.Element {
return el.Div().P(16).Gap(12).ScrollY().Child(el.Text(demoText("Type help. Ctrl+C cancels progress; Ctrl+Shift+C copies a selection.", "输入 help。Ctrl+C 取消进度;Ctrl+Shift+C 复制选区。")), term.Render(cx))
}))
})
}
Terminal() is a pure-Go ANSI display with application-owned input/output. It never starts a shell, opens a network connection or performs OSC clipboard operations. Connect OnData(func(string)) to your process, PTY, WebSocket or SSH transport, and pass received bytes to Write. WriteString is also available; both implement the usual writer return values. Calls from background work must be made inside core.Update or core.UpdateIf, like other Keel views. Output is accepted while input is disabled and never triggers OnData.
Name labels the textbox. Height sets its nested viewport height (default 320dp); Fill uses the available space. An el.Root can fill the window. Size reports character columns/rows; OnResize reports a changed size after actual visible layout, not measurement. The first visible layout also reports its size. Dimensions are bounded to 512 columns and 256 rows. Resizing preserves/clamps the current screen but does not reflow old text. Scrollback sets retained history lines, from 0 to 10000, default 1000. Reset clears screen, history, parser modes and selection without sending input. Text returns plain screen/history text, including blank screen rows.
ANSI support includes 16/256/RGB colors, bold, dim, italic, underline, inverse and strike; carriage return, line feed, backspace, tabs, delayed wrapping; cursor positioning/save/restore; erase screen/line/characters; insert/delete characters/lines; scroll regions; alternate screen 1049; cursor visibility, application cursor and bracketed paste modes. UTF-8 and escape sequences may be split across writes. Wide and combining/ZWJ text uses grapheme-aware cells. Screen history and parser buffers are bounded. Unsupported control strings are consumed, not executed. This is not full xterm/VT compatibility: mouse reporting, terminal queries, alternate character sets, colon-form SGR, advanced keyboard protocols and history reflow remain unsupported.
Input is sent without local echo; the application writes any echo. Committed text, Return, Backspace, Tab, Escape, Ctrl-letter combinations, arrows, Home/End, Delete, PageUp/PageDown and F1–F12 produce terminal sequences. Application cursor mode changes arrow sequences. Escape followed by Tab allows focus to leave; ordinary Tab is sent to the session. Pointer clicks/taps focus the terminal. IME composition is displayed locally and committed once when the composition ends; real-platform IME acceptance is separate from the event-harness tests.
Drag with a mouse to select. Ctrl+Shift+C (or Super+C) copies Selection; Ctrl+C always sends byte 3. Ctrl+Shift+V (or Super+V) requests clipboard text; bracketed paste wraps it when enabled. Clipboard input is limited to 1MiB. Copy uses displayed row boundaries and complete wide graphemes. Unrelated output preserves a selection; overwriting selected text or evicting selected history clears it. Wheel/touch scrolling can leave the bottom; incoming output retains the scrolled view, adjusting for evicted history. New keyboard input resumes following output. SetDisabled blocks interaction and cancels transient input/paste, while silent output methods remain available. Ancestor disabling is respected.
Only visible rows are drawn. ANSI backgrounds and font styles use the existing Gio/theme glyph renderer, including supported platform color emoji. The cursor is solid: an idle terminal does not schedule blink frames. Accessibility exposes visible text and disabled state using the existing textbox role. Font coverage, physical device IMEs, actual PTY applications and client memory/frame performance require separate acceptance.
The Gallery example is an in-process command demonstration (help, colors, progress, echo, clear), not an operating-system shell. Its progress command uses finite scheduled updates and Ctrl+C cancels them. Production transports, process lifecycle, backpressure and output scheduling belong to the application.
Validation: go test ./ui/kit ./ui/window -run TestTerminal; go run ./examples/components -section terminal.