UI 教程:弹层与导航

本篇是 UI 教程的第 11–12 章。第 11 章介绍浮在页面之上的各类弹层:提示、气泡卡片、对话框、侧板、菜单和通知;第 12 章介绍在多个页面和面板之间切换的导航控件,最后把它们组合成一个工作区应用。

上一篇:焦点、键盘与滚动。下一篇:数据展示。

本篇示例都使用 shadcn 主题,结构与第一个应用中的布局版 Counter 相同:状态放在一个普通的模型类里,页面写成 xxxPage(model, theme) 函数,组件的 render() 只负责调用它;根 frame 用主题的页面底色铺底。示例中会看到 import scoop.ui.component.column as makeColumn 这样的别名导入,原因是:在 column { }、row { } 块里直接写 button(...) 表示“添加一个子项”,返回 Unit;当需要把控件作为值传给另一个函数(例如作为 tooltip 的触发器、dialog 的正文)时,要调用顶层函数,别名可以避开块内同名成员。

11. 弹层体系

11.1 统一模型:open 绑定是唯一的状态来源

所有弹层都遵循同一套规则:

onOpenChange 在绑定被接受地改变时调用,onClosed 在关闭动画结束、弹层真正卸载后调用。绑定的 setter 也可以拒绝写入,例如用普通的 binding(get, set) 包一层:

fun guardedOpen(open: State<Boolean>, locked: State<Boolean>): Binding<Boolean> =
    binding({ open.value }, { next -> if (!locked.value) open.value = next })

locked 为 true 时,触发器和关闭操作写入的新值都会被忽略,弹层维持现状。

11.2 提示、悬浮卡片与 Popover

三者都锚定在一个触发控件旁边:

函数 何时显示 正文能否操作 典型用途
tooltip(trigger, text) 指针悬停、键盘聚焦或触摸长按触发器 否,只展示文字 图标按钮的说明
hoverCard(trigger, content) 悬停一段时间或触摸长按后 可以选择文字、点击链接 用户名、链接的预览
popover(open, content) 点击触发器或改变 open 可以,包含真实输入框 小型表单、筛选条件

tooltip 包装原有的按钮,不改变按钮的动作和焦点行为,默认带箭头;hoverCard 默认 600 毫秒后打开、300 毫秒后关闭。Popover 是唯一由 open 绑定控制的一个,它的 mode 决定与背景的关系:

保存为 ui-overlays-popover.scoop(下载):

//! dep: scoop:scoop.graphics:0.1.0
//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.shadcn:0.1.0
import scoop.graphics.Paint
import scoop.ui.*
import scoop.ui.component.*
import scoop.ui.component.button as makeButton
import scoop.ui.component.column as makeColumn
import scoop.ui.component.input as makeInput
import scoop.ui.component.typography as makeText
import scoop.ui.style.Insets
import scoop.ui.style.Theme
import scoop.ui.style.ThemeMode
import scoop.ui.style.ThemeSource
import scoop.ui.style.currentThemeSource
import scoop.ui.style.shadcn.shadcnTheme
import scoop.ui.text.TextEditorState

class PopoverModel {
    val open = state(false)
    val mode = state(OverlayMode.NonModal)
    val locked = state(false)
    val saved = state("No name saved yet")
    val name = TextEditorState("Ada")
    val nameFocus = FocusHandle()
    val handle = OverlayHandle()
}

fun modeName(mode: OverlayMode): String =
    when (mode) {
        case NonModal -> "NonModal"
        case FocusContained -> "FocusContained"
        case Modal -> "Modal"
    }

