Keel v0.5.1 中文 GitHub

Sidebar

Live example: a real Keel application compiled to WebAssembly. Interact with it here. The initial download is about 10 MB.Open full screen
Example sourceGo · Copyable

This is the complete source for the gallery example above.examples/components/sidebar.go

Reuse the component construction and Render methods in a scaffolded project. The example’s registerSection and shared helpers are provided by the component gallery.

package main

import (
	"github.com/dyike/keel/ui/core"
	"github.com/dyike/keel/ui/el"
	"github.com/dyike/keel/ui/kit"
	"github.com/dyike/keel/ui/theme"
)

func init() {
	registerSection("sidebar", "navigation", func() core.Widget {
		nav := kit.Sidebar().
			Section(demoText("Workspace", "工作台"), kit.SidebarItem{ID: "inbox", Label: demoText("Inbox", "收件箱"), Icon: kit.IconInbox, Badge: 12},
				kit.SidebarItem{ID: "orders", Label: demoText("Orders", "订单"), Icon: kit.IconReceipt, Children: []kit.SidebarItem{
					{ID: "pending", Label: demoText("Pending orders", "待处理订单"), Icon: kit.IconClock, Badge: 6},
					{ID: "completed", Label: demoText("Completed orders", "已完成订单"), Icon: kit.IconCheck},
					{ID: "archived", Label: demoText("Archive order", "归档订单"), Icon: kit.IconArchive, Disabled: true},
				}},
				kit.SidebarItem{ID: "calendar", Label: demoText("Schedule", "日程"), Icon: kit.IconCalendar}).
			Section(demoText("Team", "团队"), kit.SidebarItem{ID: "members", Label: demoText("Members", "成员"), Icon: kit.IconUser},
				kit.SidebarItem{ID: "saved", Label: demoText("Starred", "已收藏"), Icon: kit.IconStarOutline}).
			Section("", kit.SidebarItem{ID: "settings", Label: demoText("Preferences", "偏好设置"), Icon: kit.IconSettings})
		status, right := "", false
		nav.SetSuffix("inbox", kit.Button(demoText("Refresh", "刷新"), func() { status = demoText("Inbox refreshed", "已刷新收件箱") }).Variant(kit.ButtonGhost).Size(24))
		nav.SetContextMenu("inbox", kit.Menu().
			Item(demoText("Mark all read", "标记全部已读"), "", func() {
				nav.SetBadge("inbox", 0)
				status = demoText("All inbox messages read", "收件箱已全部读完")
			}).
			Separator().Item(demoText("Open inbox", "打开收件箱"), "", func() { nav.SetValue("inbox") }))
		nav.SetValue("inbox")
		nav.SetExpanded("orders", true)
		nav.Header(el.ViewFunc(func(cx *el.Context) el.Element {
			row := el.Div().Row().Items(el.Center).Gap(10).Py(8).Child(kit.Avatar("Keel").Size(28).Render(cx))
			if !nav.Collapsed() {
				row.Child(el.Text(demoText("Keel workspace", "Keel 工作台")).TextSize(15).Bold())
			}
			return row
		}))
		nav.Footer(el.ViewFunc(func(cx *el.Context) el.Element {
			row := el.Div().Row().Items(el.Center).Gap(10).Py(8).Child(kit.Avatar("Yike").Size(28).Render(cx))
			if !nav.Collapsed() {
				row.Child(el.Div().Gap(2).Child(el.Text("Yike").TextSize(13), el.Text(demoText("Personal workspace", "个人工作区")).TextSize(11).TextColor(theme.Muted)))
			}
			return row
		}))
		initialized, wasNarrow := false, false
		return el.Root(el.ViewFunc(func(cx *el.Context) el.Element {
			width, height := cx.ViewportSize()
			narrow := width < 600
			if !initialized || narrow != wasNarrow {
				nav.SetCollapsed(narrow)
				initialized, wasNarrow = true, narrow
			}
			nav.Height(height)
			titles := map[string]string{"pending": demoText("Pending orders", "待处理订单"), "completed": demoText("Completed orders", "已完成订单"), "archived": demoText("Archive order", "归档订单"), "inbox": demoText("Inbox", "收件箱"), "orders": demoText("Orders", "订单"), "calendar": demoText("Schedule", "日程"), "members": demoText("Team members", "团队成员"), "saved": demoText("Starred", "已收藏"), "settings": demoText("Preferences", "偏好设置")}
			body := el.Div().Grow().W(el.Dp(0)).ScrollY().Bg(theme.Surface).P(28).Gap(12).Items(el.Stretch)
			body.Child(el.Text(demoText("Workspace / ", "工作台 / ")+titles[nav.Value()]).TextSize(12).TextColor(theme.Muted),
				el.Text(titles[nav.Value()]).TextSize(24).Bold(),
				el.Text(demoText("View team activity and tasks in one place.", "集中查看团队动态与待办事项。")).TextSize(13).TextColor(theme.Muted),
				el.Div().H(el.Dp(1)).My(12).Bg(theme.Border))
			if nav.Value() == "inbox" {
				for _, item := range []struct{ title, detail string }{
					{demoText("Order awaiting confirmation", "订单待确认"), demoText("East China customer · Just now", "华东客户 · 刚刚")}, {demoText("This week's deliveries", "本周交付安排"), demoText("Project team · 20 minutes ago", "项目组 · 20 分钟前")}, {demoText("Design review updated", "设计评审已更新"), demoText("Product team · 1 hour ago", "产品团队 · 1 小时前")},
				} {
					body.Child(el.Div().Py(12).Gap(6).Child(el.Text(item.title).TextSize(14), el.Text(item.detail).TextSize(12).TextColor(theme.Muted)))
				}
			} else {
				body.Child(kit.Empty(demoText("No pending items", "暂无待处理事项")).Render(cx))
			}
			body.Child(kit.Button(demoText("Toggle sidebar position", "切换侧栏位置"), func() { right = !right }).Render(cx), el.Text(status))
			root := el.Div().Row().Items(el.Stretch)
			if right {
				nav.Side(el.Right)
				return root.Child(body, nav.Render(cx))
			}
			nav.Side(el.Left)
			return root.Child(nav.Render(cx), body)
		}))
	})
}

