package app import ( "path/filepath" "strings" "github.com/egoist/mygo/ui" ) // breadcrumb 画编辑器上方的路径导航:项目 › 子目录 › 文件名。 // // 点目录会在左侧文件树里展开并选中它,省得自己一层层点开。 func (a *App) breadcrumb(c *ui.Context, d *Doc) { t := c.Theme() segs, dirs := crumbSegments(a.root, d.path) // 项目名单独占一段,不能顶替第一层目录—— // 否则 greeter/greeter.go 会显示成「项目 › greeter.go」,中间层看不见。 showRoot := a.root != "" && len(segs) > 1 ui.Row(c).FillWidth().Height(22).Padding(0, 6).Gap(2).AlignItems(ui.Center).Children(func() { if showRoot { a.crumbButton(c, filepath.Base(a.root), t.TextMuted, func() { a.revealDir(a.root) }) ui.Text(c, "›").FontSize(11).TextColor(t.TextMuted) } for i, seg := range segs { last := i == len(segs)-1 target := dirs[i] color := t.TextMuted if last { color = t.Text } if last { ui.Text(c, seg).FontSize(11).TextColor(color).SingleLine() continue } // 这里必须用可点击的按钮壳:纯 Text 收不到点击。 a.crumbButton(c, seg, color, func() { a.revealDir(target) }) ui.Text(c, "›").FontSize(11).TextColor(t.TextMuted) } }) } // revealDir 在文件树里展开到指定目录并选中它。 func (a *App) revealDir(dir string) { if dir == "" || a.root == "" { return } // 从目标往上逐级展开,直到工作区根。 for p := filepath.Clean(dir); within(a.root, p); p = filepath.Dir(p) { if sameDir(p, a.root) { break } *a.openFlag(p) = true if parent := filepath.Dir(p); sameDir(parent, p) { break } } a.sel = map[string]bool{filepath.Clean(dir): true} // 树被收起来了就先打开侧栏,不然展开了也看不见。 a.sidebarOn = true a.win.Update(func() {}) } // crumbSegments 把文件路径拆成面包屑的各段,以及每段对应的绝对路径。 // // 返回值一一对应:最后一项是文件本身,前面的都是目录。 // 文件不在工作区内(比如从最近项目直接打开)时只返回文件名。 func crumbSegments(root, path string) ([]string, []string) { path = filepath.Clean(path) if root == "" || !within(root, path) { return []string{filepath.Base(path)}, []string{path} } rel, err := filepath.Rel(root, path) if err != nil { return []string{filepath.Base(path)}, []string{path} } parts := strings.Split(filepath.ToSlash(rel), "/") segs := make([]string, 0, len(parts)) dirs := make([]string, 0, len(parts)) cur := filepath.Clean(root) for _, p := range parts { if p == "" || p == "." { continue } cur = filepath.Join(cur, filepath.FromSlash(p)) segs = append(segs, p) dirs = append(dirs, cur) } if len(segs) == 0 { return []string{filepath.Base(path)}, []string{path} } return segs, dirs } // crumbButton 是面包屑里可点的一段。 func (a *App) crumbButton(c *ui.Context, label string, color ui.Color, onClick func()) { t := c.Theme() b := ui.ButtonBase(c).Padding(1, 3).Radius(3).Cursor(ui.CursorPointer) fg := color if b.Hovered() { b = b.Background(t.SurfaceHover) fg = t.Accent } b.Children(func() { ui.Text(c, label).FontSize(11).TextColor(fg).SingleLine() }) if b.Clicked() { onClick() } }