fun popoverPage(model: PopoverModel, theme: Theme): View {
    val save = makeButton("Save", { model.saved.value = f"Saved: ${model.name.text}" })
    val profile =
        makeColumn {
            typography("Ada Lovelace", TypographyRole.Large)
            typography("Wrote the first published program.", TypographyRole.Muted)
            spacing = 4.0
        }
    val form =
        makeColumn {
            add(makeInput(model.name) { focus = FocusOptions(Some(model.nameFocus)) })
            button("Done", { model.handle.requestClose() })
            button(
                if (model.locked.value)
                    "Unlock closing"
                else
                    "Lock closing",
                { model.locked.value = !model.locked.value }
            ) { variant = ButtonVariant.Ghost }
            spacing = 8.0
            alignment = CrossAlignment.Stretch
        }
    val content =
        makeColumn {
            row {
                tooltip(save, "Save the current name")
                hoverCard(makeText("@ada", TypographyRole.P), profile)
                spacing = 16.0
                alignment = CrossAlignment.Center
            }
            row {
                for (mode in [OverlayMode.NonModal, OverlayMode.FocusContained, OverlayMode.Modal])
                    button(modeName(mode), { model.mode.value = mode }) {
                        variant =
                            if (model.mode.value == mode)
                                ButtonVariant.Default
                            else
                                ButtonVariant.Outline
                    }
                spacing = 8.0
            }
            row {
                popover(model.open.binding(), form) {
                    trigger("Edit name")
                    title("Display name")
                    description("Changes apply when you press Save.")
                    mode = model.mode.value
                    focus = OverlayFocusOptions(Some(model.nameFocus))
                    handle = Some(model.handle)
                    onCloseRequest = { _ -> !model.locked.value }
                }
            }
            typography(f"${model.saved.value} · open = ${model.open.value}", TypographyRole.Muted)
            spacing = 16.0
            alignment = CrossAlignment.Start
        }
    return page(theme, content)
}

/** Paints the theme background and places the content at the top-left. */
fun page(theme: Theme, content: View): View =
    frame(content) {
        padding = Some(Insets.all(24.0))
        alignment = Alignment(AxisAlignment.Start, AxisAlignment.Start)
        style { background(Some(Paint(theme.tokens.palette.background.background))) }
    }

class PopoverDemo(scope: ComponentScope): Component(scope) {
    private val model = PopoverModel()
    private val theme = currentThemeSource()
    public override fun render(): View = popoverPage(model, theme.current.value)
}

fun main() {
    val source = ThemeSource(shadcnTheme(ThemeMode.Light))
    context(source) {
        runUiApplication("Popovers", { scope -> PopoverDemo(scope) })
    }
}

scoop run ui-overlays-popover.scoop --release

Popover 示例:点 Edit name 后在按钮下方打开 Display name 弹层

Windows 写作 sco run ui-overlays-popover.scoop --release,本篇其余命令同理。

窗口顶部是黑色的 Save 按钮和文字 @ada:悬停 Save 显示“Save the current name”提示,在 @ada 上停留片刻会弹出资料卡片。中间一排按钮切换 Popover 的模式。点击 Edit name 会在按钮下方打开标题为 Display name 的弹层,光标已经在输入框中。

几个值得注意的地方:

Popover 的其他常用配置有 side / alignment(首选方向与对齐,空间不够时自动翻转)、width、arrow = Some(PopupArrow()),以及用 anchor 锚定到别处的控件而不使用自带触发器。

11.3 对话框、确认框、侧板与抽屉

模态弹层打开时背景变暗,指针、键盘与读屏器操作都限于弹层。通过读屏器请求关闭时,仍由弹层已有的关闭回调决定是否接受。

四者共享同一组配置,保存在 ModalOptions 中;在配置块里它们直接以成员形式出现:title、description、header、scrollable 与 scrollState(长表单滚动)、focus、handle、backdrop、onOpenChange、onCloseRequest、onClosed 等。学会一个,其他几个的写法就都会了。

下面的例子用四个按钮分别打开这几种弹层,并在操作完成后用 Toast 通知(Toast 在 11.5 节说明)。保存为 ui-overlays-modal.scoop(下载):

//! dep: scoop:scoop.graphics:0.1.0
//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.shadcn:0.1.0
import scoop.graphics.Paint
import scoop.ui.*
import scoop.ui.component.*
import scoop.ui.component.column as makeColumn
import scoop.ui.component.input as makeInput
import scoop.ui.component.typography as makeText
import scoop.ui.style.Insets
import scoop.ui.style.Theme
import scoop.ui.style.ThemeMode
import scoop.ui.style.ThemeSource
import scoop.ui.style.currentThemeSource
import scoop.ui.style.shadcn.shadcnTheme
import scoop.ui.text.TextEditorState

class ProjectModel {
    val name = state("Atlas")
    val editOpen = state(false)
    val deleteOpen = state(false)
    val settingsOpen = state(false)
    val activityOpen = state(false)
    val draft = TextEditorState("Atlas")
    val draftFocus = FocusHandle()
    val toasts = ToastState()