The application's navigation sidebar: groups, selected items, and icons can be collapsed to only display icons.

nav := kit.Sidebar().
    Section("Workspace", kit.SidebarItem{ID: "inbox", Label: "Inbox", Icon: kit.IconInbox, Badge: 12}).
    Section("", kit.SidebarItem{ID: "settings", Label: "Settings", Icon: kit.IconSettings}).
    OnChange(navigate)
  • Mouse click only displays the selected background; Tab and arrow key navigation display the focus box. The scroll bar occupies an independent space on the right side and does not cover the row background, corner mark or click area.
  • 36dp navigation line, 16dp icon, 14sp copy; selected items use neutral background color and accent icon, count is low contrast number, and folded copy is displayed in the expanded state at the bottom.
  • Titled groups display the title; untitled groups are separated by separators.
  • Each available item can be focused using Tab, ↑ ↓ / Home / End / PageUp / PageDown to move and scroll to the target, and Enter or Space to activate. Disabled or SetItemDisabled(id, bool) disables a single item; SetDisabled disables the entire sidebar and slot operations.
  • SidebarItem.Children defines nested navigation. Click to expand/collapse the entire row of a branch without triggering the navigation callback; → expand, ← collapse or move to the parent. SetExpanded / Expanded manage the expansion state, SetValue expands the target ancestor and scrolls to the selection.
  • Header(el.View) / Footer(el.View) are located outside the navigation scroll area and are suitable for workspace switching and account information. The slot can read Collapsed() in Render and switch the icon version content by itself.
  • Height(dp) explicitly sets the height of the sidebar. When the navigation content overflows, only the middle area is scrolled. The height is set according to the content by default, and the upper limit is the window height. The height returned by cx.ViewportSize() can be passed when embedded in the application shell.
  • The bottom button can collapse the sidebar, and the width after collapse is 56dp: only the icon is displayed, the name is changed to Tooltip, and the corner icon becomes a dot.
  • Icon can be omitted (IconNone): only the text will be displayed when expanded, and the first letter of the name will be displayed when collapsed.
  • SidebarItem.IconView accepts a display-only custom icon, overriding Icon in the same 16dp slot. It remains visible when collapsed; the application controls its colors. Branch disclosure arrows sit immediately after the label, before badges and independent suffixes.
  • Filter(query) Displays only items whose names contain query (case-insensitive), and the parents leading to them, which are temporarily expanded; groups without matching items are hidden along with their titles. Pass an empty string to restore all. Selected items remain selected while being filtered out. The component library application go run ./examples/components uses it for searching.
  • Side(el.Right) Move the divider to the left, and adjust the folding arrow and the prompt direction of the collapsed state; the default is el.Left. The application still needs to place the sidebar to the right of the main content, and the component does not change the parent layout order. BorderWidth(dp) adjusts the divider, 0 hides it.
  • SidebarItem.Tag places display-only content, usually a Tag, right after the label and before the disclosure arrow. It keeps its size while the label truncates, keeps regular weight on a selected row, and is hidden when collapsed.
  • SectionAction(title, view, items...) adds trailing content to a section heading, such as an add button; such a section keeps its heading while empty (hidden while filtering). SectionTitleWeight(font.Weight) sets the heading weight, regular by default; SectionTitleColor(color) sets the heading color, theme.Muted by default (set it in Render, e.g. theme.Text, to follow theme changes).
  • Resizable(min, max) turns the divider into a separator that can be dragged, or focused and moved with the arrow keys (16dp per press, Home / End for the limits), to change the expanded width between min and max dp. A resized width is explicit, like Width, and turns off AutoWidth. OnResize(fn) reports the new width, CurrentWidth() reads it. The collapsed icon rail is not resizable.
  • Collapsible(false) hides the built-in collapse button; programs can still call SetCollapsed.
  • SidebarItem.Suffix / SetSuffix(id, view) Add independent tail content, you can put buttons or switches; click the tail to not select or expand the navigation items. When collapsed, the tail content is hidden. When expanded, the maximum width is half the configured width of the sidebar, and the height should fit within the 36dp row. Badge can still be displayed at the same time.
  • SidebarItem.ContextMenu / SetContextMenu(id, menu) adds a right-click menu to the item, supporting Menu's submenus, shortcut key tips, links and custom content. A Menu instance belongs to only one item, and its Trigger is not used; the menu appearance and position are still configured by Menu. Hiding, disabling or replacing an entry menu closes the old menu. Right-clicking does not change the selected item.
  • Value() / SetValue(id), SetBadge(id, n), Collapsed() / SetCollapsed, Width(dp) (default 220).

