Skip to content

Mobile Provider 移动端提供器 ​

为一段页面选择移动端视觉风格,并把安全区信息传给 NavBar、Popup、SafeArea 等组件。

何时使用 ​

  • 需要在自绘页面中组合移动端组件时,在页面根部调用 mobile.Provider。
  • 需要切换 Ant Design Mobile、Vant 或 shadcn 移动风格时使用 Options.Style。
  • 宿主已经提供安全区时通常不设置 Options.SafeArea;模拟设备或需要覆盖宿主值时再传入 *geom.Insets。
  • 不要把 Provider 当作全局主题配置;桌面组件的主题仍由 ui.ConfigProvider 和 ui.Theme 管理。

在线体验 ​

下方示例展示 Provider 包裹的真实移动端页面,可切换主题和明暗模式。

Mobile · 导航:NavBar / SearchBar / Tabs / NoticeBar / Grid / TabBar · 在线体验真实 Go 组件
在独立页面打开 ↗

查看此场景的 Go 源码 ↗

基本用法 ​

Provider 通过闭包建立作用域;作用域内的移动组件会读取同一套风格和安全区。

go
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 只影响移动组件的令牌和外观,组件调用方式不变。

go
func vantPage(c *ui.Context) {
    mobile.Provider(c, mobile.Options{Style: mobile.Vant}, func() {
        mobile.Button(c, "确认").Primary()
    })
}

覆盖安全区 ​

SafeArea 覆盖当前 Provider 读取到的窗口安全区,适合设备模拟和测试。

go
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> 命名空间;显式链式方法优先于默认值。

go
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 的移动主题,可用于自定义内容而不硬编码颜色。

go
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。

加载中…

Mobile · 移动端示例应用

gallery 演示 MobileApp 的 Render 函数,源码 page_mobile_gallery.go#L134。

加载中…

API ​

签名与说明由 site/tools/compdoc 从 Go 源码和文档注释提取;点击名称跳到 Go API 参考 的对应条目。

入口函数 ​

mobile.Provider ​

go
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 ​

go
func ThemeOf(c *ui.Context) *Theme

ThemeOf returns the mobile theme in effect.

返回 *Theme,可链式调用的方法见 Theme 方法。

mobile.NewTheme ​

go
func NewTheme(base *theme.Theme, style Style) *Theme

NewTheme 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 ​

go
func HighContrast(th *Theme) *Theme

HighContrast 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.