    fun startEdit() {
        draft.replaceAll(name.value)
        editOpen.value = true
    }
    fun save() {
        if (draft.text.charLength == 0L) {
            toasts.show("The name cannot be empty") { kind = ToastKind.Error }
            return
        }
        val next = draft.committedText
        name.value = next
        editOpen.value = false
        toasts.show("Project renamed") {
            kind = ToastKind.Success
            description(f"The project is now called ${next}.")
        }
    }
}

fun modalPage(model: ProjectModel, theme: Theme): View {
    val form =
        makeColumn {
            typography("Project name", TypographyRole.Small)
            add(makeInput(model.draft) { focus = FocusOptions(Some(model.draftFocus)) })
            spacing = 6.0
            alignment = CrossAlignment.Stretch
        }
    val footer =
        makeColumn {
            button("Save", { model.save() })
            alignment = CrossAlignment.Stretch
        }
    val content =
        makeColumn {
            typography(f"Project: ${model.name.value}", TypographyRole.H3)
            row {
                button("Rename…", { model.startEdit() })
                button("Delete", { model.deleteOpen.value = true }) {
                    variant = ButtonVariant.Destructive
                }
                button("Settings", { model.settingsOpen.value = true }) {
                    variant = ButtonVariant.Outline
                }
                button("Activity", { model.activityOpen.value = true }) {
                    variant = ButtonVariant.Outline
                }
                spacing = 8.0
            }
            dialog(model.editOpen.binding(), form) {
                title("Rename project")
                description("The new name is applied when you press Save.")
                focus = OverlayFocusOptions(Some(model.draftFocus))
                footer(footer)
            }
            alertDialog(
                model.deleteOpen.binding(),
                makeText("Deleting cannot be undone.", TypographyRole.Muted)
            ) {
                title(f"Delete ${model.name.value}?")
                action(
                    "Delete",
                    {
                        model.deleteOpen.value = false
                        model.toasts.show("Project deleted") { kind = ToastKind.Warning }
                    }
                ) { variant = ButtonVariant.Destructive }
                cancel("Keep project")
            }
            sheet(
                model.settingsOpen.binding(),
                makeText("Settings live in a side panel.", TypographyRole.P)
            ) {
                title("Project settings")
                side = SheetSide.End
            }
            drawer(
                model.activityOpen.binding(),
                makeText("Renamed project · just now", TypographyRole.P)
            ) { title("Recent activity") }
            toaster(model.toasts) { position = ToastPosition.BottomEnd }
            spacing = 16.0
            alignment = CrossAlignment.Start
        }
    return page(theme, content)
}

/** Paints the theme background and places the content at the top-left. */
fun page(theme: Theme, content: View): View =
    frame(content) {
        padding = Some(Insets.all(24.0))
        alignment = Alignment(AxisAlignment.Start, AxisAlignment.Start)
        style { background(Some(Paint(theme.tokens.palette.background.background))) }
    }

class ModalDemo(scope: ComponentScope): Component(scope) {
    private val model = ProjectModel()
    private val theme = currentThemeSource()
    public override fun render(): View = modalPage(model, theme.current.value)
}

fun main() {
    val source = ThemeSource(shadcnTheme(ThemeMode.Light))
    context(source) {
        runUiApplication("Dialogs", { scope -> ModalDemo(scope) })
    }
}

scoop run ui-overlays-modal.scoop --release

对话框示例:点 Rename… 后背景变暗,中央是 Rename project 对话框

窗口显示标题 Project: Atlas 和四个按钮。点 Rename… 打开 Rename project 对话框,输入框已获得焦点,内容是当前名称;把它改成 Atlas Prime 再点 Save,对话框关闭,标题随之更新,右下角出现 “Project renamed” 的成功通知。点 Delete 打开确认框,焦点在 Keep project 上;点 Activity 会从底部滑出 Recent activity 抽屉。

这个例子没有使用 trigger(...):四个弹层都由页面上的普通按钮修改状态打开。startEdit() 在打开前用 draft.replaceAll(name.value) 把草稿重置为当前名称,这样取消后再次打开,看到的仍是最新名称。

11.4 菜单

菜单内容用 menu { } 构建,得到一个 MenuContent 值,同一份内容可以给不同的入口复用:

每个条目都需要一个稳定的 ViewKey,菜单靠它在重新 render 时保持焦点与悬停位置。入口有三种:

