diff --git a/go.mod b/go.mod index fac01cc..5fa3bcb 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.27.3 require ( github.com/charmbracelet/bubbletea v1.3.10 github.com/charmbracelet/lipgloss v1.1.0 + github.com/charmbracelet/x/ansi v0.11.9 github.com/egoist/mygo v0.7.4 golang.org/x/text v0.43.0 modernc.org/sqlite v1.61.1 @@ -13,7 +14,6 @@ require ( require ( github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/charmbracelet/colorprofile v0.4.3 // indirect - github.com/charmbracelet/x/ansi v0.11.9 // indirect github.com/charmbracelet/x/cellbuf v0.0.15 // indirect github.com/charmbracelet/x/term v0.2.2 // indirect github.com/clipperhouse/displaywidth v0.11.0 // indirect diff --git a/pkg/i18n/en.go b/pkg/i18n/en.go index 0963d18..9eb03cd 100644 --- a/pkg/i18n/en.go +++ b/pkg/i18n/en.go @@ -241,7 +241,7 @@ EXAMPLES: "tui_open_title": "Which game shall we translate?", "tui_open_sub": "Slime looked for a game in the current folder.", "tui_open_box": "Choose a folder", - "tui_open_detected": "› Game detected here %s %s", + "tui_open_detected": "Game detected here %s %s", "tui_open_type_path": "Type a path…", "tui_open_path_prompt": "Game path: ", "tui_open_tip": "Tip: slime translate -i does the same without asking.", @@ -251,7 +251,7 @@ EXAMPLES: "tui_cfg_none": "(no game)", "tui_cfg_info": "%s · %s · %d files", "tui_cfg_service": "Service", - "tui_cfg_free": "Free and keyless; may throttle requests.", + "tui_hint_memory": "Uses only saved translations; nothing goes online.", "tui_cfg_source": "Source language (s)", "tui_cfg_target": "Target language (d)", "tui_cfg_incremental": "Only what changed (space)", @@ -292,7 +292,7 @@ EXAMPLES: "tui_review_saved": "Correction saved to memory; translate again to apply it to the game.", "tui_foot_path": " type or paste the path · enter open · esc cancel", "tui_foot_open": " ↑↓ move · enter choose · q quit", - "tui_foot_config": " tab field · ←→ service · s/d languages · space incremental · x proxies · enter translate · esc back", + "tui_foot_config": " ↑↓ field · ←→ change · space toggle · enter translate · esc back", "tui_foot_translating": " p pause/resume · c cancel · ctrl+c quit", "tui_foot_edit": " type the translation · enter save · esc cancel", "tui_foot_review": " ↑↓ segment · tab filter · e edit · b lock · esc/enter back to result", diff --git a/pkg/i18n/pt.go b/pkg/i18n/pt.go index 963a2c4..a57db08 100644 --- a/pkg/i18n/pt.go +++ b/pkg/i18n/pt.go @@ -241,7 +241,7 @@ EXEMPLOS: "tui_open_title": "Qual jogo vamos traduzir?", "tui_open_sub": "O Slime procurou um jogo na pasta atual.", "tui_open_box": "Escolha uma pasta", - "tui_open_detected": "› Jogo detectado aqui %s %s", + "tui_open_detected": "Jogo detectado aqui %s %s", "tui_open_type_path": "Digitar caminho…", "tui_open_path_prompt": "Caminho do jogo: ", "tui_open_tip": "Dica: slime translate -i faz o mesmo sem perguntas.", @@ -251,7 +251,7 @@ EXEMPLOS: "tui_cfg_none": "(nenhum jogo)", "tui_cfg_info": "%s · %s · %d arquivos", "tui_cfg_service": "Serviço", - "tui_cfg_free": "Grátis e sem chave; pode limitar requisições.", + "tui_hint_memory": "Usa só traduções já salvas; nada vai para a internet.", "tui_cfg_source": "Idioma de origem (s)", "tui_cfg_target": "Idioma de destino (d)", "tui_cfg_incremental": "Só o que mudou (espaço)", @@ -292,7 +292,7 @@ EXEMPLOS: "tui_review_saved": "Correção salva na memória; traduza de novo para aplicá-la ao jogo.", "tui_foot_path": " digite ou cole o caminho · enter abrir · esc cancelar", "tui_foot_open": " ↑↓ mover · enter escolher · q sair", - "tui_foot_config": " tab campo · ←→ serviço · s/d idiomas · espaço incremental · x proxies · enter traduzir · esc voltar", + "tui_foot_config": " ↑↓ campo · ←→ alterar · espaço marcar · enter traduzir · esc voltar", "tui_foot_translating": " p pausar/retomar · c cancelar · ctrl+c sair", "tui_foot_edit": " digite a tradução · enter salvar · esc cancelar", "tui_foot_review": " ↑↓ segmento · tab filtro · e editar · b bloquear · esc/enter voltar ao resultado", diff --git a/pkg/ui/tui/app.go b/pkg/ui/tui/app.go index 4d290e2..36e9d67 100644 --- a/pkg/ui/tui/app.go +++ b/pkg/ui/tui/app.go @@ -1,9 +1,11 @@ package tui import ( + "cmp" "context" "fmt" "os" + "strconv" "strings" "github.com/BGLuis/slime-rpg/pkg/detector" @@ -13,6 +15,7 @@ import ( "github.com/BGLuis/slime-rpg/pkg/memory" "github.com/BGLuis/slime-rpg/pkg/ui/theme" tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" ) // ViewState representa a tela ativa do Stepper na TUI. @@ -61,7 +64,7 @@ type Model struct { incremental bool enableProxies bool fieldValues map[string]string // opções do extrator e chave do DeepL, por ConfigSchemaField.Key - fieldFocus int // índice em configFields(); -1 = nenhum campo em edição + focus int // índice em configRows() estimate *event.EstimateEvent estimating bool estimateErr string @@ -95,7 +98,6 @@ func NewModel(initialDir string, opts ...Option) *Model { providers: []string{"Google Translate", "DeepL", "Ollama", i18n.T("tui_provider_memory")}, targetLang: "pt", incremental: true, - fieldFocus: -1, filterLabels: []string{i18n.T("tui_filter_all"), i18n.T("tui_filter_partial")}, } det, _ := detector.Detect(initialDir) @@ -115,7 +117,7 @@ func (m *Model) hasGame() bool { func (m *Model) setGame(path string, det *detector.DetectionResult) { m.gamePath, m.detectedGame = path, det m.fieldValues = map[string]string{} - m.fieldFocus = -1 + m.focus = 0 m.sourceLang = "ja" if det != nil && det.ProbableLang != "" { m.sourceLang = det.ProbableLang @@ -265,6 +267,50 @@ func (m *Model) configFields() []job.ConfigSchemaField { return fields } +// rowKind identifica cada linha navegável da tela Configurar. +type rowKind int + +const ( + rowProvider rowKind = iota + rowSource + rowTarget + rowIncremental + rowProxies + rowField +) + +type configRow struct { + kind rowKind + field job.ConfigSchemaField +} + +// configRows lista as linhas navegáveis com ↑↓; proxies só existem para o Google. +func (m *Model) configRows() []configRow { + rows := []configRow{{kind: rowProvider}, {kind: rowSource}, {kind: rowTarget}, {kind: rowIncremental}} + if providerIDs[m.selectedProvider] == "google" { + rows = append(rows, configRow{kind: rowProxies}) + } + for _, f := range m.configFields() { + rows = append(rows, configRow{kind: rowField, field: f}) + } + return rows +} + +func (m *Model) focusedRow() configRow { + rows := m.configRows() + return rows[min(m.focus, len(rows)-1)] +} + +// editingText diz se o foco está num campo de texto, onde as teclas viram digitação. +func (m *Model) editingText() bool { + r := m.focusedRow() + return r.kind == rowField && r.field.Type != "bool" +} + +func (m *Model) fieldBool(f job.ConfigSchemaField) bool { + return cmp.Or(m.fieldValues[f.Key], f.Default) == "true" +} + // editField trata a digitação no campo em foco; devolve false se a tecla não é de edição. func (m *Model) editField(msg tea.KeyMsg, key string) bool { switch msg.Type { @@ -280,33 +326,53 @@ func (m *Model) editField(msg tea.KeyMsg, key string) bool { return true } -func (m *Model) updateConfigure(msg tea.KeyMsg) (tea.Model, tea.Cmd) { - fields := m.configFields() - if msg.String() == "tab" && len(fields) > 0 { - m.fieldFocus = (m.fieldFocus + 1) % (len(fields) + 1) - if m.fieldFocus == len(fields) { - m.fieldFocus = -1 +// changeRow altera o valor da linha: delta escolhe o vizinho nas listas e alterna as caixas. +func (m *Model) changeRow(r configRow, delta int) { + switch r.kind { + case rowProvider: + n := len(m.providers) + m.selectedProvider = (m.selectedProvider + delta + n) % n + case rowSource: + m.sourceLang = stepLang(m.sourceLang, delta) + case rowTarget: + m.targetLang = stepLang(m.targetLang, delta) + case rowIncremental: + m.incremental = !m.incremental + case rowProxies: + m.enableProxies = !m.enableProxies + case rowField: + if r.field.Type == "bool" { + m.fieldValues[r.field.Key] = strconv.FormatBool(!m.fieldBool(r.field)) } - return m, m.reestimate() } - if m.fieldFocus >= 0 && m.fieldFocus < len(fields) && m.editField(msg, fields[m.fieldFocus].Key) { +} + +func (m *Model) updateConfigure(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + row := m.focusedRow() + // Num campo de texto as letras são digitadas; os atalhos de uma letra abaixo só valem fora dele. + if m.editingText() && m.editField(msg, row.field.Key) { return m, nil } + n := len(m.configRows()) switch msg.String() { + case "up", "k", "shift+tab": + m.focus = (m.focus - 1 + n) % n + case "down", "j", "tab": + m.focus = (m.focus + 1) % n case "left", "h": - if m.selectedProvider > 0 { - m.selectedProvider-- - } + m.changeRow(row, -1) case "right", "l": - if m.selectedProvider < len(m.providers)-1 { - m.selectedProvider++ + m.changeRow(row, 1) + case " ": + if row.kind == rowProxies || row.kind == rowField { + m.changeRow(row, 1) + } else { + m.incremental = !m.incremental } case "s": - m.sourceLang = nextLang(m.sourceLang) + m.sourceLang = stepLang(m.sourceLang, 1) case "d": - m.targetLang = nextLang(m.targetLang) - case " ": - m.incremental = !m.incremental + m.targetLang = stepLang(m.targetLang, 1) case "x": m.enableProxies = !m.enableProxies case "ctrl+enter", "enter": @@ -319,9 +385,7 @@ func (m *Model) updateConfigure(msg tea.KeyMsg) (tea.Model, tea.Cmd) { m.view = ViewTranslating return m, cmd } - if m.fieldFocus >= len(m.configFields()) { - m.fieldFocus = -1 - } + m.focus = min(m.focus, len(m.configRows())-1) return m, m.reestimate() } @@ -430,160 +494,227 @@ func (m *Model) updateResult(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return m, nil } -// View renderiza a tela atual em formato de grade 100x32. +// View renderiza a tela atual ajustada a m.width x m.height. func (m *Model) View() string { if m.quitting { return i18n.T("tui_quit") } + w := m.contentWidth() + rule := strings.Repeat(theme.SymBarThin, w) - var b strings.Builder - - // 1. Cabeçalho Superior com Stepper de 4 passos - b.WriteString(m.renderStepperHeader()) - b.WriteString("\n" + strings.Repeat(theme.SymBarThin, 100) + "\n\n") - - // 2. Conteúdo da Tela + head := []string{m.renderStepperHeader(w), rule, ""} + var body string switch m.view { case ViewOpenGame: - b.WriteString(m.renderOpenGame()) + body = m.renderOpenGame() case ViewConfigure: - b.WriteString(m.renderConfigure()) + body = m.renderConfigure() case ViewTranslating: - b.WriteString(m.renderTranslating()) + body = m.renderTranslating() case ViewReviewing: - b.WriteString(m.renderReviewing()) + body = m.renderReviewing() case ViewResult: - b.WriteString(m.renderResult()) + body = m.renderResult() } - - // 3. Rodapé Fixo com Atalhos - b.WriteString("\n" + strings.Repeat(theme.SymBarThin, 100) + "\n") + foot := []string{"", rule} if m.statusMsg != "" { - b.WriteString(" " + theme.StyleTagWarning.Render(theme.SymWarning+" "+m.statusMsg) + "\n") + foot = append(foot, " "+theme.StyleTagWarning.Render(theme.SymWarning+" "+truncate(m.statusMsg, w-6))) + } + for _, l := range wrapJoin(strings.Split(strings.TrimSpace(m.renderFooter()), " · "), " · ", w-2) { + foot = append(foot, " "+l) } - b.WriteString(m.renderFooter()) - return theme.StyleApp.Render(b.String()) + // Sem o corte, o terminal descarta as primeiras linhas e o cabeçalho some. + lines := strings.Split(strings.TrimRight(body, "\n"), "\n") + if room := m.height - len(head) - len(foot); room > 0 && len(lines) > room { + lines = lines[:room] + } + all := append(append(head, lines...), foot...) + for i, l := range all { + all[i] = truncate(l, m.width) + } + return theme.StyleApp.Render(strings.Join(all, "\n")) } -func (m *Model) renderStepperHeader() string { - game, config := i18n.T("tui_step_game"), i18n.T("tui_step_config") - translate, result := i18n.T("tui_step_translate"), i18n.T("tui_step_result") - step1, step2, step3, step4 := "1 "+game, "2 "+config, "3 "+translate, "4 "+result - - switch m.view { - case ViewOpenGame: - step1 = theme.StyleAccent.Render(theme.SymBullet + " " + game) - case ViewConfigure: - step1 = theme.StyleMuted.Render(theme.SymCheck + " Jogo") - step2 = theme.StyleAccent.Render(theme.SymBullet + " " + config) - case ViewTranslating, ViewReviewing: - step1 = theme.StyleMuted.Render(theme.SymCheck + " Jogo") - step2 = theme.StyleMuted.Render(theme.SymCheck + " Configurar") - step3 = theme.StyleAccent.Render(theme.SymBullet + " " + translate) - case ViewResult: - step1 = theme.StyleMuted.Render(theme.SymCheck + " Jogo") - step2 = theme.StyleMuted.Render(theme.SymCheck + " Configurar") - step3 = theme.StyleMuted.Render(theme.SymCheck + " Tradução") - step4 = theme.StyleAccent.Render(theme.SymBullet + " " + result) +func (m *Model) renderStepperHeader(width int) string { + names := []string{i18n.T("tui_step_game"), i18n.T("tui_step_config"), i18n.T("tui_step_translate"), i18n.T("tui_step_result")} + current := map[ViewState]int{ViewOpenGame: 0, ViewConfigure: 1, ViewTranslating: 2, ViewReviewing: 2, ViewResult: 3}[m.view] + + steps := make([]string, len(names)) + for i, name := range names { + switch { + case i < current: + steps[i] = theme.StyleMuted.Render(theme.SymCheck + " " + name) + case i == current: + steps[i] = theme.StyleAccent.Render(theme.SymBullet + " " + name) + default: + steps[i] = fmt.Sprintf("%d %s", i+1, name) + } } - - return fmt.Sprintf(" Slime %s %s %s %s %s %s %s", - step1, theme.SymArrow, step2, theme.SymArrow, step3, theme.SymArrow, step4) + full := " Slime " + strings.Join(steps, " "+theme.SymArrow+" ") + if ansi.StringWidth(full) <= width { + return full + } + return fmt.Sprintf(" Slime %s %s", steps[current], theme.StyleMuted.Render(fmt.Sprintf("%d/%d", current+1, len(names)))) } func (m *Model) renderOpenGame() string { - var s strings.Builder - s.WriteString(" " + theme.StyleTitle.Render(i18n.T("tui_open_title")) + "\n") - s.WriteString(" " + theme.StyleSubtitle.Render(i18n.T("tui_open_sub")) + "\n\n") - - s.WriteString(" " + boxTop(i18n.T("tui_open_box"), 96) + "\n") + w := m.contentWidth() - len(indent) - 1 + lines := []string{ + theme.StyleHeader.Render(i18n.T("tui_open_title")), + theme.StyleMuted.Render(i18n.T("tui_open_sub")), + "", + } + opts := make([]string, len(m.folderOptions)) for i, opt := range m.folderOptions { - prefix := " " + opts[i] = " " + opt if i == m.selectedFolderIndex { - prefix = " › " + opts[i] = theme.StyleAccent.Render(theme.SymArrow+" ") + opt } - s.WriteString(fmt.Sprintf(" │%s%-89s│\n", prefix, truncate(opt, 89))) } - s.WriteString(" ╰──────────────────────────────────────────────────────────────────────────────────────────────╯\n\n") + lines = append(lines, box(i18n.T("tui_open_box"), opts, w)...) + lines = append(lines, "") if m.pathInput { - s.WriteString(" " + i18n.T("tui_open_path_prompt") + m.pathBuf + "▌\n\n") + prompt := i18n.T("tui_open_path_prompt") + lines = append(lines, prompt+tail(m.pathBuf, w-ansi.StringWidth(prompt)-1)+"▌", "") } - s.WriteString(" " + theme.StyleMuted.Render(i18n.T("tui_open_tip"))) - return s.String() + lines = append(lines, theme.StyleMuted.Render(truncate(i18n.T("tui_open_tip"), w))) + return indentLines(lines) } +// Abaixo desta largura a estimativa vai para baixo do formulário em vez de ficar ao lado. +const sideBySideWidth = 92 + +const estimateWidth = 36 + func (m *Model) renderConfigure() string { - var s strings.Builder + w := m.contentWidth() - len(indent) - 1 + sideBySide := w+len(indent)+1 >= sideBySideWidth + formW := w + if sideBySide { + formW = w - estimateWidth - 2 + } + gameTitle, info := i18n.T("tui_cfg_none"), "" if m.detectedGame != nil { gameTitle = m.detectedGame.GameName info = i18n.T("tui_cfg_info", m.detectedGame.Engine, m.detectedGame.DataDir, m.detectedGame.FileCount) } - - left := []string{ - fmt.Sprintf("╭─ %s · %s ───────────────────────╮", i18n.T("tui_cfg_title"), gameTitle), - fmt.Sprintf("│ %-54s │", truncate(info, 54)), - "│ │", - "│ " + theme.SymBarV + " " + fmt.Sprintf("%-52s", i18n.T("tui_cfg_service")) + " │", - "│ " + theme.SymBarV + " " + m.providerLine() + " │", - "│ " + theme.SymBarV + " " + fmt.Sprintf("%-52s", i18n.T("tui_cfg_free")) + " │", - "│ │", - fmt.Sprintf("│ %-52s │", i18n.T("tui_cfg_source")), - fmt.Sprintf("│ %-52s │", langLabel(m.sourceLang)), - "│ │", - fmt.Sprintf("│ %-52s │", i18n.T("tui_cfg_target")), - fmt.Sprintf("│ %-52s │", langLabel(m.targetLang)), - "│ │", - fmt.Sprintf("│ %-52s │", checkbox(m.incremental)+" "+i18n.T("tui_cfg_incremental")), - fmt.Sprintf("│ %-52s │", checkbox(m.enableProxies)+" "+i18n.T("tui_cfg_proxies")), - "│ │", - fmt.Sprintf("│ %-52s │", i18n.T("tui_cfg_backup")), - "╰────────────────────────────────────────────────────────╯", - } - - right := m.renderEstimate() - - left = append(left[:len(left)-1], m.renderFieldRows()...) - left = append(left, "╰────────────────────────────────────────────────────────╯") - - for i := 0; i < len(left); i++ { - rLine := "" - if i < len(right) { - rLine = right[i] - } - s.WriteString(fmt.Sprintf(" %-57s %s\n", left[i], rLine)) + form := append([]string{theme.StyleMuted.Render(info), ""}, m.renderConfigRows(formW-4)...) + form = append(form, "", theme.StyleMuted.Render(i18n.T("tui_cfg_backup"))) + estW := formW + if sideBySide { + estW = estimateWidth } + est := m.renderEstimate(estW - 4) - return s.String() + title := i18n.T("tui_cfg_title") + " · " + gameTitle + if !sideBySide { + return indentLines(append(append(box(title, form, formW), ""), box(i18n.T("tui_est_title"), est, estW)...)) + } + for len(est) < len(form) { + est = append(est, "") + } + for len(form) < len(est) { + form = append(form, "") + } + left, right := box(title, form, formW), box(i18n.T("tui_est_title"), est, estimateWidth) + rows := make([]string, len(left)) + for i := range left { + rows[i] = left[i] + " " + right[i] + } + return indentLines(rows) } -func (m *Model) renderFieldRows() []string { - var rows []string - for i, f := range m.configFields() { - value := m.fieldValues[f.Key] - if f.Type == "secret" { - value = strings.Repeat("•", len([]rune(value))) +// renderConfigRows desenha uma linha por item navegável: rótulo à esquerda, valor à direita. +func (m *Model) renderConfigRows(inner int) []string { + rows := m.configRows() + labelOf := func(r configRow) string { + switch r.kind { + case rowProvider: + return i18n.T("tui_cfg_service") + case rowSource: + return i18n.T("tui_cfg_source") + case rowTarget: + return i18n.T("tui_cfg_target") + case rowIncremental: + return i18n.T("tui_cfg_incremental") + case rowProxies: + return i18n.T("tui_cfg_proxies") } - cursor := "" - if i == m.fieldFocus { - cursor = "▌" + return r.field.Label + } + labelW := 0 + for _, r := range rows { + if r.kind != rowIncremental && r.kind != rowProxies { + labelW = max(labelW, ansi.StringWidth(labelOf(r))) } - rows = append(rows, - "│ │", - fmt.Sprintf("│ %-52s │", f.Label), - fmt.Sprintf("│ %-52s │", "› "+value+cursor), - fmt.Sprintf("│ %-52s │", truncate(f.Help, 52)), - ) } - return rows + labelW = min(labelW, inner/2) + valueW := inner - 2 - labelW - 1 + under := strings.Repeat(" ", 2+labelW+1) + + var out []string + for i, r := range rows { + focused := i == min(m.focus, len(rows)-1) + marker, label := " ", labelOf(r) + if focused { + marker = theme.StyleAccent.Render(theme.SymArrow + " ") + } + var value, note string + switch r.kind { + case rowProvider: + value = choice(m.providers[m.selectedProvider], focused) + note = i18n.T(providerHints[m.selectedProvider]) + case rowSource: + value = choice(langLabel(m.sourceLang), focused) + case rowTarget: + value = choice(langLabel(m.targetLang), focused) + case rowIncremental: + label = checkbox(m.incremental) + " " + label + case rowProxies: + label = checkbox(m.enableProxies) + " " + label + case rowField: + switch v := m.fieldValues[r.field.Key]; { + case r.field.Type == "bool": + value = checkbox(m.fieldBool(r.field)) + case r.field.Type == "secret": + value = strings.Repeat("•", len([]rune(v))) + default: + value = v + } + if focused && r.field.Type != "bool" { + value = tail(value, valueW-1) + "▌" + } else if value == "" { + value = theme.StyleMuted.Render("—") + } + if focused { + note = r.field.Help + } + } + if focused { + label = theme.StyleAccent.Render(truncate(label, max(inner-2, 1))) + } + if value == "" { + out = append(out, marker+label) + } else { + out = append(out, marker+fit(label, labelW)+" "+truncate(value, valueW)) + } + if note != "" { + for _, l := range wrapJoin(strings.Fields(note), " ", valueW) { + out = append(out, under+theme.StyleMuted.Render(l)) + } + } + } + return out } -func truncate(s string, n int) string { - if r := []rune(s); len(r) > n { - return string(r[:n-1]) + "…" +// choice mostra as setas ‹ › só na linha em foco, onde ←→ trocam o valor. +func choice(v string, focused bool) string { + if focused { + return theme.StyleAccent.Render("‹ ") + v + theme.StyleAccent.Render(" ›") } - return s + return v } func (m *Model) renderFooter() string { diff --git a/pkg/ui/tui/app_test.go b/pkg/ui/tui/app_test.go index 94477ef..bc566ac 100644 --- a/pkg/ui/tui/app_test.go +++ b/pkg/ui/tui/app_test.go @@ -6,7 +6,12 @@ import ( "strings" "testing" + "github.com/BGLuis/slime-rpg/pkg/detector" + "github.com/BGLuis/slime-rpg/pkg/formats" + "github.com/BGLuis/slime-rpg/pkg/i18n" + "github.com/BGLuis/slime-rpg/pkg/job" tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" ) func TestModel_StepTransitions(t *testing.T) { @@ -148,9 +153,121 @@ func TestConfigureShowsExtractorOptionsAndAcceptsInput(t *testing.T) { if !strings.Contains(m.View(), "Delimitador") { t.Fatal("a tela Configurar devia listar as opções do CSV detectado") } - m.Update(tea.KeyMsg{Type: tea.KeyTab}) + for !m.editingText() { + m.Update(tea.KeyMsg{Type: tea.KeyTab}) + } m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'n', 'o', 't', 'e'}}) if got := m.fieldValues["csv.columns"]; got != "note" { t.Errorf("csv.columns = %q, esperava note", got) } } + +// Na tela Configurar, ↑↓ escolhem a linha e ←→ mudam só o valor dela; num campo de +// texto as letras são digitadas e as setas não podem trocar o serviço por baixo do usuário. +func TestConfigureNavigatesByFocusedRow(t *testing.T) { + game, _ := writeGame(t) + m := NewModel(game) + m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + key := func(k tea.KeyType) { m.Update(tea.KeyMsg{Type: k}) } + + key(tea.KeyDown) // origem + key(tea.KeyLeft) + if m.sourceLang != "it" { + t.Errorf("← na origem devia voltar ja→it, deu %q", m.sourceLang) + } + key(tea.KeyDown) // destino + key(tea.KeyRight) + if m.targetLang != "en" || m.sourceLang != "it" { + t.Errorf("→ no destino devia mudar só o destino: origem=%q destino=%q", m.sourceLang, m.targetLang) + } + + key(tea.KeyUp) + key(tea.KeyUp) // serviço + key(tea.KeyLeft) + if m.providers[m.selectedProvider] != i18n.T("tui_provider_memory") { + t.Errorf("← no primeiro serviço devia dar a volta até o último, deu %q", m.providers[m.selectedProvider]) + } + key(tea.KeyLeft) // Ollama: ganha os campos de modelo e endereço + for !m.editingText() { + key(tea.KeyDown) + } + m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("sdx")}) + key(tea.KeyRight) + if got := m.fieldValues["ollama_model"]; got != "sdx" || providerIDs[m.selectedProvider] != "ollama" { + t.Errorf("campo em foco devia receber as letras e manter o Ollama: valor=%q serviço=%d", got, m.selectedProvider) + } + if m.targetLang != "en" || m.enableProxies { + t.Error("atalhos s/d/x não podem agir enquanto se digita num campo") + } + + key(tea.KeyUp) // incremental: proxies não aparece fora do Google + if m.focusedRow().kind != rowIncremental { + t.Fatalf("esperava foco em incremental, está em %v", m.focusedRow().kind) + } +} + +func TestConfigureBoolFieldTogglesInsteadOfTyping(t *testing.T) { + m := NewModel(t.TempDir()) + m.setGame(t.TempDir(), &detector.DetectionResult{Engine: "wolfrpg"}) + m.view = ViewConfigure + for m.focusedRow().field.Key != formats.OptWolfPreserveTit { + m.Update(tea.KeyMsg{Type: tea.KeyDown}) + } + m.Update(tea.KeyMsg{Type: tea.KeySpace}) + if got := m.extractorOptions()[formats.OptWolfPreserveTit]; got != "false" { + t.Errorf("espaço devia desligar o padrão true, opção = %q", got) + } +} + +// Nenhuma linha pode passar da largura do terminal, nem com texto japonês (2 colunas por letra). +func TestViewsFitTerminalWidth(t *testing.T) { + game, _ := writeGame(t) + for _, width := range []int{60, 80, 120} { + m := NewModel(game) + m.Update(tea.WindowSizeMsg{Width: width, Height: 40}) + m.selectedProvider = 2 + m.detectedGame.GameName = strings.Repeat("勇者の旅", 10) + m.snapshot.Files = []job.FileProgress{{Path: strings.Repeat("マップ/", 20), Status: "error", Message: strings.Repeat("失敗", 30)}} + m.reviewItems = []job.ReviewItem{{Source: strings.Repeat("こんにちは", 30), Target: "olá", File: "Map001.json"}} + for _, v := range []ViewState{ViewOpenGame, ViewConfigure, ViewTranslating, ViewReviewing, ViewResult} { + m.view = v + lines := strings.Split(m.View(), "\n") + for i, l := range lines { + if w := ansi.StringWidth(l); w > width { + t.Errorf("largura %d, view %v, linha %d com %d colunas: %q", width, v, i, w, ansi.Strip(l)) + } + } + if v != ViewConfigure { + continue + } + // Bordas das caixas alinhadas: toda linha da caixa tem a mesma largura que o topo. + var boxW int + for _, l := range lines { + l = strings.TrimSpace(ansi.Strip(l)) + switch { + case strings.HasPrefix(l, "╭"): + boxW = ansi.StringWidth(strings.SplitAfter(l, "╮")[0]) + case boxW > 0 && strings.HasPrefix(l, "│"): + if got := ansi.StringWidth(l[:strings.Index(l[3:], "│")+3+len("│")]); got != boxW { + t.Errorf("largura %d: linha da caixa com %d colunas, topo com %d: %q", width, got, boxW, l) + } + } + } + } + } +} + +func TestViewKeepsHeaderWhenTerminalIsShort(t *testing.T) { + game, _ := writeGame(t) + m := NewModel(game) + m.Update(tea.WindowSizeMsg{Width: 70, Height: 20}) + m.view = ViewConfigure + m.selectedProvider = 2 + out := m.View() + if n := len(strings.Split(out, "\n")); n > 20 { + t.Errorf("view com %d linhas num terminal de 20", n) + } + if !strings.Contains(out, "Slime") || !strings.Contains(out, "enter") { + t.Error("cabeçalho e rodapé precisam continuar visíveis") + } +} diff --git a/pkg/ui/tui/estimate.go b/pkg/ui/tui/estimate.go index c964195..bee3606 100644 --- a/pkg/ui/tui/estimate.go +++ b/pkg/ui/tui/estimate.go @@ -10,6 +10,7 @@ import ( "github.com/BGLuis/slime-rpg/pkg/job" "github.com/BGLuis/slime-rpg/pkg/ui/theme" tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" ) func ollamaFields() []job.ConfigSchemaField { @@ -19,11 +20,12 @@ func ollamaFields() []job.ConfigSchemaField { } } -func nextLang(code string) string { +// stepLang anda delta posições na lista de idiomas, dando a volta nas pontas. +func stepLang(code string, delta int) string { langs := i18n.TranslationLanguages for i, l := range langs { if l == code { - return langs[(i+1)%len(langs)] + return langs[((i+delta)%len(langs)+len(langs))%len(langs)] } } return langs[0] @@ -38,12 +40,6 @@ func langLabel(code string) string { return code } -// boxTop desenha a borda superior de uma caixa com título, completada até width colunas. -func boxTop(title string, width int) string { - head := "╭─ " + title + " " - return head + strings.Repeat("─", max(width-len([]rune(head))-1, 0)) + "╮" -} - type estimateMsg struct { seq int est *event.EstimateEvent @@ -64,7 +60,7 @@ func (m *Model) enterConfigure() tea.Cmd { // reestimate dispara uma nova estimativa assíncrona se as opções mudaram e nenhum campo está em edição. func (m *Model) reestimate() tea.Cmd { key := m.currentEstimateKey() - if key == m.estimateKey || m.fieldFocus >= 0 || !m.hasGame() { + if key == m.estimateKey || m.editingText() || !m.hasGame() { return nil } m.estimateKey = key @@ -105,34 +101,29 @@ func (m *Model) handleEstimate(msg estimateMsg) { } } -func (m *Model) renderEstimate() []string { - row := func(s string) string { return fmt.Sprintf("│ %-32s │", truncate(s, 32)) } - blank := row("") - lines := []string{boxTop(i18n.T("tui_est_title"), 36)} - +// renderEstimate devolve o conteúdo do painel de estimativa com inner colunas úteis. +func (m *Model) renderEstimate(inner int) []string { switch e := m.estimate; { case m.estimating: - lines = append(lines, row(i18n.T("tui_est_calc"))) + return []string{i18n.T("tui_est_calc")} case m.estimateErr != "": - lines = append(lines, row(i18n.T("tui_est_fail")), row(m.estimateErr)) + return append([]string{i18n.T("tui_est_fail")}, wrapJoin(strings.Fields(m.estimateErr), " ", inner)...) case e != nil: toTranslate := max(e.SegmentsTotal-e.SegmentsCached, 0) pct := 0.0 if e.SegmentsTotal > 0 { pct = float64(e.SegmentsCached) / float64(e.SegmentsTotal) } - lines = append(lines, - row(fmt.Sprintf("%d %s", toTranslate, i18n.T("ui_est_to_translate"))), - blank, - "│ "+theme.RenderProgressBar(pct, 32)+" │", - row(i18n.T("ui_est_cache", e.SegmentsCached, e.SegmentsTotal, int(pct*100))), - blank, - row(i18n.T("tui_est_files", e.FilesToProcess, e.FilesTotal)), - row(i18n.T("tui_est_backup")+truncate(e.BackupPath, 22)), - ) - } - for len(lines) < 16 { - lines = append(lines, blank) + label := i18n.T("tui_est_backup") + return []string{ + fmt.Sprintf("%d %s", toTranslate, i18n.T("ui_est_to_translate")), + "", + theme.RenderProgressBar(pct, inner), + i18n.T("ui_est_cache", e.SegmentsCached, e.SegmentsTotal, int(pct*100)), + "", + i18n.T("tui_est_files", e.FilesToProcess, e.FilesTotal), + label + tail(e.BackupPath, inner-ansi.StringWidth(label)), + } } - return append(lines, "╰──────────────────────────────────╯") + return nil } diff --git a/pkg/ui/tui/i18n_test.go b/pkg/ui/tui/i18n_test.go index 485b078..b2472e7 100644 --- a/pkg/ui/tui/i18n_test.go +++ b/pkg/ui/tui/i18n_test.go @@ -57,9 +57,12 @@ func TestLanguageCyclePreservesOrder(t *testing.T) { want := []string{"pt", "en", "es", "fr", "it", "ja", "auto", "pt"} got := []string{"pt"} for range want[1:] { - got = append(got, nextLang(got[len(got)-1])) + got = append(got, stepLang(got[len(got)-1], 1)) } if strings.Join(got, ",") != strings.Join(want, ",") { t.Errorf("ciclo de idiomas = %v, quer %v", got, want) } + if back := stepLang("pt", -1); back != "auto" { + t.Errorf("voltar de pt devia dar a volta até auto, deu %q", back) + } } diff --git a/pkg/ui/tui/layout.go b/pkg/ui/tui/layout.go new file mode 100644 index 0000000..51f56c5 --- /dev/null +++ b/pkg/ui/tui/layout.go @@ -0,0 +1,88 @@ +package tui + +import ( + "strings" + + "github.com/charmbracelet/x/ansi" +) + +// Larguras medem colunas visíveis (ignoram ANSI e contam CJK como 2), porque +// nomes de jogos e segmentos em japonês ocupam o dobro de colunas por rune. + +const ( + maxContentWidth = 100 + minContentWidth = 40 + indent = " " +) + +// contentWidth é a largura útil da tela, limitada para não esticar demais em monitores largos. +func (m *Model) contentWidth() int { + return min(max(m.width, minContentWidth), maxContentWidth) +} + +// truncate corta s para caber em n colunas, terminando em "…". +func truncate(s string, n int) string { + if ansi.StringWidth(s) <= n { + return s + } + return ansi.Truncate(s, max(n, 0), "…") +} + +// fit corta ou completa s para ocupar exatamente n colunas. +func fit(s string, n int) string { + s = truncate(s, n) + return s + strings.Repeat(" ", max(n-ansi.StringWidth(s), 0)) +} + +// tail mantém o fim de s em até n colunas: em campos de digitação o cursor fica sempre visível. +func tail(s string, n int) string { + if ansi.StringWidth(s) <= n { + return s + } + r := []rune(s) + for len(r) > 0 && ansi.StringWidth(string(r)) > n-1 { + r = r[1:] + } + return "…" + string(r) +} + +// boxTop desenha a borda superior de uma caixa com título, completada até width colunas. +func boxTop(title string, width int) string { + head := "╭─ " + truncate(title, max(width-6, 1)) + " " + return head + strings.Repeat("─", max(width-ansi.StringWidth(head)-1, 0)) + "╮" +} + +// box emoldura lines numa caixa de width colunas; linhas longas são cortadas, nunca quebradas. +func box(title string, lines []string, width int) []string { + inner := max(width-4, 1) + out := make([]string, 0, len(lines)+2) + out = append(out, boxTop(title, width)) + for _, l := range lines { + out = append(out, "│ "+fit(l, inner)+" │") + } + return append(out, "╰"+strings.Repeat("─", max(width-2, 0))+"╯") +} + +// wrapJoin junta parts com sep, abrindo uma nova linha sempre que a próxima parte não cabe em width. +func wrapJoin(parts []string, sep string, width int) []string { + var lines []string + cur := "" + for _, part := range parts { + if cur != "" && ansi.StringWidth(cur+sep+part) > width { + lines, cur = append(lines, cur), "" + } + if cur != "" { + cur += sep + } + cur += part + } + return append(lines, cur) +} + +func indentLines(lines []string) string { + var b strings.Builder + for _, l := range lines { + b.WriteString(indent + l + "\n") + } + return b.String() +} diff --git a/pkg/ui/tui/render_job.go b/pkg/ui/tui/render_job.go index 95ba025..7f26764 100644 --- a/pkg/ui/tui/render_job.go +++ b/pkg/ui/tui/render_job.go @@ -8,6 +8,7 @@ import ( "github.com/BGLuis/slime-rpg/pkg/i18n" "github.com/BGLuis/slime-rpg/pkg/job" "github.com/BGLuis/slime-rpg/pkg/ui/theme" + "github.com/charmbracelet/x/ansi" ) const maxFileRows = 8 @@ -19,54 +20,56 @@ func checkbox(on bool) string { return "[ ]" } -func (m *Model) providerLine() string { - parts := make([]string, len(m.providers)) - for i, p := range m.providers { - parts[i] = " " + p - if i == m.selectedProvider { - parts[i] = "› " + p - } - } - return fmt.Sprintf("%-52s", strings.Join(parts, " ")) -} - func (m *Model) renderTranslating() string { snap := m.snapshot - var s strings.Builder - - mode := m.providers[m.selectedProvider] - s.WriteString(" " + theme.StyleHeader.Render(i18n.T("tui_trans_title", snap.GameName)) + - fmt.Sprintf(" %s · %s → %s\n", mode, snap.SourceLang, snap.TargetLang)) + w := m.contentWidth() - len(indent) - 1 phase := string(snap.Phase) if m.paused { phase = i18n.T("tui_trans_paused", phase) } - s.WriteString(" " + i18n.T("tui_trans_phase", phase) + "\n\n") + mode := fmt.Sprintf("%s · %s → %s", m.providers[m.selectedProvider], snap.SourceLang, snap.TargetLang) + lines := []string{ + theme.StyleHeader.Render(i18n.T("tui_trans_title", snap.GameName)) + " " + mode, + " " + i18n.T("tui_trans_phase", phase), + "", + } pct := 0.0 if snap.SegmentsTotal > 0 { pct = float64(snap.SegmentsDone) / float64(snap.SegmentsTotal) } - s.WriteString(" " + theme.RenderProgressBar(pct, 70) + fmt.Sprintf(" %d%%\n", int(pct*100))) - s.WriteString(" " + i18n.T("tui_trans_progress", - snap.SegmentsDone, snap.SegmentsTotal, snap.SegmentsCached, snap.SegmentsNew, snap.FilesDone, snap.FilesTotal) + "\n\n") - + progress := i18n.T("tui_trans_progress", + snap.SegmentsDone, snap.SegmentsTotal, snap.SegmentsCached, snap.SegmentsNew, snap.FilesDone, snap.FilesTotal) + lines = append(lines, theme.RenderProgressBar(pct, min(70, w-6))+fmt.Sprintf(" %d%%", int(pct*100))) + lines = append(append(lines, wrapJoin(strings.Split(progress, " · "), " · ", w)...), "") if m.throttleMsg != "" { - s.WriteString(" " + theme.StyleTagWarning.Render(theme.SymWarning+" "+m.throttleMsg) + "\n\n") + lines = append(lines, theme.StyleTagWarning.Render(theme.SymWarning+" "+truncate(m.throttleMsg, w-4)), "") } - s.WriteString(" " + boxTop(i18n.T("tui_trans_files", len(snap.Files)), 94) + "\n") - rows := orderedFiles(snap.Files) - for i, f := range rows { + // Colunas: caminho | status | mensagem | feitos/total; a mensagem some em telas estreitas. + inner := w - 4 + const statusW, countW = 11, 13 + pathW := inner - statusW - countW - 2 + msgW := 0 + if inner >= 70 { + msgW = pathW * 2 / 5 + pathW -= msgW + 1 + } + var rows []string + files := orderedFiles(snap.Files) + for i, f := range files { if i == maxFileRows { - s.WriteString(fmt.Sprintf(" │ + %-92s│\n", i18n.T("tui_trans_more", len(rows)-maxFileRows))) + rows = append(rows, "+ "+i18n.T("tui_trans_more", len(files)-maxFileRows)) break } - s.WriteString(fmt.Sprintf(" │ %-38s %-9s %-28s %5d/%-6d │\n", - truncate(f.Path, 38), f.Status, truncate(f.Message, 28), f.Done, f.Total)) + row := fit(tail(f.Path, pathW), pathW) + " " + fit(string(f.Status), statusW-1) + " " + if msgW > 0 { + row += fit(f.Message, msgW) + " " + } + rows = append(rows, row+fmt.Sprintf("%*s", countW, fmt.Sprintf("%d/%d", f.Done, f.Total))) } - s.WriteString(" ╰──────────────────────────────────────────────────────────────────────────────────────────────╯\n") - return s.String() + lines = append(lines, box(i18n.T("tui_trans_files", len(snap.Files)), rows, w)...) + return indentLines(lines) } // orderedFiles põe os arquivos em andamento ou com problema à frente dos demais. @@ -95,28 +98,31 @@ func orderedFiles(files []job.FileProgress) []job.FileProgress { func (m *Model) renderResult() string { snap := m.snapshot - var s strings.Builder + w := m.contentWidth() - len(indent) - 1 title := i18n.T("tui_result_ok") if m.runErr != nil { title = i18n.T("tui_result_fail") } - s.WriteString(" " + theme.StyleTitle.Render(title) + "\n") + lines := []string{theme.StyleHeader.Render(title)} if m.runErr != nil { - s.WriteString(" " + theme.StyleTagError.Render(theme.SymCross+" "+runErrorText(m.runErr)) + "\n\n") + lines = append(lines, theme.StyleTagError.Render(theme.SymCross+" "+truncate(runErrorText(m.runErr), w-4))) } else { - s.WriteString(" " + i18n.T("tui_result_done", snap.GameName, snap.Duration.Round(10_000_000)) + "\n\n") + lines = append(lines, i18n.T("tui_result_done", snap.GameName, snap.Duration.Round(10_000_000))) } + lines = append(lines, "") counts := map[event.StatusType]int{} for _, f := range snap.Files { counts[f.Status]++ } - s.WriteString(" " + i18n.T("tui_result_counts", + // A linha de contagens é longa; quebra nos grupos "● n rótulo" em vez de cortar. + summary := strings.TrimSpace(i18n.T("tui_result_counts", theme.SymBullet, counts[event.StatusSuccess]+counts[event.StatusCached], theme.SymBullet, counts[event.StatusPartial], theme.SymBullet, counts[event.StatusError], theme.SymBullet, snap.SegmentsNew, theme.SymBullet, snap.SegmentsCached)) + lines = append(append(lines, wrapJoin(strings.Split(summary, " "), " ", w)...), "") listed := 0 for _, f := range snap.Files { @@ -131,38 +137,38 @@ func (m *Model) renderResult() string { if f.Status == event.StatusError { tag = theme.StyleTagError.Render(theme.SymCross + " " + i18n.T("tui_tag_error")) } - s.WriteString(fmt.Sprintf(" %s %s: %s\n", tag, truncate(f.Path, 40), truncate(f.Message, 60))) + lines = append(lines, truncate(" "+tag+" "+f.Path+": "+f.Message, w)) } if listed > 0 { - s.WriteString("\n") - } - - s.WriteString(" " + boxTop(i18n.T("ui_result_where"), 96) + "\n") - s.WriteString(fmt.Sprintf(" │ %-20s %-71s│\n", i18n.T("tui_result_ok"), truncate(snap.GamePath, 70))) - s.WriteString(fmt.Sprintf(" │ %-20s %-71s│\n", i18n.T("tui_where_backup"), truncate(snap.BackupPath, 70))) - s.WriteString(fmt.Sprintf(" │ %-20s %-71s│\n", i18n.T("tui_where_log"), truncate(snap.MetaPath, 70))) - s.WriteString(" ╰──────────────────────────────────────────────────────────────────────────────────────────────╯\n\n") - s.WriteString(" " + i18n.T("tui_result_exit", snap.ExitCode)) - return s.String() + lines = append(lines, "") + } + + labelW := min(20, (w-4)/3) + where := func(label, path string) string { return fit(label, labelW) + " " + tail(path, w-4-labelW-2) } + lines = append(lines, box(i18n.T("ui_result_where"), []string{ + where(i18n.T("tui_result_ok"), snap.GamePath), + where(i18n.T("tui_where_backup"), snap.BackupPath), + where(i18n.T("tui_where_log"), snap.MetaPath), + }, w)...) + lines = append(lines, "", strings.TrimSpace(i18n.T("tui_result_exit", snap.ExitCode))) + return indentLines(lines) } func (m *Model) renderReviewing() string { - var s strings.Builder - s.WriteString(" " + theme.StyleHeader.Render(i18n.T("ui_review_title")) + " " + i18n.T("tui_review_sub") + "\n") + w := m.contentWidth() - len(indent) - 1 + lines := []string{truncate(theme.StyleHeader.Render(i18n.T("ui_review_title"))+" "+i18n.T("tui_review_sub"), w)} - chips := "" + chips := make([]string, len(m.filterLabels)) for i, f := range m.filterLabels { + chips[i] = " " + f + " " if i == m.selectedFilter { - chips += fmt.Sprintf("[%s] ", f) - } else { - chips += f + " " + chips[i] = theme.StyleAccent.Render("[" + f + "]") } } - s.WriteString(" " + chips + "\n\n") + lines = append(lines, strings.Join(chips, " "), "") if len(m.reviewItems) == 0 { - s.WriteString(" " + i18n.T("tui_review_empty") + "\n") - return s.String() + return indentLines(append(lines, i18n.T("tui_review_empty"))) } const window = 8 @@ -171,24 +177,27 @@ func (m *Model) renderReviewing() string { it := m.reviewItems[i] cursor := " " if i == m.selectedSegmentIdx { - cursor = "› " + cursor = theme.StyleAccent.Render(theme.SymArrow + " ") } - tag := theme.SymBullet + " ok " + tag := theme.StyleMuted.Render(fit(theme.SymBullet+" ok", 10)) if it.Status == "partial" { - tag = theme.StyleTagWarning.Render(theme.SymBullet + " " + i18n.T("tui_tag_partial")) + tag = theme.StyleTagWarning.Render(fit(theme.SymBullet+" "+i18n.T("tui_tag_partial"), 8)) } - s.WriteString(fmt.Sprintf(" %s%s %s\n", cursor, tag, truncate(oneLine(it.Source), 80))) + lines = append(lines, cursor+tag+" "+truncate(oneLine(it.Source), w-14)) } it := m.reviewItems[m.selectedSegmentIdx] - s.WriteString("\n " + i18n.T("tui_review_file") + truncate(it.File, 85) + "\n") - s.WriteString(" " + i18n.T("tui_review_source") + truncate(oneLine(it.Source), 85) + "\n") + detail := func(label, value string) string { return label + truncate(value, w-ansi.StringWidth(label)) } + lines = append(lines, "", + detail(i18n.T("tui_review_file"), it.File), + detail(i18n.T("tui_review_source"), oneLine(it.Source))) if m.editing { - s.WriteString(" " + i18n.T("tui_review_target") + truncate(oneLine(m.editBuf), 85) + "▌\n") + label := i18n.T("tui_review_target") + lines = append(lines, label+tail(oneLine(m.editBuf), w-ansi.StringWidth(label)-1)+"▌") } else { - s.WriteString(" " + i18n.T("tui_review_target") + truncate(oneLine(it.Target), 85) + "\n") + lines = append(lines, detail(i18n.T("tui_review_target"), oneLine(it.Target))) } - return s.String() + return indentLines(lines) } func oneLine(s string) string { return strings.ReplaceAll(s, "\n", "⏎") } diff --git a/pkg/ui/tui/run.go b/pkg/ui/tui/run.go index d6fa8b2..c031052 100644 --- a/pkg/ui/tui/run.go +++ b/pkg/ui/tui/run.go @@ -25,6 +25,9 @@ import ( // providerIDs acompanha Model.providers; o último item é o modo só-memória, sem provedor. var providerIDs = []string{"google", "deepl", "ollama", ""} +// providerHints são as chaves i18n da dica de cada provedor, na mesma ordem de providerIDs. +var providerHints = []string{"ui_hint_google", "ui_hint_deepl", "ui_hint_ollama", "tui_hint_memory"} + // ProviderFactory cria o provedor escolhido na tela Configurar. type ProviderFactory func(p ProviderParams) (provider.Provider, error) diff --git a/pkg/ui/tui/run_test.go b/pkg/ui/tui/run_test.go index ce8ce78..1a2e14b 100644 --- a/pkg/ui/tui/run_test.go +++ b/pkg/ui/tui/run_test.go @@ -295,18 +295,20 @@ func TestConfigureChangesReestimateAndReachTheJob(t *testing.T) { p.key(tea.KeyMsg{Type: tea.KeyRight}) p.key(tea.KeyMsg{Type: tea.KeyRight}) // Ollama + p.until(func() bool { return !m.estimating }) + seqBeforeTyping := m.estimateSeq fields := m.configFields() if len(fields) == 0 || fields[len(fields)-1].Key != "ollama_host" { t.Fatalf("Ollama devia mostrar modelo e endereço: %+v", fields) } - p.key(tea.KeyMsg{Type: tea.KeyTab}) + for !m.editingText() { + p.key(tea.KeyMsg{Type: tea.KeyDown}) + } for _, r := range "llama3" { p.key(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}}) } - p.key(tea.KeyMsg{Type: tea.KeyTab}) - p.key(tea.KeyMsg{Type: tea.KeyTab}) - if m.fieldFocus != -1 { - t.Fatalf("fieldFocus = %d", m.fieldFocus) + if m.estimateSeq != seqBeforeTyping { + t.Fatal("digitar num campo não deve disparar estimativas a cada tecla") } p.key(enter) p.until(func() bool { return m.view == ViewResult })