SidebarItem.SuffixOnHover reveals the suffix while the row is hovered, contains keyboard focus, or has an open context menu. Hidden suffixes retain their layout space and cannot be activated.

Options structures are copied recursively; IconView, Suffix and ContextMenu retain the passed-in instance. The ID of the entire Sidebar must be non-empty and unique; when the new Section contains empty values or duplicate IDs, the entire group will not be added. Parent disabling does not implicitly disable children.

Sidebar skips painting rows outside the scroll viewport, but still constructs and lays out the expanded rows each frame; it is not a fully virtualized list. Menu cleanup visits the complete model once with a set of listed IDs, and row hover/focus queries reuse el's per-render indexes. The regression tests cover 1000 rows at 1x/2x, offscreen paint, keyboard reveal/activation and menu closure after collapsing a parent. Run go test ./ui/kit -run '^$' -bench BenchmarkSidebarScroll -benchmem to measure flat lists and closed project trees with per-item menus and hover suffixes.

Agent: container role navigation; the leaf item is link, the branch is button with an expanded Boolean value, selected represents the current page; the collapse button is named "Collapse Sidebar" and "Expand Sidebar"; with Resizable, the divider is a separator named "Resize" whose value is the width.

Verify: go run ./examples/components -section sidebar, add -theme dark to check the dark theme.

Large text automatically increases row and heading heights. The default sidebar also grows its preferred width with text scale, capped at 420dp while reserving 240dp for page content; if that cannot fit the original width, it uses an icon rail and restores on resize. Width(dp) keeps an explicit width; Width(dp).AutoWidth(true) opts back into adaptation. Automatic width adjustment applies when text scale exceeds 1. Truncated labels expose their full text on hover or focus, dismissible with Escape. Custom header/footer content remains the application’s responsibility.

SectionTitleSize(sp) sets the section heading font size. Zero restores theme.TextSm; invalid values are ignored. Heading height and scroll offsets adapt to the font size.