保存为 ui-overlays-menus.scoop(下载)。菜单项的快捷键标签用到了 scoop.window 中的 ShortcutChord,所以多声明了一个依赖:

//! dep: scoop:scoop.graphics:0.1.0
//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.shadcn:0.1.0
//! dep: scoop:scoop.window:0.1.0
import scoop.graphics.Paint
import scoop.ui.*
import scoop.ui.component.*
import scoop.ui.component.button as makeButton
import scoop.ui.component.column as makeColumn
import scoop.ui.style.Insets
import scoop.ui.style.Theme
import scoop.ui.style.ThemeMode
import scoop.ui.style.ThemeSource
import scoop.ui.style.currentThemeSource
import scoop.ui.style.shadcn.shadcnTheme
import scoop.window.LogicalKey
import scoop.window.ShortcutChord
import scoop.window.ShortcutKey
import scoop.window.ShortcutModifiers

class MenuModel {
    val open = state(false)
    val statusBar = state(true)
    val appearance = state("System")
    val result = state("Choose a command")
}

fun fileMenu(model: MenuModel): MenuContent =
    menu {
        label(ViewKey.Text("title"), "Project")
        item(ViewKey.Text("open"), "Open…", { model.result.value = "Open" }) {
            shortcut =
                Some(
                    ShortcutChord(
                        ShortcutKey.Logical(LogicalKey.Character("o")),
                        ShortcutModifiers(primary = true)
                    )
                )
        }
        submenu(
            ViewKey.Text("share"),
            "Share",
            menu {
                item(ViewKey.Text("link"), "Copy link", { model.result.value = "Link copied" })
                item(ViewKey.Text("mail"), "Email…", { model.result.value = "Email" })
            }
        )
        separator(ViewKey.Text("sep-1"))
        checkboxItem(ViewKey.Text("status"), "Show status bar", model.statusBar.binding())
        label(ViewKey.Text("appearance"), "Appearance")
        for (name in ["System", "Light", "Dark"])
            radioItem(ViewKey.Text(name), name, name, model.appearance.binding())
        separator(ViewKey.Text("sep-2"))
        item(ViewKey.Text("delete"), "Delete", { model.result.value = "Deleted" }) {
            destructive = true
        }
    }

fun menuPage(model: MenuModel, theme: Theme): View {
    val canvas =
        makeButton("Right-click here", { model.result.value = "Normal click" }) {
            variant = ButtonVariant.Outline
            style { surface { padding = Some(Insets.all(32.0)) } }
        }
    val content =
        makeColumn {
            row {
                dropdownMenu(model.open.binding(), fileMenu(model)) {
                    trigger("File")
                    width = 220.0
                }
                contextMenu(canvas, fileMenu(model))
                spacing = 16.0
                alignment = CrossAlignment.Center
            }
            typography(model.result.value, TypographyRole.P)
            typography(
                f"Status bar: ${model.statusBar.value} · Appearance: ${model.appearance.value}",
                TypographyRole.Muted
            )
            spacing = 16.0
            alignment = CrossAlignment.Start
        }
    return page(theme, content)
}

/** Paints the theme background and places the content at the top-left. */
fun page(theme: Theme, content: View): View =
    frame(content) {
        padding = Some(Insets.all(24.0))
        alignment = Alignment(AxisAlignment.Start, AxisAlignment.Start)
        style { background(Some(Paint(theme.tokens.palette.background.background))) }
    }

class MenuDemo(scope: ComponentScope): Component(scope) {
    private val model = MenuModel()
    private val theme = currentThemeSource()
    public override fun render(): View = menuPage(model, theme.current.value)
}

fun main() {
    val source = ThemeSource(shadcnTheme(ThemeMode.Light))
    context(source) {
        runUiApplication("Menus", { scope -> MenuDemo(scope) })
    }
}

scoop run ui-overlays-menus.scoop --release

菜单示例:点 File 后弹出的菜单,包含命令、子菜单、勾选项、单选组和红色的 Delete

点 File 弹出菜单:第一组是 Open…(右侧显示 ⌘o)和带箭头的 Share 子菜单,下面是勾选项、Appearance 单选组和红色的 Delete。右键点击“Right-click here”方框会在指针处弹出同一份菜单。选择普通命令后菜单关闭,底部文字显示所选命令;勾选项和单选项在切换后保持菜单打开,方便连续调整,按 Escape 或点击外部关闭。方向键移动高亮,直接键入字母可以跳到以它开头的条目。

