Mobile Provider 移动端提供器
为一段页面选择移动端视觉风格,并把安全区信息传给 NavBar、Popup、SafeArea 等组件。
何时使用
- 需要在自绘页面中组合移动端组件时,在页面根部调用
mobile.Provider。 - 需要切换 Ant Design Mobile、Vant 或 shadcn 移动风格时使用
Options.Style。 - 宿主已经提供安全区时通常不设置
Options.SafeArea;模拟设备或需要覆盖宿主值时再传入*geom.Insets。 - 不要把 Provider 当作全局主题配置;桌面组件的主题仍由
ui.ConfigProvider和ui.Theme管理。
在线体验
下方示例展示 Provider 包裹的真实移动端页面,可切换主题和明暗模式。
基本用法
Provider 通过闭包建立作用域;作用域内的移动组件会读取同一套风格和安全区。
import (
"github.com/tangoui/tango/ui"
"github.com/tangoui/tango/ui/layout"
"github.com/tangoui/tango/ui/mobile"
)
func page(c *ui.Context) {
mobile.Provider(c, mobile.Options{Style: mobile.AntMobile}, func() {
ui.Column(c, func() {
mobile.NavBar(c, "账户").Back("")
mobile.List(c, "").Body(func() {
mobile.Cell(c, "个人资料").Arrow()
})
}, layout.Grow(1))
})
}常见用法
选择 Vant 风格
Style 只影响移动组件的令牌和外观,组件调用方式不变。
func vantPage(c *ui.Context) {
mobile.Provider(c, mobile.Options{Style: mobile.Vant}, func() {
mobile.Button(c, "确认").Primary()
})
}覆盖安全区
SafeArea 覆盖当前 Provider 读取到的窗口安全区,适合设备模拟和测试。
import "github.com/tangoui/tango/ui/geom"
func devicePage(c *ui.Context) {
insets := geom.Insets{Top: 47, Bottom: 34}
mobile.Provider(c, mobile.Options{SafeArea: &insets}, func() {
mobile.NavBar(c, "设备预览")
mobile.SafeArea(c, mobile.Bottom)
})
}为组件设置默认值
ConfigProvider 的默认值使用 mobile.<Component> 命名空间;显式链式方法优先于默认值。
func defaultsPage(c *ui.Context) {
ui.ConfigProvider(c).
Defaults("mobile.Button", ui.Props{"size": "large", "shape": "round"}).
Body(func() {
mobile.Provider(c, mobile.Options{}, func() {
mobile.Button(c, "大号按钮")
})
})
}读取移动主题令牌
ThemeOf 返回当前 Provider 的移动主题,可用于自定义内容而不硬编码颜色。
func customPage(c *ui.Context) {
mobile.Provider(c, mobile.Options{}, func() {
th := mobile.ThemeOf(c)
ui.Text(c, "跟随移动主题").Color(th.TextSecondary)
})
}主题与样式
Provider 支持 AntMobile、Vant 和 Shadcn。它们共享组件 API,但令牌、圆角、间距和浮层视觉不同;暗色由外层 ui 主题提供。组件默认值可通过 ConfigProvider.Defaults("mobile.Button", ...) 等键配置,显式 modifier 总是覆盖默认值。
注意事项
Provider 只建立当前页面构建期间的作用域,状态仍放在页面函数外的变量或页面闭包中。安全区不要重复叠加:如果 Provider 已配置 SafeArea,底部再按需要调用一次 mobile.SafeArea(c, mobile.Bottom)。RTL 应由 ui.ConfigProvider(c).Direction(ui.RTL) 设置,Provider 会让移动组件跟随方向。
示例代码
以下是上方在线演示运行的 Go 源码(来自官方 gallery),点击标题展开。函数接收的 c *ui.Context 由窗口的 UI 循环每帧传入,接入方式见 Go GUI 入门。
Mobile · 导航:NavBar / SearchBar / Tabs / NoticeBar / Grid / TabBar
gallery 演示 MobileNav 的 Render 函数,源码 page_mobile_gallery.go#L134。
加载中…
API
签名与说明由 site/tools/compdoc 从 Go 源码和文档注释提取;点击名称跳到 Go API 参考 的对应条目。
入口函数
mobile.Provider
func Provider(c *ui.Context, o Options, fn func())Provider runs fn with the mobile options o (design style, safe area) and then renders imperative toasts queued with ShowToast. Wrap a mobile page in one Provider; without it components use the Ant Design Mobile style.
mobile.ThemeOf
func ThemeOf(c *ui.Context) *ThemeThemeOf returns the mobile theme in effect.
返回 *Theme,可链式调用的方法见 Theme 方法。
mobile.NewTheme
func NewTheme(base *theme.Theme, style Style) *ThemeNewTheme derives the mobile tokens for style from the ui theme base. Under a high-contrast base (theme.HighContrast) the neutrals are lifted to WCAG AA like the ui theme's: text 4.5:1, arrows, borders and switch tracks 3:1 (see highContrast).
返回 *Theme,可链式调用的方法见 Theme 方法。
theme.HighContrast
func HighContrast(th *Theme) *ThemeHighContrast returns a copy of th in which every required contrast pair of CheckContrast meets WCAG 2.2 AA — text 4.5:1, large text and the non-text parts that identify a control, its state or focus 3:1 — including the design-system defaults the stock themes keep (placeholder and tertiary text, links, input borders, switch tracks, primary and danger fills). Use it when the system asks for increased contrast (docs/accessibility.md, "Increase contrast"); it works on any theme, including WithPrimary and ShadcnOptions variants and app overrides.
The style is kept: geometry, typography, shadows, focus-ring shapes and hues do not change. Each color below its minimum moves the shortest distance (2% steps) towards the theme's own text color, then towards black (white on dark themes), so Ant Design stays Ant blue on white, Element stays Element and shadcn stays neutral — only with darker (in dark mode lighter) ink, borders and fills. A solid fill (Primary, Error) moves as a whole palette (hover and pressed shades follow) and keeps its label color when some shade satisfies both the label and the fill's own contrast on the page. In dark themes the danger color is both text on the page and the fill under a white label, and no red is light enough for one and dark enough for the other; the label then switches to the page's dark ink (TextOnSolid), the usual dark high-contrast arrangement.
Component tokens (Theme.Components) are processed after the global ones, overrides included: colors copied from a moved palette follow it, every field with a contrast tag reaches its minimum (components_contrast.go) and the Alias themes of Theme.For go through HighContrast too.
Exempt pairs (disabled controls, decorative rules) are left alone. The result has HighContrast set and reports label it "<style>-hc".
返回通用类型 *theme.Theme,其方法见 Theme 的 API。
Theme 方法
mobile.Theme:Theme holds the mobile design tokens. It is derived from the ui theme (dark mode, brand color, mask) and the selected Style (sizes, neutrals). Components capture it at build time; read it with ThemeOf.
| 字段 | 说明 | 类型 |
|---|---|---|
Style | Style | |
Dark | bool | |
Base | *theme.Theme | |
Primary | Brand and status colors. | theme.Color |
Success | Brand and status colors. | theme.Color |
Warning | Brand and status colors. | theme.Color |
Danger | Brand and status colors. | theme.Color |
PrimaryLight | tinted background (tags, notice bars) | theme.Color |
Text | Neutrals. | theme.Color |
TextSecondary | Neutrals. | theme.Color |
TextWeak | Neutrals. | theme.Color |
TextLight | Neutrals. | theme.Color |
Border | hairlines between cells | theme.Color |
PageBg | page background behind lists | theme.Color |
Box | cells, bars, panels | theme.Color |
Fill | stepper buttons, search fields, skeleton | theme.Color |
Press | overlay drawn over a pressed item | theme.Color |
Mask | theme.Color | |
ToastBg | theme.Color | |
OnPrimary | text on solid colored controls | theme.Color |
FontTiny | Typography (logical px; 1pt = 1px at the mobile reference density). | float32 |
FontSmall | Typography (logical px; 1pt = 1px at the mobile reference density). | float32 |
FontMain | Typography (logical px; 1pt = 1px at the mobile reference density). | float32 |
FontBody | Typography (logical px; 1pt = 1px at the mobile reference density). | float32 |
FontTitle | Typography (logical px; 1pt = 1px at the mobile reference density). | float32 |
FontLarge | Typography (logical px; 1pt = 1px at the mobile reference density). | float32 |
TouchMin | Geometry. | float32 |
PadH | horizontal page padding | float32 |
Radius | float32 | |
RadiusLarge | float32 | |
PopupRad | float32 | |
NavBarHeight | float32 | |
TabBarHeight | float32 | |
CellPadV | float32 | |
CellMinHeight | float32 | |
ButtonHeight | Mini, Small, Middle, Large | [4]float32 |
ButtonFont | [4]float32 | |
ButtonRadius | float32 | |
PickerItemHeight | float32 | |
PickerVisible | rows shown in a picker wheel | int |
TabsHeight | float32 | |
TabsLineWidth | 0 width = as wide as the title | float32 |
TabsLineHeight | 0 width = as wide as the title | float32 |
DialogWidth | float32 | |
ActionHeight | float32 | |
ToastPad | float32 | |
SearchHeight | float32 | |
SearchRadius | float32 | |
StepperHeight | float32 | |
StepperInputW | float32 | |
BadgeColor | theme.Color | |
NoticeBg | theme.Color | |
NoticeText | theme.Color | |
TitleWeight | text.Weight | |
FormLabelWidth | float32 | |
OnSolid | Tokens of the shadcn derivation; the Ant Mobile and Vant values keep their looks (zero colors mean "none"). | theme.Color |
ButtonWeight | button label weight | text.Weight |
CardBorder | outline of lists, cards, sheets and dialogs | theme.Color |
DrawerHandle | grab handle on top of bottom sheets | theme.Color |
ToastText | toast message color (on ToastBg) | theme.Color |
ToastBorder | toast outline | theme.Color |
NoticeBorder | notice bar top / bottom lines | theme.Color |
SwitchOff | switch track when off | theme.Color |
SwitchThumb | switch thumb when off | theme.Color |
SwitchThumbOn | switch thumb when on | theme.Color |
SwitchW | switch track size | float32 |
SwitchH | float32 | |
Ring | keyboard focus outline | theme.Color |
SegmentThumb | selected tab of the segmented (shadcn) Tabs | theme.Color |
Theme 的方法:
| 方法 | 说明 | 签名 |
|---|---|---|
ColorOf | ColorOf maps a status name ("primary", "success", "warning", "danger", "default") to a color. | ColorOf(name string) theme.Color |
Font | Font returns a text style of px size and weight with a mobile line height (1.5×, rounded). | Font(px float32, w text.Weight) text.Style |
Options 参数类型
mobile.Options:Options configure the mobile components inside a Provider.
| 字段 | 说明 | 类型 |
|---|---|---|
Style | Style | |
SafeArea | SafeArea overrides the window's safe-area insets (ui.Context.SafeArea, set by the host through ui.SafeAreaWindow or Runner.SetSafeArea). | *geom.Insets |
Theme 参数类型
theme.Theme:Theme is the complete token set read by components.
| 字段 | 说明 | 类型 |
|---|---|---|
Name | string | |
Flavor | Flavor | |
Dark | bool | |
HighContrast | HighContrast is set on themes built by the HighContrast function. | bool |
Icons | Icons restyles the icons components draw: the design system's own icons in place of the built-in set (AntIcons, ElementIcons, LucideIcons) and its stroke width. | *icon.Style |
Primary | Palette | |
Success | Palette | |
Warning | Palette | |
Error | Palette | |
Info | Palette | |
Text | Neutral text. | Color |
TextHeading | Color | |
TextSecondary | Color | |
TextTertiary | Color | |
TextQuaternary | placeholder / disabled text | Color |
TextDisabled | Color | |
TextOnPrimary | text on solid colored controls | Color |
TextLink | Color | |
TextLinkHover | Color | |
TextLinkActive | Color | |
Border | Borders and fills. | Color |
BorderHover | input border under the pointer | Color |
BorderSecondary | colorBorderSecondary (cards, tables, dividers) | Color |
Split | Color | |
Fill | strongest neutral fill | Color |
FillSecondary | Color | |
FillTertiary | Color | |
FillQuaternary | Color | |
FillAlter | table header / zebra rows | Color |
BgContainer | Backgrounds. | Color |
BgElevated | popovers, dropdowns, modals | Color |
BgLayout | Color | |
BgSpotlight | tooltip background | Color |
BgMask | Color | |
BgContainerDisabled | Color | |
BgTextHover | Color | |
BgTextActive | Color | |
ItemHoverBg | Selection inside menus, selects, trees. | Color |
ItemSelectedBg | Color | |
ItemSelected | text color of selected item | Color |
ControlOutline | Focus ring: Ant draws an outer shadow, Element a tinted border, shadcn a ring separated from the control by an offset gap. | Color |
ControlOutlineWidth | halo width | float32 |
ControlOutlineOffset | gap between the control edge and the halo (0: halo touches the border) | float32 |
ControlOutlineError | halo of a focused input in error status | Color |
ControlOutlineWarning | halo of a focused input in warning status | Color |
ControlFocusBorder | border of a focused input | Color |
FocusRing | :focus-visible outline of small controls (icon buttons, tags) | Color |
FocusOutline | :focus-visible ring of buttons, checkboxes, switches | Color |
FocusRingWidth | width of the FocusOutline ring | float32 |
FocusRingOffset | gap between the control and the FocusOutline ring | float32 |
TextOnSpotlight | Text on special surfaces. | Color |
TextOnSolid | text on solid success/warning/error fills (badges, danger buttons) | Color |
ButtonFontWeight | Buttons. | int |
ButtonPaddingH | Horizontal padding, middle size. | float32 |
ButtonPaddingHSM | Deprecated: use Components.Button.PaddingInlineSM and Components.Button.PaddingInlineLG (the field remains the source of the derived default). | float32 |
ButtonPaddingHLG | Deprecated: use Components.Button.PaddingInlineSM and Components.Button.PaddingInlineLG (the field remains the source of the derived default). | float32 |
SecondaryBg | "secondary" button / neutral filled controls | Color |
SecondaryText | "secondary" button / neutral filled controls | Color |
SecondaryBgHover | Color | |
LabelFontWeight | Checkbox / radio label weight. | int |
SwitchHandle | Switch thumb. | Color |
SwitchOffBg | Switch track when off. | Color |
SwitchOffBgHover | Deprecated: use Components.Switch.OffHoverBg (the field remains the source of the derived default). | Color |
SwitchHeight | Middle-size track height (width follows the design system) | float32 |
SwitchWidth | Deprecated: use Components.Switch.TrackMinWidth (the field remains the source of the derived default). | float32 |
CheckboxSize | Deprecated: use Components.Checkbox.ControlInteractiveSize / Components.Radio.RadioSize (the field remains the source of the derived default). | float32 |
CheckboxRadius | float32 | |
ControlBg | Data-entry surfaces (shad2a). | Color |
ControlBgHover | Data-entry surfaces (shad2a). | Color |
ButtonDangerBg | Deprecated: use Components.Button.DangerBg (the field remains the source of the derived default). | Color |
SwitchHandleOff | Deprecated: use Components.Switch.HandleOffBg (the field remains the source of the derived default). | Color |
RateStar | Deprecated: use Components.Rate.StarColor and Components.Rate.StarBg (the field remains the source of the derived default). | Color |
RateStarEmpty | Deprecated: use Components.Rate.StarColor and Components.Rate.StarBg (the field remains the source of the derived default). | Color |
SliderRailHeight | Deprecated: use Components.Slider.RailSize (the field remains the source of the derived default). | float32 |
CardBorder | Cards and overlays. | Color |
CardShadow | []paint.Shadow | |
CardRadius | Card corner radius (zero: the design system default, RadiusLG / Element Radius) | float32 |
PopupBorder | dropdown / popover / select panel outline (zero: none) | Color |
ModalBorder | Dialog outline (zero: none) | Color |
TooltipShadow | small floating tips (FloatButton, Slider) | []paint.Shadow |
TableHeaderText | Deprecated: use Components.Table.HeaderColor (the field remains the source of the derived default). | Color |
TableHeaderWeight | Deprecated: use Components.Table.HeaderFontWeight (the field remains the source of the derived default). | int |
TableSorterIdle | Sorter / filter icon when inactive. | Color |
TableFixedShadowAlpha | Opacity of the shadow beside fixed columns. | float64 |
TableSortedBg | Body cells of the sorted column (zero: no column tint) | Color |
TableHeaderActiveBg | Header cell of the sorted / hovered sortable column (zero: none) | Color |
StatusDefault | Badge status="default" dot. | Color |
AvatarBg | Deprecated: use Components.Avatar.Bg (the field remains the source of the derived default). | Color |
AvatarText | Deprecated: use Components.Avatar.Color (the field remains the source of the derived default). | Color |
SkeletonBg | Deprecated: use Components.Skeleton.GradientFromColor (the field remains the source of the derived default). | Color |
SkeletonHighlight | Deprecated: use Components.Skeleton.GradientToColor (the field remains the source of the derived default). | Color |
SkeletonIcon | Picture placeholder icon of Skeleton.Image. | Color |
AddonBg | Input addon / Compact addon background. | Color |
AddonText | Deprecated: use Components.Input.AddonColor (the field remains the source of the derived default). | Color |
MarkText | Text over MarkBg (zero: keep the span color) | Color |
MarkBg | Typography Mark highlight. | Color |
Illustration | Illustration | |
LineHeights | LineHeights maps a font size to its line height in px; nil uses Ant's rule (size + 8, rounded to even). | map[float32]float32 |
Shadcn | Shadcn holds the shadcn/ui CSS variable values and the options the theme was built with; nil for the other design systems. | *ShadcnVars |
Radius | Geometry. | float32 |
RadiusSM | Geometry. | float32 |
RadiusLG | Geometry. | float32 |
RadiusXS | Geometry. | float32 |
ControlHeight | float32 | |
ControlHeightSM | float32 | |
ControlHeightLG | float32 | |
ControlPaddingH | horizontal padding inside inputs/buttons | float32 |
ControlPaddingHSM | float32 | |
LineWidth | float32 | |
FontFamily | Typography (logical px). | string |
FontSize | float32 | |
FontSizeSM | float32 | |
FontSizeLG | float32 | |
FontSizeXL | float32 | |
Heading | h1..h5 | [5]float32 |
LineHeight | ratio: 22/14 for Ant | float32 |
FontWeightStrong | int | |
PaddingXXS | Spacing scale. | float32 |
PaddingXS | Spacing scale. | float32 |
PaddingSM | Spacing scale. | float32 |
Padding | Spacing scale. | float32 |
PaddingMD | Spacing scale. | float32 |
PaddingLG | Spacing scale. | float32 |
PaddingXL | Spacing scale. | float32 |
MarginXS | float32 | |
MarginSM | float32 | |
Margin | float32 | |
MarginMD | float32 | |
MarginLG | float32 | |
MarginXL | float32 | |
Shadow | Shadows. | []paint.Shadow |
ShadowSecondary | modals, message, notification | []paint.Shadow |
ShadowTertiary | cards | []paint.Shadow |
ButtonShadow | []paint.Shadow | |
InputShadow | inputs and selects (shadcn shadow-xs) | []paint.Shadow |
PrimaryShadow | Deprecated: use Components.Button.PrimaryShadow (the field remains the source of the derived default). | []paint.Shadow |
DangerShadow | Deprecated: use Components.Button.DangerShadow (the field remains the source of the derived default). | []paint.Shadow |
DurationFast | Motion. | time.Duration |
DurationMid | Motion. | time.Duration |
DurationSlow | Motion. | time.Duration |
HeaderBg | Deprecated: use Components.Layout.ProHeaderBg (the field remains the source of the derived default). | Color |
HeaderHeight | Deprecated: use Components.Layout.ProHeaderHeight (the field remains the source of the derived default). | float32 |
SiderBg | dark sider | Color |
SiderLightBg | Color | |
SiderWidth | Deprecated: use Components.Layout.SiderWidth (the field remains the source of the derived default). | float32 |
SiderCollapsed | float32 | |
SiderText | menu text on dark sider | Color |
SiderTextActive | Color | |
SiderSubmenuBg | Deprecated: use Components.Menu.DarkSubMenuItemBg / Components.Layout.TriggerBg (the field remains the source of the derived default of Components.Menu.DarkSubMenuItemBg, and of Layout.TriggerBg except in the light Ant theme, which uses antd's #002140). | Color |
SiderItemHoverBg | Color | |
MenuItemHeight | Deprecated: use Components.Menu.ItemHeight (the field remains the source of the derived default). | float32 |
TableHeaderBg | Deprecated: use Components.Table.HeaderBg (the field remains the source of the derived default). | Color |
TableRowHoverBg | Deprecated: use Components.Table.RowHoverBg (the field remains the source of the derived default). | Color |
TablePaddingV | Deprecated: use Components.Table.CellPaddingBlock (the field remains the source of the derived default). | float32 |
TablePaddingH | Deprecated: use Components.Table.CellPaddingInline (the field remains the source of the derived default). | float32 |
SegmentedBg | Segmented control. | Color |
SegmentedSelectedBg | sliding thumb under the selected item | Color |
TabsHeaderBg | Tabs. | Color |
Components | Components holds the resolved component tokens (components.go). | Components |
Theme 的方法:
| 方法 | 说明 | 签名 |
|---|---|---|
ButtonPalette | ButtonPalette derives the interaction palette (hover, active, tints) of an arbitrary button color with t's design-system algorithm, as Button does for the preset and hex colors of Button.Color. | ButtonPalette(c Color) Palette |
CSS | CSS returns the variables of CSSVars as a ":root" rule. | CSS() string |
CSSVars | CSSVars exports the main tokens as CSS custom properties, so a WebView page of the same application can reuse the colors and metrics of the self-drawn UI: | CSSVars() map[string]string |
CSSVarsWith | CSSVarsWith is CSSVars plus the component tokens selected by o. | CSSVarsWith(o CSSOptions) map[string]string |
ColorOf | ColorOf returns the palette for a status name ("primary", "success", "warning", "error"/"danger", "info"); unknown names give Primary. | ColorOf(status string) Palette |
For | For returns the theme a component reads: t with the component's Alias applied, or t itself (no allocation) when the component has none. | For(k Comp) *Theme |
LineHeightFor | LineHeightFor returns the theme-appropriate line height in px for a font size. | LineHeightFor(size float32) float32 |
Override | Override returns a copy of t with c layered over its component overrides and every component token re-derived (scoped themes of ConfigProvider). | Override(c Components) *Theme |
Overrides | Overrides returns the component overrides t was built with. | Overrides() Components |
TextOn | TextOn returns the color for text or marks drawn on a solid fill bg: onDark (the usual white of solid controls, e.g. TextOnSolid or a component's text token) unless bg is light (Luma above 0.75, such as shadcn's near-white primary in dark mode), where a dark color reads better — the theme's Text when it is dark, else BgContainer (dark themes, whose Text is light). | TextOn(bg, onDark Color) Color |
UsesElementPlusControls | UsesElementPlusControls reports whether the Element Plus component refinements are enabled. | UsesElementPlusControls() bool |