Files
Sameen Karim 49a753708c insert branches with modify (#107)
* add insert branch operation to modify TUI

Add `i` (insert below) and `I` (insert above) key bindings to the
interactive modify view, allowing users to insert new empty branches
into an existing stack. This follows Vim-inspired semantics where
lowercase `i` inserts below the cursor and uppercase `I` inserts above.

## TUI behavior

When the user presses `i` or `I`, the TUI enters an insert input mode
(similar to rename mode) where they type a new branch name. The input
is validated against git ref naming rules, local branch uniqueness, and
in-stack name collisions. On confirm, a placeholder node is inserted at
the correct position in the branch list with a green "✚ insert"
annotation badge and green connector styling.

Insert is a structure operation — it works alongside fold, rename, and
drop, but is mutually exclusive with reorder (consistent with existing
mode exclusivity rules). Undo (`z`) removes the inserted node cleanly.

## Apply engine

At apply time (Step 2 in the pipeline, between renames and folds), the
engine creates the new git branch at the parent branch's tip via
`git.CreateBranch` and inserts a `BranchRef` into the stack metadata at
the correct position. If the insertion changes the base of a branch
that has an open PR, `affectsPRs` is set to trigger a required
`gh stack submit` afterward.

## Header shortcut updates

- Combined the fold shortcuts into a single line: `d/u - fold down/up`
- Added insert shortcuts on their own line: `i/I - insert below/above`
- Reordered fold references throughout to list "down" before "up" for
  consistency with the insert shortcut ordering

## Files changed

- types.go: ActionInsertBelow/ActionInsertAbove types, IsInserted field,
  InsertedBranches in ApplyResult
- model.go: key bindings, insert input mode, undo, mode exclusivity,
  annotation, styling, header shortcuts, effective-index tracking to
  prevent false reorder detection when inserts shift node positions
- styles.go: green insert badge/branch/connector styles
- status.go: insert counting in pending change summary
- help.go: new "Insert below / above" section, reordered fold heading
- apply.go: BuildPlan and ApplyPlan handle insert actions
- modify.go: updated command description and success summary
- README.md: updated keybindings table

## Test coverage

- 16 new TUI tests: insert below/above, top/bottom edges, undo, mode
  exclusivity, merged branch guard, cancel/empty input, duplicate name
  validation, pending summary counting, annotation rendering, mixed
  operations with drop/fold, apply acceptance
- 4 new apply tests: BuildPlan produces correct insert actions,
  ApplyPlan creates branches and updates stack metadata, insert at
  stack start uses trunk as parent, affectsPRs triggered when inserting
  before a branch with an open PR

* update add error msg to direct users to modify for inserting branches

* docs updates

* fix insert branch bugs in modify TUI

Fix three bugs with the insert branch feature in the modify TUI, and
adjust rename behavior on inserted nodes.

## Bug 1: False "moved" annotations on existing branches

After inserting a branch, all branches below the insertion point
displayed "↕ moved 1 layer down" annotations. This happened because
`nodeAnnotation` and `toNodeData` compared each node's
`OriginalPosition` against its raw array index, which gets shifted
when an inserted node is added to the slice.

Fix: introduce an `effectiveIdx` parameter that counts only
non-inserted nodes, so position comparisons reflect the original
ordering. The View loop computes effective indices by incrementing
only for non-inserted nodes and passes them to the rendering
functions.

## Bug 2: Header branch count inflated by staged inserts

The branch count in the header ("N branches") included inserted
placeholder nodes, making it appear as though the stack had grown
before changes were applied.

Fix: `buildHeaderConfig` now excludes `IsInserted` nodes from the
branch count. The count reflects only the original branches in the
stack.

## Bug 3: Operations allowed on inserted placeholder nodes

Inserted nodes could be folded into other branches, which makes no
sense for a placeholder with no commits. Additionally, the "last
branch" guard counted inserted nodes as active, allowing users to
drop all original branches and bypass the empty-stack check.

Fix:
- `fold()` rejects inserted nodes with a descriptive error message.
- `toggleDrop()` on an inserted node removes it entirely and pops
  the original insert action from the undo stack (clean cancellation
  rather than a separate undo entry).
- All three "active branch" guards (`toggleDrop`, `fold`, `tryApply`)
  now exclude `IsInserted` nodes, ensuring at least one original
  branch always remains in the stack.

## Rename on inserted branches

Instead of blocking renames on inserted nodes, pressing `r` now
enters rename mode and updates the insert action's name in place.
The node's `Ref.Branch` and `PendingAction.NewName` are both updated
directly — no separate rename action is created in the undo stack.
This lets users fix a typo without having to drop and re-insert.

## Tests added

- `TestInsertDoesNotShowMovedAnnotation` — verifies no false move
  annotations appear on existing branches after an insert
- `TestBranchCountExcludesInserts` — verifies header count stays
  stable after insert
- `TestCannotFoldInsertedBranch` — verifies fold is blocked
- `TestCannotRenameInsertedBranch` — verifies rename updates the
  insert name in place
- `TestDropInsertedBranchRemovesIt` — verifies drop removes the node
- `TestDropInsertedBranchCanBeUndone` — verifies drop pops the
  original insert from the undo stack
- `TestCannotDropAllOriginalBranchesWithInsert` — verifies the
  empty-stack guard excludes inserted nodes

* ensure cannot fold into an inserted branch

* rm dead code

* delete inserted branches during abort
2026-05-26 17:39:38 -04:00

320 lines
9.3 KiB
Go

package shared
import (
"strings"
"github.com/charmbracelet/lipgloss"
)
// HeaderHeight is the total number of lines the header occupies.
const HeaderHeight = 12
// MinHeightForHeader is the minimum terminal height to show the header.
const MinHeightForHeader = 25
// MinWidthForShortcuts is the minimum width to show keyboard shortcuts.
const MinWidthForShortcuts = 65
// MinWidthForHeader is the minimum width to show the header at all.
const MinWidthForHeader = 53
// MinWidthForArt is the minimum width to show ASCII art in the header.
const MinWidthForArt = 96
// ShortcutEntry represents a keyboard shortcut for the header.
type ShortcutEntry struct {
Key string
Desc string
Disabled bool // when true, rendered in gray (dimmed)
}
// HeaderInfoLine represents an info line in the header (icon + label).
type HeaderInfoLine struct {
Icon string
Label string
IconStyle *lipgloss.Style // optional override; nil uses default HeaderInfoStyle (cyan)
}
// ArtLines is the braille ASCII art for the View header.
var ArtLines = [10]string{
"⠀⠀⠀⠀⠀⠀⣀⣤⣤⣤⣤⣤⣤⣀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⣠⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣄⠀⠀⠀",
"⠀⢀⣼⣿⣿⠛⠛⠿⠿⠿⠿⠿⠿⠛⠛⣿⣿⣷⡀⠀",
"⠀⣾⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⣿⣷⡀",
"⢸⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⡇",
"⢸⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⡇",
"⠘⣿⣿⣿⣿⣦⡀⠀⠀⠀⠀⠀⠀⢀⣤⣿⣿⣿⣿⠇",
"⠀⠹⣿⣦⡈⠻⢿⠟⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⠏⠀",
"⠀⠀⠈⠻⣷⣤⣀⡀⠀⠀⠀⠀⢸⣿⣿⣿⡿⠃⠀⠀",
"⠀⠀⠀⠀⠈⠙⠻⠇⠀⠀⠀⠀⠸⠟⠛⠁⠀⠀⠀⠀",
}
// ArtDisplayWidth is the visual column width of each art line.
const ArtDisplayWidth = 20
// HeaderConfig controls what the header displays.
type HeaderConfig struct {
ShowArt bool // whether to display GitHub logo
Title string // heading next to logo art
Subtitle string // version string, or empty
InfoLines []HeaderInfoLine // info rows (stack info)
Shortcuts []ShortcutEntry // keyboard shortcuts
ShortcutColumns int // number of columns for shortcuts (default 1; set 2 for side-by-side)
}
// ShouldShowHeader returns whether the header should be displayed.
func ShouldShowHeader(width, height int) bool {
return height >= MinHeightForHeader && width >= MinWidthForHeader
}
// ShouldShowShortcuts returns whether shortcuts should be displayed.
func ShouldShowShortcuts(width int) bool {
return width >= MinWidthForShortcuts
}
// RenderHeader renders the full-width header box.
// Progressive disclosure as width narrows: first hides the art, then the
// info text, keeping keyboard shortcuts always visible.
func RenderHeader(b *strings.Builder, cfg HeaderConfig, width, height int) {
if width < 2 {
return
}
innerWidth := width - 2
// Always build shortcut lines
type shortcutLine struct {
text string
visWidth int
}
var shortcuts []shortcutLine
maxShortcutWidth := 0
rightColWidth := 0
cols := cfg.ShortcutColumns
if cols < 1 {
cols = 1
}
if len(cfg.Shortcuts) > 0 {
if cols >= 2 {
// Two-column layout with aligned keys and descriptions.
// First pass: compute max visual key width per column.
maxKeyLeft := 0
maxKeyRight := 0
for i := 0; i < len(cfg.Shortcuts); i += 2 {
kw := lipgloss.Width(cfg.Shortcuts[i].Key)
if kw > maxKeyLeft {
maxKeyLeft = kw
}
if i+1 < len(cfg.Shortcuts) {
kw = lipgloss.Width(cfg.Shortcuts[i+1].Key)
if kw > maxKeyRight {
maxKeyRight = kw
}
}
}
// Second pass: compute max visual width of the left column
// so the right column starts at a consistent position.
maxLeftWidth := 0
for i := 0; i < len(cfg.Shortcuts); i += 2 {
left := renderShortcutEntryPadded(cfg.Shortcuts[i], maxKeyLeft)
lw := lipgloss.Width(left)
if lw > maxLeftWidth {
maxLeftWidth = lw
}
}
colGap := " "
colGapWidth := lipgloss.Width(colGap)
for i := 0; i < len(cfg.Shortcuts); i += 2 {
left := renderShortcutEntryPadded(cfg.Shortcuts[i], maxKeyLeft)
// Pad left entry to maxLeftWidth for consistent right column start
leftPad := maxLeftWidth - lipgloss.Width(left)
if leftPad < 0 {
leftPad = 0
}
line := left + strings.Repeat(" ", leftPad)
if i+1 < len(cfg.Shortcuts) {
right := renderShortcutEntryPadded(cfg.Shortcuts[i+1], maxKeyRight)
line = line + colGap + right
}
visW := lipgloss.Width(line)
// Account for column gap width in case right column is missing
if i+1 >= len(cfg.Shortcuts) {
visW = maxLeftWidth + colGapWidth + maxKeyRight + 10 // approximate
}
shortcuts = append(shortcuts, shortcutLine{text: line, visWidth: visW})
if visW > maxShortcutWidth {
maxShortcutWidth = visW
}
}
} else {
// Single-column layout with aligned keys.
maxKeyW := 0
for _, sc := range cfg.Shortcuts {
kw := lipgloss.Width(sc.Key)
if kw > maxKeyW {
maxKeyW = kw
}
}
for _, sc := range cfg.Shortcuts {
rendered := renderShortcutEntryPadded(sc, maxKeyW)
visW := lipgloss.Width(rendered)
shortcuts = append(shortcuts, shortcutLine{text: rendered, visWidth: visW})
if visW > maxShortcutWidth {
maxShortcutWidth = visW
}
}
}
rightColWidth = maxShortcutWidth + 2
}
// Determine what fits: shortcuts always shown, art and info are progressive.
// Hide art first (below 88 cols), then info text, as width narrows.
showArt := cfg.ShowArt
showInfo := true
// Hide art when viewport is too narrow for art + info + shortcuts
if showArt && width < MinWidthForArt {
showArt = false
}
// If info + shortcuts don't fit, hide info
infoMinWidth := 20 // rough minimum for title/info text
if innerWidth < rightColWidth+infoMinWidth+4 {
showInfo = false
}
// Map info lines to row indices
infoByRow := make(map[int]string)
if showInfo {
infoByRow[2] = HeaderTitleStyle.Render(cfg.Title)
if cfg.Subtitle != "" {
infoByRow[3] = HeaderInfoLabelStyle.Render(cfg.Subtitle)
}
for i, info := range cfg.InfoLines {
row := 5 + i
if row > 9 {
break
}
iconStyle := HeaderInfoStyle
if info.IconStyle != nil {
iconStyle = *info.IconStyle
}
infoByRow[row] = iconStyle.Render(info.Icon) + HeaderInfoLabelStyle.Render(" "+info.Label)
}
}
// Left content base width
leftContentBase := 1 // margin
if showArt {
leftContentBase += ArtDisplayWidth
}
// Vertically center shortcuts
scStartRow := 0
if len(shortcuts) > 0 {
scStartRow = (10 - len(shortcuts)) / 2
}
gap := " "
// Top border
b.WriteString(HeaderBorderStyle.Render("┌" + strings.Repeat("─", innerWidth) + "┐"))
b.WriteString("\n")
// Content rows
for i := 0; i < 10; i++ {
// Left column: art (optional) + info
artText := ""
if showArt {
artText = ArtLines[i]
}
infoText := ""
infoVisualLen := 0
if info, ok := infoByRow[i]; ok {
infoText = gap + info
infoVisualLen = 2 + lipgloss.Width(info)
}
leftUsed := leftContentBase + infoVisualLen
if len(shortcuts) > 0 {
shortcutCol := innerWidth - rightColWidth
midPad := shortcutCol - leftUsed
if midPad < 0 {
midPad = 0
}
scIdx := i - scStartRow
shortcutRendered := ""
scVisWidth := 0
if scIdx >= 0 && scIdx < len(shortcuts) {
shortcutRendered = shortcuts[scIdx].text
scVisWidth = shortcuts[scIdx].visWidth
}
scTrailingPad := rightColWidth - scVisWidth
if scTrailingPad < 0 {
scTrailingPad = 0
}
b.WriteString(HeaderBorderStyle.Render("│"))
b.WriteString(" ")
if showArt {
b.WriteString(artText)
}
b.WriteString(infoText)
b.WriteString(strings.Repeat(" ", midPad))
b.WriteString(shortcutRendered)
b.WriteString(strings.Repeat(" ", scTrailingPad))
b.WriteString(HeaderBorderStyle.Render("│"))
} else {
trailingPad := innerWidth - leftUsed
if trailingPad < 0 {
trailingPad = 0
}
b.WriteString(HeaderBorderStyle.Render("│"))
b.WriteString(" ")
if showArt {
b.WriteString(artText)
}
b.WriteString(infoText)
b.WriteString(strings.Repeat(" ", trailingPad))
b.WriteString(HeaderBorderStyle.Render("│"))
}
b.WriteString("\n")
}
// Bottom border
b.WriteString(HeaderBorderStyle.Render("└" + strings.Repeat("─", innerWidth) + "┘"))
b.WriteString("\n")
}
// disabledShortcutStyle renders both key and desc in dim gray.
var disabledShortcutStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("240"))
// renderShortcutEntry renders a single shortcut, dimmed if disabled.
func renderShortcutEntry(sc ShortcutEntry) string {
if sc.Disabled {
return disabledShortcutStyle.Render(sc.Key + " " + sc.Desc)
}
return HeaderShortcutKey.Render(sc.Key) + HeaderShortcutDesc.Render(" "+sc.Desc)
}
// renderShortcutEntryPadded renders a shortcut with the key right-padded
// to keyWidth visual columns so descriptions align across rows.
func renderShortcutEntryPadded(sc ShortcutEntry, keyWidth int) string {
keyVisWidth := lipgloss.Width(sc.Key)
pad := ""
if keyVisWidth < keyWidth {
pad = strings.Repeat(" ", keyWidth-keyVisWidth)
}
if sc.Disabled {
return disabledShortcutStyle.Render(sc.Key) + pad + disabledShortcutStyle.Render(" "+sc.Desc)
}
return HeaderShortcutKey.Render(sc.Key) + pad + HeaderShortcutDesc.Render(" "+sc.Desc)
}