横向菜单栏的写法:

menubar(model.bar.binding()) {
    menu(
        ViewKey.Text("file"),
        "File",
        menu { item(ViewKey.Text("new"), "New", { model.save() }) }
    )
}

其中 model.bar 是 state<ViewKey?>(None)。这些都是窗口内自绘的菜单;系统菜单栏、原生右键菜单见桌面集成。

11.5 通知 Toast

Toast 是窗口一角短暂出现的通知。它不使用 open 绑定,而是由一个 ToastState 管理队列:

  1. 在模型中创建 val toasts = ToastState();
  2. 在页面中放一个 toaster(model.toasts),它负责显示,position 选择六个位置之一(例如 ToastPosition.BottomEnd);
  3. 在回调里调用 toasts.show(title) { kind = ...; description(...) }。

kind 有 Default、Success、Info、Warning、Error、Loading 六种。show 返回 ToastId,可以随后原位更新或关闭同一条通知:

val id = toasts.show("Saving…") { kind = ToastKind.Loading }
toasts.update(id, "Saved") { kind = ToastKind.Success }

update 和 dismiss(id) 在通知已经关闭时返回 false,后台任务晚到的结果因此不会让一条旧通知重新出现。默认 5 秒后自动消失,指针悬停、获得焦点或窗口失去焦点时暂停计时;duration = None 表示不自动关闭,action("Undo", onClick) 添加一个操作按钮。一个 ToastState 同一时刻只能交给一个 toaster 显示。在后台任务中更新通知的完整写法见桌面集成与异步。

11.6 焦点:打开时去哪里,关闭后回到哪里

弹层打开时,焦点自动移入弹层:默认是其中第一个可聚焦的控件(AlertDialog 是取消按钮)。关闭后,焦点默认回到打开前所在的控件,通常就是触发器。这些行为由 OverlayFocusOptions 描述:

字段 默认 含义
initialFocus None 打开后聚焦的 FocusHandle
autoFocus true 没有指定 initialFocus 时是否自动聚焦第一个控件
restoreFocus true 关闭后是否恢复焦点
restoreTarget None 关闭后改为聚焦这个 FocusHandle

既可以像 11.2 节那样直接构造 OverlayFocusOptions(Some(handle)),也可以用配置块逐项修改:

dialog(guardedOpen(model.open, model.locked), form) {
    title("Rename")
    focus {
        initialFocus = Some(model.nameFocus)
        restoreTarget = Some(model.triggerFocus)
    }
    onCloseRequest = { reason -> reason != OverlayCloseReason.OutsidePress }
}

这个对话框打开时聚焦名称输入框,关闭后焦点回到 triggerFocus 对应的控件;点击遮罩不会关闭它,Escape 和关闭按钮仍然有效。弹层可以嵌套(对话框里再开 Sheet),每关闭一层,焦点回到上一层中原来的位置。

12. 导航与工作区布局

12.1 Tabs、面包屑与导航菜单

三种控件解决不同层级的导航:

这些控件只负责呈现和交互,“跳转到哪一页”由应用自己的状态决定。保存为 ui-overlays-nav.scoop(下载):

//! dep: scoop:scoop.graphics:0.1.0
//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.shadcn:0.1.0
import scoop.graphics.Paint
import scoop.ui.*
import scoop.ui.component.*
import scoop.ui.component.column as makeColumn
import scoop.ui.component.input as makeInput
import scoop.ui.component.typography as makeText
import scoop.ui.style.Insets
import scoop.ui.style.Theme
import scoop.ui.style.ThemeMode
import scoop.ui.style.ThemeSource
import scoop.ui.style.currentThemeSource
import scoop.ui.style.shadcn.shadcnTheme
import scoop.ui.text.TextEditorState

class NavModel {
    val page = state("Overview")
    val menuOpen = state<ViewKey?>(None)
    val tab = state<Int?>(Some(0))
    val notes = TextEditorState("Drafts survive switching tabs.")

    fun navigate(target: String) {
        page.value = target
        menuOpen.value = None
    }
}

