commit 0c16bc15a230e4cb2e0e634490e96e9f680aef9b Author: katistix <2018.tpg@gmail.com> Date: Tue Oct 6 17:41:50 2026 +0300 initial diff --git a/README.md b/README.md new file mode 100644 index 0000000..b67c342 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# termitype + +A simple monkeytype clone for the terminal written in Go with Bubbletea and Lipgloss. diff --git a/cmd/termitype/main.go b/cmd/termitype/main.go new file mode 100644 index 0000000..486b023 --- /dev/null +++ b/cmd/termitype/main.go @@ -0,0 +1,32 @@ +package main + +import ( + "errors" + "flag" + "fmt" + "os" + + tea "github.com/charmbracelet/bubbletea" + "github.com/katistix/termitype/internal/config" + "github.com/katistix/termitype/internal/ui" +) + +func main() { + cfg, err := config.Parse(os.Args[1:]) + if err != nil { + if errors.Is(err, flag.ErrHelp) { + fmt.Println(config.Usage()) + return + } + fmt.Fprintln(os.Stderr, "termitype:", err) + fmt.Fprintln(os.Stderr, "try: termitype --help") + os.Exit(1) + } + + m := ui.New(cfg) + p := tea.NewProgram(m, tea.WithAltScreen()) + if _, err := p.Run(); err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..ac67ee1 --- /dev/null +++ b/go.mod @@ -0,0 +1,25 @@ +module github.com/katistix/termitype + +go 1.26.5 + +require ( + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/charmbracelet/bubbletea v1.3.10 // indirect + github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect + github.com/charmbracelet/lipgloss v1.1.0 // indirect + github.com/charmbracelet/x/ansi v0.10.1 // indirect + github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect + github.com/charmbracelet/x/term v0.2.1 // indirect + github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-localereader v0.0.1 // indirect + github.com/mattn/go-runewidth v0.0.16 // indirect + github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/muesli/termenv v0.16.0 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + golang.org/x/sys v0.36.0 // indirect + golang.org/x/text v0.3.8 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..cc7a40a --- /dev/null +++ b/go.sum @@ -0,0 +1,41 @@ +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw= +github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= +github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= +github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= +github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= +github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ= +github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE= +github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8= +github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= +github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= +github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= +github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= +github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= +github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= +github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= +github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= +github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= +golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..c53ce0e --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,156 @@ +// Package config parses command-line settings for termitype. +// +// Examples: +// +// termitype # time mode, 15s (default) +// termitype --mode time --time 30 +// termitype --mode words --words 50 +// termitype -w 25 # shorthand, implies words mode +// termitype -t 60 # shorthand, implies time mode +package config + +import ( + "errors" + "flag" + "fmt" + "strings" +) + +// Mode selects the test type. +type Mode string + +const ( + ModeTime Mode = "time" + ModeWords Mode = "words" +) + +// Config holds all user-facing settings. +type Config struct { + Mode Mode // time or words + Seconds int // test length in time mode + Words int // test length in words mode +} + +const ( + DefaultSeconds = 15 + DefaultWords = 30 +) + +// Default returns the default config: 15s time mode. +func Default() Config { + return Config{Mode: ModeTime, Seconds: DefaultSeconds, Words: DefaultWords} +} + +// Usage returns help text. +func Usage() string { + return `termitype - monkeytype in your terminal + +usage: + termitype [-t seconds | -w count] + +options: + -t, --time timed test, s seconds (default 15) + -w, --words word-count test, n words (default 30) + -h, --help show this help + +keys: + esc restart test + ctrl+c quit + ctrl+w delete word (also opt+backspace) + +examples: + termitype 15 second test + termitype -t 30 30 second test + termitype -w 50 50 word test` +} + +// Parse parses args (without program name) into a Config. +func Parse(args []string) (Config, error) { + cfg := Default() + modeStr := string(cfg.Mode) + + fs := flag.NewFlagSet("termitype", flag.ContinueOnError) + fs.StringVar(&modeStr, "mode", modeStr, "test mode: time|words") + fs.IntVar(&cfg.Seconds, "time", cfg.Seconds, "time limit in seconds") + fs.IntVar(&cfg.Words, "words", cfg.Words, "word count") + // Shorthands sharing the same backing vars. + fs.IntVar(&cfg.Seconds, "t", cfg.Seconds, "shorthand for --time") + fs.IntVar(&cfg.Words, "w", cfg.Words, "shorthand for --words") + + // Suppress default usage output; caller prints Usage(). + fs.Usage = func() {} + if err := fs.Parse(args); err != nil { + if errors.Is(err, flag.ErrHelp) { + return cfg, err + } + return Config{}, fmt.Errorf("%w", err) + } + if fs.NArg() > 0 { + return Config{}, fmt.Errorf("unexpected argument %q", fs.Arg(0)) + } + + modeStr = strings.ToLower(strings.TrimSpace(modeStr)) + modeFlagSet := hasFlag(args, "mode") + timeFlagSet := hasFlag(args, "time", "t") + wordsFlagSet := hasFlag(args, "words", "w") + + // Shorthands imply their mode when --mode was not given explicitly. + if !modeFlagSet { + switch { + case wordsFlagSet && !timeFlagSet: + modeStr = string(ModeWords) + case timeFlagSet && !wordsFlagSet: + modeStr = string(ModeTime) + } + } + + cfg.Mode = Mode(modeStr) + if err := cfg.Validate(); err != nil { + return Config{}, err + } + return cfg, nil +} + +// Validate checks ranges. +func (c Config) Validate() error { + switch c.Mode { + case ModeTime, ModeWords: + default: + return fmt.Errorf("invalid mode %q: must be %q or %q", c.Mode, ModeTime, ModeWords) + } + if c.Seconds < 5 || c.Seconds > 300 { + return fmt.Errorf("invalid time %d: must be 5..300 seconds", c.Seconds) + } + if c.Words < 5 || c.Words > 500 { + return fmt.Errorf("invalid words %d: must be 5..500", c.Words) + } + return nil +} + +// Label returns a short "time 15s" / "words 30" description. +func (c Config) Label() string { + if c.Mode == ModeWords { + return fmt.Sprintf("words %d", c.Words) + } + return fmt.Sprintf("time %ds", c.Seconds) +} + +func hasFlag(args []string, names ...string) bool { + set := make(map[string]bool, len(names)) + for _, n := range names { + set[n] = true + set["-"+n] = true + } + for _, a := range args { + // Split --flag=value. + name := strings.SplitN(strings.TrimLeft(a, "-"), "=", 2)[0] + if !strings.HasPrefix(a, "-") { + continue + } + // Match -t / --time style; single-dash long flags also accepted. + if set[name] || set[strings.TrimLeft(a, "-")] { + return true + } + } + return false +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..51a39f5 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,62 @@ +package config + +import ( + "errors" + "flag" + "testing" +) + +func TestDefaultIs15s(t *testing.T) { + cfg, err := Parse(nil) + if err != nil { + t.Fatal(err) + } + if cfg.Mode != ModeTime || cfg.Seconds != 15 { + t.Fatalf("got %+v, want time 15s", cfg) + } +} + +func TestWordsMode(t *testing.T) { + cfg, err := Parse([]string{"--mode", "words", "--words", "50"}) + if err != nil { + t.Fatal(err) + } + if cfg.Mode != ModeWords || cfg.Words != 50 { + t.Fatalf("got %+v", cfg) + } +} + +func TestShorthandImpliesMode(t *testing.T) { + cfg, err := Parse([]string{"-w", "25"}) + if err != nil { + t.Fatal(err) + } + if cfg.Mode != ModeWords { + t.Fatalf("got %+v, want words mode", cfg) + } + cfg, err = Parse([]string{"-t", "60"}) + if err != nil { + t.Fatal(err) + } + if cfg.Mode != ModeTime || cfg.Seconds != 60 { + t.Fatalf("got %+v, want time 60", cfg) + } +} + +func TestInvalid(t *testing.T) { + if _, err := Parse([]string{"--mode", "bogus"}); err == nil { + t.Fatal("want error for bad mode") + } + if _, err := Parse([]string{"--time", "1"}); err == nil { + t.Fatal("want error for tiny time") + } + if _, err := Parse([]string{"extra"}); err == nil { + t.Fatal("want error for positional arg") + } +} + +func TestHelpPassthrough(t *testing.T) { + if _, err := Parse([]string{"--help"}); !errors.Is(err, flag.ErrHelp) { + t.Fatalf("want ErrHelp, got %v", err) + } +} diff --git a/internal/typing/engine.go b/internal/typing/engine.go new file mode 100644 index 0000000..9421665 --- /dev/null +++ b/internal/typing/engine.go @@ -0,0 +1,426 @@ +// Package typing holds the core typing-test state machine. +// It mirrors monkeytype: typing stays on the current word (extra letters +// are kept as extras), Space submits the word and advances, Backspace +// edits within the word, and you can only jump back to fix incorrect words. +package typing + +import ( + "strings" + "time" +) + +// maxExtra caps extra letters beyond the target word length, +// like monkeytype which stops accepting endless extras. +const maxExtra = 10 + +// Config controls a test. +type Config struct { + WordCount int // words per test + TimeLimit time.Duration // 0 = no limit, finish when all words done +} + +// DefaultConfig is words-mode with 30 words (time mode sets TimeLimit). +func DefaultConfig() Config { + return Config{WordCount: 30, TimeLimit: 0} +} + +// Engine tracks target words vs per-word user input. +type Engine struct { + cfg Config + target []string + input [][]rune // typed runes per word, len == len(target) + current int // index of active word + started time.Time + ended *time.Time + begun bool + + // Keystroke counters for monkeytype-style accuracy. + strokes, correctStrokes int +} + +// New creates an Engine for the given target text (space-separated words). +func New(target string, cfg Config) *Engine { + ws := strings.Fields(target) + in := make([][]rune, len(ws)) + return &Engine{cfg: cfg, target: ws, input: in} +} + +// Target returns the full target text. +func (e *Engine) Target() string { return strings.Join(e.target, " ") } + +// Typed returns submitted + current input joined as text (no trailing space). +func (e *Engine) Typed() string { + end := e.current + if e.ended != nil && end < len(e.input) { + end++ + } + parts := make([]string, 0, end) + for i := 0; i < end && i < len(e.input); i++ { + parts = append(parts, string(e.input[i])) + } + return strings.Join(parts, " ") +} + +func (e *Engine) wordSubmitted(i int) bool { return i < e.current } + +// WordCount returns number of target words. +func (e *Engine) WordCount() int { return len(e.target) } + +// TargetWord returns target word i. +func (e *Engine) TargetWord(i int) string { + if i < 0 || i >= len(e.target) { + return "" + } + return e.target[i] +} + +// InputWord returns typed input for word i. +func (e *Engine) InputWord(i int) string { + if i < 0 || i >= len(e.input) { + return "" + } + return string(e.input[i]) +} + +// CurrentWord is the active word index. +func (e *Engine) CurrentWord() int { return e.current } + +// CursorPos is the caret offset inside the current word. +func (e *Engine) CursorPos() int { + if e.current >= len(e.input) { + return 0 + } + return len(e.input[e.current]) +} + +// Done reports whether the test is complete. +func (e *Engine) Done() bool { return e.ended != nil } + +// Started reports whether the user typed anything yet. +func (e *Engine) Started() bool { return e.begun } + +func (e *Engine) ensureStarted() { + if !e.begun { + e.begun = true + e.started = time.Now() + } +} + +// TypeRune handles a letter (non-space) keystroke. +// It appends to the current word and never auto-advances: +// wrong letters become extras you must fix or leave until Space. +func (e *Engine) TypeRune(r rune) bool { + if e.Done() { + return false + } + if r == '\n' || r == '\r' || r == '\t' { + return true + } + if r == ' ' { + e.Space() + return true + } + e.ensureStarted() + if e.current >= len(e.target) { + return true + } + tw := []rune(e.target[e.current]) + cur := e.input[e.current] + if len(cur) >= len(tw)+maxExtra { + return true // cap extras like monkeytype + } + e.input[e.current] = append(cur, r) + e.strokes++ + if len(cur) < len(tw) && r == tw[len(cur)] { + e.correctStrokes++ + } + e.checkWordsDone() + return true +} + +// Space submits the current word and advances, like monkeytype. +// Empty input ignores the space (no double spaces). A correct word's +// trailing space counts as a correct keystroke. +func (e *Engine) Space() { + if e.Done() { + return + } + if e.current >= len(e.target) { + return + } + if len(e.input[e.current]) == 0 { + return // ignore leading / double space + } + e.ensureStarted() + e.strokes++ + if string(e.input[e.current]) == e.target[e.current] { + e.correctStrokes++ + } + e.current++ + if e.current >= len(e.target) { + e.Finish() + } +} + +func (e *Engine) checkWordsDone() { + // Words mode finishes when the last word exactly matches, + // no trailing space required. + if e.cfg.TimeLimit == 0 && len(e.target) > 0 { + last := len(e.target) - 1 + if e.current == last && string(e.input[last]) == e.target[last] { + e.Finish() + } + } +} + +// Backspace deletes one char in the current word. At word start it jumps +// back to the previous word only if that word is incorrect (monkeytype +// won't let you edit already-correct words). +func (e *Engine) Backspace() { + if e.Done() || e.current >= len(e.input) { + return + } + if len(e.input[e.current]) > 0 { + e.input[e.current] = e.input[e.current][:len(e.input[e.current])-1] + return + } + if e.current == 0 { + return + } + prev := e.current - 1 + if string(e.input[prev]) == e.target[prev] { + return // correct words are locked + } + e.current = prev +} + +// DeleteWord clears the current word (ctrl+w / option+backspace). +// If the current word is already empty it jumps back and clears the +// previous incorrect word. +func (e *Engine) DeleteWord() { + if e.Done() { + return + } + if e.current >= len(e.input) { + return + } + if len(e.input[e.current]) > 0 { + e.input[e.current] = nil + return + } + if e.current == 0 { + return + } + prev := e.current - 1 + if string(e.input[prev]) == e.target[prev] { + return // don't wipe correct words + } + e.current = prev + e.input[prev] = nil +} + +// BackspaceWord is an alias kept for callers (ctrl+w / alt+backspace). +func (e *Engine) BackspaceWord() { e.DeleteWord() } + +// Reset clears input and timers, keeping the same words. +func (e *Engine) Reset() { + for i := range e.input { + e.input[i] = nil + } + e.current = 0 + e.begun = false + e.ended = nil + e.strokes, e.correctStrokes = 0, 0 +} + +// SetTarget replaces the words and resets. +func (e *Engine) SetTarget(target string) { + ws := strings.Fields(target) + e.target = ws + e.input = make([][]rune, len(ws)) + e.current = 0 + e.Reset() +} + +// AppendWords adds more target words (time mode refill). +func (e *Engine) AppendWords(ws []string) { + if len(ws) == 0 { + return + } + e.target = append(e.target, ws...) + for range ws { + e.input = append(e.input, nil) + } +} + +// AppendText extends the target (splits on whitespace). +func (e *Engine) AppendText(suffix string) { e.AppendWords(strings.Fields(suffix)) } + +// RemainingWords counts words from current to end. +func (e *Engine) RemainingWords() int { + if e.current >= len(e.target) { + return 0 + } + return len(e.target) - e.current +} + +// NeedsMoreWords reports whether fewer than threshold words remain. +func (e *Engine) NeedsMoreWords(threshold int) bool { + return e.RemainingWords() < threshold +} + +// Finish marks the test complete. +func (e *Engine) Finish() { + if e.ended == nil { + t := time.Now() + e.ended = &t + } +} + +// Elapsed is capped at TimeLimit so tick overshoot doesn't deflate WPM. +func (e *Engine) Elapsed() time.Duration { + if !e.begun { + return 0 + } + var d time.Duration + if e.ended != nil { + d = e.ended.Sub(e.started) + } else { + d = time.Since(e.started) + } + if e.cfg.TimeLimit > 0 && d > e.cfg.TimeLimit { + return e.cfg.TimeLimit + } + return d +} + +// TimeLimit returns the configured limit (0 = none). +func (e *Engine) TimeLimit() time.Duration { return e.cfg.TimeLimit } + +// Remaining returns time left in time mode. +func (e *Engine) Remaining() time.Duration { + if e.cfg.TimeLimit <= 0 || !e.begun { + if e.cfg.TimeLimit > 0 { + return e.cfg.TimeLimit + } + return 0 + } + rem := e.cfg.TimeLimit - e.Elapsed() + if rem < 0 { + return 0 + } + return rem +} + +// CheckTimeout finishes the test if the time limit expired. +func (e *Engine) CheckTimeout() bool { + if e.ended != nil { + return true + } + if e.cfg.TimeLimit > 0 && e.begun && time.Since(e.started) >= e.cfg.TimeLimit { + e.Finish() + return true + } + return false +} + +// CorrectChars counts correct letters in typed words plus one per +// correctly submitted word (its trailing space), monkeytype-style. +func (e *Engine) CorrectChars() int { + n := 0 + end := e.current + if e.ended != nil && end < len(e.input) { + end = e.current + 1 + } + for i := 0; i < end && i < len(e.target); i++ { + tw := []rune(e.target[i]) + in := e.input[i] + for j, r := range in { + if j < len(tw) && r == tw[j] { + n++ + } + } + // Submitted (or finished) exact words earn their space. + if i < e.current && string(in) == e.target[i] { + n++ + } + if e.ended != nil && i == e.current && string(in) == e.target[i] && e.cfg.TimeLimit == 0 { + // Last word finished without trailing space: no extra point. + } + } + return n +} + +// TypedChars counts all typed letters plus submitted spaces (for raw WPM). +func (e *Engine) TypedChars() int { + n := 0 + end := e.current + if e.ended != nil && end < len(e.input) { + end = e.current + 1 + } + for i := 0; i < end && i < len(e.input); i++ { + n += len(e.input[i]) + if i < e.current { + n++ // space that submitted the word + } + } + return n +} + +// Accuracy is correct keystrokes / total keystrokes (monkeytype-style). +// Corrections count: fixing a mistake still leaves the wrong keystroke. +func (e *Engine) Accuracy() float64 { + if e.strokes == 0 { + return 1 + } + return float64(e.correctStrokes) / float64(e.strokes) +} + +// WPM = (correct chars / 5) / minutes. +func (e *Engine) WPM() float64 { + mins := e.Elapsed().Minutes() + if mins <= 0 { + return 0 + } + return (float64(e.CorrectChars()) / 5) / mins +} + +// RawWPM counts all typed chars regardless of correctness. +func (e *Engine) RawWPM() float64 { + mins := e.Elapsed().Minutes() + if mins <= 0 { + return 0 + } + return (float64(e.TypedChars()) / 5) / mins +} + +// LetterStatus reports per-letter state of word i, position j: +// 0 = pending, 1 = correct, 2 = incorrect/extra. +func (e *Engine) LetterStatus(i, j int) int { + if i < 0 || i >= len(e.target) { + return 0 + } + tw := []rune(e.target[i]) + var in []rune + if i < len(e.input) { + in = e.input[i] + } + if j >= len(in) { + return 0 + } + if j < len(tw) && in[j] == tw[j] { + return 1 + } + return 2 +} + +// WordError reports whether word i was submitted (or finished) incorrectly. +func (e *Engine) WordError(i int) bool { + if i >= len(e.target) { + return false + } + if i < e.current || (e.ended != nil && i <= e.current) { + return string(e.input[i]) != e.target[i] + } + return false +} diff --git a/internal/typing/engine_test.go b/internal/typing/engine_test.go new file mode 100644 index 0000000..0ea3684 --- /dev/null +++ b/internal/typing/engine_test.go @@ -0,0 +1,114 @@ +package typing + +import "testing" + +func typeStr(e *Engine, s string) { + for _, r := range s { + e.TypeRune(r) + } +} + +func TestStaysOnWordUntilSpace(t *testing.T) { + e := New("hello world", DefaultConfig()) + typeStr(e, "hellx") + if e.CurrentWord() != 0 { + t.Fatalf("word=%d want 0 (must not advance on wrong letter)", e.CurrentWord()) + } + if got := e.InputWord(0); got != "hellx" { + t.Fatalf("input=%q want hellx (extra kept)", got) + } + e.Space() + if e.CurrentWord() != 1 { + t.Fatalf("word=%d want 1 after space", e.CurrentWord()) + } + if e.WordError(0) != true { + t.Fatal("word 0 should be marked wrong") + } +} + +func TestSpaceIgnoredWhenEmpty(t *testing.T) { + e := New("hello world", DefaultConfig()) + e.Space() + e.Space() + if e.CurrentWord() != 0 { + t.Fatalf("word=%d want 0 (empty space ignored)", e.CurrentWord()) + } + typeStr(e, "hello") + e.Space() + e.Space() + if e.CurrentWord() != 1 { + t.Fatalf("word=%d want 1 (double space ignored)", e.CurrentWord()) + } +} + +func TestBackspaceStaysAndFixes(t *testing.T) { + e := New("hello world", DefaultConfig()) + typeStr(e, "hellx") + e.Backspace() + typeStr(e, "o") + if got := e.InputWord(0); got != "hello" { + t.Fatalf("input=%q want hello", got) + } +} + +func TestBackspaceToPreviousOnlyIfIncorrect(t *testing.T) { + e := New("hello world", DefaultConfig()) + typeStr(e, "hello") + e.Space() // correct, locked + e.Backspace() + if e.CurrentWord() != 1 { + t.Fatalf("word=%d want 1 (must not jump back to correct word)", e.CurrentWord()) + } + + e2 := New("hello world", DefaultConfig()) + typeStr(e2, "hellx") + e2.Space() // incorrect + e2.Backspace() + if e2.CurrentWord() != 0 { + t.Fatalf("word=%d want 0 (can jump back to incorrect word)", e2.CurrentWord()) + } +} + +func TestDeleteWordClearsCurrent(t *testing.T) { + e := New("hello world", DefaultConfig()) + typeStr(e, "hellx") + e.DeleteWord() // option+backspace / ctrl+w + if got := e.InputWord(0); got != "" { + t.Fatalf("input=%q want empty", got) + } + if e.CurrentWord() != 0 { + t.Fatalf("word=%d want 0", e.CurrentWord()) + } + // Empty current + incorrect previous -> wipes previous. + typeStr(e, "hellx") + e.Space() + e.DeleteWord() + if e.CurrentWord() != 0 || e.InputWord(0) != "" { + t.Fatalf("want jump back and wipe, got word=%d input=%q", e.CurrentWord(), e.InputWord(0)) + } +} + +func TestAccuracyCountsKeystrokes(t *testing.T) { + e := New("hello world", DefaultConfig()) + typeStr(e, "hello") + e.Space() + if got := e.Accuracy(); got != 1 { + t.Fatalf("acc=%v want 1", got) + } + typeStr(e, "worlx") + e.Backspace() + typeStr(e, "d") // fixed, but the wrong keystroke still counts + if got := e.Accuracy(); got >= 1 { + t.Fatalf("acc=%v want <1 after corrected mistake", got) + } +} + +func TestWordsDoneOnLastWordNoSpace(t *testing.T) { + e := New("hi yo", DefaultConfig()) + typeStr(e, "hi") + e.Space() + typeStr(e, "yo") + if !e.Done() { + t.Fatal("should finish when last word exactly typed") + } +} diff --git a/internal/ui/model.go b/internal/ui/model.go new file mode 100644 index 0000000..4b3c751 --- /dev/null +++ b/internal/ui/model.go @@ -0,0 +1,269 @@ +package ui + +import ( + "fmt" + "strings" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/katistix/termitype/internal/config" + "github.com/katistix/termitype/internal/typing" + "github.com/katistix/termitype/internal/words" +) + +type tickMsg time.Time + +func tick() tea.Cmd { + return tea.Every(250*time.Millisecond, func(t time.Time) tea.Msg { + return tickMsg(t) + }) +} + +// Model is the bubbletea model for the typing test. +type Model struct { + cfg config.Config + engine *typing.Engine + styles Styles + width int +} + +// New creates a model with a fresh test from cfg. +func New(cfg config.Config) Model { + return Model{ + cfg: cfg, + engine: newEngine(cfg), + styles: DefaultStyles(), + } +} + +// newEngine builds a typing engine matching the mode. +// Time mode pre-generates a generous buffer and refills as you type. +func newEngine(cfg config.Config) *typing.Engine { + if cfg.Mode == config.ModeWords { + tcfg := typing.Config{WordCount: cfg.Words} + return typing.New(words.Generate(cfg.Words), tcfg) + } + tcfg := typing.Config{TimeLimit: time.Duration(cfg.Seconds) * time.Second} + return typing.New(words.Generate(timeBufferWords(cfg.Seconds)), tcfg) +} + +// timeBufferWords estimates enough words so refills are rare. +func timeBufferWords(seconds int) int { + n := seconds * 4 // ~48 wpm in 5-char words, with headroom + if n < 60 { + n = 60 + } + return n +} + +func (m *Model) reset() { + m.engine = newEngine(m.cfg) +} + +func (m Model) Init() tea.Cmd { return tick() } + +func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.width = msg.Width + return m, nil + + case tickMsg: + if m.engine.CheckTimeout() { + return m, nil // stopped: no more ticks needed + } + if m.engine.Done() { + return m, nil + } + return m, tick() + + case tea.KeyMsg: + // Option+Backspace arrives as Alt+Backspace on macOS terminals. + // Treat it (and ctrl+w) as delete-word, like monkeytype. + if msg.Type == tea.KeyBackspace && msg.Alt { + m.engine.DeleteWord() + return m, nil + } + // Some terminals send ctrl+backspace as ctrl+w. + if s := msg.String(); s == "ctrl+backspace" || s == "alt+backspace" { + m.engine.DeleteWord() + return m, nil + } + switch msg.Type { + case tea.KeyCtrlC: + return m, tea.Quit + + case tea.KeyEsc: + // Esc restarts with fresh words. + m.reset() + return m, tick() + + case tea.KeyTab, tea.KeyEnter: + return m, nil + + case tea.KeyBackspace: + m.engine.Backspace() + return m, nil + + case tea.KeyCtrlW: + m.engine.DeleteWord() + return m, nil + + case tea.KeyRunes: + for _, r := range msg.Runes { + m.typeRune(r) + } + return m, nil + + case tea.KeySpace: + m.typeRune(' ') + return m, nil + } + } + return m, nil +} + +// typeRune types one rune, refilling words in time mode and enforcing timeout. +func (m *Model) typeRune(r rune) { + if m.engine.Done() { + return + } + m.engine.TypeRune(r) + if m.cfg.Mode == config.ModeTime && m.engine.NeedsMoreWords(30) { + m.engine.AppendWords(words.GenerateSlice(30)) + } + m.engine.CheckTimeout() +} + +func (m Model) View() string { + s := m.styles + + var b strings.Builder + b.WriteString(s.Title.Render("termitype")) + b.WriteString(s.Hint.Render(" " + m.cfg.Label())) + b.WriteString("\n\n") + + if m.engine.Done() { + b.WriteString(m.renderResults()) + } else { + b.WriteString(m.renderLiveStats()) + b.WriteString("\n\n") + b.WriteString(m.renderText()) + } + + return s.App.Render(b.String()) +} + +func (m Model) renderLiveStats() string { + s := m.styles + parts := "" + if m.cfg.Mode == config.ModeTime { + secs := int(m.engine.Remaining().Round(time.Second).Seconds()) + parts += s.Stat.Render("time ") + s.StatVal.Render(fmt.Sprintf("%d", secs)) + " " + } + wpm := fmt.Sprintf("%.0f", m.engine.WPM()) + acc := fmt.Sprintf("%.0f%%", m.engine.Accuracy()*100) + parts += s.Stat.Render("wpm ") + s.StatVal.Render(wpm) + + s.Stat.Render(" acc ") + s.StatVal.Render(acc) + return parts +} + +// renderText draws words with per-letter states. The caret stays on the +// current word; wrong letters show as extras until Space submits the word. +func (m Model) renderText() string { + s := m.styles + e := m.engine + + // Window the view so long time-mode buffers stay readable. + start, end := 0, e.WordCount() + if e.WordCount() > 60 { + start = e.CurrentWord() - 10 + if start < 0 { + start = 0 + } + end = start + 60 + if end > e.WordCount() { + end = e.WordCount() + start = end - 60 + } + } + + var sb strings.Builder + for i := start; i < end; i++ { + tw := []rune(e.TargetWord(i)) + in := []rune(e.InputWord(i)) + caret := i == e.CurrentWord() && !e.Done() + caretPos := len(in) // caret sits after last typed rune + + // Target letters + extras. + max := len(tw) + if len(in) > max { + max = len(in) + } + for j := 0; j < max; j++ { + var ch string + var st int + isExtra := j >= len(tw) + if isExtra { + ch = string(in[j]) + } else { + ch = string(tw[j]) + } + if j < len(in) { + st = e.LetterStatus(i, j) + } else { + st = 0 + } + atCaret := caret && j == caretPos + switch { + case atCaret && isExtra: + sb.WriteString(s.Cursor.Render(ch)) + case atCaret: + sb.WriteString(s.Cursor.Render(ch)) + case j < len(in) && st == 1: + sb.WriteString(s.Correct.Render(ch)) + case j < len(in) && st == 2: + if isExtra { + sb.WriteString(s.Extra.Render(ch)) + } else { + sb.WriteString(s.Wrong.Render(ch)) + } + default: + sb.WriteString(s.Pending.Render(ch)) + } + } + // Caret on the inter-word gap (input longer than nothing to show, + // or empty caret past last letter handled above for last word). + if caret && caretPos == len(tw) && len(in) == len(tw) { + // Caret is on the space after this word (or end marker). + if i+1 < end { + sb.WriteString(s.Cursor.Render(" ")) + } else { + sb.WriteString(s.Cursor.Render("ยท")) + } + } else if i+1 < end { + sb.WriteString(" ") + } + } + w := m.width - 8 + if w <= 0 || w > 80 { + w = 80 + } + return s.Box.Width(w).Render(sb.String()) +} + +func (m Model) renderResults() string { + s := m.styles + wpm := fmt.Sprintf("%.0f", m.engine.WPM()) + raw := fmt.Sprintf("%.0f", m.engine.RawWPM()) + acc := fmt.Sprintf("%.1f%%", m.engine.Accuracy()*100) + correct := m.engine.CorrectChars() + total := m.engine.TypedChars() + lines := []string{ + s.Stat.Render(fmt.Sprintf("%s ", m.cfg.Label())) + s.StatVal.Render("done"), + s.Stat.Render("wpm ") + s.StatVal.Render(wpm) + s.Stat.Render(" raw ") + s.StatVal.Render(raw), + s.Stat.Render("acc ") + s.StatVal.Render(acc), + s.Stat.Render("chars ") + s.StatVal.Render(fmt.Sprintf("%d/%d", correct, total)), + } + return s.Box.Render(strings.Join(lines, "\n")) +} diff --git a/internal/ui/styles.go b/internal/ui/styles.go new file mode 100644 index 0000000..ea7ab88 --- /dev/null +++ b/internal/ui/styles.go @@ -0,0 +1,47 @@ +// Package ui contains the bubbletea model and lipgloss styles. +package ui + +import ( + "github.com/charmbracelet/lipgloss" +) + +var ( + // Palette: muted background, monkeytype-ish yellow accent. + accent = lipgloss.Color("#e2b714") + muted = lipgloss.Color("#646669") + fg = lipgloss.Color("#d1d0c5") + bad = lipgloss.Color("#ca4754") + bg = lipgloss.Color("#323437") + cursorBg = lipgloss.Color("#e2b714") + cursorFg = lipgloss.Color("#323437") +) + +type Styles struct { + App lipgloss.Style + Title lipgloss.Style + Hint lipgloss.Style + Box lipgloss.Style + Pending lipgloss.Style + Correct lipgloss.Style + Wrong lipgloss.Style + Extra lipgloss.Style + Cursor lipgloss.Style + Stat lipgloss.Style + StatVal lipgloss.Style +} + +func DefaultStyles() Styles { + return Styles{ + App: lipgloss.NewStyle().Padding(1, 2), + Title: lipgloss.NewStyle().Bold(true).Foreground(accent), + Hint: lipgloss.NewStyle().Foreground(muted), + Box: lipgloss.NewStyle().Padding(1, 2).Border(lipgloss.RoundedBorder()).BorderForeground(bg), + Pending: lipgloss.NewStyle().Foreground(muted), + Correct: lipgloss.NewStyle().Foreground(fg), + Wrong: lipgloss.NewStyle().Foreground(bad), + Extra: lipgloss.NewStyle().Foreground(bad).Background(lipgloss.Color("#4a2b2e")), + Cursor: lipgloss.NewStyle().Background(cursorBg).Foreground(cursorFg), + Stat: lipgloss.NewStyle().Foreground(muted), + StatVal: lipgloss.NewStyle().Bold(true).Foreground(accent), + } +} diff --git a/internal/words/words.go b/internal/words/words.go new file mode 100644 index 0000000..9a6d09d --- /dev/null +++ b/internal/words/words.go @@ -0,0 +1,48 @@ +// Package words provides word lists and random test generation. +package words + +import ( + "math/rand" + "strings" + "time" +) + +// Common English words for typing tests. Kept small for simplicity; +// expand as desired. +var common = []string{ + "the", "be", "of", "and", "a", "to", "in", "he", "have", "it", + "that", "for", "they", "with", "as", "not", "on", "she", "at", "by", + "this", "we", "you", "do", "but", "from", "or", "which", "one", "would", + "all", "will", "there", "say", "who", "make", "when", "can", "more", "if", + "time", "up", "out", "who", "into", "way", "could", "my", "than", "first", + "water", "been", "call", "oil", "its", "now", "find", "long", "down", "day", + "did", "get", "come", "made", "may", "part", "over", "new", "sound", "take", + "only", "little", "work", "know", "place", "year", "live", "me", "back", "give", + "most", "very", "after", "thing", "our", "just", "name", "good", "sentence", "man", + "think", "help", "low", "line", "differ", "turn", "cause", "much", "mean", "before", + "move", "right", "boy", "old", "too", "same", "tell", "does", "set", "three", + "want", "air", "well", "also", "play", "small", "end", "put", "home", "read", + "hand", "port", "large", "spell", "add", "even", "land", "here", "must", "big", + "high", "such", "follow", "act", "why", "ask", "men", "change", "went", "light", + "kind", "off", "need", "house", "picture", "try", "again", "animal", "point", "mother", + "world", "near", "build", "self", "earth", "father", "head", "stand", "own", "page", + "should", "country", "found", "answer", "school", "grow", "study", "still", "learn", "plant", + "cover", "food", "sun", "four", "between", "state", "keep", "eye", "never", "last", + "let", "thought", "city", "tree", "cross", "farm", "hard", "start", "might", "story", + "code", "keyboard", "terminal", "fast", "type", "monkey", "speed", "focus", "rhythm", "flow", +} + +// Generate returns n random words joined for a typing test. +func Generate(n int) string { + return strings.Join(GenerateSlice(n), " ") +} + +// GenerateSlice returns n random words. +func GenerateSlice(n int) []string { + r := rand.New(rand.NewSource(time.Now().UnixNano())) + out := make([]string, n) + for i := range out { + out[i] = common[r.Intn(len(common))] + } + return out +}