字段说明类型
StyleStyle
Darkbool
Base*theme.Theme
PrimaryBrand and status colors.theme.Color
SuccessBrand and status colors.theme.Color
WarningBrand and status colors.theme.Color
DangerBrand and status colors.theme.Color
PrimaryLighttinted background (tags, notice bars)theme.Color
TextNeutrals.theme.Color
TextSecondaryNeutrals.theme.Color
TextWeakNeutrals.theme.Color
TextLightNeutrals.theme.Color
Borderhairlines between cellstheme.Color
PageBgpage background behind liststheme.Color
Boxcells, bars, panelstheme.Color
Fillstepper buttons, search fields, skeletontheme.Color
Pressoverlay drawn over a pressed itemtheme.Color
Masktheme.Color
ToastBgtheme.Color
OnPrimarytext on solid colored controlstheme.Color
FontTinyTypography (logical px; 1pt = 1px at the mobile reference density).float32
FontSmallTypography (logical px; 1pt = 1px at the mobile reference density).float32
FontMainTypography (logical px; 1pt = 1px at the mobile reference density).float32
FontBodyTypography (logical px; 1pt = 1px at the mobile reference density).float32
FontTitleTypography (logical px; 1pt = 1px at the mobile reference density).float32
FontLargeTypography (logical px; 1pt = 1px at the mobile reference density).float32
TouchMinGeometry.float32
PadHhorizontal page paddingfloat32
Radiusfloat32
RadiusLargefloat32
PopupRadfloat32
NavBarHeightfloat32
TabBarHeightfloat32
CellPadVfloat32
CellMinHeightfloat32
ButtonHeightMini, Small, Middle, Large[4]float32
ButtonFont[4]float32
ButtonRadiusfloat32
PickerItemHeightfloat32
PickerVisiblerows shown in a picker wheelint
TabsHeightfloat32
TabsLineWidth0 width = as wide as the titlefloat32
TabsLineHeight0 width = as wide as the titlefloat32
DialogWidthfloat32
ActionHeightfloat32
ToastPadfloat32
SearchHeightfloat32
SearchRadiusfloat32
StepperHeightfloat32
StepperInputWfloat32
BadgeColortheme.Color
NoticeBgtheme.Color
NoticeTexttheme.Color
TitleWeighttext.Weight
FormLabelWidthfloat32
OnSolidTokens of the shadcn derivation; the Ant Mobile and Vant values keep their looks (zero colors mean "none").theme.Color
ButtonWeightbutton label weighttext.Weight
CardBorderoutline of lists, cards, sheets and dialogstheme.Color
DrawerHandlegrab handle on top of bottom sheetstheme.Color
ToastTexttoast message color (on ToastBg)theme.Color
ToastBordertoast outlinetheme.Color
NoticeBordernotice bar top / bottom linestheme.Color
SwitchOffswitch track when offtheme.Color
SwitchThumbswitch thumb when offtheme.Color
SwitchThumbOnswitch thumb when ontheme.Color
SwitchWswitch track sizefloat32
SwitchHfloat32
Ringkeyboard focus outlinetheme.Color
SegmentThumbselected tab of the segmented (shadcn) Tabstheme.Color

Theme 的方法:

方法说明签名
ColorOfColorOf maps a status name ("primary", "success", "warning", "danger", "default") to a color.ColorOf(name string) theme.Color
FontFont 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.

字段说明类型
StyleStyle
SafeAreaSafeArea 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.