fun guidesPanel(model: NavModel): View =
    makeColumn {
        navigationMenuLink("Getting started", { model.navigate("Getting started") })
        navigationMenuLink("Language guide", { model.navigate("Language guide") })
        navigationMenuLink("UI tutorial", { model.navigate("UI tutorial") })
        spacing = 4.0
        alignment = CrossAlignment.Stretch
    }

fun navPage(model: NavModel, theme: Theme): View {
    val overview = makeText(f"You are reading: ${model.page.value}", TypographyRole.P)
    val notes = makeInput(model.notes)
    val content =
        makeColumn {
            navigationMenu(Some(model.menuOpen.binding())) {
                link(ViewKey.Text("home"), "Home", { model.navigate("Overview") })
                item(ViewKey.Text("guides"), "Guides", guidesPanel(model))
            }
            breadcrumb {
                item("Home", { model.navigate("Overview") })
                item("Guides", { model.navigate("Guides") })
                current(model.page.value)
            }
            tabs(model.tab.binding()) {
                variant = TabsVariant.Line
                retention = ContentRetention.KeepMounted
                item(Choice(ViewKey.Text("overview"), 0, "Overview"), overview)
                item(Choice(ViewKey.Text("notes"), 1, "Notes"), notes)
            }
            spacing = 20.0
            alignment = CrossAlignment.Stretch
        }
    return page(theme, content)
}

/** Paints the theme background and places the content at the top-left. */
fun page(theme: Theme, content: View): View =
    frame(content) {
        padding = Some(Insets.all(24.0))
        alignment = Alignment(AxisAlignment.Start, AxisAlignment.Start)
        style { background(Some(Paint(theme.tokens.palette.background.background))) }
    }

class NavDemo(scope: ComponentScope): Component(scope) {
    private val model = NavModel()
    private val theme = currentThemeSource()
    public override fun render(): View = navPage(model, theme.current.value)
}

fun main() {
    val source = ThemeSource(shadcnTheme(ThemeMode.Light))
    context(source) {
        runUiApplication("Navigation", { scope -> NavDemo(scope) })
    }
}

scoop run ui-overlays-nav.scoop --release

导航示例:顶部导航菜单、Home › Guides › Overview 面包屑和 Overview/Notes 页签

窗口顶部是 Home 和带下拉箭头的 Guides;下面是面包屑 Home › Guides › Overview,再下面是 Overview / Notes 两个页签。悬停或点击 Guides 展开三个链接,点 Language guide 后面板收起,面包屑末项和正文都变成 Language guide。切到 Notes 页签修改输入框,再切回 Overview 又切回来,修改仍在——这是 KeepMounted 的效果。

12.2 侧栏、可调面板与命令面板

桌面应用常见的工作区由三部分组成:

侧栏 sidebar(open, content) { inset(main) }。 open 表示展开还是收起,inset(...) 是侧栏旁边的主区域。content 可以是一个 View,也可以是 { shown -> ... } 形式的函数:shown 是 SidebarPresentation,其中 collapsed 告诉你当前是否处于收起状态,便于只显示图标。主要配置:

侧栏内的导航条目用 sidebarMenu { item(key, label, onClick) { active = ...; icon(view) } } 编写,它的 collapsed 属性应跟随 shown.collapsed。sidebarTrigger(open) 生成标准的切换按钮。改成移出式、放在右侧的侧栏:

sidebar(model.nav.binding(), links) {
    collapsible = SidebarCollapse.Offcanvas
    side = SidebarSide.End
    inset(main)
}

可调面板 resizable(sizes) { panel(key, content) }。 sizes 是 Binding<Array<ResizableSize>>,每项记录一个面板 key 及其所占比例(例如 0.7 和 0.3),拖动把手时更新它。panel 的配置块可设 minimum / maximum(逻辑像素)和 collapsible;withHandle = true 在分隔线上显示可见的拖动把手,把手也能用 Tab 聚焦后按方向键调整。orientation = Orientation.Vertical 改为上下分割。比例保存在你的状态里,因此可以持久化,也可以通过修改状态恢复默认布局。

命令面板 command(source, query)。 source 通常用 commandItems { group(key, title) { item(key, text, onRun) } } 构建,query 是一个 TextEditorState,保存搜索框中的文字。默认使用模糊匹配(CommandFilter.Ranked),标题和 keywords 都参与搜索;方向键移动高亮时焦点始终留在搜索框,Enter 执行高亮的命令,onSelect 在执行后调用。命令面板本身只是一个普通控件,放进 dialog 就成了常见的“⌘K 面板”。需要自己提供搜索结果时可改用 filter = CommandFilter.Provided。

