1package ui23import (4 "strconv"56 tea "charm.land/bubbletea/v2"7 "github.com/charmbracelet/x/ansi"89 "src.rest/cat/012/internal/macro"10 "src.rest/cat/012/internal/sheet"11)1213// Column widths: typed on the context line with a live preview, dragged14// by the header border (mouse.go), or fitted to the contents by15// double-clicking it, as in Sheets.1617// openWidth asks for the width of the selected columns, previewing it18// live as the arrows change it. Esc restores the original widths.19func (m *Model) openWidth() tea.Cmd {20 r := m.selection()21 orig := map[int]int{}22 for c := r.From.Col; c <= r.To.Col; c++ {23 orig[c] = m.sheet.ColWidth(c)24 }25 restore := func() {26 for c, w := range orig {27 m.sheet.SetColWidth(c, w)28 }29 }30 m.openPrompt(&prompt{31 kind: promptWidth,32 label: "Column width (1-240):",33 indicator: "WIDTH",34 fresh: true,35 resize: m.setWidths,36 maxSize: 240,37 onText: func(text string) tea.Cmd {38 w, err := strconv.Atoi(text)39 if err != nil || w < 1 || w > 240 {40 restore()41 m.fail("Column width must be between 1 and 240")42 return nil43 }44 m.setWidths(w)45 m.changed = true46 return nil47 },48 onCancel: restore,49 }, strconv.Itoa(m.sheet.ColWidth(m.cur.Col)))50 return nil51}5253// setWidths sets the width of every selected column, as one step.54func (m *Model) setWidths(w int) {55 r := m.selection()56 m.sheet.Batch(sheet.Change{Label: "column width", Focus: r}, func() error {57 for c := r.From.Col; c <= r.To.Col; c++ {58 m.sheet.SetColWidth(c, w)59 }60 return nil61 })62}6364// autofit sizes column c to its widest content, as double-clicking a65// header border does in Sheets. Selected columns fit together.66func (m *Model) autofit(c int) {67 cols := []int{c}68 if r := m.selection(); m.whole == wholeCols && c >= r.From.Col && c <= r.To.Col {69 cols = cols[:0]70 for k := r.From.Col; k <= r.To.Col; k++ {71 cols = append(cols, k)72 }73 }74 widest := map[int]int{}75 for _, a := range m.sheet.Addrs() {76 widest[a.Col] = max(widest[a.Col], ansi.StringWidth(m.sheet.Value(a).String()))77 }78 for _, k := range cols {79 // One column of padding each side, and never narrower than the80 // header letters.81 w := clamp(widest[k]+2, len(sheet.ColName(k))+2, 240)82 m.sheet.SetColWidth(k, w)83 m.record(widthAction(k, k, w))84 }85 m.changed = true86}8788// widthAction records setting columns from..to to width w.89func widthAction(from, to, w int) macro.Action {90 cols := sheet.ColName(from)91 if to != from {92 cols += ":" + sheet.ColName(to)93 }94 return macro.Call("set_width", cols, w)95}