字段说明类型
Namestring
FlavorFlavor
Darkbool
HighContrastHighContrast is set on themes built by the HighContrast function.bool
IconsIcons 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
PrimaryPalette
SuccessPalette
WarningPalette
ErrorPalette
InfoPalette
TextNeutral text.Color
TextHeadingColor
TextSecondaryColor
TextTertiaryColor
TextQuaternaryplaceholder / disabled textColor
TextDisabledColor
TextOnPrimarytext on solid colored controlsColor
TextLinkColor
TextLinkHoverColor
TextLinkActiveColor
BorderBorders and fills.Color
BorderHoverinput border under the pointerColor
BorderSecondarycolorBorderSecondary (cards, tables, dividers)Color
SplitColor
Fillstrongest neutral fillColor
FillSecondaryColor
FillTertiaryColor
FillQuaternaryColor
FillAltertable header / zebra rowsColor
BgContainerBackgrounds.Color
BgElevatedpopovers, dropdowns, modalsColor
BgLayoutColor
BgSpotlighttooltip backgroundColor
BgMaskColor
BgContainerDisabledColor
BgTextHoverColor
BgTextActiveColor
ItemHoverBgSelection inside menus, selects, trees.Color
ItemSelectedBgColor
ItemSelectedtext color of selected itemColor
ControlOutlineFocus ring: Ant draws an outer shadow, Element a tinted border, shadcn a ring separated from the control by an offset gap.Color
ControlOutlineWidthhalo widthfloat32
ControlOutlineOffsetgap between the control edge and the halo (0: halo touches the border)float32
ControlOutlineErrorhalo of a focused input in error statusColor
ControlOutlineWarninghalo of a focused input in warning statusColor
ControlFocusBorderborder of a focused inputColor
FocusRing:focus-visible outline of small controls (icon buttons, tags)Color
FocusOutline:focus-visible ring of buttons, checkboxes, switchesColor
FocusRingWidthwidth of the FocusOutline ringfloat32
FocusRingOffsetgap between the control and the FocusOutline ringfloat32
TextOnSpotlightText on special surfaces.Color
TextOnSolidtext on solid success/warning/error fills (badges, danger buttons)Color
ButtonFontWeightButtons.int
ButtonPaddingHHorizontal padding, middle size.float32
ButtonPaddingHSMDeprecated: use Components.Button.PaddingInlineSM and Components.Button.PaddingInlineLG (the field remains the source of the derived default).float32
ButtonPaddingHLGDeprecated: use Components.Button.PaddingInlineSM and Components.Button.PaddingInlineLG (the field remains the source of the derived default).float32
SecondaryBg"secondary" button / neutral filled controlsColor
SecondaryText"secondary" button / neutral filled controlsColor
SecondaryBgHoverColor
LabelFontWeightCheckbox / radio label weight.int
SwitchHandleSwitch thumb.Color
SwitchOffBgSwitch track when off.Color
SwitchOffBgHoverDeprecated: use Components.Switch.OffHoverBg (the field remains the source of the derived default).Color
SwitchHeightMiddle-size track height (width follows the design system)float32
SwitchWidthDeprecated: use Components.Switch.TrackMinWidth (the field remains the source of the derived default).float32
CheckboxSizeDeprecated: use Components.Checkbox.ControlInteractiveSize / Components.Radio.RadioSize (the field remains the source of the derived default).float32
CheckboxRadiusfloat32
ControlBgData-entry surfaces (shad2a).Color
ControlBgHoverData-entry surfaces (shad2a).Color
ButtonDangerBgDeprecated: use Components.Button.DangerBg (the field remains the source of the derived default).Color
SwitchHandleOffDeprecated: use Components.Switch.HandleOffBg (the field remains the source of the derived default).Color
RateStarDeprecated: use Components.Rate.StarColor and Components.Rate.StarBg (the field remains the source of the derived default).Color
RateStarEmptyDeprecated: use Components.Rate.StarColor and Components.Rate.StarBg (the field remains the source of the derived default).Color
SliderRailHeightDeprecated: use Components.Slider.RailSize (the field remains the source of the derived default).float32
CardBorderCards and overlays.Color
CardShadow[]paint.Shadow
CardRadiusCard corner radius (zero: the design system default, RadiusLG / Element Radius)float32
PopupBorderdropdown / popover / select panel outline (zero: none)Color
ModalBorderDialog outline (zero: none)Color
TooltipShadowsmall floating tips (FloatButton, Slider)[]paint.Shadow
TableHeaderTextDeprecated: use Components.Table.HeaderColor (the field remains the source of the derived default).Color
TableHeaderWeightDeprecated: use Components.Table.HeaderFontWeight (the field remains the source of the derived default).int
TableSorterIdleSorter / filter icon when inactive.Color
TableFixedShadowAlphaOpacity of the shadow beside fixed columns.float64
TableSortedBgBody cells of the sorted column (zero: no column tint)Color
TableHeaderActiveBgHeader cell of the sorted / hovered sortable column (zero: none)Color
StatusDefaultBadge status="default" dot.Color
AvatarBgDeprecated: use Components.Avatar.Bg (the field remains the source of the derived default).Color
AvatarTextDeprecated: use Components.Avatar.Color (the field remains the source of the derived default).Color
SkeletonBgDeprecated: use Components.Skeleton.GradientFromColor (the field remains the source of the derived default).Color
SkeletonHighlightDeprecated: use Components.Skeleton.GradientToColor (the field remains the source of the derived default).Color
SkeletonIconPicture placeholder icon of Skeleton.Image.Color
AddonBgInput addon / Compact addon background.Color
AddonTextDeprecated: use Components.Input.AddonColor (the field remains the source of the derived default).Color
MarkTextText over MarkBg (zero: keep the span color)Color
MarkBgTypography Mark highlight.Color
IllustrationIllustration
LineHeightsLineHeights maps a font size to its line height in px; nil uses Ant's rule (size + 8, rounded to even).map[float32]float32
ShadcnShadcn holds the shadcn/ui CSS variable values and the options the theme was built with; nil for the other design systems.*ShadcnVars
RadiusGeometry.float32
RadiusSMGeometry.float32
RadiusLGGeometry.float32
RadiusXSGeometry.float32
ControlHeightfloat32
ControlHeightSMfloat32
ControlHeightLGfloat32
ControlPaddingHhorizontal padding inside inputs/buttonsfloat32
ControlPaddingHSMfloat32
LineWidthfloat32
FontFamilyTypography (logical px).string
FontSizefloat32
FontSizeSMfloat32
FontSizeLGfloat32
FontSizeXLfloat32
Headingh1..h5[5]float32
LineHeightratio: 22/14 for Antfloat32
FontWeightStrongint
PaddingXXSSpacing scale.float32
PaddingXSSpacing scale.float32
PaddingSMSpacing scale.float32
PaddingSpacing scale.float32
PaddingMDSpacing scale.float32
PaddingLGSpacing scale.float32
PaddingXLSpacing scale.float32
MarginXSfloat32
MarginSMfloat32
Marginfloat32
MarginMDfloat32
MarginLGfloat32
MarginXLfloat32
ShadowShadows.[]paint.Shadow
ShadowSecondarymodals, message, notification[]paint.Shadow
ShadowTertiarycards[]paint.Shadow
ButtonShadow[]paint.Shadow
InputShadowinputs and selects (shadcn shadow-xs)[]paint.Shadow
PrimaryShadowDeprecated: use Components.Button.PrimaryShadow (the field remains the source of the derived default).[]paint.Shadow
DangerShadowDeprecated: use Components.Button.DangerShadow (the field remains the source of the derived default).[]paint.Shadow
DurationFastMotion.time.Duration
DurationMidMotion.time.Duration
DurationSlowMotion.time.Duration
HeaderBgDeprecated: use Components.Layout.ProHeaderBg (the field remains the source of the derived default).Color
HeaderHeightDeprecated: use Components.Layout.ProHeaderHeight (the field remains the source of the derived default).float32
SiderBgdark siderColor
SiderLightBgColor
SiderWidthDeprecated: use Components.Layout.SiderWidth (the field remains the source of the derived default).float32
SiderCollapsedfloat32
SiderTextmenu text on dark siderColor
SiderTextActiveColor
SiderSubmenuBgDeprecated: 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
SiderItemHoverBgColor
MenuItemHeightDeprecated: use Components.Menu.ItemHeight (the field remains the source of the derived default).float32
TableHeaderBgDeprecated: use Components.Table.HeaderBg (the field remains the source of the derived default).Color
TableRowHoverBgDeprecated: use Components.Table.RowHoverBg (the field remains the source of the derived default).Color
TablePaddingVDeprecated: use Components.Table.CellPaddingBlock (the field remains the source of the derived default).float32
TablePaddingHDeprecated: use Components.Table.CellPaddingInline (the field remains the source of the derived default).float32
SegmentedBgSegmented control.Color
SegmentedSelectedBgsliding thumb under the selected itemColor
TabsHeaderBgTabs.Color
ComponentsComponents holds the resolved component tokens (components.go).Components

Theme 的方法:

方法说明签名
ButtonPaletteButtonPalette 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
CSSCSS returns the variables of CSSVars as a ":root" rule.CSS() string
CSSVarsCSSVars 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
CSSVarsWithCSSVarsWith is CSSVars plus the component tokens selected by o.CSSVarsWith(o CSSOptions) map[string]string
ColorOfColorOf returns the palette for a status name ("primary", "success", "warning", "error"/"danger", "info"); unknown names give Primary.ColorOf(status string) Palette
ForFor 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
LineHeightForLineHeightFor returns the theme-appropriate line height in px for a font size.LineHeightFor(size float32) float32
OverrideOverride 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
OverridesOverrides returns the component overrides t was built with.Overrides() Components
TextOnTextOn 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
UsesElementPlusControlsUsesElementPlusControls reports whether the Element Plus component refinements are enabled.UsesElementPlusControls() bool

相关链接 ​

以 MIT 许可发布