12.3 实战:一个精简的工作区

下面把上述控件组合起来:左侧是可收起为图标栏的导航,右侧顶部是侧栏开关和 Commands 按钮,下面是 Document / Preview 两个页签;Document 页签中是左右可调的编辑区和检查器,Commands 打开一个包含命令面板的对话框。保存为 ui-overlays-workspace.scoop(下载):

//! dep: scoop:scoop.graphics:0.1.0
//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.shadcn:0.1.0
import scoop.graphics.Paint
import scoop.ui.*
import scoop.ui.component.*
import scoop.ui.component.column as makeColumn
import scoop.ui.component.command as makeCommand
import scoop.ui.component.frame as makeFrame
import scoop.ui.component.resizable as makeResizable
import scoop.ui.component.sidebarMenu as makeSidebarMenu
import scoop.ui.component.textarea as makeEditor
import scoop.ui.component.typography as makeText
import scoop.ui.style.Insets
import scoop.ui.style.Theme
import scoop.ui.style.ThemeMode
import scoop.ui.style.ThemeSource
import scoop.ui.style.currentThemeSource
import scoop.ui.style.shadcn.shadcnTheme
import scoop.ui.text.TextEditorState

class WorkspaceModel {
    val navigation = state(true)
    val tab = state<Int?>(Some(0))
    val commandsOpen = state(false)
    val log = state("Ready")
    val draft = TextEditorState("Write the project plan here.")
    val query = TextEditorState()
    val queryFocus = FocusHandle()
    val sizes =
        state(
            [
                ResizableSize(ViewKey.Text("editor"), 0.7),
                ResizableSize(ViewKey.Text("inspector"), 0.3)
            ]
        )
    val commands = workspaceCommands(this)

    fun openCommands() {
        query.replaceAll("")
        commandsOpen.value = true
    }
}

fun workspaceCommands(model: WorkspaceModel): CommandContent =
    commandItems {
        group(ViewKey.Text("view"), "View") {
            item(ViewKey.Text("document"), "Show document", { model.tab.value = Some(0) })
            item(ViewKey.Text("preview"), "Show preview", { model.tab.value = Some(1) }) {
                keywords = ["read", "render"]
            }
            item(
                ViewKey.Text("sidebar"),
                "Toggle sidebar",
                { model.navigation.value = !model.navigation.value }
            )
        }
        group(ViewKey.Text("project"), "Project") {
            item(ViewKey.Text("save"), "Save draft", { model.log.value = "Draft saved" })
        }
    }

fun navigationMenuFor(model: WorkspaceModel, collapsed: Boolean): View =
    makeSidebarMenu {
        this.collapsed = collapsed
        item(ViewKey.Text("document"), "Document", { model.tab.value = Some(0) }) {
            active = model.tab.value == Some(0)
            icon(makeText("D", TypographyRole.Small))
        }
        item(ViewKey.Text("preview"), "Preview", { model.tab.value = Some(1) }) {
            active = model.tab.value == Some(1)
            icon(makeText("P", TypographyRole.Small))
        }
    }

fun editorPanels(model: WorkspaceModel): View =
    makeResizable(model.sizes.binding()) {
        panel(
            ViewKey.Text("editor"),
            makeFrame(makeEditor(model.draft) { rows = 10L }) { padding = Some(Insets.all(8.0)) }
        ) { minimum = 200.0 }
        panel(
            ViewKey.Text("inspector"),
            makeColumn {
                typography("Inspector", TypographyRole.Small)
                typography(model.log.value, TypographyRole.Muted)
                spacing = 8.0
                padding = Insets.all(8.0)
            }
        ) {
            minimum = 120.0
            collapsible = true
        }
        withHandle = true
    }

fun workspaceContent(model: WorkspaceModel): View =
    makeColumn {
        row {
            sidebarTrigger(model.navigation.binding())
            button("Commands", { model.openCommands() }) { variant = ButtonVariant.Outline }
            spacing = 8.0
            alignment = CrossAlignment.Center
        }
        tabs(model.tab.binding()) {
            variant = TabsVariant.Line
            retention = ContentRetention.KeepMounted
            item(Choice(ViewKey.Text("document"), 0, "Document"), editorPanels(model))
            item(Choice(ViewKey.Text("preview"), 1, "Preview"), makeText(model.draft.text))
        }
        dialog(
            model.commandsOpen.binding(),
            makeCommand(model.commands, model.query) {
                focus = FocusOptions(Some(model.queryFocus))
                onSelect = { _ -> model.commandsOpen.value = false }
            }
        ) {
            title("Commands")
            focus { initialFocus = Some(model.queryFocus) }
        }
        spacing = 12.0
        padding = Insets.all(12.0)
        alignment = CrossAlignment.Stretch
    }

fun workspacePage(model: WorkspaceModel, theme: Theme): View {
    val shell =
        sidebar(
            model.navigation.binding(),
            { shown -> navigationMenuFor(model, shown.collapsed) }
        ) {
            variant = SidebarVariant.Inset
            collapsible = SidebarCollapse.Icon
            rail = true
            header {
                shown -> makeText(
                    if (shown.collapsed)
                        "A"
                    else
                        "Atlas",
                    TypographyRole.Small
                )
            }
            inset(workspaceContent(model))
        }
    return makeFrame(shell) {
        style { background(Some(Paint(theme.tokens.palette.background.background))) }
    }
}

class Workspace(scope: ComponentScope): Component(scope) {
    private val model = WorkspaceModel()
    private val theme = currentThemeSource()
    public override fun render(): View = workspacePage(model, theme.current.value)
}

fun main() {
    val source = ThemeSource(shadcnTheme(ThemeMode.Light))
    context(source) {
        runUiApplication("Workspace", { scope -> Workspace(scope) })
    }
}

scoop run ui-overlays-workspace.scoop --release

工作区示例:左侧侧栏,右侧页签与可调面板,中央打开了 Commands 命令面板

可以这样试用:

  1. 在编辑区输入几行文字,拖动编辑区与 Inspector 之间的把手调整宽度;也可以按 Tab 把焦点移到把手上,再用左右方向键调整。Inspector 设置了 collapsible = true,宽度拖到小于 minimum 时会折叠到 collapsedSize(默认 0),而不是停在一个过窄的宽度。
  2. 点左上角的侧栏按钮或按 ⌘B,侧栏收窄为只显示 A、D、P 的图标栏;再按一次恢复。
  3. 点 Commands,输入 render,结果中出现 Show preview(它的 keywords 包含 render),按 Enter 后对话框关闭并切换到 Preview 页签,显示刚才输入的文字。
  4. 切回 Document,之前的文字和面板宽度都还在。

这个程序里所有“当前状态”——侧栏是否展开、当前页签、面板比例、对话框是否打开、草稿文字——都在 WorkspaceModel 中。侧栏菜单、页签和命令面板只是同一份状态的三个入口:侧栏点 Preview、页签点 Preview、命令面板执行 Show preview,修改的都是 model.tab,因此三处显示始终一致。命令对话框通过 focus { initialFocus = Some(model.queryFocus) } 在打开时直接聚焦搜索框;openCommands() 在打开前清空上次的搜索词。

常见错误与继续阅读

现象 原因与处理
把 button(...) 传给 tooltip 或 dialog 时报 “argument must be of type View, found Unit” 在 builder 块里,button 是“添加子项”的成员函数;先在块外构造好 View,或用 import ... as makeButton 调用顶层函数
onCloseRequest 返回 false,弹层仍被关闭 代码直接写了 open.value = false;需要受拦截的关闭请用 OverlayHandle.requestClose()
AlertDialog 点了确认按钮却不关闭 action 不会替应用关闭,在回调中把状态改回 false
触发按钮被拉伸到整行宽 外层 column 拉伸了子项;把弹层放进 row 或给外层设置合适的对齐
菜单报重复 key,或重新 render 后高亮跳动 每个菜单条目、侧栏条目都要有唯一且稳定的 ViewKey
Toast 不显示 页面中没有放 toaster(state),或同一个 ToastState 交给了多个 toaster
关闭对话框后焦点回到了意外的位置 用 focus { restoreTarget = Some(handle) } 指定关闭后的焦点

下一篇数据展示介绍卡片、表格、日历、图表和会话组件。弹层与焦点的完整规则见 Scoop 仓库的 UI 规范;各控件的全部配置项可以在 API 文档中查找。以上示例在 macOS 上验证,Linux 上用法相同。