core

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 39 Imported by: 6 modules, 19 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package core is what NSGo apps are written with: elements, styles, the reactive graph and regions, the services an app asks for, and the shadow tree that turns them into mount items, laid out and with text prepared.

The values it shares with the platforms, such as geometry, colors and configurations, are defined in driver, the platform protocol, and aliased here, so apps import core alone. It never imports a platform package or cgo, so it builds and tests headless on every OS.

Index

Constants

View Source
const (
	// AccessNetwork is fetch and the images and videos loaded from the
	// network, by URL.
	AccessNetwork = "network"
	// AccessWebView is the pages a web view shows, by URL, with AccessInput the trusted input Ref.SendInput gives them, with AccessMedia the devices WebView.Media lets them capture, and with AccessCookies the cookies SetWebCookies writes, by a URL each goes to.
	AccessWebView = "webview"
	// AccessOpenURL is OpenURL, by URL.
	AccessOpenURL = "openUrl"
	// AccessClipboard is reading and writing the system clipboard.
	AccessClipboard = "clipboard"
	// AccessPicker is the system's photo, camera and file pickers.
	AccessPicker = "picker"
	// AccessSpeech is the microphone and the speech recognizer.
	AccessSpeech = "speech"
	// AccessTextToSpeech is speaking text aloud with the system's voices (Speak), refused with SpeakNotAllowed, and listing them (Voices).
	AccessTextToSpeech = "textToSpeech"
	// AccessStatusBar is setting the status bar.
	AccessStatusBar = "statusBar"
	// AccessNotifications is system notifications and the app's badge.
	AccessNotifications = "notifications"
	// AccessBiometrics is Face ID, Touch ID and device biometric unlock.
	AccessBiometrics = "biometrics"
	// AccessSignInWithApple is Sign in with Apple and its credentials' states.
	AccessSignInWithApple = "signInWithApple"
	// AccessPurchases is in-app purchases: the store's products, buying them, their transactions and updates.
	AccessPurchases = "purchases"
	// AccessSecrets is the app's secure store (Scope.Secrets), with Resource the service of a refused item.
	AccessSecrets = "secrets"
	// AccessPermissions is checking, asking for and opening the settings of the system's permissions, by the permission's key (AccessRequest.Resource), and guiding the user to give them.
	AccessPermissions = "permissions"
	// AccessOverlay is windows over other apps on Android (OpenOverlay), and desktop windows that let the pointer through to them (SetWindowPointerEvents), which TSX packages cannot declare.
	AccessOverlay = "overlay"
	// AccessAudio is the audio package's sounds and players, refused with AudioNotAllowed.
	AccessAudio = "audio"
	// AccessAuthSession is signing in through the system's authentication session (AuthSession).
	AccessAuthSession = "authSession"
	// AccessHost is the host's handlers, by name (CallHost, PostHost).
	AccessHost = "host"
	// AccessLocation is the location fixes Locate and WatchLocation give and PermissionLocation, AccessBackgroundLocation a stream that goes on in the background and PermissionBackgroundLocation, and AccessMotion the motion samples WatchMotion gives and PermissionMotion: three independent grants.
	AccessLocation           = "location"
	AccessBackgroundLocation = "backgroundLocation"
	AccessMotion             = "motion"
	// AccessFrontmostApp is the application in front on the desktop (Scope.FrontmostApp and Scope.CanReadFrontmostApp), as it says what else the user runs.
	AccessFrontmostApp = "frontmostApp"
)

The capabilities Access is asked for, by NSH's keys.

View Source
const (
	AccessInput   = "input"
	AccessMedia   = "media"
	AccessCookies = "cookies"
)

AccessInput is AccessRequest.Method for a web view's trusted input, AccessMedia for the devices its pages capture, and AccessCookies for a cookie written to the store every web view of the app shares, which no TSX capability grants.

View Source
const (
	// EdgeEffectAutomatic is soft under the bars.
	EdgeEffectAutomatic = driver.EdgeEffectAutomatic
	EdgeEffectSoft      = driver.EdgeEffectSoft
	EdgeEffectHard      = driver.EdgeEffectHard
	// EdgeEffectHidden draws none.
	EdgeEffectHidden = driver.EdgeEffectHidden
)
View Source
const (
	BorderSolid  = driver.BorderSolid
	BorderDashed = driver.BorderDashed
	BorderDotted = driver.BorderDotted
	BorderNone   = driver.BorderNone
	BorderHidden = driver.BorderHidden
)
View Source
const (
	GradientLinear = driver.GradientLinear
	GradientRadial = driver.GradientRadial
	GradientConic  = driver.GradientConic
)
View Source
const (
	ToTopLeft     = driver.ToTopLeft
	ToTopRight    = driver.ToTopRight
	ToBottomRight = driver.ToBottomRight
	ToBottomLeft  = driver.ToBottomLeft
)
View Source
const (
	ExtentFarthestCorner = driver.ExtentFarthestCorner
	ExtentClosestSide    = driver.ExtentClosestSide
	ExtentClosestCorner  = driver.ExtentClosestCorner
	ExtentFarthestSide   = driver.ExtentFarthestSide
)
View Source
const (
	ColorSpaceOklab      = driver.ColorSpaceOklab
	ColorSpaceSRGB       = driver.ColorSpaceSRGB
	ColorSpaceLinearSRGB = driver.ColorSpaceLinearSRGB
	ColorSpaceOklch      = driver.ColorSpaceOklch
)
View Source
const (
	FilterBlur       = driver.FilterBlur
	FilterBrightness = driver.FilterBrightness
	FilterContrast   = driver.FilterContrast
	FilterGrayscale  = driver.FilterGrayscale
	FilterHueRotate  = driver.FilterHueRotate
	FilterInvert     = driver.FilterInvert
	FilterOpacity    = driver.FilterOpacity
	FilterSaturate   = driver.FilterSaturate
	FilterSepia      = driver.FilterSepia
	FilterDropShadow = driver.FilterDropShadow
)
View Source
const (
	BlendNormal      = driver.BlendNormal
	BlendMultiply    = driver.BlendMultiply
	BlendScreen      = driver.BlendScreen
	BlendOverlay     = driver.BlendOverlay
	BlendDarken      = driver.BlendDarken
	BlendLighten     = driver.BlendLighten
	BlendColorDodge  = driver.BlendColorDodge
	BlendColorBurn   = driver.BlendColorBurn
	BlendHardLight   = driver.BlendHardLight
	BlendSoftLight   = driver.BlendSoftLight
	BlendDifference  = driver.BlendDifference
	BlendExclusion   = driver.BlendExclusion
	BlendHue         = driver.BlendHue
	BlendSaturation  = driver.BlendSaturation
	BlendColor       = driver.BlendColor
	BlendLuminosity  = driver.BlendLuminosity
	BlendPlusLighter = driver.BlendPlusLighter
	BlendPlusDarker  = driver.BlendPlusDarker
)
View Source
const (
	BackdropUltraThin = driver.BackdropUltraThin
	BackdropThin      = driver.BackdropThin
	BackdropRegular   = driver.BackdropRegular
	BackdropThick     = driver.BackdropThick
	BackdropChrome    = driver.BackdropChrome
)
View Source
const (
	GlassNone    = driver.GlassNone
	GlassRegular = driver.GlassRegular
	GlassClear   = driver.GlassClear
)
View Source
const (
	KeyframesSpin   = driver.KeyframesSpin
	KeyframesPing   = driver.KeyframesPing
	KeyframesPulse  = driver.KeyframesPulse
	KeyframesBounce = driver.KeyframesBounce
)
View Source
const (
	// CodeAccessDenied says the capabilities do not grant what was asked,
	// Error's Permission and Resource saying which and of what.
	CodeAccessDenied = "ERR_ACCESS_DENIED"
	// CodeUnavailable says this platform does not do what was asked.
	CodeUnavailable = "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM"
	// CodeQuotaExceeded says a runtime quota ran out: calls waiting at
	// once, storage.
	CodeQuotaExceeded = "ERR_NSH_QUOTA_EXCEEDED"
	// CodeHostError says the embedding app answered with an error.
	CodeHostError = "ERR_NSH_HOST_ERROR"
	// CodeTimedOut says an answer did not come in time.
	CodeTimedOut = "ETIMEDOUT"
	// CodeNotFound and CodeDenied are what the system answered: never
	// the capabilities, which are CodeAccessDenied.
	CodeNotFound = "ENOENT"
	CodeDenied   = "EACCES"
)

The stable codes of failures an app can handle, NSH's and Node's: the message is for people and may change.

View Source
const (
	MouseButtonNone    = driver.MouseButtonNone
	MouseButtonLeft    = driver.MouseButtonLeft
	MouseButtonRight   = driver.MouseButtonRight
	MouseButtonMiddle  = driver.MouseButtonMiddle
	MouseButtonBack    = driver.MouseButtonBack
	MouseButtonForward = driver.MouseButtonForward
)

The mouse buttons of a MouseEvent; none is the zero value.

View Source
const (
	ProductConsumable    = driver.ProductConsumable
	ProductNonConsumable = driver.ProductNonConsumable
	ProductAutoRenewable = driver.ProductAutoRenewable
	ProductNonRenewable  = driver.ProductNonRenewable
)

The kinds of product.

View Source
const (
	PeriodDay   = driver.PeriodDay
	PeriodWeek  = driver.PeriodWeek
	PeriodMonth = driver.PeriodMonth
	PeriodYear  = driver.PeriodYear
)

The units of a subscription's period.

View Source
const (
	OfferFreeTrial  = driver.OfferFreeTrial
	OfferPayAsYouGo = driver.OfferPayAsYouGo
	OfferPayUpFront = driver.OfferPayUpFront
)

How an offer is paid.

View Source
const (
	PurchaseProducts     = driver.PurchaseProducts
	PurchaseBuy          = driver.PurchaseBuy
	PurchaseFinish       = driver.PurchaseFinish
	PurchaseEntitlements = driver.PurchaseEntitlements
	PurchaseSync         = driver.PurchaseSync
)

What a PurchaseRequest asks of the store.

View Source
const (
	SecretAccessibleDefault              = driver.SecretAccessibleDefault
	SecretWhenUnlocked                   = driver.SecretWhenUnlocked
	SecretAfterFirstUnlock               = driver.SecretAfterFirstUnlock
	SecretWhenUnlockedThisDeviceOnly     = driver.SecretWhenUnlockedThisDeviceOnly
	SecretAfterFirstUnlockThisDeviceOnly = driver.SecretAfterFirstUnlockThisDeviceOnly
	SecretWhenPasscodeSetThisDeviceOnly  = driver.SecretWhenPasscodeSetThisDeviceOnly
)
View Source
const (
	SensorAccelerometer = driver.SensorAccelerometer
	SensorGyroscope     = driver.SensorGyroscope
	SensorMagnetometer  = driver.SensorMagnetometer
	SensorDeviceMotion  = driver.SensorDeviceMotion
)
View Source
const (
	OSMacOS   = driver.OSMacOS
	OSIOS     = driver.OSIOS
	OSAndroid = driver.OSAndroid
	OSWindows = driver.OSWindows
	OSLinux   = driver.OSLinux
	OSWeb     = driver.OSWeb
)
View Source
const (
	IdiomPhone   = driver.IdiomPhone
	IdiomTablet  = driver.IdiomTablet
	IdiomDesktop = driver.IdiomDesktop
	IdiomMac     = driver.IdiomMac
	IdiomTV      = driver.IdiomTV
	IdiomWatch   = driver.IdiomWatch
)
View Source
const (
	WebInputClick = driver.WebInputClick
	WebInputText  = driver.WebInputText
	WebInputKey   = driver.WebInputKey
)
View Source
const (
	SpeechStart = driver.SpeechStart
	SpeechStop  = driver.SpeechStop
	SpeechAbort = driver.SpeechAbort
)
View Source
const (
	LifecycleActive     = driver.LifecycleActive
	LifecycleInactive   = driver.LifecycleInactive
	LifecycleBackground = driver.LifecycleBackground
)
View Source
const (
	HingeUnknown  = driver.HingeUnknown
	HingeClosed   = driver.HingeClosed
	HingeHalfOpen = driver.HingeHalfOpen
	HingeOpen     = driver.HingeOpen
)
View Source
const (
	VerticalBarUnspecified = driver.VerticalBarUnspecified
	VerticalBarLeading     = driver.VerticalBarLeading
	VerticalBarTrailing    = driver.VerticalBarTrailing
)
View Source
const (
	WindowLevelNormal   = driver.WindowLevelNormal
	WindowLevelFloating = driver.WindowLevelFloating
	WindowLevelDesktop  = driver.WindowLevelDesktop
)
View Source
const (
	WindowWorkspacesCurrent = driver.WindowWorkspacesCurrent
	WindowWorkspacesAll     = driver.WindowWorkspacesAll
)
View Source
const (
	WindowPointerAuto    = driver.WindowPointerAuto
	WindowPointerNone    = driver.WindowPointerNone
	WindowPointerPainted = driver.WindowPointerPainted
)
View Source
const (
	MenuBarShown    = driver.MenuBarShown
	MenuBarAutoHide = driver.MenuBarAutoHide
)
View Source
const (
	AppearanceSystem = driver.AppearanceSystem
	AppearanceLight  = driver.AppearanceLight
	AppearanceDark   = driver.AppearanceDark
)
View Source
const (
	PickCompatible = driver.PickCompatible
	PickCurrent    = driver.PickCurrent
)
View Source
const (
	SubmitBehaviorDefault       = driver.SubmitBehaviorDefault
	SubmitBehaviorSubmit        = driver.SubmitBehaviorSubmit
	SubmitBehaviorBlurAndSubmit = driver.SubmitBehaviorBlurAndSubmit
	SubmitBehaviorNewline       = driver.SubmitBehaviorNewline
)
View Source
const (
	ReturnKeyDefault = driver.ReturnKeyDefault
	ReturnKeyDone    = driver.ReturnKeyDone
	ReturnKeyGo      = driver.ReturnKeyGo
	ReturnKeyNext    = driver.ReturnKeyNext
	ReturnKeySearch  = driver.ReturnKeySearch
	ReturnKeySend    = driver.ReturnKeySend
)
View Source
const (
	AutoCapitalizeSentences  = driver.AutoCapitalizeSentences
	AutoCapitalizeNone       = driver.AutoCapitalizeNone
	AutoCapitalizeWords      = driver.AutoCapitalizeWords
	AutoCapitalizeCharacters = driver.AutoCapitalizeCharacters
)
View Source
const (
	AutoCompleteDefault                = driver.AutoCompleteDefault
	AutoCompleteOff                    = driver.AutoCompleteOff
	AutoCompleteUsername               = driver.AutoCompleteUsername
	AutoCompletePassword               = driver.AutoCompletePassword
	AutoCompleteNewPassword            = driver.AutoCompleteNewPassword
	AutoCompleteOneTimeCode            = driver.AutoCompleteOneTimeCode
	AutoCompleteEmail                  = driver.AutoCompleteEmail
	AutoCompleteTel                    = driver.AutoCompleteTel
	AutoCompleteName                   = driver.AutoCompleteName
	AutoCompleteGivenName              = driver.AutoCompleteGivenName
	AutoCompleteFamilyName             = driver.AutoCompleteFamilyName
	AutoCompleteMiddleName             = driver.AutoCompleteMiddleName
	AutoCompleteNickname               = driver.AutoCompleteNickname
	AutoCompleteOrganization           = driver.AutoCompleteOrganization
	AutoCompleteStreetAddress          = driver.AutoCompleteStreetAddress
	AutoCompleteAddressLine1           = driver.AutoCompleteAddressLine1
	AutoCompleteAddressLine2           = driver.AutoCompleteAddressLine2
	AutoCompleteCity                   = driver.AutoCompleteCity
	AutoCompleteRegion                 = driver.AutoCompleteRegion
	AutoCompletePostalCode             = driver.AutoCompletePostalCode
	AutoCompleteCountry                = driver.AutoCompleteCountry
	AutoCompleteCreditCardNumber       = driver.AutoCompleteCreditCardNumber
	AutoCompleteCreditCardExpiration   = driver.AutoCompleteCreditCardExpiration
	AutoCompleteCreditCardSecurityCode = driver.AutoCompleteCreditCardSecurityCode
	AutoCompleteCreditCardName         = driver.AutoCompleteCreditCardName
	AutoCompleteURL                    = driver.AutoCompleteURL
	AutoCompleteBirthdate              = driver.AutoCompleteBirthdate
)
View Source
const (
	DrawSave           = driver.DrawSave
	DrawRestore        = driver.DrawRestore
	DrawTranslate      = driver.DrawTranslate
	DrawScale          = driver.DrawScale
	DrawRotate         = driver.DrawRotate
	DrawBeginPath      = driver.DrawBeginPath
	DrawMoveTo         = driver.DrawMoveTo
	DrawLineTo         = driver.DrawLineTo
	DrawQuadTo         = driver.DrawQuadTo
	DrawCubicTo        = driver.DrawCubicTo
	DrawArc            = driver.DrawArc
	DrawRect           = driver.DrawRect
	DrawRoundRect      = driver.DrawRoundRect
	DrawEllipse        = driver.DrawEllipse
	DrawClosePath      = driver.DrawClosePath
	DrawFill           = driver.DrawFill
	DrawStroke         = driver.DrawStroke
	DrawClip           = driver.DrawClip
	DrawFillColor      = driver.DrawFillColor
	DrawStrokeColor    = driver.DrawStrokeColor
	DrawLineWidth      = driver.DrawLineWidth
	DrawLineCap        = driver.DrawLineCap
	DrawLineJoin       = driver.DrawLineJoin
	DrawAlpha          = driver.DrawAlpha
	DrawFillText       = driver.DrawFillText
	DrawClear          = driver.DrawClear
	DrawFillGradient   = driver.DrawFillGradient
	DrawStrokeGradient = driver.DrawStrokeGradient
	DrawTransform      = driver.DrawTransform
	DrawSetTransform   = driver.DrawSetTransform
	DrawComposite      = driver.DrawComposite
	DrawLineDash       = driver.DrawLineDash
	DrawLineDashOffset = driver.DrawLineDashOffset
	DrawMiterLimit     = driver.DrawMiterLimit
	DrawShadow         = driver.DrawShadow
	DrawStrokeText     = driver.DrawStrokeText
	DrawImage          = driver.DrawImage
	DrawTextAlign      = driver.DrawTextAlign
	DrawTextBaseline   = driver.DrawTextBaseline
)
View Source
const (
	ArgX     = driver.ArgX
	ArgY     = driver.ArgY
	ArgX1    = driver.ArgX1
	ArgY1    = driver.ArgY1
	ArgX2    = driver.ArgX2
	ArgY2    = driver.ArgY2
	ArgW     = driver.ArgW
	ArgH     = driver.ArgH
	ArgR     = driver.ArgR
	ArgA     = driver.ArgA
	ArgA0    = driver.ArgA0
	ArgA1    = driver.ArgA1
	ArgRY    = driver.ArgRY
	ArgColor = driver.ArgColor
)
View Source
const (
	CompositeSourceOver      = driver.CompositeSourceOver
	CompositeSourceIn        = driver.CompositeSourceIn
	CompositeSourceOut       = driver.CompositeSourceOut
	CompositeSourceAtop      = driver.CompositeSourceAtop
	CompositeDestinationOver = driver.CompositeDestinationOver
	CompositeDestinationIn   = driver.CompositeDestinationIn
	CompositeDestinationOut  = driver.CompositeDestinationOut
	CompositeDestinationAtop = driver.CompositeDestinationAtop
	CompositeLighter         = driver.CompositeLighter
	CompositeCopy            = driver.CompositeCopy
	CompositeXor             = driver.CompositeXor
	CompositeMultiply        = driver.CompositeMultiply
	CompositeScreen          = driver.CompositeScreen
	CompositeOverlay         = driver.CompositeOverlay
	CompositeDarken          = driver.CompositeDarken
	CompositeLighten         = driver.CompositeLighten
	CompositeColorDodge      = driver.CompositeColorDodge
	CompositeColorBurn       = driver.CompositeColorBurn
	CompositeHardLight       = driver.CompositeHardLight
	CompositeSoftLight       = driver.CompositeSoftLight
	CompositeDifference      = driver.CompositeDifference
	CompositeExclusion       = driver.CompositeExclusion
	CompositeHue             = driver.CompositeHue
	CompositeSaturation      = driver.CompositeSaturation
	CompositeColor           = driver.CompositeColor
	CompositeLuminosity      = driver.CompositeLuminosity
)
View Source
const (
	BaselineAlphabetic  = driver.BaselineAlphabetic
	BaselineTop         = driver.BaselineTop
	BaselineHanging     = driver.BaselineHanging
	BaselineMiddle      = driver.BaselineMiddle
	BaselineIdeographic = driver.BaselineIdeographic
	BaselineBottom      = driver.BaselineBottom
)
View Source
const (
	NonZero = driver.NonZero
	EvenOdd = driver.EvenOdd
)
View Source
const (
	JumpEnd   = driver.JumpEnd
	JumpStart = driver.JumpStart
	JumpNone  = driver.JumpNone
	JumpBoth  = driver.JumpBoth
)
View Source
const (
	CapButt   = driver.CapButt
	CapRound  = driver.CapRound
	CapSquare = driver.CapSquare
)
View Source
const (
	JoinMiter = driver.JoinMiter
	JoinRound = driver.JoinRound
	JoinBevel = driver.JoinBevel
)
View Source
const (
	AlertDefault     = driver.AlertDefault
	AlertCancel      = driver.AlertCancel
	AlertDestructive = driver.AlertDestructive
)
View Source
const (
	KeyboardDefault = driver.KeyboardDefault
	KeyboardEmail   = driver.KeyboardEmail
	KeyboardNumber  = driver.KeyboardNumber
	KeyboardDecimal = driver.KeyboardDecimal
	KeyboardPhone   = driver.KeyboardPhone
	KeyboardURL     = driver.KeyboardURL
)
View Source
const (
	RoleNone       = driver.RoleNone
	RoleButton     = driver.RoleButton
	RoleLink       = driver.RoleLink
	RoleHeader     = driver.RoleHeader
	RoleImage      = driver.RoleImage
	RoleCheckbox   = driver.RoleCheckbox
	RoleSwitch     = driver.RoleSwitch
	RoleRadio      = driver.RoleRadio
	RoleTab        = driver.RoleTab
	RoleText       = driver.RoleText
	RoleTextField  = driver.RoleTextField
	RoleRadioGroup = driver.RoleRadioGroup
	RoleTabList    = driver.RoleTabList
	RoleMenu       = driver.RoleMenu
	RoleMenuItem   = driver.RoleMenuItem
	// RoleMenuItemCheckbox and RoleMenuItemRadio are menu items with a
	// checked state.
	RoleMenuItemCheckbox = driver.RoleMenuItemCheckbox
	RoleMenuItemRadio    = driver.RoleMenuItemRadio
	// RoleListbox holds RoleOptions the user picks from.
	RoleListbox = driver.RoleListbox
	RoleOption  = driver.RoleOption
	// RoleGroup, RoleRegion and RoleNavigation are parts of a page.
	RoleGroup      = driver.RoleGroup
	RoleRegion     = driver.RoleRegion
	RoleNavigation = driver.RoleNavigation
	// RoleTree holds RoleTreeItems.
	RoleTree     = driver.RoleTree
	RoleTreeItem = driver.RoleTreeItem
	RoleToolbar  = driver.RoleToolbar
	RoleDialog   = driver.RoleDialog
	// RoleAlertDialog is a dialog asking for an answer, a confirmation.
	RoleAlertDialog = driver.RoleAlertDialog
	RoleAlert       = driver.RoleAlert
	// RoleStatus is advisory information that changes, such as a save or upload status, and a polite live region by default.
	RoleStatus = driver.RoleStatus
	// RoleSearchField is an Input used to search or filter content.
	RoleSearchField = driver.RoleSearchField
	RoleAdjustable  = driver.RoleAdjustable
	// RoleSpinButton is a field for a number, stepped with its actions.
	RoleSpinButton = driver.RoleSpinButton
	// RoleCombobox picks a value from a list it opens.
	RoleCombobox    = driver.RoleCombobox
	RoleProgressBar = driver.RoleProgressBar
	// RoleTable and RoleGrid are a table and an interactive one, around
	// RoleRowGroup, RoleRow, RoleColumnHeader and RoleCell.
	RoleTable        = driver.RoleTable
	RoleGrid         = driver.RoleGrid
	RoleRowGroup     = driver.RoleRowGroup
	RoleRow          = driver.RoleRow
	RoleColumnHeader = driver.RoleColumnHeader
	RoleCell         = driver.RoleCell
)
View Source
const (
	PasteInsert = driver.PasteInsert
	PasteReport = driver.PasteReport
)
View Source
const (
	DecelerationFast = driver.DecelerationFast
	ActionActivate   = driver.ActionActivate
	ActionIncrement  = driver.ActionIncrement
	ActionDecrement  = driver.ActionDecrement
	ActionEscape     = driver.ActionEscape
	ActionMagicTap   = driver.ActionMagicTap
	FontMonospace    = driver.FontMonospace
)
View Source
const (
	SnapStart  = driver.SnapStart
	SnapCenter = driver.SnapCenter
	SnapEnd    = driver.SnapEnd
)
View Source
const (
	KeyboardTapsNever   = driver.KeyboardTapsNever
	KeyboardTapsAlways  = driver.KeyboardTapsAlways
	KeyboardTapsHandled = driver.KeyboardTapsHandled
)
View Source
const (
	LiveRegionNone      = driver.LiveRegionNone
	LiveRegionPolite    = driver.LiveRegionPolite
	LiveRegionAssertive = driver.LiveRegionAssertive
)
View Source
const (
	PointerEventsAuto    = driver.PointerEventsAuto
	PointerEventsNone    = driver.PointerEventsNone
	PointerEventsBoxNone = driver.PointerEventsBoxNone
	PointerEventsBoxOnly = driver.PointerEventsBoxOnly
	PointerEventsOn      = driver.PointerEventsOn
)
View Source
const (
	ExtrapolateClamp    = driver.ExtrapolateClamp
	ExtrapolateExtend   = driver.ExtrapolateExtend
	ExtrapolateIdentity = driver.ExtrapolateIdentity
)
View Source
const (
	EasingBezier  = driver.EasingBezier
	EasingQuad    = driver.EasingQuad
	EasingCubic   = driver.EasingCubic
	EasingPoly    = driver.EasingPoly
	EasingSin     = driver.EasingSin
	EasingCircle  = driver.EasingCircle
	EasingExp     = driver.EasingExp
	EasingElastic = driver.EasingElastic
	EasingBack    = driver.EasingBack
	EasingBounce  = driver.EasingBounce
	EasingSteps   = driver.EasingSteps
)
View Source
const (
	EaseModeIn    = driver.EaseModeIn
	EaseModeOut   = driver.EaseModeOut
	EaseModeInOut = driver.EaseModeInOut
)
View Source
const (
	AnimationTiming   = driver.AnimationTiming
	AnimationSpring   = driver.AnimationSpring
	AnimationDecay    = driver.AnimationDecay
	AnimationSequence = driver.AnimationSequence
	AnimationParallel = driver.AnimationParallel
	AnimationStagger  = driver.AnimationStagger
	AnimationDelay    = driver.AnimationDelay
	AnimationLoop     = driver.AnimationLoop
)
View Source
const (
	CursorAuto       = driver.CursorAuto
	CursorDefault    = driver.CursorDefault
	CursorPointer    = driver.CursorPointer
	CursorText       = driver.CursorText
	CursorWait       = driver.CursorWait
	CursorProgress   = driver.CursorProgress
	CursorHelp       = driver.CursorHelp
	CursorCrosshair  = driver.CursorCrosshair
	CursorMove       = driver.CursorMove
	CursorGrab       = driver.CursorGrab
	CursorGrabbing   = driver.CursorGrabbing
	CursorNotAllowed = driver.CursorNotAllowed
	CursorZoomIn     = driver.CursorZoomIn
	CursorZoomOut    = driver.CursorZoomOut
	CursorColResize  = driver.CursorColResize
	CursorRowResize  = driver.CursorRowResize
	CursorNwseResize = driver.CursorNwseResize
	CursorNeswResize = driver.CursorNeswResize
	CursorNone       = driver.CursorNone
)
View Source
const (
	TitleBarDefault = driver.TitleBarDefault
	TitleBarHidden  = driver.TitleBarHidden
)
View Source
const (
	WindowDragInherit = driver.WindowDragInherit
	WindowDragOn      = driver.WindowDragOn
	WindowDragOff     = driver.WindowDragOff
)
View Source
const (
	WindowMaterialNone         = driver.WindowMaterialNone
	WindowMaterialWindow       = driver.WindowMaterialWindow
	WindowMaterialContent      = driver.WindowMaterialContent
	WindowMaterialSidebar      = driver.WindowMaterialSidebar
	WindowMaterialHeader       = driver.WindowMaterialHeader
	WindowMaterialTitlebar     = driver.WindowMaterialTitlebar
	WindowMaterialUnderWindow  = driver.WindowMaterialUnderWindow
	WindowMaterialUnderPage    = driver.WindowMaterialUnderPage
	WindowMaterialMenu         = driver.WindowMaterialMenu
	WindowMaterialPopover      = driver.WindowMaterialPopover
	WindowMaterialHUD          = driver.WindowMaterialHUD
	WindowMaterialSheet        = driver.WindowMaterialSheet
	WindowMaterialTooltip      = driver.WindowMaterialTooltip
	WindowMaterialSelection    = driver.WindowMaterialSelection
	WindowMaterialFullScreenUI = driver.WindowMaterialFullScreenUI
	WindowMaterialMica         = driver.WindowMaterialMica
	WindowMaterialAcrylic      = driver.WindowMaterialAcrylic
	WindowMaterialTabbed       = driver.WindowMaterialTabbed
)
View Source
const (
	WindowSetTitleBar      = driver.WindowSetTitleBar
	WindowMinimize         = driver.WindowMinimize
	WindowToggleMaximize   = driver.WindowToggleMaximize
	WindowToggleFullScreen = driver.WindowToggleFullScreen
	WindowClose            = driver.WindowClose
	WindowSetFrame         = driver.WindowSetFrame
	WindowSetLevel         = driver.WindowSetLevel
	WindowOrderFront       = driver.WindowOrderFront
	WindowSetMenuBar       = driver.WindowSetMenuBar
	WindowSetControls      = driver.WindowSetControls
	WindowSetMaterial      = driver.WindowSetMaterial
	WindowSetWorkspaces    = driver.WindowSetWorkspaces
)
View Source
const (
	MenuRoleNone           = driver.MenuRoleNone
	MenuAbout              = driver.MenuAbout
	MenuHide               = driver.MenuHide
	MenuHideOthers         = driver.MenuHideOthers
	MenuShowAll            = driver.MenuShowAll
	MenuQuit               = driver.MenuQuit
	MenuUndo               = driver.MenuUndo
	MenuRedo               = driver.MenuRedo
	MenuCut                = driver.MenuCut
	MenuCopy               = driver.MenuCopy
	MenuPaste              = driver.MenuPaste
	MenuSelectAll          = driver.MenuSelectAll
	MenuMinimize           = driver.MenuMinimize
	MenuZoom               = driver.MenuZoom
	MenuToggleFullScreen   = driver.MenuToggleFullScreen
	MenuClose              = driver.MenuClose
	MenuPasteAndMatchStyle = driver.MenuPasteAndMatchStyle
	MenuDelete             = driver.MenuDelete
	MenuStartSpeaking      = driver.MenuStartSpeaking
	MenuStopSpeaking       = driver.MenuStopSpeaking
	MenuBringAllToFront    = driver.MenuBringAllToFront
	MenuServices           = driver.MenuServices
	MenuWindowMenu         = driver.MenuWindowMenu
	MenuHelpMenu           = driver.MenuHelpMenu
)
View Source
const (
	SelectableAuto = driver.SelectableAuto
	SelectableOn   = driver.SelectableOn
	SelectableOff  = driver.SelectableOff
)
View Source
const (
	AudioSessionDefault       = driver.AudioSessionDefault
	AudioSessionPlayback      = driver.AudioSessionPlayback
	AudioSessionMixWithOthers = driver.AudioSessionMixWithOthers
)
View Source
const (
	Cover     = driver.Cover
	Contain   = driver.Contain
	Stretch   = driver.Stretch
	Center    = driver.Center
	ScaleDown = driver.ScaleDown
)
View Source
const (
	ModalFullScreen = driver.ModalFullScreen
	ModalPageSheet  = driver.ModalPageSheet
	ModalFormSheet  = driver.ModalFormSheet
)
View Source
const (
	OrientationPortrait           = driver.OrientationPortrait
	OrientationPortraitUpsideDown = driver.OrientationPortraitUpsideDown
	OrientationLandscapeLeft      = driver.OrientationLandscapeLeft
	OrientationLandscapeRight     = driver.OrientationLandscapeRight
	OrientationLandscape          = driver.OrientationLandscape
)
View Source
const (
	ScreenDefault = driver.ScreenDefault
	ScreenSlide   = driver.ScreenSlide
	ScreenFade    = driver.ScreenFade
	ScreenNone    = driver.ScreenNone
	ModalSlide    = driver.ModalSlide
	ModalFade     = driver.ModalFade
	ModalNone     = driver.ModalNone
)
View Source
const (
	TransitionOpacity    = driver.TransitionOpacity
	TransitionBackground = driver.TransitionBackground
	TransitionTransform  = driver.TransitionTransform
	TransitionBorder     = driver.TransitionBorder
	TransitionShadow     = driver.TransitionShadow
	TransitionLayout     = driver.TransitionLayout
)
View Source
const (
	GestureBegan     = driver.GestureBegan
	GestureChanged   = driver.GestureChanged
	GestureEnded     = driver.GestureEnded
	GestureCancelled = driver.GestureCancelled
)
View Source
const (
	DefaultPanSlop  = driver.DefaultPanSlop
	DefaultFontSize = driver.DefaultFontSize
)
View Source
const (
	StatusBarInherit = driver.StatusBarInherit
	StatusBarAuto    = driver.StatusBarAuto
	StatusBarDark    = driver.StatusBarDark
	StatusBarLight   = driver.StatusBarLight
)
View Source
const (
	FontWeightLight    = driver.FontWeightLight
	FontWeightNormal   = driver.FontWeightNormal
	FontWeightMedium   = driver.FontWeightMedium
	FontWeightSemibold = driver.FontWeightSemibold
	FontWeightBold     = driver.FontWeightBold
)
View Source
const (
	TextAlignStart   = driver.TextAlignStart
	TextAlignCenter  = driver.TextAlignCenter
	TextAlignEnd     = driver.TextAlignEnd
	TextAlignLeft    = driver.TextAlignLeft
	TextAlignRight   = driver.TextAlignRight
	TextAlignJustify = driver.TextAlignJustify
)
View Source
const (
	VerticalAlignBaseline   = driver.VerticalAlignBaseline
	VerticalAlignTextTop    = driver.VerticalAlignTextTop
	VerticalAlignTextBottom = driver.VerticalAlignTextBottom
	VerticalAlignMiddle     = driver.VerticalAlignMiddle
)
View Source
const (
	TextDecorationNone        = driver.TextDecorationNone
	TextDecorationUnderline   = driver.TextDecorationUnderline
	TextDecorationLineThrough = driver.TextDecorationLineThrough
)
View Source
const (
	HeaderItemAdd     = driver.HeaderItemAdd
	HeaderItemDone    = driver.HeaderItemDone
	HeaderItemClose   = driver.HeaderItemClose
	HeaderItemEdit    = driver.HeaderItemEdit
	HeaderItemCompose = driver.HeaderItemCompose
	HeaderItemSearch  = driver.HeaderItemSearch
	HeaderItemShare   = driver.HeaderItemShare
	HeaderItemTrash   = driver.HeaderItemTrash
	HeaderItemSave    = driver.HeaderItemSave
	HeaderItemCancel  = driver.HeaderItemCancel
)
View Source
const (
	FontVariantNormal    = driver.FontVariantNormal
	FontSmallCaps        = driver.FontSmallCaps
	FontOldstyleNums     = driver.FontOldstyleNums
	FontLiningNums       = driver.FontLiningNums
	FontTabularNums      = driver.FontTabularNums
	FontProportionalNums = driver.FontProportionalNums
)
View Source
const (
	DecorationSolid  = driver.DecorationSolid
	DecorationDouble = driver.DecorationDouble
	DecorationDotted = driver.DecorationDotted
	DecorationDashed = driver.DecorationDashed
	DecorationWavy   = driver.DecorationWavy
)
View Source
const (
	EllipsizeTail   = driver.EllipsizeTail
	EllipsizeHead   = driver.EllipsizeHead
	EllipsizeMiddle = driver.EllipsizeMiddle
	EllipsizeClip   = driver.EllipsizeClip
)
View Source
const (
	AccessibleAuto = driver.AccessibleAuto
	AccessibleYes  = driver.AccessibleYes
	AccessibleNo   = driver.AccessibleNo
)
View Source
const (
	SpreadPad     = driver.SpreadPad
	SpreadReflect = driver.SpreadReflect
	SpreadRepeat  = driver.SpreadRepeat
)
View Source
const (
	LayoutLinear        = driver.LayoutLinear
	LayoutEaseIn        = driver.LayoutEaseIn
	LayoutEaseOut       = driver.LayoutEaseOut
	LayoutEaseInEaseOut = driver.LayoutEaseInEaseOut
	LayoutSpring        = driver.LayoutSpring
	LayoutKeyboard      = driver.LayoutKeyboard
)
View Source
const (
	LayoutOpacity = driver.LayoutOpacity
	LayoutScale   = driver.LayoutScale
)
View Source
const (
	Downstream = driver.Downstream
	Upstream   = driver.Upstream
)
View Source
const (
	StorageSet    = driver.StorageSet
	StorageRemove = driver.StorageRemove
	StorageClear  = driver.StorageClear
)
View Source
const (
	SideTop Sides = 1 << iota
	SideRight
	SideBottom
	SideLeft
	// SidesHorizontal and SidesVertical are left and right, top and bottom.
	SidesHorizontal = SideLeft | SideRight
	SidesVertical   = SideTop | SideBottom
	SidesAll        = SidesHorizontal | SidesVertical
)
View Source
const (
	// WebSameSiteDefault leaves the attribute out, so the platform's default for a cookie without one applies, which differs: Chromium's web views, on Windows and Android, take it as Lax.
	WebSameSiteDefault = driver.WebSameSiteDefault
	WebSameSiteLax     = driver.WebSameSiteLax
	WebSameSiteStrict  = driver.WebSameSiteStrict
	// WebSameSiteNone sends the cookie with requests from other sites too, which needs Secure.
	WebSameSiteNone = driver.WebSameSiteNone
)

The SameSite attributes of a WebCookie.

View Source
const (
	WebMicrophone = driver.WebMicrophone
	WebCamera     = driver.WebCamera
)
View Source
const (
	WebDownloadStarted  = driver.WebDownloadStarted
	WebDownloadFinished = driver.WebDownloadFinished
	WebDownloadFailed   = driver.WebDownloadFailed
)

How far a WebDownload got.

View Source
const (
	// HotKeyPending is the core's part of desktop.HotKeyPending.
	HotKeyPending = driver.HotKeyPending
	// HotKeyRegistered is the core's part of desktop.HotKeyRegistered.
	HotKeyRegistered = driver.HotKeyRegistered
	// HotKeyTaken is the core's part of desktop.HotKeyTaken.
	HotKeyTaken = driver.HotKeyTaken
	// HotKeyUnsupported is the core's part of desktop.HotKeyUnsupported.
	HotKeyUnsupported = driver.HotKeyUnsupported
)
View Source
const CurrentColor = driver.CurrentColor

CurrentColor, in a style's colors other than Color, is the text color the view has: its own, else the one it inherits, else its subtree's Palette.Text, as CSS's currentColor. It is the one color value set aside: it never draws as itself.

View Source
const Forever = -1

Forever is the Iterations of keyframes that repeat until stopped.

View Source
const HostCallTimeout = 30 * time.Second

HostCallTimeout is how long CallHost waits for the host's answer.

View Source
const HostInbox = 256

HostInbox is how many events a Host or an app keeps for later: those sent while no app runs, and those of names no listener hears yet. Past it the oldest are dropped.

View Source
const MaxClipboardImage = driver.MaxClipboardImage

MaxClipboardImage is the most bytes of a PNG ReadClipboardImage gives.

View Source
const MaxPicked = driver.MaxPicked

MaxPicked is the most images, files or folders one PickImages, PickFiles or PickDirectories answers with.

View Source
const MaxURLLength = 16 << 10

MaxURLLength is the longest URL OpenURL opens, in bytes: a mailto: link with a body fits.

View Source
const NoLineLimit = -1

NoLineLimit, as a style's NumberOfLines, lifts a limit a text has.

View Source
const QuitTimeout = 200 * time.Millisecond

QuitTimeout is how long the engine waits for the work of the OnQuit handlers as the app quits, at most, as GPUI's shutdown timeout. The platform's main thread waits for the engine meanwhile, so it stays short.

View Source
const StorageQuota = 5 << 20

StorageQuota is the most an app may keep, in UTF-8 bytes of its keys and values.

Variables

View Source
var (
	// LayoutEaseInEaseOutPreset eases every change in and out over 300 ms.
	LayoutEaseInEaseOutPreset = allLayout(driver.LayoutTransition{Curve: driver.LayoutEaseInEaseOut, Duration: 300 * time.Millisecond})
	// LayoutLinearPreset moves every change at constant speed over 500 ms.
	LayoutLinearPreset = allLayout(driver.LayoutTransition{Curve: driver.LayoutLinear, Duration: 500 * time.Millisecond})
	// LayoutSpringPreset springs frames (damping 0.4) over 700 ms and fades
	// views linearly.
	LayoutSpringPreset = LayoutAnimation{
		Create: &driver.LayoutTransition{Curve: driver.LayoutLinear, Duration: 700 * time.Millisecond},
		Update: &driver.LayoutTransition{Curve: driver.LayoutSpring, Damping: 0.4, Duration: 700 * time.Millisecond},
		Delete: &driver.LayoutTransition{Curve: driver.LayoutLinear, Duration: 700 * time.Millisecond},
	}
)

React Native's presets.

View Source
var (
	MinContent = driver.MinContent
	MaxContent = driver.MaxContent
	FitContent = driver.FitContent
)

The intrinsic sizes, for Width, Height and their limits: the narrowest a box gets without overflowing (its longest word), the widest its content asks for (no wrapping), and that up to the space it has.

View Source
var (
	PositionStart  = PositionAxis{Offset: Pct(0)}
	PositionCenter = PositionAxis{Offset: Pct(50)}
	PositionEnd    = PositionAxis{Offset: Pct(100)}
)

Positions along an axis.

View Source
var (
	Linear    = driver.Linear
	Ease      = driver.Ease
	EaseIn    = driver.EaseIn
	EaseOut   = driver.EaseOut
	EaseInOut = driver.EaseInOut
	Auto      = driver.Auto
	// PaintNone paints nothing; PaintCurrentColor paints with the text
	// color.
	PaintNone         = driver.PaintNone
	PaintCurrentColor = driver.PaintCurrentColor
)
View Source
var AutoMinimum = driver.AutoMinimum

AutoMinimum is CSS's automatic minimum, for MinWidth and MinHeight: a flex item keeps its content's size, where an unset minimum is 0.

View Source
var ErrHostTimeout = errors.New("core: the host did not answer in time")

ErrHostTimeout is the error a call the host did not answer in time fails with.

View Source
var ErrNoCamera = errors.New("core: no camera to take a photo with")

ErrNoCamera is TakePhoto's failure where Env.CanTakePhoto is false.

View Source
var ErrNoHostHandler = errors.New("core: the host has no handler")

ErrNoHostHandler is the error a call to a name the host handles no longer, or never did, fails with.

View Source
var ErrNoTrash = errors.New("core: the volume has no trash")

ErrNoTrash is what TrashFile answers when the item's volume has no Trash or Recycle Bin, or its Recycle Bin would not keep the item, such as a file larger than the bin on Windows, which leaves the item where it was.

View Source
var ErrNotification = errors.New("nsgo: a notification needs an ID and a title, and a repeated one a time")

ErrNotification is ShowNotification's error for a notification without an ID or a title, or with a Repeat it does not know or no At to repeat.

View Source
var ErrSecretsUnavailable = &Error{Code: CodeUnavailable, Message: "core: the platform has no secure store for secrets", Err: driver.ErrNoSecretStore}

ErrSecretsUnavailable is what Secrets fails with where the platform has no secure store, such as the web, or a Linux session without a Secret Service: NSGo never keeps a secret in plain storage instead.

Functions

func AppRoot

func AppRoot(app func(cx *Scope)) func(cx *Scope) Node

AppRoot is the root view nsgo.Run mounts for app, which opens its views itself: app runs once, and the root shows what SetMainView sets, unless the platform opens windows, where it stays empty.

func CheckURL

func CheckURL(u string) error

CheckURL reports why OpenURL would refuse u: it must be absolute, at most MaxURLLength bytes, without spaces or control characters, a web address with a host, and of a scheme that opens another app, not javascript:, data:, blob:, file:, about: or asset:.

func DownloadUpdate

func DownloadUpdate(ctx context.Context, update UpdateCheck, dir string, progress func(UpdateDownloadProgress)) (string, error)

DownloadUpdate stages an update through the platform's HTTP client.

func EditsText

func EditsText(key string) bool

EditsText reports whether a text input with the keyboard focus uses the normalized key itself: keys that type, move the caret or delete, and select all, cut, copy, paste, undo and redo. A binding of it fires in text inputs only with KeyAlways.

func ErrorCode

func ErrorCode(err error) string

ErrorCode is the stable code of a failure, "" for one with none.

func From

func From[T comparable](cx *Scope, initial T, subscribe func(set func(T)) (stop func())) func() T

From returns an accessor of the latest value a source outside the graph delivers, as Solid's from does: a subscription to a store, a socket or a file watcher. subscribe runs once, untracked, with set, which any goroutine may call; it returns stop, which runs when the current owner is disposed. A value set while subscribe runs, as a source handing its current value does, is the accessor's at once; values that arrive before the graph takes them coalesce, the latest winning, and a value equal to the one held changes nothing.

Its values reach the graph through Post, so the graph needs a host: an engine or a test driver.

func FromFunc

func FromFunc[T any](cx *Scope, initial T, equal func(a, b T) bool, subscribe func(set func(T)) (stop func())) func() T

FromFunc returns an accessor as From does that compares values with equal; with a nil equal every value notifies, as slices and maps need.

func InsetsFunc

func InsetsFunc(cx *Scope) func() Edges

InsetsFunc returns what reads Insets of cx's place, found now and tracked as it is called, wherever that is.

func InstallUpdate

func InstallUpdate(cx *Scope, path string, done func(error))

InstallUpdate hands a verified package to the platform's installer.

func InstallUpdateInBackground

func InstallUpdateInBackground(cx *Scope, update UpdateCheck, dir string, done func(app *Scope, path string, err error))

InstallUpdateInBackground is the core's part of the Update action of package updater's alert on Linux and Android: off the graph's goroutine it downloads and verifies update's package into dir (DownloadUpdate), within updateDownloadTimeout, then hands it to the platform's installer (InstallUpdate). The work belongs to the app's root scope rather than cx, so it finishes though the scope that offered the update is disposed meanwhile; done runs on the graph's goroutine under the root scope, which it is given, with the package's path and what failed, nil once Linux's package manager installed it or Android's installer started.

func KeyLabel

func KeyLabel(key string, os OS, apple bool) string

KeyLabel is key as menus and hints show it: ⌃⌥⇧⌘K where "mod" is Command (apple), else Ctrl+Alt+Shift+K, with "meta" as Win on Windows, Meta on the web and Super elsewhere.

func NewSelector

func NewSelector[K comparable](cx *Scope, source func() K) (is func(key K) bool)

NewSelector returns is, which reports whether source gives key, as Solid's createSelector does. A computation that calls is subscribes to its key alone, so when source moves from a to b only the readers of a and b run again, however many rows ask: a list's selected row. source is tracked; its value is compared with ==.

func ParseEnvLength

func ParseEnvLength(s string) (EnvInset, Points, error)

ParseEnvLength reads a length of CSS's environment variables: env(safe-area-inset-*) or env(keyboard-inset-height), alone or in a calc() that adds lengths to it, as an inset and the points added. A variable's fallback is ignored, as every platform has its value.

func ProjectDecay

func ProjectDecay(from float64, c DecayConfig) float64

ProjectDecay returns where Decay with c brings a value from from to rest: where a fling released at c.Velocity lands, to snap from before it starts. A clamped one stops at the bound it passes, whatever its bounce.

func ProvideInsets added in v0.2.0

func ProvideInsets(cx *Scope, insets func() Edges)

ProvideInsets makes insets, read tracked, what content built under cx keeps clear of (Insets, EnvSafeArea), screens below it included: a component that keeps its own part of the safe area clear, such as ui.TabShell's drawn tab bar, takes that part away from its content.

func Restarting

func Restarting() bool

Restarting reports whether the app asked to restart before it quit, for nsgo.Run.

func RubberBandClamp

func RubberBandClamp(x, lo, hi, dimension float64) float64

RubberBandClamp resists x past lo and hi as a scroll view's edge resists a drag, with UIKit's constant: past a bound it moves less the farther it goes, never more than dimension, the size of what moves. Resist is the node that does it on the frame clock.

func SampleDecay

func SampleDecay(from float64, c DecayConfig) []float64

SampleDecay returns where Decay takes a value from from, as SampleSpring does.

func SampleEasing

func SampleEasing(e Easing, n int) []float64

SampleEasing returns e at n evenly spaced fractions from 0 to 1, both included, as the platform evaluates it: for drawing the curve.

func SampleSpring

func SampleSpring(from, to float64, c SpringConfig) []float64

SampleSpring returns where Spring takes a value from from to to, 60 times a second until it rests, from the platforms' own code.

func SetLanguageMatch

func SetLanguageMatch(match func(locale string) string)

SetLanguageMatch sets how the language the app shows follows its locale: package i18n's SetApp sets its catalog's match, nil none. It is set as the program initializes, for every app it runs.

func SystemSwitchAvailable

func SystemSwitchAvailable(cx *Scope) bool

SystemSwitchAvailable reports whether the platform has a SystemSwitch: macOS and iOS.

func UTF16Len

func UTF16Len(s string) int

UTF16Len is the length of s in UTF-16 units.

func UTF16Offset

func UTF16Offset(s string, units int) int

UTF16Offset returns the UTF-8 byte offset at units in s, clamped to a complete UTF-16 code point.

func UnknownClasses

func UnknownClasses(s string) []string

UnknownClasses returns the classes of s that are no utility of Tailwind's default theme, in order: what an element would log and ignore. A tool checks classes written for it with it before they draw.

func Untracked

func Untracked[T any](cx *Scope, fn func() T) (v T)

Untracked returns fn's result without subscribing the running computation to what it reads.

Types

type Access

type Access interface {
	// Allows reports whether req is granted. It is called on the engine's goroutine, so it may read only what does not change.
	Allows(req AccessRequest) bool
	// WebHosts are the hosts a web view's pages may navigate to at the top level: "*", "*.example.com" or a host. The platform refuses navigations to other http and https hosts, and to other schemes but the pages' own (AccessWebSchemes) and the app's (Scope.ServeScheme), as they start.
	WebHosts() []string
}

Access says what code under a scope may reach (NSH's nsh_core::access): a host gives it to code it did not write, such as a plugin, with Scope.ProvideAccess. Without one, as for an app's own code, everything is allowed. Core checks it where each request is made, whoever makes it, so a Go component showing the code's data is held to it too: images, videos and web views refused show nothing and report OnError, and the services fail as AccessDenied or answer as the system would with nothing there.

Allows is asked about a web view's source, not about where its pages go: the platform decides those as they start, from WebHosts and, for the about:, blob: and data: pages a page makes itself, AccessWebSchemes.

Elements are held by the Access of the owner that rendered them, services by the running owner's, the one whose render, effect, handler or Run is running, or outside one by that of the scope they are called on. A Host's handlers run outside the owner that called them, so they are held to the scope they call services on.

type AccessRequest

type AccessRequest struct {
	// Permission is the capability asked for: AccessNetwork, ...
	Permission string
	// Resource is what is asked of it: a URL, a host handler's name, or
	// with AccessMedia "microphone" or "camera"; "" for a capability
	// with none.
	Resource string
	// Method is a network request's HTTP method, AccessInput for a web view's trusted input, AccessMedia for what its pages capture, or AccessCookies for a cookie the web views' store takes.
	Method string
}

AccessRequest is what Access is asked for.

type AccessWebSchemes added in v0.2.0

type AccessWebSchemes interface {
	Access
	WebSchemes() []string
}

AccessWebSchemes is an Access that also says which pages of their own making a web view's pages may navigate to at the top level, by scheme: "about", "blob" and "data"; other names are ignored. The platform refuses the rest as they start, as it refuses hosts WebHosts leaves out, but for an about: page on Linux, which WebKitGTK shows before the app can tell the top level's navigation from a frame's: it is refused as it commits, posts nothing, reports no load start or navigation state, and the view goes back to the page before it. An Access without WebSchemes allows all three; one whose WebSchemes returns nil allows none. The app's own sources, WebView.Source and what Ref.Load loads, and the schemes it serves (Scope.ServeScheme) are not held to it, nor are a page's frames, nor, on the native backends, Ref.Reload, GoBack and GoForward taking the view to such a source's page again. A page reloading itself or stepping through its history is held to it, but on Android, which checks neither, and on Apple platforms for a reload of the app's source. On the web, where a web view is an iframe whose navigations the page cannot see, neither WebHosts nor WebSchemes holds its pages.

type AccessibilityAction

type AccessibilityAction = driver.AccessibilityAction

AccessibilityAction is an action assistive technology offers on an element; OnAccessibilityAction receives its Name.

type AccessibilityValue

type AccessibilityValue = driver.AccessibilityValue

AccessibilityValue is a range's or a textual element's value (accessibilityValue).

type Accessible

type Accessible = driver.Accessible

Accessible says whether a view is one element for assistive technology.

type Affinity

type Affinity = driver.Affinity

Affinity says which line a caret offset is on where one offset is two places on screen: the end of a wrapped line and the start of the next.

type AlertAction

type AlertAction = driver.AlertAction

AlertAction is one button of an alert.

type AlertConfig

type AlertConfig = driver.AlertConfig

AlertConfig is a native alert: a title, a message and its buttons.

type AlertRole

type AlertRole = driver.AlertRole

AlertRole says what an alert's button does.

type Align

type Align uint8

Align places children on the cross axis (align-items, align-self, align-content) and grid items along the row (justify-items, justify-self). Start and end are React Native's flex-start and flex-end.

const (
	AlignStretch Align = iota + 1
	AlignStart
	AlignCenter
	AlignEnd
	AlignSpaceBetween // align-content only
	AlignSpaceAround  // align-content only
	AlignBaseline     // items only
	AlignSpaceEvenly  // align-content only
)

type AndroidEventMapper

type AndroidEventMapper = driver.AndroidEventMapper

AndroidEventMapper is implemented by an Android component that receives the listener callbacks of its view itself.

type AndroidModalProps

type AndroidModalProps struct {
	// StatusBarTranslucent lets the content reach under Android's status
	// bar; otherwise the modal starts below it.
	StatusBarTranslucent bool
}

AndroidModalProps are a Modal's props only Android has.

type AndroidPropMapper

type AndroidPropMapper = driver.AndroidPropMapper

AndroidPropMapper is implemented by an Android component that chooses the setter calls a prop makes, in order.

type AndroidViewProp

type AndroidViewProp = driver.AndroidViewProp

AndroidViewProp is one setter call on a component's view: set<Name>(Value), Name's first letter upper-cased.

type AndroidViewProps

type AndroidViewProps struct {
	// Ripple spreads from the touch while the view is pressed; it shows
	// on views that take presses. Keep one value for the view's life.
	Ripple *Ripple
	// Elevation lifts the view, which casts the system's shadow below it.
	Elevation Points
}

AndroidViewProps are a View's props only Android has.

type AnimatedArg

type AnimatedArg = driver.AnimatedArg

AnimatedArg is an animated node a drawing binds an argument to.

type AnimatedNode

type AnimatedNode interface {

	// AnimatedNodeID is the node's ID in the platform's graph, which a
	// Drawing binds arguments to.
	AnimatedNodeID() uint32
	// contains filtered or unexported methods
}

AnimatedNode is a value of the animation graph: an AnimatedValue or a node derived from others.

func Add

func Add(a, b AnimatedNode) AnimatedNode

Add returns a + b. One of them may be a Constant; so for Sub, Mul, Div and Mod.

func DiffClamp

func DiffClamp(in AnimatedNode, min, max float64) AnimatedNode

DiffClamp follows the changes of in but stays within min and max, as a header that hides as content scrolls up and shows as it scrolls down.

func Div

func Div(a, b AnimatedNode) AnimatedNode

func Interpolate

func Interpolate(in AnimatedNode, r Interpolation) AnimatedNode

Interpolate returns a node that maps in through r. Its output is a color when r has Colors.

func Mod

func Mod(a, b AnimatedNode) AnimatedNode

func Mul

func Mul(a, b AnimatedNode) AnimatedNode

func Resist

func Resist(in AnimatedNode, min, max, dimension float64) AnimatedNode

Resist follows in but resists it past min and max as RubberBandClamp does, on the frame clock: bound to a view's translation with in a value PanValues drags, it slows the drag at its ends with no commit per move. in keeps the unresisted value, which a pan's end reports to snap back from.

func SnappingDiffClamp

func SnappingDiffClamp(in AnimatedNode, min, max float64) AnimatedNode

SnappingDiffClamp is DiffClamp that settles at its nearer bound in 200 ms, easing out, when the scroll view whose offset its input follows comes to rest, so a header is never left half hidden. It settles at max only once its input reached max; scrolling again ends the settling where it is.

func Sub

func Sub(a, b AnimatedNode) AnimatedNode

type AnimatedPropSetter

type AnimatedPropSetter = driver.AnimatedPropSetter

AnimatedPropSetter is implemented by a native component that takes its animated props as numbers and colors.

type AnimatedStyle

type AnimatedStyle struct {
	Opacity                AnimatedNode
	TranslateX, TranslateY AnimatedNode
	Scale, ScaleX, ScaleY  AnimatedNode
	// Rotate is in degrees, clockwise.
	Rotate AnimatedNode
	// Background, BorderColor and ShadowColor take color
	// interpolations.
	Background, BorderColor, ShadowColor AnimatedNode
	ShadowRadius                         AnimatedNode
	// ShadowOpacity multiplies the shadow color's alpha.
	ShadowOpacity AnimatedNode
	// TextColor colors a text's whole content, its spans included.
	TextColor AnimatedNode
	// RotateX and RotateY turn the view out of its plane, in degrees.
	RotateX, RotateY AnimatedNode
	// StickyInset is how far a sticky view pins from its scroll view's
	// start, in place of its Top (Left across).
	StickyInset AnimatedNode
}

AnimatedStyle binds a view's properties to animated nodes, over its style. The platform writes them every frame they change.

type AnimatedValue

type AnimatedValue struct {
	// contains filtered or unexported fields
}

AnimatedValue is a number the platform animates. Bind it to a view through Style.Animated, or derive other nodes from it.

func NewAnimatedValue

func NewAnimatedValue(cx *Scope, v float64) *AnimatedValue

NewAnimatedValue returns a value starting at v, released with the current owner.

func (*AnimatedValue) AnimatedNodeID

func (n *AnimatedValue) AnimatedNodeID() uint32

AnimatedNodeID implements AnimatedNode.

func (*AnimatedValue) ExtractOffset

func (v *AnimatedValue) ExtractOffset()

ExtractOffset moves the value into the offset and resets it to 0.

func (*AnimatedValue) FlattenOffset

func (v *AnimatedValue) FlattenOffset()

FlattenOffset adds the offset into the value and resets it to 0.

func (*AnimatedValue) Read

func (v *AnimatedValue) Read(cx *Scope, fn func(float64))

Read asks the platform for the value, with its offset, and passes it to fn under the current owner.

func (*AnimatedValue) Set

func (v *AnimatedValue) Set(x float64)

Set jumps the value to v, stopping its animation.

func (*AnimatedValue) SetOffset

func (v *AnimatedValue) SetOffset(x float64)

SetOffset sets what is added to the value, as a drag's start.

func (*AnimatedValue) Stop

func (v *AnimatedValue) Stop()

Stop stops the value's animation where it is.

type AnimatedXY

type AnimatedXY struct{ X, Y *AnimatedValue }

AnimatedXY are the values a drag or a scroll view moves.

type Animation

type Animation = driver.Animation

Animation is a description of how values move: Timing, Spring and Decay move one value, and Sequence, Parallel, Stagger, Delay and Loop compose them.

func AtFrameRate

func AtFrameRate(a *Animation, rate float64) *Animation

AtFrameRate has a move its values at most rate times a second, on the animation StartAnimation runs, and returns it. What loops for as long as work lasts, such as a pulsing dot, wants this: a compositor redraws at the rate anything on screen moves, however small, and at 120 Hz that costs the system far more than the animation shows. Reserve the display's full rate for what follows a finger or travels across the window.

func Decay

func Decay(v *AnimatedValue, c DecayConfig) *Animation

Decay slows v down from a velocity, as a fling.

func Delay

func Delay(d time.Duration) *Animation

Delay waits for d, as a step of a composite.

func Loop

func Loop(a *Animation, iterations int) *Animation

Loop runs a again each time it ends, with its values back at their start, iterations times; forever when 0. LoopOn starts each iteration where the last ended.

func LoopOn

func LoopOn(a *Animation, iterations int) *Animation

LoopOn is Loop without putting the values back before each iteration.

func Parallel

func Parallel(steps ...*Animation) *Animation

Parallel runs steps together and ends when all have.

func Sequence

func Sequence(steps ...*Animation) *Animation

Sequence runs steps one after another, each starting when the one before ends.

func Spring

func Spring(v *AnimatedValue, to float64, c SpringConfig) *Animation

Spring moves v to to on a damped spring.

func Stagger

func Stagger(interval time.Duration, steps ...*Animation) *Animation

Stagger runs steps together, each starting interval after the one before.

func Timing

func Timing(v *AnimatedValue, to float64, c TimingConfig) *Animation

Timing moves v to to over c.Duration.

func ValueKeyframes

func ValueKeyframes(v *AnimatedValue, t KeyframeTiming, stops ...KeyframeStop) *Animation

ValueKeyframes moves v through stops as t says, as CSS keyframes and the Web Animations API do: each iteration starts at its first stop, so a loop that ends where it starts never jumps, and the value stays where the last iteration leaves it.

type AnimationKind

type AnimationKind = driver.AnimationKind

AnimationKind is what an Animation does.

type AnimationRun

type AnimationRun struct {
	// contains filtered or unexported fields
}

AnimationRun is an animation StartAnimation runs on the platform.

func (*AnimationRun) Reset

func (r *AnimationRun) Reset()

Reset ends the run, unfinished if it still runs, and puts the values it moves back where they were as it started.

func (*AnimationRun) Stop

func (r *AnimationRun) Stop()

Stop ends the run where its values are, unfinished.

type AppInfo

type AppInfo struct {
	// ID and Name are nsgo.yaml's id and name.
	ID, Name string
	// Version is nsgo.yaml's version, and Build the build's number:
	// build_number, else Version. Both are "" where nsgo.yaml has none.
	Version, Build string
	// Development is true unless nsgo build built the app: under nsgo dev,
	// nsgo test and a plain go build.
	Development bool
}

AppInfo is the app's identity as nsgo.yaml gives it.

func App

func App() AppInfo

App returns the app's identity, which the nsgo tool builds into it.

type Appearance

type Appearance = driver.Appearance

Appearance is the light or dark appearance an app asks for, or the system's.

type AppleCredential added in v0.2.0

type AppleCredential struct {
	// User is the user's stable ID for the app's team, the same on each sign-in and what AppleCredentialState asks about.
	User string
	// IdentityToken is a JSON Web Token Apple signed, for the app's server to verify, and AuthorizationCode a short-lived code the server exchanges for tokens.
	IdentityToken, AuthorizationCode string
	// Email, which may be a private relay address, and the name's parts are given only on the user's first sign-in to the app and only as AppleSignInOptions asked for them; "" otherwise, so keep them then.
	Email                                                               string
	GivenName, FamilyName, MiddleName, NamePrefix, NameSuffix, Nickname string
}

AppleCredential is what a sign-in with Apple answers.

type AppleCredentialState added in v0.2.0

type AppleCredentialState uint8

AppleCredentialState is the state of a user's Sign in with Apple credential for the app.

const (
	// AppleCredentialAuthorized: the user is signed in to the app with Apple.
	AppleCredentialAuthorized AppleCredentialState = driver.AppleCredentialAuthorized
	// AppleCredentialRevoked: the user stopped using Sign in with Apple with the app, so it signs them out.
	AppleCredentialRevoked AppleCredentialState = driver.AppleCredentialRevoked
	// AppleCredentialNotFound: no credential of the user is known for the app.
	AppleCredentialNotFound AppleCredentialState = driver.AppleCredentialNotFound
	// AppleCredentialTransferred: the app moved to another team, and the user's ID with it, which the app's server migrates.
	AppleCredentialTransferred AppleCredentialState = driver.AppleCredentialTransferred
)

func (AppleCredentialState) String added in v0.2.0

func (s AppleCredentialState) String() string

String returns the state's name in TSX: "authorized", "revoked", "notFound" or "transferred"; "" for the zero state.

type AppleSignInError added in v0.2.0

type AppleSignInError string

AppleSignInError is why Sign in with Apple answered without a credential or a state.

const (
	// AppleSignInCancelled: the user closed the sheet, which is no failure.
	AppleSignInCancelled AppleSignInError = driver.AppleSignInCancelled
	// AppleSignInFailed: the system refused or could not answer, as it does for an app not signed with the entitlement (nsgo.yaml's apple.sign_in_with_apple) or a device signed in to no Apple Account.
	AppleSignInFailed AppleSignInError = driver.AppleSignInFailed
	// AppleSignInUnavailable: this platform has no Sign in with Apple (Env.CanSignInWithApple).
	AppleSignInUnavailable AppleSignInError = driver.AppleSignInUnavailable
)

func (AppleSignInError) Error added in v0.2.0

func (e AppleSignInError) Error() string

type AppleSignInOptions added in v0.2.0

type AppleSignInOptions struct {
	// FullName and Email ask for the user's name and email, which Apple gives only the first time the user signs in to the app.
	FullName, Email bool
	// Nonce goes into the request as its SHA-256, in lowercase hex, which the identity token's nonce claim then holds, so the app's server, which knows Nonce, can tell the token was made for this sign-in. "" sends none.
	Nonce string
}

AppleSignInOptions are what SignInWithApple asks for.

type AppleSignInRequest added in v0.2.0

type AppleSignInRequest = driver.AppleSignInRequest

AppleSignInRequest is a sign-in with Apple as the platform carries it out, as a test's model sees it: AppleSignInOptions with the nonce hashed.

type ApproxLayout

type ApproxLayout struct {
	Lines []string
	Size  Size
	// contains filtered or unexported fields
}

ApproxLayout is the TextLayout of ApproxTextEngine: the text's lines.

func (*ApproxLayout) Attachment

func (l *ApproxLayout) Attachment(i int) (Bounds, bool)

Attachment implements AttachmentLayout.

func (*ApproxLayout) CaretRect

func (l *ApproxLayout) CaretRect(c Caret) (Bounds, bool)

CaretRect returns the caret at c, as high as its line.

func (*ApproxLayout) HitTest

func (l *ApproxLayout) HitTest(p Point) Caret

HitTest returns the caret nearest p in the layout's content box.

func (*ApproxLayout) RangeRects

func (l *ApproxLayout) RangeRects(start, end int, out []Bounds) []Bounds

RangeRects appends to out the boxes covering UTF-16 offsets start to end.

func (*ApproxLayout) Release

func (*ApproxLayout) Release()

Release implements TextLayout.

func (*ApproxLayout) TextLines

func (l *ApproxLayout) TextLines() []TextLine

TextLines implements LineLayout.

type ApproxTextEngine

type ApproxTextEngine struct{}

ApproxTextEngine measures text without a platform: every character is 0.6 of the font size wide, lines are 1.2 of it tall, and lines wrap at spaces. Its font's ascent is the line, its descent 0 and its x height half the font size. Headless tests use it.

func (ApproxTextEngine) Prepare

Prepare implements TextEngine.

type AttachmentLayout

type AttachmentLayout interface {
	// Attachment returns the box of attachment i in the content box, or
	// false when the line limit cut it off.
	Attachment(i int) (Bounds, bool)
}

AttachmentLayout is a TextLayout of text with attachments. The engine asks it where each went after laying the text out.

type AttributedText

type AttributedText = driver.AttributedText

type AudioError

type AudioError string

AudioError is why a sound or a player failed, named as NSH's codes, which follow the web's MediaError: the core's part of audio.Error, which apps use. A failure that says more is one wrapped with the platform's words, which errors.Is and errors.As find.

const (
	// AudioNotAllowed: the current owner's Access refuses AccessAudio, or AccessNetwork for an http(s) source; or, on the web, the browser refused to play before a user gesture.
	AudioNotAllowed AudioError = driver.AudioNotAllowed
	// AudioNetwork: the source could not be fetched.
	AudioNetwork AudioError = driver.AudioNetwork
	// AudioDecode: the source is in a format the platform cannot read.
	AudioDecode AudioError = driver.AudioDecode
	// AudioNotSupported: the source is none the platform plays, such as one with neither a URI nor bytes.
	AudioNotSupported AudioError = driver.AudioNotSupported
	// AudioQuotaExceeded: past a limit of the engine's, which a sound's load meets: more than 8 MiB encoded or 5 seconds decoded, a 65th sound, or more than 16 MiB decoded among them.
	AudioQuotaExceeded AudioError = driver.AudioQuotaExceeded
	// AudioUnavailable: the platform plays no audio (Env.CanPlayAudio).
	AudioUnavailable AudioError = driver.AudioUnavailable
	// AudioFailed: the platform failed otherwise, such as a player whose output went away.
	AudioFailed AudioError = driver.AudioFailed
)

func (AudioError) Error

func (e AudioError) Error() string

type AudioPlayer

type AudioPlayer struct {
	// contains filtered or unexported fields
}

AudioPlayer plays long audio, streamed and decoded as it plays: the core's part of audio.Player, which apps use. Its methods are called on the engine's goroutine, and all but the getters are commands in the batch of the turn that calls them.

func (*AudioPlayer) Close

func (p *AudioPlayer) Close()

Close stops the player and releases the platform's; its callbacks, Play's among them, never run after it. Calling it again does nothing.

func (*AudioPlayer) Duration

func (p *AudioPlayer) Duration() time.Duration

Duration returns how long the player plays, 0 until it loaded and for a stream without one.

func (*AudioPlayer) Pause

func (p *AudioPlayer) Pause()

Pause pauses the player.

func (*AudioPlayer) Play

func (p *AudioPlayer) Play(done func(error))

Play plays the player from where it is, loading it first if needed, and calls done, when not nil, once it plays or with why it cannot, an AudioError. Where the platform plays no audio it fails at once with AudioUnavailable, without asking it.

func (*AudioPlayer) Position

func (p *AudioPlayer) Position() time.Duration

Position returns where the player is, as its last report or seek said.

func (*AudioPlayer) Preload

func (p *AudioPlayer) Preload()

Preload has the platform load the player without playing it, so that Play starts at once.

func (*AudioPlayer) Seek

func (p *AudioPlayer) Seek(position time.Duration)

Seek moves the player to position, clamped to its duration once it is known. Paused, or before it loaded, it applies once the platform can seek, and Play starts from there.

func (*AudioPlayer) SetLoop

func (p *AudioPlayer) SetLoop(loop bool)

SetLoop has the player start over at its end, with no OnEnd.

func (*AudioPlayer) SetRate

func (p *AudioPlayer) SetRate(r float32)

SetRate sets the playback speed, from 0.5 to 2; 0 is 1, as Video's, and other values are clamped.

func (*AudioPlayer) SetVolume

func (p *AudioPlayer) SetVolume(v float32)

SetVolume sets the volume, from 0 to 1; 0 is 1, as Video's, and other values are clamped.

func (*AudioPlayer) State

func (p *AudioPlayer) State() AudioPlayerState

State returns where the player is.

type AudioPlayerOptions

type AudioPlayerOptions struct {
	// OnLoad runs once the player knows its duration, 0 for a stream without one.
	OnLoad func(duration time.Duration)
	// OnProgress receives the position and the duration every ProgressInterval while the player plays, and once more as it pauses or ends. The position goes back only with a seek or a loop starting over.
	OnProgress func(position, duration time.Duration)
	// ProgressInterval is the time between OnProgress calls: 250 milliseconds when 0, and at least 16, as Video's.
	ProgressInterval time.Duration
	// OnBuffer receives whether playback waits for data.
	OnBuffer func(buffering bool)
	// OnEnd runs each time the player plays to its end; never while it loops.
	OnEnd func()
	// OnError receives why the player failed, an AudioError.
	OnError func(err error)
	// AudioSession is what the player does to other apps' audio while it plays: by default it mixes with them and, on iOS, the Ring/Silent switch silences it; with AudioSessionPlayback or AudioSessionMixWithOthers it plays in silent mode, the first pausing other apps' audio.
	AudioSession AudioSession
}

AudioPlayerOptions are an AudioPlayer's: the core's part of audio.PlayerOptions, which apps use. Its callbacks run on the engine's goroutine, in a later turn than what caused them.

type AudioPlayerState

type AudioPlayerState uint8

AudioPlayerState is where an AudioPlayer is, as the core follows it from the platform's events: the core's part of audio.PlayerState, which apps use.

const (
	// AudioPlayerIdle: nothing asked of it yet.
	AudioPlayerIdle AudioPlayerState = iota
	// AudioPlayerLoading: loading its source, or waiting for data as it plays.
	AudioPlayerLoading
	// AudioPlayerPlaying: playing.
	AudioPlayerPlaying
	// AudioPlayerPaused: loaded, not playing; paused by the app or by the system, as for a call.
	AudioPlayerPaused
	// AudioPlayerEnded: played to its end; Play starts it over.
	AudioPlayerEnded
	// AudioPlayerFailed: it failed and plays nothing until Play or Preload loads it again.
	AudioPlayerFailed
)

func (AudioPlayerState) String

func (s AudioPlayerState) String() string

String returns the state's name: idle, loading, playing, paused, ended or failed.

type AudioSession

type AudioSession = driver.AudioSession

AudioSession is what a video's sound does to the rest of the device's audio while it plays.

type AudioSource

type AudioSource struct {
	URI  string
	Data []byte
}

AudioSource is what a sound or a player plays, as an image's source says what it shows: the core's part of audio.Source, which apps use. URI is an "asset:" path in the app's resources, a file path or file: URL, a data: URL or an http(s) URL; Data, when set, is the bytes of a file, such as one embedded with go:embed, whose format their first bytes say.

type AuthError added in v0.2.0

type AuthError string

AuthError is why an auth session ended without its callback.

const (
	// AuthCancelled: the user closed the session, or the app cancelled it.
	AuthCancelled AuthError = driver.AuthCancelled
	// AuthUnavailable: this platform has no session for the redirect asked for, or the scope's Access does not grant AccessAuthSession.
	AuthUnavailable AuthError = driver.AuthUnavailable
	// AuthTimeout: AuthSessionOptions.Timeout passed first.
	AuthTimeout AuthError = driver.AuthTimeout
	// AuthFailed: the session or its options failed; the error wraps it with what failed.
	AuthFailed AuthError = driver.AuthFailed
)

func (AuthError) Error added in v0.2.0

func (e AuthError) Error() string

type AuthSessionOptions added in v0.2.0

type AuthSessionOptions struct {
	// Scheme is the app's own callback scheme, such as "com.example.app", which macOS's and iOS's session catches without the app registering it: the redirect is scheme:/path. "https" with Host catches an HTTPS redirect to the app's associated domain, from iOS 17.4 and macOS 14.4. Without one, desktops serve a loopback redirect, http://127.0.0.1:port/path on a random port, and the web one on the page's origin.
	Scheme string
	Host   string
	// Path is the redirect's path, "/" when empty.
	Path string
	// Ephemeral asks the session to share no cookies or data with the user's browser (prefersEphemeralWebBrowserSession), where the platform can.
	Ephemeral bool
	// Timeout ends the session with AuthTimeout after it, 0 never. A loopback session cannot tell that the user closed the browser's tab, so give it a timeout or a way to cancel.
	Timeout time.Duration
}

AuthSessionOptions say what redirect an auth session catches.

type AutoCapitalize

type AutoCapitalize = driver.AutoCapitalize

AutoCapitalize is a field's automatic capitalization; sentences are the default.

type AutoComplete

type AutoComplete = driver.AutoComplete

AutoComplete says what a field holds, for the system's autofill and suggestions: React Native's autoComplete, which iOS maps to its textContentType.

type BackdropMaterial

type BackdropMaterial = driver.BackdropMaterial

BackdropMaterial is the system material iOS draws a backdrop blur with. macOS draws its closest material for one other than BackdropUltraThin, the zero value, and blurs by the radius for that.

type BiometricKind

type BiometricKind uint8

BiometricKind says which enrolled biometric the system can use.

const (
	BiometricNone BiometricKind = iota
	BiometricFace
	BiometricFingerprint
)

type BiometricResult

type BiometricResult uint8

BiometricResult is the result of AuthenticateBiometric.

const (
	BiometricSuccess BiometricResult = iota + 1
	BiometricFailure
	BiometricCancelled
	BiometricUnavailable
)

type BlendMode

type BlendMode = driver.BlendMode

BlendMode is how a view's pixels mix with what is behind it.

type BorderCurve

type BorderCurve uint8

BorderCurve is the shape of rounded corners.

const (
	BorderCurveCircular BorderCurve = iota + 1
	BorderCurveContinuous
)

type BorderStyle

type BorderStyle = driver.BorderStyle

BorderStyle is how a border or an outline is drawn; the zero value is solid.

type Bounds

type Bounds = driver.Bounds

Bounds is a rectangle: its origin relative to the parent's and its size.

type BoxShadow

type BoxShadow = driver.BoxShadow

BoxShadow is one of CSS's box-shadow layers: the box's shape grown by Spread, moved by Offset and blurred by Blur (CSS's blur radius), inside the box when Inset.

func ParseBoxShadows

func ParseBoxShadows(s string) ([]BoxShadow, error)

ParseBoxShadows reads a CSS box-shadow list; none is no shadows.

func Ring

func Ring(width Points, c Color) BoxShadow

Ring returns the shadow Tailwind's ring utilities draw: a solid line width wide around the box, outside its border, taking no space. A ring offset is a ring in the offset's color over a wider one, as Tailwind stacks them:

Shadows: []BoxShadow{Ring(2, white), Ring(4, blue)}

type BoxSizing

type BoxSizing uint8

BoxSizing is the CSS box-sizing property.

const (
	BorderBox BoxSizing = iota + 1
	ContentBox
)

type Canvas

type Canvas struct {
	Draw func(d *Drawing, size Size)
	// Class is Tailwind CSS classes, as View's.
	Class     string
	ClassFunc func() string
	Style     Style
	StyleFunc func() Style
	OnPress   func(PressEvent)
	OnLayout  func(Bounds)
	Ref       *Ref
	// Label names the drawing for assistive technology, which reads it as an image; LabelFunc follows what it reads, as Text's does.
	Label     string
	LabelFunc func() string
	TestID    string
	// Em sizes the canvas where its style sets no size, in ems of the font size it inherits, scaled by the user's text size setting as text is: Em.Width wide and Em.Ascent+Em.Descent high, so it grows with the text around it as an icon does. In a text's attachment aligned to the baseline (VerticalAlignBaseline), its baseline, Em.Descent ems above its bottom, sits on the line's, and the text's NoFontScaling and MaxFontSizeMultiplier hold it too. EmFunc follows what it reads, laying the canvas out again; base/formula sizes its formulas so.
	Em     EmBox
	EmFunc func() EmBox
}

Canvas draws what Draw records, at the canvas's size, again whenever a signal Draw read, the size or the available fonts change. The platform plays the recording on the main thread; Draw itself runs on the engine.

The Drawing measures text with the platform's text engine (MeasureText, TextMetrics) and answers hit tests (IsPointInPath, IsPointInStroke) during Draw and after it, so OnPress can test the shapes of the last drawing Draw was given. Arguments bound to animated nodes (Drawing.Bind) redraw on the platform's frame clock without a commit, and Drawing.Node names parts of the drawing for assistive technology and tests.

A drawing that fills shapes with its view's background (Drawing.FillBackgroundFromView) takes the canvas's Background and Gradients, which the view then does not draw.

func (Canvas) Render

func (c Canvas) Render(*Scope) Node

Render implements Node.

type CanvasGradient

type CanvasGradient = driver.CanvasGradient

CanvasGradient is a linear, radial or conic color gradient that a Drawing fills and strokes with.

func CanvasConic

func CanvasConic(angle, x, y float32, stops ...GradientStop) *CanvasGradient

CanvasConic returns a canvas gradient around (x, y) from angle radians, turning clockwise.

func CanvasLinear

func CanvasLinear(x0, y0, x1, y1 float32, stops ...GradientStop) *CanvasGradient

CanvasLinear returns a canvas gradient from (x0, y0) to (x1, y1).

func CanvasRadial

func CanvasRadial(x0, y0, r0, x1, y1, r1 float32, stops ...GradientStop) *CanvasGradient

CanvasRadial returns a canvas gradient from the circle (x0, y0, r0) to the circle (x1, y1, r1).

type CanvasNode

type CanvasNode = driver.CanvasNode

CanvasNode is a named part of a drawing, which assistive technology and tests see as a child of the canvas.

type Caret

type Caret = driver.Caret

Caret is a caret position in a text: a UTF-16 offset and the side it is on.

type CaretEvent

type CaretEvent struct {
	Bounds     Bounds
	PageBounds Bounds
}

CaretEvent is where an input's caret is: Bounds in the input's view, as wide as the platform draws the caret and as tall as its line, and PageBounds the same in the surface, which an Overlay's AnchorBounds takes. Empty Bounds mean the platform could not place it yet.

type Catch

type Catch struct {
	Try      func(cx *Scope) Node
	Fallback func(cx *Scope, err error, reset func()) Node
}

Catch builds Try and, when it or anything under it panics, Fallback instead, disposing what failed before its bindings can run again. Calling reset builds Try again.

func (Catch) Render

func (c Catch) Render(*Scope) Node

Render implements Node.

type ClipboardImage

type ClipboardImage = driver.ClipboardImage

ClipboardImage is an image read from the clipboard: a PNG and its size in pixels.

type Clock

type Clock interface {
	Now() time.Time
	// AfterFunc calls f on its own goroutine after d, unless stop is
	// called first; stop reports whether it prevented the call.
	AfterFunc(d time.Duration, f func()) (stop func() bool)
}

Clock is the time a graph's timers run on. Go cannot hook time globally, so tests inject a ManualClock where an app would use the system's.

type Collection

type Collection[K comparable, T any] struct {
	// contains filtered or unexported fields
}

Collection holds items by key, in order, each in a signal of its own, as a Solid store holds an array: a computation that reads one item follows that item alone, and one that reads the order follows only insertions, removals and moves. A list's rows read their own items, so changing one item runs one row where a signal of the whole slice runs them all.

Like a signal's, its methods belong to the graph's goroutine.

func NewCollection

func NewCollection[K, T comparable](cx *Scope, key func(T) K, items []T) *Collection[K, T]

NewCollection returns a collection of items, keyed by key; an item set equal to the one held changes nothing. Two items with the same key panic.

func NewCollectionFunc

func NewCollectionFunc[K comparable, T any](cx *Scope, key func(T) K, equal func(a, b T) bool, items []T) *Collection[K, T]

NewCollectionFunc returns a collection as NewCollection does that compares items with equal; with a nil equal every item set notifies its readers, as items holding slices or maps need.

func (*Collection[K, T]) At

func (c *Collection[K, T]) At(i int) (T, bool)

At returns the item at i, following the order and that item, and whether i is in range, as a list's row reads its item: unlike KeyAt it never panics.

func (*Collection[K, T]) Delete

func (c *Collection[K, T]) Delete(k K) bool

Delete removes the item keyed k, and reports whether the collection held one.

func (*Collection[K, T]) Get

func (c *Collection[K, T]) Get(k K) (T, bool)

Get returns the item keyed k, following that item alone, and whether the collection holds one; without one it follows the order, to see one added.

func (*Collection[K, T]) Items

func (c *Collection[K, T]) Items() []T

Items returns the items in order, following the order and every item.

func (*Collection[K, T]) KeyAt

func (c *Collection[K, T]) KeyAt(i int) K

KeyAt returns the key of the item at i, following the order; it panics when i is out of range, as a slice does.

func (*Collection[K, T]) Keys

func (c *Collection[K, T]) Keys() []K

Keys returns the keys in order, following the order. The slice is the collection's: it does not change, and must not be changed.

func (*Collection[K, T]) Len

func (c *Collection[K, T]) Len() int

Len returns the number of items, following the order.

func (*Collection[K, T]) Replace

func (c *Collection[K, T]) Replace(items []T)

Replace makes the collection hold items, in their order, as Solid's reconcile does: an item whose key it held replaces that item, notifying its readers only when it differs, items with new keys are added, the others removed, and the order notifies only when it changes. Two items with the same key panic.

func (*Collection[K, T]) Set

func (c *Collection[K, T]) Set(item T)

Set replaces the item with item's key, or adds item at the end.

func (*Collection[K, T]) Update

func (c *Collection[K, T]) Update(k K, fn func(T) T) bool

Update replaces the item keyed k with what fn returns for it, and reports whether the collection held one. fn must keep the item's key.

type Color

type Color = driver.Color

Color is an sRGB color packed as 0xRRGGBBAA, the wire form of mount items.

const Transparent Color = 0x00000100

Transparent is a color that draws nothing but, unlike 0, is set: a border Transparent colors draws none, where one left 0 draws in the text color.

func ParseColor

func ParseColor(s string) (Color, error)

ParseColor reads a CSS color, as a host's Tokens give them: hex ("#e11d48", "#fff8"), rgb(), rgba(), hsl(), hsla(), a color name or transparent.

func RGB

func RGB(hex uint32) Color

RGB returns an opaque color from 0xRRGGBB.

func RGBA

func RGBA(hex uint32, alpha float32) Color

RGBA returns a color from 0xRRGGBB and an alpha from 0 to 1.

func SetColor

func SetColor(c Color) Color

SetColor returns c as a style field takes a color the app set: Transparent when c is fully transparent black, 0, which would leave the field unset.

type ColorMatrix

type ColorMatrix = driver.ColorMatrix

ColorMatrix is a 4×5 color matrix in rows, as SVG's feColorMatrix.

type ColorSpace

type ColorSpace = driver.ColorSpace

ColorSpace is where a gradient's colors mix between stops.

type ColorStop

type ColorStop = driver.ColorStop

ColorStop is a color at a place along a gradient.

type CompositeOp

type CompositeOp = driver.CompositeOp

CompositeOp is how drawing mixes with what a canvas holds, as the web's globalCompositeOperation.

type Composition

type Composition struct {
	// Composing is false once the composition ended.
	Composing bool
	// Text is what is being composed; empty once it ended.
	Text string
}

Composition is an input method's composition in a text field.

type Constant

type Constant float64

Constant is a fixed operand for Add, Sub, Mul, Div and Mod.

func (Constant) AnimatedNodeID

func (Constant) AnimatedNodeID() uint32

AnimatedNodeID implements AnimatedNode: a constant is no node.

type ContextMenuEvent

type ContextMenuEvent struct {
	Position     Point
	PagePosition Point
	Modifiers    Modifiers
}

ContextMenuEvent is where a context menu was asked for. PagePosition is where a menu for it opens.

type Corners

type Corners = driver.Corners

Corners holds a radius per corner of a box.

func AllCorners

func AllCorners(r Points) Corners

AllCorners returns corners of the same radius.

type Cursor

type Cursor = driver.Cursor

Cursor is the pointer's look over a view (cursor).

type Curve

type Curve = driver.Curve

Curve is an easing curve: CSS's cubic Bézier from (0,0) to (1,1) through two control points.

type DataStyle

type DataStyle struct {
	Name  string
	Style *Style
}

DataStyle styles a node, or a group, that shows the data-* attribute Name (PartStates.Data).

type DecayConfig

type DecayConfig = driver.DecayConfig

DecayConfig slows a value from Velocity (units per second; the value's current velocity when 0) by Deceleration per millisecond (0.998 when 0).

type DesktopViewProps

type DesktopViewProps struct {
	// WindowDrag makes the view a handle that moves the desktop window.
	WindowDrag WindowDrag
}

DesktopViewProps are a View's props only the desktops have.

type DirectoriesRequest

type DirectoriesRequest = driver.DirectoriesRequest

DirectoriesRequest is a folder pick as the platform carries it out, PickDirectoriesOptions resolved.

type Directory

type Directory = driver.Directory

Directory is a folder the user picked, read as an fs.FS: its name, and where it is on disk where it has a path.

type Display

type Display uint8

Display says whether a node takes part in layout.

const (
	DisplayFlex Display = iota + 1
	// DisplayNone hides the node and takes it out of layout.
	DisplayNone
	// DisplayGrid lays children out in a CSS grid.
	DisplayGrid
	// DisplayBlock stacks children as CSS block boxes, collapsing their
	// vertical margins.
	DisplayBlock
)

type DisplayInfo

type DisplayInfo = driver.DisplayInfo

DisplayInfo is one desktop display reported by Env.Displays.

type DrawArg

type DrawArg = driver.DrawArg

DrawArg is an argument of a DrawOp that Drawing.Bind binds to an animated node.

type DrawKind

type DrawKind = driver.DrawKind

DrawKind is a drawing operation.

type DrawOp

type DrawOp = driver.DrawOp

DrawOp is one operation; Kind says which fields it uses.

type DrawSlot

type DrawSlot = driver.DrawSlot

DrawSlot binds an argument of a drawing's operation to an animated node.

type Drawing

type Drawing = driver.Drawing

Drawing is a recording of 2D drawing operations, modeled on the web's CanvasRenderingContext2D: a current path, fill and stroke settings, and a transform, saved and restored as a stack.

type Dynamic

type Dynamic func(cx *Scope) Node

Dynamic builds its nodes again whenever what fn read changes. The nodes it built before go first, so their bindings never run against what replaced them.

func (Dynamic) Render

func (d Dynamic) Render(*Scope) Node

Render implements Node.

type EaseMode

type EaseMode = driver.EaseMode

EaseMode applies a curve as is, mirrored, or both halves.

type Easing

type Easing = driver.Easing

Easing is how a timing animation or an interpolation segment progresses: a cubic Bézier, or one of React Native's curves.

func BezierEasing

func BezierEasing(c Curve) Easing

BezierEasing returns the easing of c.

func StepsEasing

func StepsEasing(count int, position StepPosition) Easing

StepsEasing returns CSS's steps(count, position): count equal jumps.

type EasingKind

type EasingKind = driver.EasingKind

EasingKind is an easing's shape.

type EdgeBar

type EdgeBar struct {
	Scroll *Ref
	// Side is the one side it is over.
	Side Sides
}

EdgeBar makes a view a bar over a side of the scroll view Scroll refers to, which content scrolls under: a header or a toolbar placed over it. The scroll view's edge effect at that side reaches as far as its bars do:

scroll := &core.Ref{}
core.View{Children: []core.Node{
	core.Scroll{Ref: scroll, EdgeEffects: core.EdgeEffects{Top: core.EdgeEffectSoft}, ...},
	core.View{EdgeBar: core.EdgeBar{Scroll: scroll, Side: core.SideTop},
		Style: core.Style{Position: core.Absolute, Top: core.Pt(0), Left: core.Pt(0), Right: core.Pt(0)}, ...},
}}

type EdgeColors

type EdgeColors = driver.EdgeColors

EdgeColors is a color for each side of a box.

func AllColors

func AllColors(c Color) EdgeColors

AllColors returns edge colors of the same color on every side.

type EdgeEffect

type EdgeEffect = driver.EdgeEffect

EdgeEffect is how a scroll view's side sets the views over it, its bars (View.EdgeBar), apart from the content scrolling under them, as iOS 26's scroll edge effects do: Scroll.EdgeEffects.

A soft edge blurs the content more toward the side, as far as the bars reach and a little past them, and fades it into the background it scrolls over; a hard edge frosts it evenly under the bars, with a hairline along them. All but Linux blur by a radius that grows toward the side; Linux only fades the content into the background.

type EdgeEffects

type EdgeEffects struct {
	Top, Right, Bottom, Left EdgeEffect
}

EdgeEffects are a scroll view's edge effects, by side.

type Edges

type Edges = driver.Edges

Edges holds a length per side.

func All

func All(p Points) Edges

All returns edges of the same length on every side.

func Insets

func Insets(cx *Scope) Edges

Insets returns what content under cx must keep clear of: the insets of the nearest screen, modal or ProvideInsets, or the surface's safe area.

func Symmetric

func Symmetric(vertical, horizontal Points) Edges

Symmetric returns edges with vertical and horizontal lengths.

type Effects

type Effects = driver.Effects

Effects are the shadows, gradients, filters and mask a view draws.

type Element

type Element struct {
	// contains filtered or unexported fields
}

Element is an element built one change at a time, as nsh-core's operations (ops.rs) build what NSH's renderer runs: the tsx package's. It is made detached, shows where it is inserted into another element or mounted as a Node, and is released with the owner it was made under.

func NewElement

func NewElement(cx *Scope, props Node) *Element

NewElement returns a detached element whose props are props: a View, a Text, a Scroll, an Input or an Image. Its functions are read when it is made and on each Set, never bound: the tsx runtime binds what changes itself. With nil props it is a region, whose children lay out as its parent's.

func (*Element) Insert

func (e *Element) Insert(child, before *Element)

Insert puts child among e's children before before, at the end when before is nil or not e's, moving it from where it was.

func (*Element) Mount

func (e *Element) Mount(node Node)

Mount shows node in region element e, built under e's owner: Go components among an element's children.

func (*Element) Release

func (e *Element) Release()

Release takes the element out and frees it, with what Go code mounted in it; the elements among its children only leave it.

func (*Element) Remove

func (e *Element) Remove(child *Element)

Remove takes child out of e's children; it stays until released.

func (*Element) Render

func (e *Element) Render(*Scope) Node

Render implements Node: mounted, the element moves there.

func (*Element) Set

func (e *Element) Set(props Node)

Set replaces the element's props with props, of the type it was made with.

type EllipsizeMode

type EllipsizeMode = driver.EllipsizeMode

EllipsizeMode is where a text cut by its line limit loses the rest.

type EmBox

type EmBox struct {
	Width, Ascent, Descent float32
}

EmBox is a canvas's natural size in ems of its font size (Canvas.Em): Width wide, reaching Ascent above its baseline and Descent below it.

type Env

type Env struct {
	// contains filtered or unexported fields
}

Env is the environment as signals, one per part, so a binding runs again only when a part it read changes.

func (*Env) AppClip

func (e *Env) AppClip() bool

AppClip reports whether the app runs as an iOS App Clip: the core's part of mobile.IsAppClip, which apps use.

func (*Env) Appearance

func (e *Env) Appearance() Appearance

Appearance returns the appearance Scope.SetAppearance forces, or AppearanceSystem.

func (*Env) AppleKeys

func (e *Env) AppleKeys() bool

AppleKeys reports whether shortcuts follow Apple's conventions: "mod" is Command and labels use ⌘.

func (*Env) CanLookUp added in v0.2.0

func (e *Env) CanLookUp() bool

CanLookUp reports whether desktop.LookUp can show the system dictionary panel.

func (*Env) CanMakeWindowsTransparent added in v0.2.0

func (e *Env) CanMakeWindowsTransparent() bool

CanMakeWindowsTransparent reports whether the scope's desktop window shows what is behind it while transparent (WindowOptions.Transparent, SetWindowTransparent): the core's part of desktop.CanMakeWindowsTransparent, which apps use.

func (*Env) CanPickScreenColor

func (e *Env) CanPickScreenColor() bool

CanPickScreenColor reports whether Scope.PickScreenColor works here: macOS and browsers with an EyeDropper.

func (*Env) CanPlaceWindows added in v0.2.0

func (e *Env) CanPlaceWindows() bool

CanPlaceWindows reports whether SetWindowFrame places the scope's window where it says, an Android overlay's included: the core's part of desktop.CanPlaceWindows, which apps use.

func (*Env) CanPlayAudio

func (e *Env) CanPlayAudio() bool

CanPlayAudio reports whether the platform plays the audio package's sounds and players; elsewhere they fail with AudioUnavailable without asking it.

func (*Env) CanPurchase added in v0.2.0

func (e *Env) CanPurchase() bool

CanPurchase reports whether Scope.Products, Purchase and the other in-app purchase services reach a store here: the App Store on macOS, iOS and tvOS, in a build nsgo.yaml's apple.purchases gives StoreKit.

func (*Env) CanRecognizeSpeech

func (e *Env) CanRecognizeSpeech() bool

CanRecognizeSpeech reports whether Scope.StartSpeech recognizes speech here: macOS and iOS.

func (*Env) CanScheduleNotifications added in v0.2.0

func (e *Env) CanScheduleNotifications() bool

CanScheduleNotifications reports whether a Notification with a later At or a Repeat is scheduled here, for the system to show with the app's process ended: on macOS and iOS in an app bundle, Android, and Windows for one without a Repeat. Elsewhere ShowNotification answers false for one without asking the platform.

func (*Env) CanSendInput

func (e *Env) CanSendInput() bool

CanSendInput reports whether Ref.SendInput can give a web view's page trusted input here. macOS supports this through AppKit; other backends currently drop it.

func (*Env) CanSetWindowLevel added in v0.2.0

func (e *Env) CanSetWindowLevel() bool

CanSetWindowLevel reports whether SetWindowLevel stacks the scope's desktop window: the core's part of desktop.CanSetWindowLevel, which apps use.

func (*Env) CanSetWindowWorkspaces added in v0.2.0

func (e *Env) CanSetWindowWorkspaces() bool

CanSetWindowWorkspaces reports whether SetWindowWorkspaces puts the scope's desktop window on the workspaces it names: the core's part of desktop.CanSetWindowWorkspaces, which apps use.

func (*Env) CanSignInWithApple added in v0.2.0

func (e *Env) CanSignInWithApple() bool

CanSignInWithApple reports whether Scope.SignInWithApple and Scope.AppleCredentialState reach Sign in with Apple here: macOS, iOS and tvOS.

func (*Env) CanSkipTaskbar added in v0.2.0

func (e *Env) CanSkipTaskbar() bool

CanSkipTaskbar reports whether WindowOptions.SkipTaskbar and SetSkipTaskbar keep the scope's desktop window off the taskbar: the core's part of desktop.CanSkipTaskbar, which apps use.

func (*Env) CanSpeak added in v0.2.0

func (e *Env) CanSpeak() bool

CanSpeak reports whether Scope.Speak speaks text here: macOS, iOS, tvOS, Android, Windows, the web where the browser has speechSynthesis, and Linux where speech-dispatcher is installed. Elsewhere an utterance fails with SpeakUnavailable without asking the platform.

func (*Env) CanTakePhoto

func (e *Env) CanTakePhoto() bool

CanTakePhoto reports whether Scope.TakePhoto shows a camera here: iOS and Android devices with one, and browsers on touch screens.

func (*Env) Dark

func (e *Env) Dark() bool

Dark reports whether the app shows dark: the appearance Scope.SetAppearance forces, else the system's.

func (*Env) Desktop

func (e *Env) Desktop() bool

Desktop reports whether the device is a desktop.

func (*Env) DeviceModel added in v0.2.0

func (e *Env) DeviceModel() string

DeviceModel returns the device's hardware model: its model identifier on Apple's platforms, such as "iPhone15,2" or "Mac15,7", its maker and model on Android, such as "Google Pixel 8", and the firmware's product name on Windows and Linux; it is empty on the web and where the hardware names none.

func (*Env) DeviceName added in v0.2.0

func (e *Env) DeviceName() string

DeviceName returns the name the user gave the device, such as "Ada's MacBook Pro", as the system's settings show it; it is empty on the web and where the platform keeps it private, as iOS does from apps without Apple's user-assigned device name entitlement.

func (*Env) Displays

func (e *Env) Displays() []DisplayInfo

Displays returns the desktop displays in screen coordinates. Frame is the whole display, VisibleFrame is the area available to windows, Scale is device pixels per point, and Main marks the primary display. It is empty where the platform has no desktop display information.

func (*Env) FontScale

func (e *Env) FontScale() float32

FontScale returns the user's text size multiplier.

func (*Env) FullScreen

func (e *Env) FullScreen() bool

FullScreen reports whether the window is in full screen: the core's part of desktop.FullScreen, which apps use.

func (*Env) Geometry

func (e *Env) Geometry() Geometry

Geometry returns how a fold or hinge divides the surface: its usable regions, each with the safe area that falls in it, and the obstructions between them, in the surface's coordinates and measured at Window's size, which it changes with. A surface without a fold, as on every target but Android and iOS 27.1, has one region and no obstructions. Core lays nothing out by it: an app or component reads it and chooses its own panes.

func (*Env) HasWebView

func (e *Env) HasWebView() bool

HasWebView reports whether this target provides the native or browser web view host used by WebView.

func (*Env) Idiom

func (e *Env) Idiom() Idiom

Idiom returns the kind of device.

func (*Env) IncreaseContrast added in v0.2.0

func (e *Env) IncreaseContrast() bool

IncreaseContrast reports whether the user asked the system for stronger contrast, such as macOS Increase Contrast or a Windows contrast theme.

func (*Env) KeyboardDuration

func (e *Env) KeyboardDuration() time.Duration

KeyboardDuration returns how long the keyboard takes to move.

func (*Env) KeyboardHeight

func (e *Env) KeyboardHeight() Points

KeyboardHeight returns how much of the bottom the keyboard covers.

func (*Env) Language

func (e *Env) Language() string

Language returns the language the app shows: of its catalogs' languages, the one that suits Locale best, as SetLanguageMatch says; "" for an app without catalogs. Package i18n's Language, which apps use, reads it.

func (*Env) LaunchedAtLogin added in v0.2.0

func (e *Env) LaunchedAtLogin() bool

LaunchedAtLogin reports whether the system started this run as a login item: the core's part of desktop.LaunchedAtLogin, which apps use.

func (*Env) Lifecycle

func (e *Env) Lifecycle() Lifecycle

Lifecycle returns whether the app is in use: active, inactive (shown without the focus) or in the background. On desktops it is the window's the scope is in, a minimized or covered window's in the background while the others show, and the app's own scope's is every window's together.

func (*Env) Locale

func (e *Env) Locale() string

Locale returns the locale the app runs in, a BCP 47 tag: the one Scope.SetLocale forces, else the embedding host's, else the user's.

func (*Env) LocaleSettings

func (e *Env) LocaleSettings() LocaleSettings

LocaleSettings returns how the user reads weeks, times and measures, apart from the language, where the platform says: zero where it does not. Package i18n's Regional fills them in from the locale's region.

func (*Env) Maximized

func (e *Env) Maximized() bool

Maximized reports whether the window is maximized or zoomed: the core's part of desktop.Maximized, which apps use.

func (*Env) Minimized

func (e *Env) Minimized() bool

Minimized reports whether the window is minimized: the core's part of desktop.Minimized, which apps use.

func (*Env) OS

func (e *Env) OS() OS

OS returns the operating system.

func (*Env) OSVersion

func (e *Env) OSVersion() OSVersion

OSVersion returns the system's version: Android's API level as its major, zero on the web.

func (*Env) OpenedURL

func (e *Env) OpenedURL() string

OpenedURL returns the web link that last opened the app, "" when none did: the core's part of mobile.OpenedURL, which apps use.

func (*Env) PixelRatio

func (e *Env) PixelRatio() float32

PixelRatio returns device pixels per point.

func (*Env) RTL

func (e *Env) RTL() bool

RTL reports whether the app lays out right to left: as the language it shows is written (Language), else the locale it forces, else as the system lays out.

func (*Env) ReduceMotion

func (e *Env) ReduceMotion() bool

ReduceMotion reports whether the user asked for less motion.

func (*Env) SafeArea

func (e *Env) SafeArea() Edges

SafeArea returns the insets system UI covers on each edge.

func (*Env) ScreenReader

func (e *Env) ScreenReader() bool

ScreenReader reports whether a screen reader is running.

func (*Env) TitleBar

func (e *Env) TitleBar() Edges

TitleBar returns what a hidden desktop title bar covers: the core's part of desktop.TitleBar, which apps use.

func (*Env) VerticalBarEdge

func (e *Env) VerticalBarEdge() VerticalBarEdge

VerticalBarEdge returns the edge the system chose for a vertical bar, such as a tab bar drawn down a side, where it may place one, as iOS 27.1 does; VerticalBarUnspecified elsewhere.

func (*Env) Window

func (e *Env) Window() Size

Window returns the surface's size.

func (*Env) WindowFrame

func (e *Env) WindowFrame() WindowFrame

WindowFrame returns where the window is and how large: the core's part of desktop.Frame, which apps use.

func (*Env) WindowMaterial

func (e *Env) WindowMaterial() WindowMaterial

WindowMaterial returns the material behind the window's content, or WindowMaterialNone when the window is opaque: the core's part of desktop.ShowsMaterial, which apps use.

func (*Env) WindowTransparent added in v0.2.0

func (e *Env) WindowTransparent() bool

WindowTransparent reports whether the scope's window or panel draws nothing of its own now, no background, frame or shadow, so what is behind it shows wherever the content draws nothing: a panel opened with PanelOptions.Transparent, or a window opened with WindowOptions.Transparent or made so by SetWindowTransparent, where the platform could. It is the core's part of desktop.Transparent, which apps use. CanMakeWindowsTransparent is whether a window could be; this is whether it is. Where it is false, give the content a background of its own.

type EnvEdges

type EnvEdges struct{ Top, Right, Bottom, Left EnvInset }

EnvEdges are the environment's terms on each edge of a padding or a margin. Right to left, a term follows its edge's swap and takes the inset of the edge it lands on.

func EnvAll

func EnvAll(e EnvInset) EnvEdges

EnvAll returns e on every edge.

type EnvInset

type EnvInset uint8

EnvInset is a value of the environment a padding or margin adds to its length, as CSS's env() in NSH's styles: the safe area's inset on the edge, or the software keyboard's height. The node follows it as it changes, the keyboard's moves animating with the keyboard natively.

const (
	EnvNone EnvInset = iota
	// EnvSafeArea is the inset on the edge of the root view the node renders in (Insets): the surface's safe area, a dialog's, a page's below its header, or a tab section's above a drawn tab bar.
	EnvSafeArea
	// EnvKeyboard is the software keyboard's height over the surface, 0
	// while it is hidden or on a hardware keyboard. As a view's bottom
	// padding or margin it keeps the content above the keyboard.
	EnvKeyboard
)

type Environment

type Environment = driver.Environment

Environment is what the platform reports about where the app runs.

type Error

type Error struct {
	Code    string
	Message string
	// Permission is the capability a refusal lacks and Resource the path,
	// URL or name asked for, with CodeAccessDenied.
	Permission, Resource string
	// Err is what failed underneath, if anything.
	Err error
}

Error is a failure with a stable Code.

func AccessDenied

func AccessDenied(permission, resource string) *Error

AccessDenied is the failure of what a capability does not grant.

func Unavailable

func Unavailable(message string) *Error

Unavailable is the failure of what this platform does not do.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Extrapolate

type Extrapolate = driver.Extrapolate

Extrapolate is what an interpolation does outside its input range; 0 clamps.

type File

type File = driver.File

File is a file the user picked: its name, type, size, modification time and where it is on disk.

func FileFromURL

func FileFromURL(raw string) (File, error)

FileFromURL returns the file a URL from OnFileDrop, ReadClipboardFiles or a PasteEvent names, for File.Open to read. A file: URL names a local file, which has its path, size and modification time; the web's blob: URL, whose fragment is the file's name, names a file the page holds, which has no path, and has its size, type and time when the page made the URL from a drop. A folder, a file that is not there, a file: URL with a remote host outside Windows, a blob: URL off the web and every other scheme return an error.

type FilesRequest

type FilesRequest = driver.FilesRequest

FilesRequest is a file pick as the platform carries it out, PickFilesOptions resolved.

type FillRule

type FillRule = driver.FillRule

FillRule is how a fill or a clip decides what is inside a path.

type Filter

type Filter = driver.Filter

Filter is one of CSS's filter functions; Blur, Brightness and the other constructors make them.

func Blur

func Blur(radius Points) Filter

Blur blurs what a view draws (in Filters) or what is behind it (in BackdropFilters) by radius, CSS's blur().

func Brightness

func Brightness(f float32) Filter

Brightness multiplies the colors by f: 0 is black, 1 unchanged.

func Contrast

func Contrast(f float32) Filter

Contrast scales the colors away from grey by f: 0 is grey, 1 unchanged.

func DropShadow

func DropShadow(offset Point, blur Points, c Color) Filter

DropShadow draws a shadow of what the view draws, in its shape rather than its box's: offset, blur radius and color.

func Fade

func Fade(f float32) Filter

Fade multiplies the alpha by f, CSS's opacity().

func Grayscale

func Grayscale(f float32) Filter

Grayscale takes f of the color away: 1 is grey.

func HueRotate

func HueRotate(degrees float32) Filter

HueRotate turns the hues by degrees.

func Invert

func Invert(f float32) Filter

Invert inverts f of the colors: 1 is a negative.

func ParseFilters

func ParseFilters(s string) ([]Filter, error)

ParseFilters reads a CSS filter list; none is no filters.

func Saturate

func Saturate(f float32) Filter

Saturate scales the saturation by f: 0 is grey, 1 unchanged.

func Sepia

func Sepia(f float32) Filter

Sepia tones f of the colors sepia.

type FilterKind

type FilterKind = driver.FilterKind

FilterKind is which filter function a Filter is.

type FlexDirection

type FlexDirection uint8

FlexDirection is the main axis of a container, as in CSS.

const (
	// Column lays children out top to bottom, the default as in React Native.
	Column FlexDirection = iota + 1
	Row
	ColumnReverse
	RowReverse
)

type FlexWrap

type FlexWrap uint8

FlexWrap says whether children wrap onto more lines.

const (
	NoWrap FlexWrap = iota + 1
	Wrap
	WrapReverse
)

type Font

type Font = driver.Font

Font is what a text engine needs to pick a font.

type FontExtent

type FontExtent = driver.FontExtent

type FontStyle

type FontStyle uint8

FontStyle is upright or italic.

const (
	FontStyleNormal FontStyle = iota + 1
	FontStyleItalic
)

type FontVariant

type FontVariant = driver.FontVariant

FontVariant is a set of OpenType features, as CSS's font-variant-caps and font-variant-numeric set them; the values combine.

type FontWeight

type FontWeight = driver.FontWeight

FontWeight is a CSS font weight from 100 to 900; 0 is unset.

type FrontmostAppInfo added in v0.2.0

type FrontmostAppInfo = driver.FrontmostAppInfo

FrontmostAppInfo is the application in front on the desktop, which Scope.FrontmostApp returns: the core's part of desktop.FrontmostAppInfo.

type Func

type Func func(cx *Scope) Node

Func is a component written as a function.

func (Func) Render

func (f Func) Render(cx *Scope) Node

Render implements Node.

type Geometry

type Geometry = driver.Geometry

Geometry is how a fold or hinge divides a surface: Env.Geometry.

type GestureEvent

type GestureEvent struct {
	Phase    GesturePhase
	Value    float32
	Velocity float32
	// Position is the gesture's center in the view, where the fingers
	// are or the pointer over a touchpad is; a rotation's is the origin.
	Position Point
}

GestureEvent is a pinch or a rotation: its amount since it began and how fast that changes per second. A pinch's amount is its scale, 1 when it begins; a rotation's is an angle in radians, clockwise.

type GesturePhase

type GesturePhase = driver.GesturePhase

GesturePhase is where a gesture is in its course.

type GlassEffect

type GlassEffect = driver.GlassEffect

GlassEffect is Apple's Liquid Glass.

type Gradient

type Gradient = driver.Gradient

Gradient is a linear, radial or conic gradient image, as CSS's.

func ConicGradient

func ConicGradient(angle float32, colors ...Color) Gradient

ConicGradient returns a gradient around the center, starting at angle in degrees clockwise from up, through stops spread evenly over a turn.

func LinearGradient

func LinearGradient(angle float32, colors ...Color) Gradient

LinearGradient returns a gradient along angle, in degrees clockwise from up (90 runs left to right), through stops spread evenly.

func ParseGradients

func ParseGradients(s string) ([]Gradient, error)

ParseGradients reads a CSS background-image list of linear-, radial- and conic-gradient() and their repeating forms; none is no gradients.

func RadialGradient

func RadialGradient(colors ...Color) Gradient

RadialGradient returns an elliptical gradient from the center out to the farthest corner, through stops spread evenly.

type GradientCorner

type GradientCorner = driver.GradientCorner

GradientCorner points a linear gradient at a corner.

type GradientExtent

type GradientExtent = driver.GradientExtent

GradientExtent is how far a radial gradient's last stop reaches.

type GradientKind

type GradientKind = driver.GradientKind

GradientKind is a gradient's geometry.

type GradientPaint

type GradientPaint = driver.GradientPaint

GradientPaint is a gradient resolved against a box, what platforms draw.

type GradientSpread

type GradientSpread = driver.GradientSpread

GradientSpread is how a CanvasGradient paints beyond offsets 0 and 1.

type GradientStop

type GradientStop = driver.GradientStop

GradientStop is a color at an offset of a Gradient.

type GridFlow

type GridFlow uint8

GridFlow is the CSS grid-auto-flow property: how a grid places items that do not say where they go.

const (
	FlowRow GridFlow = iota + 1
	FlowColumn
	FlowRowDense
	FlowColumnDense
)

type GridLines

type GridLines struct{ Start, End GridPlacement }

GridLines is where a grid item starts and ends on one axis. The zero value is auto: the grid places the item.

func ParseGridLines

func ParseGridLines(s string) (GridLines, error)

ParseGridLines reads grid-row or grid-column: a placement, or a start and an end apart by a slash ("1 / 3", "span 2", "header / footer").

type GridPlacement

type GridPlacement struct {
	// contains filtered or unexported fields
}

GridPlacement is one end of a grid item's row or column: a line, a span of tracks, or a named line. The zero value is auto.

func GridLine

func GridLine(n int) GridPlacement

GridLine places an item at line n, counting from 1; negative lines count from the end of the explicit grid.

func GridNamed

func GridNamed(name string, n int) GridPlacement

GridNamed places an item at the nth line called name (the first when n is 0); with a span it spans until the nth such line.

func GridSpan

func GridSpan(n int) GridPlacement

GridSpan makes an item span n tracks.

func ParseGridPlacement

func ParseGridPlacement(s string) (GridPlacement, error)

ParseGridPlacement reads one end of a grid item: auto, a line, "span n", a line's name, or a name and which of its lines ("a 2").

func (GridPlacement) Span

func (p GridPlacement) Span(n int) GridPlacement

Span returns p spanning n named lines rather than placed at one.

func (GridPlacement) String

func (p GridPlacement) String() string

String returns p in CSS syntax.

type GridTracks

type GridTracks string

GridTracks is a list of grid tracks in CSS syntax: lengths in px, percentages, fr, auto, min-content, max-content, fit-content(…), minmax(…, …), repeat(n | auto-fill | auto-fit, …) and [line names], as in "repeat(auto-fill, minmax(100px, 1fr))". A list layout cannot parse has no tracks. The zero value is unset: none.

func (GridTracks) Valid

func (g GridTracks) Valid() bool

Valid reports whether layout can parse the tracks.

type Group

type Group []Node

Group is several nodes in a row, laid out as children of the parent.

func (Group) Render

func (g Group) Render(*Scope) Node

Render implements Node.

type GroupStyle

type GroupStyle struct {
	Name                                                                string
	Hover, Focus, Active, Selected, Checked, Indeterminate, Disabled    *Style
	FocusWithin, AriaBusy, AriaChecked, Expanded, Pressed, AriaSelected *Style
	FocusVisible, AriaInvalid                                           *Style
	// Data are styles of data-* attributes of the group, sorted by name.
	Data []DataStyle
}

GroupStyle styles a node by the states of its nearest group: the nearest ancestor whose Group is Name, or any group when Name is empty, as Tailwind's group-hover and its kin do.

type Haptic

type Haptic uint8

Haptic is feedback the device plays under the user's finger: the core's part of mobile.Haptic, which apps use.

const (
	// HapticSelection is a selection changing: a picker's value, a
	// segment, a slider's step.
	HapticSelection Haptic = iota + 1
	// HapticLight to HapticRigid are elements colliding, by their weight
	// and give.
	HapticLight
	HapticMedium
	HapticHeavy
	HapticSoft
	HapticRigid
	// HapticSuccess, HapticWarning and HapticError are a task ending so.
	HapticSuccess
	HapticWarning
	HapticError
)

The haptics, as iOS's feedback generators name them: a selection changing, an impact of a weight, and a task's outcome.

type HeaderSymbol

type HeaderSymbol struct{ Name, Label string }

HeaderSymbol is a button of iOS's header: Name is its SF Symbol, and Label what assistive technology reads.

type HeaderSystemItem

type HeaderSystemItem = driver.HeaderSystemItem

HeaderSystemItem is a button iOS draws in a navigation bar in UIKit's own look, its symbol or label.

type HingeState

type HingeState = driver.HingeState

HingeState is how far a fold or hinge is open.

type HintChange

type HintChange uint8

HintChange is what happened to a tooltip's view.

const (
	// HintHover is the pointer coming onto the view.
	HintHover HintChange = iota + 1
	// HintLeave is the pointer leaving it or pressing it.
	HintLeave
	// HintFocus is the keyboard moving the focus onto it or into it.
	HintFocus
	// HintBlur is that focus leaving it.
	HintBlur
)

type HintTooltip

type HintTooltip interface {
	Node
	Hint(cx *Scope, anchor *Ref) (tip Node, change func(HintChange))
}

A HintTooltip is a View's Tooltip that decides itself when it shows, as base.Tooltip does: Hint mounts it against the view anchor names, and change tells it what the pointer and the keyboard's focus did.

type History

type History[T any] struct {
	// contains filtered or unexported fields
}

History is a value with the steps it took, to undo and redo: a document, a canvas or a form the app's Edit menu and keys walk back through. Only its own Set and Update record steps. Its value, CanUndo and CanRedo are signals.

Like a signal's, its methods belong to the graph's goroutine.

func NewHistory

func NewHistory[T comparable](cx *Scope, v T, opts HistoryOptions) *History[T]

NewHistory returns a history starting at v; setting a value equal to the current one records nothing.

func NewHistoryFunc

func NewHistoryFunc[T any](cx *Scope, v T, equal func(a, b T) bool, opts HistoryOptions) *History[T]

NewHistoryFunc returns a history as NewHistory does that compares values with equal; with a nil equal every Set records a step, as slices and maps need.

func (*History[T]) Break

func (h *History[T]) Break()

Break ends the latest step, so the next change starts a step of its own however soon it comes: a word typed, a selection moved.

func (*History[T]) CanRedo

func (h *History[T]) CanRedo() bool

CanRedo reports whether Redo has a step to go forward, subscribing the running computation.

func (*History[T]) CanUndo

func (h *History[T]) CanUndo() bool

CanUndo reports whether Undo has a step to go back, subscribing the running computation.

func (*History[T]) Clear

func (h *History[T]) Clear()

Clear forgets every step, keeping the value: a document just saved or opened.

func (*History[T]) Get

func (h *History[T]) Get() T

Get returns the value, subscribing the running computation.

func (*History[T]) GetUntracked

func (h *History[T]) GetUntracked() T

GetUntracked returns the value without subscribing.

func (*History[T]) Group

func (h *History[T]) Group(fn func())

Group runs fn, making every change it sets one step, as a paste or a replace-all is.

func (*History[T]) Redo

func (h *History[T]) Redo() bool

Redo goes forward to the value the latest Undo left, and reports whether there was one.

func (*History[T]) Set

func (h *History[T]) Set(v T)

Set makes v the value as a step that Undo goes back from, merged into the latest step within Merge of it or within a running Group, and drops the steps undone.

func (*History[T]) Undo

func (h *History[T]) Undo() bool

Undo goes back to the value the latest step started from, and reports whether there was one.

func (*History[T]) Update

func (h *History[T]) Update(fn func(T) T)

Update sets what fn returns for the current value, as Set does.

type HistoryOptions

type HistoryOptions struct {
	// Limit is the most steps it keeps, dropping the oldest first; 0 keeps 100, and a negative limit every step.
	Limit int
	// Merge makes a change within this long of the latest step's last part of that step, as typing groups into one undo; 0 makes each change a step.
	Merge time.Duration
}

HistoryOptions are how a History records its steps.

type Holder

type Holder struct {
	// contains filtered or unexported fields
}

A Holder keeps content built while the places that show it come and go, so it moves between parts of the tree with its state (its signals, a field's text, a scroll offset, a web view's page) instead of being built again. It is NSH's render keys (core/renders.rs), where the core moves what JS rendered for a key into the last placeholder placing it.

func NewHolder

func NewHolder(cx *Scope, content func(cx *Scope) Node) *Holder

NewHolder returns a holder of what content builds, which it builds when a place first shows it. Unlike what code usually creates, the content belongs to cx itself rather than to the owner running, so it outlives the places that show it: until cx goes or Dispose.

func (*Holder) Dispose

func (h *Holder) Dispose()

Dispose discards the content; places show nothing after it.

func (*Holder) Place

func (h *Holder) Place() Node

Place returns a node that shows the content while it is mounted and no place mounted after it is: the content moves to the newest place, and back to the one before when that goes. With no place it stays built, out of the tree, its overlays hidden.

type Host

type Host struct {
	// contains filtered or unexported fields
}

Host is the channel between an app and the host app that embeds it, without a view between them: launch parameters, events the host sends, and the host's functions the app calls. A host makes one for each view and keeps it across the apps the view runs, one at a time (RootOptions.Host). Its methods are safe to call from any goroutine.

Values cross it as JSON does, so iOS and Android hosts see the same: what Send, SetParams and HostCall.Resolve take is encoded and decoded again, maps becoming map[string]any and numbers float64.

func NewHost

func NewHost() *Host

NewHost returns a channel with no parameters or handlers.

func (*Host) Handle

func (h *Host) Handle(name string, fn func(call *HostCall))

Handle has fn answer the app's calls and posts of name (Scope.CallHost, Scope.PostHost), replacing the handler it had. fn runs on the app's goroutine, so it must not block: it answers the call once, then or later from any goroutine. It runs outside the owner that called, so the services it calls are held to the Access of the scope it calls them on, as when it answers later through Scope.Post: a plugin's Access does not hold the app's scope.

func (*Host) HandleDefault

func (h *Host) HandleDefault(fn func(call *HostCall))

HandleDefault has fn answer the calls and posts of every name without a handler of its own, as Handle's handlers do, for a host that looks names up itself, such as a web page's. nil removes it.

func (*Host) HandleOpenURL

func (h *Host) HandleOpenURL(fn func(url string, answer func(handled bool)))

HandleOpenURL has fn see the URLs the app opens (Scope.OpenURL) before the platform does, once they pass CheckURL, so the host routes its own links through its own router. fn runs on the app's goroutine and must not block; it calls answer once, from any goroutine: true takes the URL, and the app hears it opened; false hands it to the platform. nil removes the handler.

func (*Host) RemoveHandler

func (h *Host) RemoveHandler(name string)

RemoveHandler removes the handler of name: calls of it fail at once.

func (*Host) Send

func (h *Host) Send(name string, data any) error

Send sends the app an event, which its OnHostEvent listeners of name hear on its goroutine. It never waits. While no app runs, or none of its listeners hears name yet, the event is kept for later, at most HostInbox of them. It fails only for data JSON cannot encode.

func (*Host) SetParams

func (h *Host) SetParams(params map[string]any) error

SetParams sets the parameters the next app to start reads with Scope.HostParams, fixed for its life. Later requests are events.

type HostCall

type HostCall struct {
	// Name is the handler's name; Data what the app sent, as JSON
	// decodes it.
	Name string
	Data any
	// contains filtered or unexported fields
}

HostCall is one call or post of the app's to a host's handler.

func (*HostCall) IsPost

func (c *HostCall) IsPost() bool

IsPost reports whether the app posted rather than called: nothing hears the answer.

func (*HostCall) Reject

func (c *HostCall) Reject(err error)

Reject fails the call with err.

func (*HostCall) Resolve

func (c *HostCall) Resolve(result any)

Resolve answers the call with result. Only the first answer counts.

type HotKey

type HotKey struct {
	// contains filtered or unexported fields
}

HotKey is the core's part of desktop.HotKey: a global shortcut's registration, whose State follows the platform's answers.

func (*HotKey) State

func (h *HotKey) State() HotKeyState

State returns the registration state and subscribes the running computation to it. It is Pending until the platform answers, and again each time the app's set of shortcuts changes and the platform registers them anew; where the platform has no global shortcuts it is Unsupported from the start.

type HotKeyState

type HotKeyState = driver.HotKeyState

HotKeyState is the core's part of desktop.HotKeyState: the answer to a global shortcut registration.

type IOSInputProps

type IOSInputProps struct {
	// KeyboardAppearance picks iOS's light or dark keyboard.
	KeyboardAppearance KeyboardAppearance
}

IOSInputProps are an Input's props only iOS has.

type IOSModalProps

type IOSModalProps struct {
	// SupportedOrientations are the orientations iOS allows while the
	// modal shows; 0 keeps the app's.
	SupportedOrientations Orientation
}

IOSModalProps are a Modal's props only iOS has.

type IOSScreenProps

type IOSScreenProps struct {
	// HeaderRightSystemItem shows UIKit's own bar button, in the system's
	// look, at the header's end in place of HeaderRight's views. A press
	// on it presses HeaderRight's first view that takes presses, so keep
	// one there; it is what the other platforms show.
	HeaderRightSystemItem HeaderSystemItem
	// HeaderRightSymbols shows UIKit's own bar buttons, each on glass of
	// its own, in place of HeaderRight's views, none while it returns none.
	// A press on one presses that of HeaderRight's views that take presses,
	// in order: keep one there for each.
	HeaderRightSymbols func() []HeaderSymbol
}

IOSScreenProps are a Screen's props only iOS has.

type IOSViewProps

type IOSViewProps struct {
	// BackdropMaterial is the system material iOS draws the view's backdrop blur with. macOS draws its closest material for one other than BackdropUltraThin, and blurs by the radius for that.
	BackdropMaterial BackdropMaterial
}

IOSViewProps are a View's props only iOS has.

type Icon

type Icon struct {
	// Class is Tailwind CSS classes, as View's: size-6 sizes it and
	// text-* colors it.
	Class     string
	SVG       *SVG
	SVGFunc   func() *SVG
	Style     Style
	StyleFunc func() Style
	OnPress   func(PressEvent)
	OnLayout  func(Bounds)
	Ref       *Ref
	Label     string
	TestID    string
	// contains filtered or unexported fields
}

Icon draws an SVG — an icon, a logo, an illustration — in the text color it inherits, so a theme colors it as it colors text: its shapes scale to the icon's size and stay sharp.

An icon is as high as the inherited font size, keeping the SVG's aspect ratio, unless Style sets a size. Its drawing is fitted and centered in the icon's box, whose aspect ratio a non-square box does not change.

core.Icon{SVG: lucide.Search(), Style: core.Style{FontSize: 20}, Label: "Search"}

An icon is a decoration assistive technology does not see unless Label names it.

func (Icon) Render

func (i Icon) Render(*Scope) Node

Render implements Node.

type Idiom

type Idiom = driver.Idiom

Idiom is the kind of device, which decides how components present.

type Image

type Image struct {
	// Class is Tailwind CSS classes, as View's.
	Class        string
	Source       ImageSource
	SourceFunc   func() ImageSource
	Placeholder  ImageSource
	ResizeMode   ResizeMode
	BlurRadius   Points
	FadeDuration time.Duration // 0 is the platform's
	Style        Style
	StyleFunc    func() Style

	OnLoadStart func()
	// OnProgress receives bytes loaded and the total, 0 when unknown.
	OnProgress func(loaded, total int64)
	// OnLoad receives the source's size in pixels.
	OnLoad    func(pixels Size)
	OnError   func(err error)
	OnLoadEnd func()
	OnPress   func(PressEvent)
	OnLayout  func(Bounds)
	Ref       *Ref
	Label     string
	// ElementsHidden hides it from assistive technology, as a part of a
	// control that says it for it.
	ElementsHidden bool
	TestID         string
}

Image shows a picture the platform loads, decodes and caches. Layout knows only the size Source declares: one dimension derives the other, and an image without one is 0 by 0 until its style sizes it.

func (Image) Render

func (i Image) Render(*Scope) Node

Render implements Node.

type ImageScales

type ImageScales = driver.ImageScales

ImageScales is a set of ImageScaleValues: the variants an image asset ships in.

func ScalesOf

func ScalesOf(scales ...float32) ImageScales

ScalesOf returns the set of scales, leaving out any that is not one of ImageScaleValues.

type ImageSource

type ImageSource = driver.ImageSource

ImageSource is where an image comes from: a URI (https, file path, file:, data:), bytes, such as a file embedded with go:embed, or pixels the app draws (Pixels and Version).

func Src

func Src(uri string) ImageSource

Src returns a source for uri.

type Importance

type Importance uint8

Importance is importantForAccessibility, Android's name for Accessible and AccessibilityElementsHidden in one prop.

const (
	// ImportantAuto leaves it to the view's other props.
	ImportantAuto Importance = iota
	// ImportantYes is Accessible.
	ImportantYes
	// ImportantNo makes the view no element; its descendants still are.
	ImportantNo
	// ImportantNoHideDescendants hides the view and its subtree.
	ImportantNoHideDescendants
)

type Input

type Input struct {
	// Class is Tailwind CSS classes, as View's.
	Class        string
	Value        func() string
	DefaultValue string
	Placeholder  string
	// PlaceholderFunc replaces Placeholder and may change.
	PlaceholderFunc func() string
	// Masked hides the characters, for passwords.
	Masked       bool
	Readonly     bool
	Disabled     func() bool
	KeyboardType KeyboardType
	// AutoFocus focuses the field as it mounts; under a confined owner, only as Scope.Confine allows.
	AutoFocus bool
	// Multiline wraps the text in lines and grows with them unless its
	// style sizes it; Return inserts a line break unless SubmitBehavior
	// says else.
	Multiline bool
	// MaxLength caps the text the user enters, in UTF-16 units; 0 sets
	// no cap.
	MaxLength int
	// ReturnKeyType labels the software keyboard's return key.
	ReturnKeyType  ReturnKeyType
	SubmitBehavior SubmitBehavior
	AutoCapitalize AutoCapitalize
	// NoAutoCorrect turns the system's autocorrection off.
	NoAutoCorrect bool
	// AutoComplete says what the field holds, for the system's autofill.
	AutoComplete AutoComplete
	// IOS holds the props only iOS has.
	IOS IOSInputProps
	// HideCaret draws no caret.
	HideCaret bool
	// SelectedRange, when set, selects its range whenever it changes.
	SelectedRange func() TextRange
	// InputAccessoryViewID names the InputAccessoryView shown above the
	// software keyboard while the field has focus.
	InputAccessoryViewID string
	// Suggest follows a trigger query in the field, such as a mention after "@", for a list beside it, base.SuggestList. What it accepts sets the field's text, through OnChange when Value controls it, and puts the caret after it; it needs no Ref.
	Suggest *Suggest
	// NoFontScaling and MaxFontSizeMultiplier limit the user's text size
	// setting for the field's text, as Text's do.
	NoFontScaling         bool
	MaxFontSizeMultiplier float32
	Style                 Style
	StyleFunc             func() Style

	OnChange func(text string)
	// OnSubmit runs on Return, as SubmitBehavior says.
	OnSubmit func(text string)
	// OnFocus and OnBlur follow the focus to and from the field; a focused field that leaves the tree hears OnBlur once, after the commit that removed it, or before the next view's OnFocus when the platform reports that first.
	OnFocus func()
	OnBlur  func()
	// OnSelectionChange receives the selection, or the caret, as the user
	// moves it.
	OnSelectionChange func(TextRange)
	// OnKeyPress receives each key the user types: the text it enters,
	// "Backspace" or "Enter".
	OnKeyPress func(key string)
	// OnCompositionChange follows an input method composing text: as the
	// composition starts and changes, and as it ends, after the OnChange
	// of the text it commits. While one lasts, the field holds a Value the
	// app sets and shows it when the composition ends, unless the user
	// edited the text since.
	OnCompositionChange func(Composition)
	// OnContentSizeChange receives the size of the value's text, wrapped
	// at the content width when Multiline, after a layout that changed
	// it. An empty field's is one empty line's.
	OnContentSizeChange func(Size)
	// OnCaretMove receives where the caret is while the input has the
	// focus, whenever it moves: with the selection, and when the text
	// scrolls or wraps again. Something that opens at the caret, such as
	// an @-mention's suggestions, anchors to its PageBounds.
	OnCaretMove func(CaretEvent)
	// OnPaste receives what the user pastes, before the text it inserts
	// is reported; PasteBehavior PasteReport keeps the text out. Images
	// and files are never inserted, nor the text naming pasted files.
	OnPaste       func(PasteEvent)
	PasteBehavior PasteBehavior
	OnLayout      func(Bounds)
	Ref           *Ref
	Label         string
	LabelFunc     func() string
	// LabelledBy names the input from visible elements, as a View's.
	LabelledBy []*Ref
	// AccessibilityDescription and Invalid are a View's: what the field
	// expects, and that the app rejected its content.
	AccessibilityDescription     string
	AccessibilityDescriptionFunc func() string
	Invalid                      func() bool
	// Role is what it is for assistive technology, a text field when 0; RoleSearchField keeps it a text field that reads as a search field.
	Role Role
	// ReadonlyFunc and KeyboardTypeFunc are Readonly and KeyboardType
	// following what they read.
	ReadonlyFunc     func() bool
	KeyboardTypeFunc func() KeyboardType
	// AccessibilityValue, AccessibilityActions and OnAccessibilityAction
	// are as a View's, for a field that is a spin button.
	AccessibilityValue    func() AccessibilityValue
	AccessibilityActions  []AccessibilityAction
	OnAccessibilityAction func(name string)
	// Expanded is a View's, for a field that opens a list.
	Expanded func() bool
	TestID   string
}

Input is the platform's text field, a single line unless Multiline: the core's part of base.Input, which apps use. With Value it is controlled: the app updates the value in OnChange. Its style's PlaceholderColor colors the placeholder and SelectionColor the caret and the selection.

func (Input) Render

func (i Input) Render(*Scope) Node

Render implements Node.

type InputAccessoryView

type InputAccessoryView struct {
	// ID is what inputs name in InputAccessoryViewID.
	ID        string
	Style     Style
	StyleFunc func() Style
	Children  []Node
	TestID    string
}

InputAccessoryView is the core's part of mobile.InputAccessoryView, which apps use: a bar iOS and Android show above the software keyboard, as React Native's.

func (InputAccessoryView) Render

func (a InputAccessoryView) Render(*Scope) Node

Render implements Node.

type Interpolation

type Interpolation = driver.Interpolation

Interpolation maps a node through piecewise-linear ranges.

type Justify

type Justify uint8

Justify places children on the main axis (justify-content).

const (
	JustifyStart Justify = iota + 1
	JustifyCenter
	JustifyEnd
	JustifySpaceBetween
	JustifySpaceAround
	JustifySpaceEvenly
	// JustifyStretch stretches a grid's auto tracks across the row, which
	// grids do when it is unset.
	JustifyStretch
)

type KeepAwake

type KeepAwake = driver.KeepAwake

KeepAwake is a power assertion request.

type KeepAwakeOptions

type KeepAwakeOptions struct {
	Display bool
}

KeepAwakeOptions control a power assertion. Display keeps the display on as well as preventing idle sleep; false keeps only the computer awake.

type Key

type Key[T any] struct {
	// contains filtered or unexported fields
}

Key is a context key: a value an owner provides to everything below it. Declare one as a package-level variable.

func NewKey

func NewKey[T any](name string, def T) *Key[T]

NewKey returns a key whose Use returns def where nothing provides one.

func (*Key[T]) Provide

func (k *Key[T]) Provide(cx *Scope, v T)

Provide makes v the key's value for the current owner and below.

func (*Key[T]) String

func (k *Key[T]) String() string

func (*Key[T]) Use

func (k *Key[T]) Use(cx *Scope) T

Use returns the value the nearest owner provides, or the default.

type KeyEvent added in v0.2.0

type KeyEvent struct {
	// Key names the key as OnKey does, without modifiers: "k", "1", "space", "enter", "f5", "left", "escape"; a modifier pressed alone is "shift", "ctrl", "alt" or "meta", which is Command on macOS and the Windows or Super key elsewhere. A letter or a digit is the one the keyboard layout types unshifted.
	Key string
	// Modifiers are the modifier keys held, the one pressed alone included.
	Modifiers Modifiers
	// Repeat is whether the press is a held key's auto-repeat.
	Repeat bool
}

KeyEvent is a key going down on a hardware keyboard while a view has the keyboard focus (View.OnKeyDown).

func (KeyEvent) Shortcut added in v0.2.0

func (e KeyEvent) Shortcut() string

Shortcut returns the press in OnKey's and desktop.RegisterHotKey's form, with each modifier by its own name, as driver.NormalizeKey writes it: "ctrl+shift+k" or "alt+space" on Windows and Linux, "shift+meta+k" for Command+Shift+K on macOS. A modifier pressed alone is "".

type KeyOptions

type KeyOptions struct {
	When KeyWhen
	// Repeat fires it again on the auto-repeats of a held key.
	Repeat bool
	// OverModals keeps it firing while a modal its owner's views are not in covers them, for an app-wide shortcut such as a menu's.
	OverModals bool
	// YieldsToMenu leaves the key to the application menu while an enabled item takes the same shortcut where the focus is on macOS, Windows and Linux, which show the menu, for a default shortcut an app's menu may take over. An item that leaves its shortcut to a focused text input or web view does not suppress the binding. Else a binding takes its key before the menu does.
	YieldsToMenu bool
	// AllSurfaces binds the key in every surface of the app rather than only the one it is bound in: the app's own and each window, panel and tray view it opens, those it opens later too, for an app-wide shortcut. In the surface it is bound in it is as OnKey says; in each other one it comes before that surface's own bindings, so one of the same key there wins over it, whenever it was made, and rests while a modal shows there unless OverModals keeps it. It rests in all of them while what its owner shows is hidden in the surface it is bound in, a modal covering it there aside, so a component's shortcut does not run while the user cannot see the component; one bound at the app's root, which shows nothing, fires everywhere. It ends in all of them as its owner goes. Where the platform opens no windows it is OnKey's.
	AllSurfaces bool
}

KeyOptions are how a binding fires.

type KeyWhen

type KeyWhen uint8

KeyWhen says when a binding fires.

const (
	// KeyAuto fires it unless the view with the keyboard focus uses the key itself: a text input or a web view the keys EditsText reports, a view that takes presses (a button, a menu row, a switch) Return and Space, a slider or spin button the arrows, Page Up, Page Down, Home and End, and a tab bar, radio group, list, menu or tree, or one of their items, the same keys to move in it. Modified keys, such as Shift+Space, are none of these but a text input's.
	KeyAuto KeyWhen = iota
	// KeyAlways fires it wherever the keyboard focus is.
	KeyAlways
	// KeyNotEditing fires it only while no text input or web view has the keyboard focus, and takes its key from any other focused view: a control binds its own keys with it while it has the focus, as a select does Return while its trigger keeps the focus, where KeyAuto would leave them to the control.
	KeyNotEditing
)

type KeyboardAppearance

type KeyboardAppearance = driver.KeyboardAppearance

KeyboardAppearance is the look of iOS's keyboard; the default follows the app's appearance.

const (
	KeyboardAppearanceDefault KeyboardAppearance = iota
	KeyboardAppearanceLight
	KeyboardAppearanceDark
)

type KeyboardDismissMode

type KeyboardDismissMode = driver.KeyboardDismissMode

KeyboardDismissMode is whether dragging a scroll view dismisses the software keyboard.

const (
	KeyboardDismissNone KeyboardDismissMode = iota
	// KeyboardDismissOnDrag dismisses it as a drag starts.
	KeyboardDismissOnDrag
	// KeyboardDismissInteractive follows the finger dragging down into
	// it (iOS; on drag elsewhere).
	KeyboardDismissInteractive
)

type KeyboardTaps

type KeyboardTaps = driver.KeyboardTaps

KeyboardTaps is what a tap in a scroll view does while the software keyboard shows.

type KeyboardType

type KeyboardType = driver.KeyboardType

KeyboardType picks a software keyboard.

type Keyframe

type Keyframe = driver.Keyframe

Keyframe is one step of a keyframe animation.

type KeyframeAnimation

type KeyframeAnimation = driver.KeyframeAnimation

KeyframeAnimation runs Keyframes over a view on the platform.

type KeyframeStop

type KeyframeStop struct {
	Value float64
	// contains filtered or unexported fields
}

KeyframeStop is where a value is at a point of a keyframe animation: Stops spreads values evenly, StopAt places one, and Eased curves the segment that starts at it.

func StopAt

func StopAt(offset, value float64) KeyframeStop

StopAt returns value at offset, from 0 to 1, of an iteration.

func Stops

func Stops(values ...float64) []KeyframeStop

Stops returns values as keyframe stops spread evenly through an iteration, the first at its start and the last at its end.

func (KeyframeStop) Eased

func (s KeyframeStop) Eased(e Easing) KeyframeStop

Eased returns s with e curving the segment from it to the next stop.

func (KeyframeStop) Offset

func (s KeyframeStop) Offset() (float64, bool)

Offset returns where s is in an iteration, from 0 to 1, and whether it was placed there rather than spread evenly.

type KeyframeTiming

type KeyframeTiming struct {
	Duration   time.Duration
	Delay      time.Duration
	Easing     Easing
	Iterations int
	Direction  PlaybackDirection
}

KeyframeTiming is how keyframes play, as CSS's animation-duration, -delay, -timing-function, -iteration-count and -direction: Duration (300 ms when 0) an iteration, Easing for the segments without one of their own, Iterations (once when 0, Forever) and the Direction they play in, after Delay. During the delay the value already holds the first keyframe, as CSS's animation-fill-mode backwards does.

type Keyframes

type Keyframes = driver.Keyframes

Keyframes are a keyframe animation's steps.

type LayoutAnimation

type LayoutAnimation = driver.LayoutAnimation

LayoutAnimation animates the frame changes, insertions and removals of one commit on the platform, as React Native's LayoutAnimation does.

type LayoutAudit

type LayoutAudit struct {
	Bounds bool
	Grid   Points
}

LayoutAudit is what DevTools' layout audit shows as it starts (UpdateHighlights.Layout): every view's border, padding and margin boxes, and a grid of Grid points, at least 4, or none for 0. One that shows anything, as nsgo dev -layout's does, binds auditKey to show and hide the audit; the zero LayoutAudit shows nothing and binds no key, so the audit shows only when DevTools show it, with the boxes.

type LayoutCurve

type LayoutCurve = driver.LayoutCurve

LayoutCurve is how a layout change progresses.

type LayoutDirection

type LayoutDirection uint8

LayoutDirection is the direction a node's content flows in.

const (
	DirectionLTR LayoutDirection = iota + 1
	DirectionRTL
)

type LayoutProperty

type LayoutProperty = driver.LayoutProperty

LayoutProperty is what appearing and disappearing views animate.

type LayoutTransition

type LayoutTransition = driver.LayoutTransition

LayoutTransition is how one kind of change animates.

type Length

type Length = driver.Length

Length is a style's length.

func Pct

func Pct(percent float32) Length

Pct returns a length in percent of the containing block's size.

func Pt

func Pt(p Points) Length

Pt returns a length in points.

type Lifecycle

type Lifecycle = driver.Lifecycle

Lifecycle is whether the app is in use: Env.Lifecycle.

type LineCap

type LineCap = driver.LineCap

LineCap ends open strokes.

type LineDash

type LineDash = driver.LineDash

LineDash is the lengths of a stroke's dashes and gaps in turn.

type LineJoin

type LineJoin = driver.LineJoin

LineJoin joins stroke segments.

type LineLayout

type LineLayout interface {
	TextLines() []TextLine
}

LineLayout is a TextLayout that reports its lines. The core asks it only when the text has an OnTextLayout handler, on the engine side, before the layout goes to the main thread; the core fills Text in.

type List

type List struct {
	Count func() int
	// Key returns row i's identity, a comparable value such as an ID.
	// With it, rows that stay keep their cells and sizes as rows come and
	// go, and rows inserted or removed above the viewport keep the
	// visible rows in place.
	Key func(i int) any
	// Row builds a cell's content; row says which row it shows.
	Row func(cx *Scope, row ListRow) Node
	// EstimatedSize is a row's expected size along the list; 50 when 0.
	EstimatedSize Points
	// NumColumns lays that many rows side by side across the list, each
	// line of rows as long as its longest.
	NumColumns    int
	Horizontal    bool
	HideIndicator bool
	// Bar draws its scroll bar, over the app's (Scope.SetScrollbars).
	Bar ScrollbarMaker
	// Inverted puts row 0 at the end (a chat): the list starts scrolled
	// to the end and keeps its distance from it as content changes. With
	// OnLoadMoreAtStart it does so only while row 0 shows; scrolled away,
	// rows arriving at row 0's end keep the visible rows in place.
	Inverted bool
	// Alignment is where the list rests: at its start, or with
	// ListAlignEnd at its end, as a chat without inverting its rows: it
	// opens there before its first frame, keeps there as rows come,
	// measure or shrink, stops following while scrolled away and follows
	// again once back, and holds content shorter than its viewport at its
	// end. An inverted list, or one in its parent's viewport, ignores it.
	Alignment ListAlignment
	// MaintainVisibleContentPosition, when set, follows the end of a list
	// that is not inverted while it is within AutoscrollToBottomThreshold
	// of it, as content grows or the viewport shrinks.
	MaintainVisibleContentPosition *VisibleContentPosition
	// Gap separates rows, ColumnGap columns; the style's padding is the
	// content's.
	Gap       Points
	ColumnGap Points
	Header    Node
	Footer    Node
	// Empty shows while Count is 0.
	Empty Node
	// Separator builds what goes after each row but the last (before it
	// in an inverted list), in the row's cell.
	Separator func(cx *Scope) Node
	// StickyHeaderIndices stick those rows to the viewport's start, at
	// StickyHeaderOffset from it, while scrolled past, until the next one
	// pushes them out; one column, not inverted. The platform pins them on
	// every scroll.
	StickyHeaderIndices     []int
	StickyHeaderIndicesFunc func() []int
	StickyHeaderOffset      Points
	// StickyHeaderOffsetValue, when set, is the animated value the
	// headers' offset follows in place of StickyHeaderOffset, as a header
	// above the list hides and shows.
	StickyHeaderOffsetValue AnimatedNode
	// InitialScrollIndex is the row the list starts scrolled to.
	InitialScrollIndex int
	// OnViewableItemsChange receives the viewable rows when they change,
	// by ViewabilityConfig's rules.
	OnViewableItemsChange func(ViewableItems)
	ViewabilityConfig     ViewabilityConfig
	// OnLoadMore runs when the viewport comes within LoadMoreThreshold
	// viewports of the content's end (1 when 0), once per count: also as
	// the list opens, so a first page shorter than that asks for the next.
	OnLoadMore        func()
	LoadMoreThreshold float32
	// OnLoadMoreAtStart is its counterpart at item 0's end, for a list
	// opened at an old item that loads what comes before it, within
	// LoadMoreAtStartThreshold viewports (1 when 0). It runs once per
	// approach: again after the viewport left that zone, or when the count
	// changed while it stayed there, and never before the user or a
	// scroll command moved the list.
	OnLoadMoreAtStart        func()
	LoadMoreAtStartThreshold float32
	// Viewport is what the list scrolls in: a scroll view of its own, or
	// with ListViewportParent the nearest scroll view around it on its
	// axis (or its screen, modal or overlay), which scrolls it with what
	// else it holds. Fixed when the list mounts.
	Viewport ListViewport

	// Behavior, ContentOffset, the scroll events, OnRefresh,
	// Refreshing, PullValue and OffsetValues are Scroll's, for the list's
	// scroll view. In its parent's viewport they are ignored, as are Inverted
	// and MaintainVisibleContentPosition.
	Behavior            ScrollBehavior
	BehaviorFunc        func() ScrollBehavior
	ContentOffset       Point
	OnScroll            func(ScrollEvent)
	ScrollEventThrottle time.Duration
	OnScrollDragStart   func(ScrollEvent)
	OnScrollDragEnd     func(ScrollEvent)
	OnMomentumStart     func(ScrollEvent)
	OnMomentumEnd       func(ScrollEvent)
	// OnScrollEnd hears the list come to rest, as Scroll's.
	OnScrollEnd  func(ScrollEvent)
	OnRefresh    func()
	Refreshing   func() bool
	PullValue    *AnimatedValue
	OffsetValues AnimatedXY
	OnLayout     func(Bounds)
	// Class is Tailwind CSS classes, as View's; its padding, as the
	// style's, is the content's.
	Class     string
	Style     Style
	StyleFunc func() Style
	Ref       *Ref
	TestID    string
}

List renders a long run of rows lazily, as NSH's <List>: only the rows within a viewport of the visible ones are mounted, each in a cell that is reused for another row when it scrolls away. A cell's content is built once; its ListRow changes, so the content's bindings update instead of it being rebuilt. Row sizes start as an estimate and are corrected as rows are laid out, so offsets, columns, sticky rows and viewability are all decided in the core.

Every scroll view prop of Scroll a list takes (Behavior, the scroll events, refreshing, OffsetValues) applies to its scroll view. Keep a row's state in the app's data, keyed by Key, not in the row's scope, which moves to other rows.

func (List) Render

func (l List) Render(*Scope) Node

Render implements Node.

type ListAlignment

type ListAlignment uint8

ListAlignment is where a List rests.

const (
	ListAlignStart ListAlignment = iota
	ListAlignEnd
)

type ListPosition

type ListPosition struct {
	Index  int
	Offset Points
}

ListPosition is where a list's viewport starts among its rows: the row it starts in, from the side row 0 is on, and how far past that row's start, as GPUI's ListOffset.

type ListRow

type ListRow struct {
	// contains filtered or unexported fields
}

ListRow is the row a list cell shows, as signals, so content reading it follows the cell to its next row.

func (ListRow) Count

func (p ListRow) Count() int

Count returns the number of rows.

func (ListRow) First

func (p ListRow) First() bool

First reports whether the row is the first.

func (ListRow) Index

func (p ListRow) Index() int

Index returns the row's index.

func (ListRow) Last

func (p ListRow) Last() bool

Last reports whether the row is the last.

type ListViewport

type ListViewport uint8

ListViewport is what a list scrolls in.

const (
	// ListViewportOwn is a scroll view of the list's own.
	ListViewportOwn ListViewport = iota
	// ListViewportParent lays the list out at its full length in its
	// parent and renders the rows near the viewport of the scroll view
	// around it.
	ListViewportParent
)

type LiveRegion

type LiveRegion = driver.LiveRegion

LiveRegion says how screen readers announce changes of a view's label and text (accessibilityLiveRegion).

type LocaleSettings

type LocaleSettings = driver.LocaleSettings

LocaleSettings are the user's regional preferences: Env.LocaleSettings.

type LocationFix added in v0.2.0

type LocationFix = driver.LocationFix

LocationFix is a WGS 84 fix, with optional measurements and provider times.

type LocationOptions added in v0.2.0

type LocationOptions = driver.LocationOptions

LocationOptions chooses accuracy, distance, caching and background policy.

type ManualClock

type ManualClock struct {
	// contains filtered or unexported fields
}

ManualClock moves only when Advance is called. It is safe for concurrent use.

func NewManualClock

func NewManualClock(start time.Time) *ManualClock

NewManualClock returns a clock reading start.

func (*ManualClock) Advance

func (c *ManualClock) Advance(d time.Duration)

Advance moves the clock by d, calling the timers that come due on the way in order, each at its own time.

func (*ManualClock) AfterFunc

func (c *ManualClock) AfterFunc(d time.Duration, f func()) func() bool

func (*ManualClock) Jump

func (c *ManualClock) Jump(d time.Duration)

Jump moves the clock ahead by d at once, as a machine waking from sleep: each timer due by then runs once, in order, at the end; timers those set run on later moves.

func (*ManualClock) Now

func (c *ManualClock) Now() time.Time

func (*ManualClock) SetWallTime

func (c *ManualClock) SetWallTime(t time.Time)

SetWallTime sets the wall time the app reads (Scope.WallTime, a TSX app's Date) to t, in t's location, moving no timer: the clock's own time goes on.

func (*ManualClock) WallTime

func (c *ManualClock) WallTime() time.Time

WallTime is the wall time the app reads: Now, unless SetWallTime set it apart, in the location of the time it was given.

type Matrix3D

type Matrix3D = driver.Matrix3D

Matrix3D is a 4×4 transform, stored column by column as CSS's matrix3d() lists it.

type MediaError

type MediaError struct {
	Message string
	Reason  MediaErrorReason
}

MediaError is a video that failed to open or play. Message is the platform's words; Reason says why for the failures an app can act on.

func (*MediaError) Error

func (e *MediaError) Error() string

type MediaErrorReason added in v0.2.0

type MediaErrorReason uint8

MediaErrorReason says why a video failed (MediaError.Reason).

const (
	// MediaErrorOther is any failure without a reason of its own: a missing file, a network error, a codec the platform lacks.
	MediaErrorOther MediaErrorReason = iota
	// MediaErrorAlphaUnsupported is a local file that declares an alpha channel the platform's player cannot keep, so it did not play rather than show an opaque picture; an app can decode such a clip itself and draw its frames with their alpha.
	MediaErrorAlphaUnsupported
)

func (MediaErrorReason) String added in v0.2.0

func (r MediaErrorReason) String() string

String names a media error reason for logs and diagnostics.

type Memo

type Memo[T any] struct {
	// contains filtered or unexported fields
}

Memo caches a computed value and notifies its readers only when the value changes.

func NewMemo

func NewMemo[T comparable](cx *Scope, fn func() T) *Memo[T]

NewMemo returns a memo of fn, computed now and again when what fn read changes.

func NewMemoFunc

func NewMemoFunc[T any](cx *Scope, fn func() T, equal func(a, b T) bool) *Memo[T]

NewMemoFunc returns a memo that compares values with equal; with a nil equal every computation notifies.

func (*Memo[T]) Get

func (m *Memo[T]) Get() T

Get returns the value, recomputing it first if needed, and subscribes the running computation to it.

func (*Memo[T]) GetUntracked

func (m *Memo[T]) GetUntracked() T

GetUntracked returns the up-to-date value without subscribing.

type MemorySecrets added in v0.2.0

type MemorySecrets = driver.MemorySecrets

SecretItem names a secret in the platform's secure store, SecretStore is where a platform keeps secrets (RootOptions.Secrets), and MemorySecrets is one in memory, which tests keep theirs in (nsgotest.App.Secrets).

type MenuBarMode = driver.MenuBarMode

MenuBarMode says when Windows and Linux show the menu bar.

type MenuEntry = driver.MenuEntry

MenuEntry is a MenuItem as an ItemMenu carries it: the item's handler replaced by an ID the platform reports with EventMenu (0: none), its shortcut normalized and its role's label filled in. An editing role with an ID reports it only when no focused field, web view or text selection takes the role.

type MenuItem struct {
	Label string
	// Shortcut is in OnKey's form, such as "mod+n".
	Shortcut  string
	Role      MenuRole
	Disabled  bool
	Checkable bool
	Checked   bool
	// Radio makes the item checkable and shows it as one of a group of choices, a radio on Windows and Linux; the app still says which item is Checked.
	Radio     bool
	Separator bool
	Items     []MenuItem
	// When says whether the shortcut chooses the item while a text input
	// or a web view has the keyboard focus.
	When MenuWhen
	// OnSelect runs when the item is chosen, by a click or its shortcut. An editing Role (MenuUndo through MenuSelectAll, MenuPasteAndMatchStyle and MenuDelete) goes to the focused field or web view first, and Copy and Select All to selected text, so OnSelect runs when none of them takes it: Select All selecting the app's own items, as Finder's does.
	OnSelect func()
}

MenuItem is one item of a menu: an action, a submenu when it has Items, or a line between groups when Separator. Apps name it desktop.MenuItem.

type MenuRole = driver.MenuRole

MenuRole is a standard menu item the platform carries out, labelling it and giving it its usual shortcut when the item has none of its own.

type MenuWhen uint8

MenuWhen says when a menu item's shortcut chooses it while a text input or a web view has the keyboard focus.

const (
	// MenuAlways chooses it there too.
	MenuAlways MenuWhen = iota
	// MenuAuto leaves the input the keys it uses itself (EditsText).
	MenuAuto
	// MenuNotEditing never chooses it there.
	MenuNotEditing
)
type Modal struct {
	Animation ModalAnimation
	// TransitionShader, when set, is how it comes and goes instead,
	// where the platform draws it.
	TransitionShader *TransitionShader
	// Presentation is how it covers the screen on iOS; other platforms
	// ignore it and cover the host.
	Presentation ModalPresentation
	// NoCloseOnSwipe keeps an iOS sheet from being swiped away; the swipe
	// still asks to close it ("swipe"). NoCloseOnEscape and
	// NoCloseOnBackdropPress say a dialog over it stays on those, which
	// its component decides (base.Dialog).
	NoCloseOnSwipe                          bool
	NoCloseOnEscape, NoCloseOnBackdropPress bool
	// IOS and Android hold the props only iOS, or only Android, has.
	IOS     IOSModalProps
	Android AndroidModalProps
	// StatusBar is set over the app's status bar while the modal is in
	// the tree.
	StatusBar     StatusBarSetting
	StatusBarFunc func() StatusBarSetting
	// Class is Tailwind CSS classes, as View's.
	Class     string
	Style     Style
	StyleFunc func() Style
	Children  []Node
	// OnRequestClose receives Escape or back ("cancel") while the modal is the topmost, and an iOS sheet's swipe ("swipe"); the app decides whether to remove it, except that back takes a confined owner's away regardless (Scope.Confine). A sheet swiped away has left the screen already and stays hidden until the app removes it.
	OnRequestClose func(reason string)
	// OnShown and OnDismissed receive the platform's reports that it
	// finished presenting the modal and taking it away, where it makes
	// them (EventModalShown, EventModalDismissed).
	OnShown, OnDismissed func()
	Role                 Role
	Label                string
	TestID               string
}

Modal covers its host, the surface or an outer modal, with a layer of its own laid out at the host's size: the core's part of base.Dialog, which apps use. Mounting it presents it, and removing it dismisses it. A confined owner's mounts only as Scope.Confine allows, else nothing shows.

func (Modal) Render

func (m Modal) Render(*Scope) Node

Render implements Node.

type ModalAnimation

type ModalAnimation = driver.ModalAnimation

ModalAnimation is how a modal appears.

type ModalPresentation

type ModalPresentation = driver.ModalPresentation

ModalPresentation is how a modal covers the screen on iOS.

type Modifiers

type Modifiers = driver.Modifiers

Modifiers are the modifier keys held during an event.

type Motion

type Motion struct {
	// contains filtered or unexported fields
}

Motion moves a view's opacity and transform through MotionSpecs: bind its Style, then Play. It has no look of its own: it only moves what the app styled.

func NewMotion

func NewMotion(cx *Scope, enter *MotionSpec) *Motion

NewMotion returns a motion with every channel at rest, or where enter starts, which it then plays: an entrance shows its first frame, never the view at rest. The motion's values go with the current owner.

func (*Motion) Animation

func (m *Motion) Animation(spec MotionSpec, reduced bool) *Animation

Animation returns spec as an animation of the motion's values, not started, to compose: Parallel over its tracks. With reduced, each channel lands where it ends at once.

func (*Motion) Exit

func (m *Motion) Exit(spec MotionSpec)

Exit plays spec as the motion's view leaves the Presence branch it is in (Scope.OnExit), which keeps the view until spec ends: a sheet or a toast built with an exit leaves with it, whatever removes it.

func (*Motion) Play

func (m *Motion) Play(spec MotionSpec, done func(finished bool)) *AnimationRun

Play runs spec on the motion's values, landing where it ends at once when the user asked for reduced motion, and calls done as StartAnimation does.

func (*Motion) Style

func (m *Motion) Style() *AnimatedStyle

Style returns what binds the motion to a view: its Style.Animated.

func (*Motion) Value

func (m *Motion) Value(c MotionChannel) *AnimatedValue

Value returns the value of channel c, to derive other nodes from.

type MotionChannel

type MotionChannel uint8

MotionChannel is what a motion moves: the opacity of a view and the parts of its transform.

const (
	MotionOpacity MotionChannel = iota
	MotionTranslateX
	MotionTranslateY
	MotionRotate
	MotionRotateX
	MotionRotateY
	MotionScale
	MotionScaleX
	MotionScaleY
)

type MotionKind

type MotionKind uint8

MotionKind is what a preset is for.

const (
	// MotionEnter brings a view in: it starts hidden or away and ends at
	// rest.
	MotionEnter MotionKind = iota
	// MotionExit takes a view out: it starts at rest and ends hidden or
	// away.
	MotionExit
	// MotionAttention draws the eye: it starts and ends at rest.
	MotionAttention
	// MotionLoop repeats until stopped.
	MotionLoop
)

type MotionOptions added in v0.2.0

type MotionOptions = driver.MotionOptions

MotionOptions chooses a sensor set and sample interval.

type MotionPreset

type MotionPreset uint8

MotionPreset is a ready-made motion, as NSH's: entrances, exits, attention seekers and loops. Distances are in points, sized for controls and cards.

const (
	FadeIn MotionPreset = iota
	FadeInUp
	FadeInDown
	FadeInLeft
	FadeInRight
	ZoomIn
	PopIn
	BounceIn
	SlideInUp
	SlideInDown
	FlipInX
	FlipInY
	FadeOut
	FadeOutUp
	FadeOutDown
	FadeOutLeft
	FadeOutRight
	ZoomOut
	PopOut
	SlideOutDown
	SlideOutUp
	Shake
	HeadShake
	Wiggle
	Swing
	Pulse
	Heartbeat
	RubberBand
	Jello
	Tada
	Jump
	Flash
	Spin
	Float
	Breathe
	Sway
	Bob
	Glow
)

func MotionPresets

func MotionPresets() []MotionPreset

MotionPresets lists every preset, in order.

func (MotionPreset) Kind

func (p MotionPreset) Kind() MotionKind

Kind returns what the preset is for.

func (MotionPreset) Name

func (p MotionPreset) Name() string

Name returns the preset's name, as NSH's JS names it: "fadeIn", "shake".

func (MotionPreset) Spec

func (p MotionPreset) Spec() MotionSpec

Spec returns the preset's motion, to play or change.

type MotionSample added in v0.2.0

type MotionSample = driver.MotionSample

MotionSample is one sensor's latest sample and its dropped-sample count.

type MotionSensors added in v0.2.0

type MotionSensors = driver.MotionSensors

MotionSensors is a set of raw and fused device sensors.

type MotionSpec

type MotionSpec struct {
	Tracks []MotionTrack
	Timing KeyframeTiming
}

MotionSpec is several channels of a view through keyframes with one timing: a preset's (MotionPreset.Spec) or the app's own.

type MotionTrack

type MotionTrack struct {
	Channel MotionChannel
	Stops   []KeyframeStop
}

MotionTrack is a channel through keyframe stops.

type MouseButton

type MouseButton = driver.MouseButton

MouseButton is a button of the mouse held in a MouseEvent.

type MouseEvent

type MouseEvent struct {
	Position     Point
	PagePosition Point
	Modifiers    Modifiers
	// PressedButton is the button held down, none as the mouse hovers.
	PressedButton MouseButton
}

MouseEvent is where the mouse is over a view, as GPUI's MouseMoveEvent says, or was last when it leaves.

type Native

type Native struct {
	// Component is the registered name.
	Component string
	// Props are the component's own props; PropsFunc, when set, replaces
	// them, again when what it reads changes. A prop that goes away is
	// set to nil. Values cross to Android as JSON. A prop whose value is
	// an AnimatedNode is bound to it instead: the platform's frame clock
	// hands the component its number or color on the frames it changes,
	// with no work for the engine (driver.AnimatedPropSetter).
	Props     map[string]any
	PropsFunc func() map[string]any
	Style     Style
	StyleFunc func() Style

	// OnEvent receives what the component emits.
	OnEvent    func(name string, data any)
	OnPress    func(PressEvent)
	OnLayout   func(Bounds)
	Ref        *Ref
	Label      string
	LabelledBy []*Ref
	Invalid    func() bool
	TestID     string
}

Native shows a view of a component the app registered with its platform by name (nsgo.Component), filling the element's box. Props reach the component's SetProp when they change, events it emits reach OnEvent, and Ref.Command runs its commands. An unknown name shows an empty box.

func (Native) Render

func (v Native) Render(*Scope) Node

Render implements Node.

type NativeComponent

type NativeComponent = driver.NativeComponent

NativeComponent is one Native element's platform view.

type NativeComponents

type NativeComponents = driver.NativeComponents

NativeComponents are the components an app registers with its platform, by name.

type NativeContext

type NativeContext = driver.NativeContext

NativeContext is how a component talks back to its element.

type NativeFactory

type NativeFactory = driver.NativeFactory

NativeFactory makes a component's view for one Native element, on the platform's main thread; nil leaves the box empty.

type Node

type Node interface {
	Render(cx *Scope) Node
}

Node is what a tree is made of: a host element (View, Text, Input, Scroll), a region (Group, Dynamic, Show, Each, Catch) or a component.

A component is any type whose Render returns its nodes; its fields are its props. Render runs once, under a scope of the component's own, and signals keep what it returned up to date. Host elements and regions return themselves.

func AfterEachRow added in v0.2.0

func AfterEachRow(node Node, after func(cx *Scope, row Node) Node) (Node, bool)

AfterEachRow returns a copy of node, an Each, that builds after's node after each of its rows, from the node the row built and under the row's scope, so it moves and goes with its row. For any other node it returns node and false. ui.FormSection hangs a hairline below each row of an Each with it.

func Each

func Each[T any, K comparable](items func() []T, key func(T) K,
	row func(cx *Scope, item func() T, index func() int) Node) Node

Each builds a row per item, matched to items by key: a row whose key stays is kept and moved, its item and index updated; rows are built for new keys and disposed for keys gone. An item of plain values (numbers, strings, and arrays and structs of them) updates its row only when it changes; any other item, which may point at what changed, every time the items are read again. Go methods cannot take type parameters, so Each is a function.

type NodeID

type NodeID = driver.NodeID

NodeID identifies a view of one tree.

type Notification

type Notification struct {
	// ID is the app's name for it: showing another with the same ID replaces it, shown or still to show, CloseNotification removes it and a press reports it. Keep in it what the press opens ("chat:42"), as a press can start the app anew.
	ID string
	// Title and Body are its text.
	Title, Body string
	// Silent shows it without the system's sound or vibration.
	Silent bool
	// At, when later than now (Scope.WallTime), schedules it to show then, whether the app runs or not, where Env.CanScheduleNotifications says the platform does; zero or earlier shows it at once.
	At time.Time
	// Repeat shows it again and again, at At's time of day, its clock reading in At's location, which the device keeps to in its own time zone, and for NotificationWeekly on At's weekday: first at the next such time after now, whatever At's date. It needs At.
	Repeat NotificationRepeat
}

Notification is a system notification (ShowNotification).

type NotificationPermission

type NotificationPermission uint8

NotificationPermission is whether the app may show notifications.

const (
	// NotificationsNotAsked is the user not asked yet:
	// RequestNotificationPermission shows the system's prompt.
	NotificationsNotAsked NotificationPermission = iota
	// NotificationsGranted lets the app show them.
	NotificationsGranted
	// NotificationsDenied keeps the app from showing them; only the
	// system's settings change it.
	NotificationsDenied
	// NotificationsUnavailable is a platform or a build that shows none,
	// such as a macOS app run outside its bundle, or code its Access does
	// not grant AccessNotifications.
	NotificationsUnavailable
)

func (NotificationPermission) String

func (p NotificationPermission) String() string

String returns NSH's name of p: "default", "granted", "denied" or "unavailable".

type NotificationRepeat added in v0.2.0

type NotificationRepeat uint8

NotificationRepeat is how often a scheduled notification shows (Notification.Repeat).

const (
	// NotificationOnce shows it once.
	NotificationOnce NotificationRepeat = iota
	// NotificationDaily shows it every day at At's time of day.
	NotificationDaily
	// NotificationWeekly shows it every week on At's weekday at its time of day.
	NotificationWeekly
)

type OS

type OS = driver.OS

OS names the operating system the app runs on.

type OSVersion

type OSVersion = driver.OSVersion

OSVersion is an operating system's version.

type ObjectPosition

type ObjectPosition = driver.ObjectPosition

ObjectPosition is where an image sits in its view once its ResizeMode has sized it, as CSS's object-position places it.

func ParseObjectPosition

func ParseObjectPosition(s string) (ObjectPosition, error)

ParseObjectPosition reads CSS's <position>: one value, two, or four (edges with offsets).

type Obstruction

type Obstruction = driver.Obstruction

Obstruction is a fold or a hinge on a surface.

type OfferPaymentMode added in v0.2.0

type OfferPaymentMode = driver.OfferPaymentMode

OfferPaymentMode is how an offer is paid: OfferFreeTrial, OfferPayAsYouGo or OfferPayUpFront.

type Opacity

type Opacity struct {
	// contains filtered or unexported fields
}

Opacity is a node's opacity from 0 to 1. Its zero value is unset, which is opaque; make one with Alpha.

func Alpha

func Alpha(a float32) Opacity

Alpha returns an opacity from 0 (invisible) to 1 (opaque).

func (Opacity) Value

func (o Opacity) Value() float32

Value returns the opacity, 1 when unset.

type Orientation

type Orientation = driver.Orientation

Orientation is a set of interface orientations.

type Outline

type Outline = driver.Outline

Outline is a line around a view's border box, as platforms draw it.

type Overflow

type Overflow uint8

Overflow says whether a node clips its children.

const (
	Visible Overflow = iota + 1
	Hidden
	// OverflowScroll makes the node a scroll container in layout, as
	// CSS's overflow: scroll, and clips it; only Scroll views scroll.
	OverflowScroll
)

type Overlay

type Overlay struct {
	Anchor *Ref
	// AnchorContent places it against the box around what Anchor holds
	// rather than Anchor's own: a popup's trigger, a view its column
	// stretches around the app's element.
	AnchorContent bool
	// AnchorBounds, when set and Anchor is not, places the overlay beside
	// the bounds it returns in the surface, again when they change: an
	// input's caret (CaretEvent.PageBounds), or a point.
	AnchorBounds func() Bounds
	Placement    Placement
	// Align places the overlay along the anchor's side; centered when 0.
	Align Align
	// Offset is the gap to the anchor; Margin keeps the overlay off the
	// edges of its host.
	Offset, Margin Points
	// Cover, while CoverShown holds, names a view inside the overlay to
	// lay over the anchor, a select's selected row over its trigger: the
	// overlay starts where the anchor does, the view centered on it, then
	// moves to stay in its host. Its frame in the overlay is kept while
	// the overlay keeps its size and the view its place in its parent, so
	// the overlay stays put while its rows scroll. Without the view it
	// goes on its side as usual.
	Cover      *Ref
	CoverShown func() bool
	// Class is Tailwind CSS classes, as View's.
	Class     string
	ClassFunc func() string
	Style     Style
	StyleFunc func() Style
	Children  []Node
	// PointerEvents says which of the overlay and its children take
	// touches and the pointer: None for a tooltip, BoxNone for a layer
	// that passes presses through around its content.
	PointerEvents PointerEvents

	// OnPressOutside receives presses outside the overlay and its anchor.
	OnPressOutside func(at Point)
	// OnCancel receives Escape or back while it is the topmost overlay
	// that listens.
	OnCancel func()
	// OnMouseEnter and OnMouseLeave are View's.
	OnMouseEnter, OnMouseLeave func(MouseEvent)
	// OnPosition reports where an anchored overlay went, again when it
	// moves or its room changes.
	OnPosition func(OverlayPosition)
	// HoldToRoom keeps an anchored overlay no taller than the room on the
	// side it goes, which the core picks at the overlay's natural height:
	// the side where it fits whole, else the one with more room. What it
	// holds scrolls past that, as a menu's items do.
	HoldToRoom bool
	// Topmost keeps the overlay above the other overlays and modals its host holds, those shown after it too: a developer's layer over the app, as DevTools' overlay (UpdateHighlights). Topmost overlays stay in the order they came in, and the root view's that listen for cancel hear Escape and back before its modals do.
	Topmost bool
	// OnTransitionEnd is View's.
	OnTransitionEnd func()
	// Ref names the overlay's view: its bounds.
	Ref    *Ref
	Role   Role
	Label  string
	TestID string
}

Overlay floats its children above everything in the nearest Modal or the surface, or a confined owner's in its frame when that is nearer (Scope.Confine), outside the flow: placed beside Anchor on Placement, or by its style's Top, Right, Bottom and Left without one. It never closes itself; the app removes it.

func (Overlay) Render

func (o Overlay) Render(*Scope) Node

Render implements Node.

type OverlayEnd

type OverlayEnd uint8

OverlayEnd is why the platform closed an overlay itself, which OverlayOptions.OnEnd hears.

const (
	// OverlayEndDenied is an overlay opened without the permission: no window showed.
	OverlayEndDenied OverlayEnd = iota + 1
	// OverlayEndUnavailable is one opened where the app's manifest does not ask for the permission.
	OverlayEndUnavailable
	// OverlayEndRevoked is the user taking the permission away while it showed.
	OverlayEndRevoked
	// OverlayEndRemoved is the system or the user stopping the service that kept it.
	OverlayEndRemoved
	// OverlayEndFailed is the platform failing to show it or to start its service, as Android refuses a foreground service it does not allow.
	OverlayEndFailed
)

func (OverlayEnd) String

func (e OverlayEnd) String() string

String returns "denied", "unavailable", "revoked", "removed" or "failed".

type OverlayOptions

type OverlayOptions struct {
	// Width and Height are the content's size in points; 320 by 180 when either is zero.
	Width, Height Points
	// Frame, when it moves, opens the overlay there at its size instead of centered. The platform keeps every frame on the screen's usable area and reports the one it applied in the overlay's Env.WindowFrame; its content moves and resizes it with SetWindowFrame, as desktop.SetWindowFrame does a window.
	Frame WindowFrame
	// Hidden opens it without showing it, for Window.Show.
	Hidden bool
	// Focusable lets it take the focus, which text input needs; by default it takes touches and the keys stay with the app in front.
	Focusable bool
	// Passive lets every touch through to the apps below it, at most at the window opacity Android lets touches pass through (0.8 by default); it takes none and never the focus.
	Passive bool
	// Accessible shows its content to screen readers, which it is hidden from by default.
	Accessible bool
	// OnEnd hears, once, that the platform closed the overlay itself and why, as the overlay's owner hears it; Window.Close and its owner going do not call it.
	OnEnd func(OverlayEnd)
}

OverlayOptions are an overlay's: the core's part of mobile.OverlayOptions, which apps use.

type OverlayPermission

type OverlayPermission uint8

OverlayPermission is whether the app may show windows over other apps, Android's special access to draw over them: the core's part of mobile.OverlayPermission's answer, in NotificationPermission's words without its not asked, as the special access has no such state.

const (
	// OverlayDenied keeps the app from showing overlays until the user grants it in the system's settings (RequestOverlayPermission).
	OverlayDenied OverlayPermission = iota
	// OverlayGranted lets the app show them.
	OverlayGranted
	// OverlayUnavailable is a platform without overlays, every one but Android, an app whose manifest does not ask for SYSTEM_ALERT_WINDOW, or code its Access does not grant AccessOverlay.
	OverlayUnavailable
)

func (OverlayPermission) String

func (p OverlayPermission) String() string

String returns "denied", "granted" or "unavailable".

type OverlayPosition

type OverlayPosition struct {
	Placement Placement
	Bounds    Bounds
	Available Size
}

OverlayPosition is where an anchored overlay went: the side of its anchor, its frame in its host and the room on that side inside the safe area less its margin, what a menu may grow to.

type Paint

type Paint = driver.Paint

Paint is what Fill and Stroke paint with: a color, nothing or the text color. The zero Paint is unset, so the property inherits.

func PaintColor

func PaintColor(c Color) Paint

PaintColor paints with c.

type PaintStyle

type PaintStyle = driver.PaintStyle

PaintStyle is the SVG paint properties a canvas view inherits.

type Palette

type Palette struct {
	// Background is the page; Surface a card or control on it, under
	// the pointer and held down.
	Background, Surface, SurfaceHover, SurfacePressed Color
	Border                                            Color
	Text, TextMuted                                   Color
	// Accent is the accent fill, AccentText what is drawn on it.
	Accent, AccentHover, AccentPressed, AccentText Color
	Danger, Warning, Success                       Color
	// Selection is selected text's, Focus a focus ring's and Scrollbar a
	// scroll indicator's.
	Selection, Focus, Scrollbar Color
	// Colors are roles by name past the ones above, such as "inset".
	Colors map[string]Color
}

Palette is a theme's colors in one appearance. Its roles are NSGo's; Colors holds the ones a component library or an app adds, by name.

func (*Palette) Color

func (p *Palette) Color(name string) (Color, bool)

Color returns the role named name: a field's name in lower camel case ("surfaceHover") or one of Colors, and whether the palette has it.

func (*Palette) ColorNames

func (p *Palette) ColorNames() []string

ColorNames are the names Color takes: the roles' and Colors', sorted.

func (*Palette) SetColor

func (p *Palette) SetColor(name string, c Color)

SetColor sets the role named name, as Color names it.

type PanActivation

type PanActivation = driver.PanActivation

PanActivation decides on the main thread when a drag on a view becomes its pan, so it can share touches with the scroll views around it, as react-native-gesture-handler's offsets do.

type PanEvent

type PanEvent struct {
	Phase       GesturePhase
	Translation Point
	Velocity    Point
	// Values are the PanValues as the pan begins and ends: a drag may grab
	// them mid animation, which a snap after it starts from.
	Values Point
}

PanEvent is a drag: its translation since it began and its velocity, in points and points per second.

type PanGesture

type PanGesture struct {
	// Position is the centroid in the surface, Origin where it was as the
	// gesture began, and Delta how far it moved since.
	Position, Origin, Delta Point
	// Velocity is the centroid's, in points per second, smoothed over a
	// few moves.
	Velocity Point
	// Touches counts the fingers down.
	Touches int
	// contains filtered or unexported fields
}

PanGesture follows the centroid of the fingers down, since the first went down or since the responder was granted.

type PanelOptions

type PanelOptions struct {
	// Width and Height are the content's size in points, 360 by 420 when either is zero; with FitContent, its largest.
	Width, Height Points
	// FitContent sizes the panel to its content, as an overlay sizes, up to Width and Height: before it first shows, and again as the content grows or shrinks, keeping the edge it is placed by, the side of what ShowAt placed it beside, the top under a tray icon or elsewhere.
	FitContent bool
	// Transparent has the panel draw nothing of its own: no background, no system frame and no shadow, so only what the content draws shows, its own corners and BoxShadow inside the panel's bounds. Env.WindowTransparent, read in the panel, reports whether the platform could; where it could not, as Linux without a compositor, the panel keeps its background.
	Transparent bool
	// HideOnBlur hides the panel as it loses the focus, as a tray icon's
	// panel or a launcher does.
	HideOnBlur bool
	// NoActivate keeps the panel from ever taking the keyboard or activating the app, shown, focused or clicked, so the app the user types in keeps its focus and caret, as an input method's candidate window or an on-screen keyboard needs. Focus and Toggle then only bring it to the front, and HideOnBlur never hides it, as it never has the focus to lose. Linux keeps it from the focus on X11 alone; a Wayland compositor gives it the focus as it shows.
	NoActivate bool
	// Material is the material behind the content (WindowMaterial).
	Material WindowMaterial
	// PointerEvents is where the panel takes the pointer (SetWindowPointerEvents), from its first frame.
	PointerEvents WindowPointerEvents
}

PanelOptions are a panel's: the core's part of desktop.PanelOptions, which apps use.

type PanicError

type PanicError struct {
	Value any
	Stack []byte
}

PanicError is a panic recovered from app code or an engine's fault boundary.

func (*PanicError) Error

func (e *PanicError) Error() string

func (*PanicError) Unwrap

func (e *PanicError) Unwrap() error

Unwrap returns the panic's value when it is an error.

type PartStates

type PartStates struct {
	Checked, Indeterminate, Selected, Disabled bool
	// Invalid applies aria-invalid styles without reporting a separate accessible state.
	Invalid bool
	// Focused styles the part as focused while the keyboard is on the
	// control around it: a tree's row, a code input's cell.
	Focused bool
	// Data are the data-* attributes the part shows, without their
	// prefix, as a calendar's day shows range-start: its data-*: classes
	// and data styles read them, and those of views inside it when it is
	// a group.
	Data []string
}

PartStates are the states a part of a control is styled in: its Style's Checked, Indeterminate, Selected, Disabled and Invalid merge in while they hold.

type PasteBehavior

type PasteBehavior = driver.PasteBehavior

PasteBehavior says whether an input inserts the text the user pastes.

type PasteEvent

type PasteEvent = driver.PasteEvent

PasteEvent is what the user pasted into an input, read from the clipboard as they pasted: its plain text (empty without any), files with their bytes, such as an image copied in another app, and the file: URLs of local files copied in a file manager, which FileFromURL opens.

type PastedFile

type PastedFile = driver.PastedFile

PastedFile is a file the clipboard held: its name when it has one, its MIME type and its bytes.

type Path

type Path = driver.Path

Path is a path to fill, stroke or clip with, as the web's Path2D.

func MustParsePath

func MustParsePath(data string) *Path

MustParsePath is ParsePath for path data that is part of the program: it panics when the data is in error.

func ParsePath

func ParsePath(data string) (*Path, error)

ParsePath reads SVG path data into a Path.

type PeriodUnit added in v0.2.0

type PeriodUnit = driver.PeriodUnit

PeriodUnit is PeriodDay, PeriodWeek, PeriodMonth or PeriodYear.

type Permission

type Permission string

Permission is something the system keeps for the user to give apps, named by its key. The app checks it (Scope.PermissionStatus), asks for it with the system's prompt (Scope.RequestPermission), opens the page of the system's settings that gives it (Scope.OpenPermissionSettings) and, on desktops, guides the user there (desktop.GuidePermission).

const (
	// PermissionAccessibility is controlling the computer through the accessibility API, on macOS, which names it Device Control and Data Access from macOS 27.
	PermissionAccessibility Permission = driver.PermissionAccessibility
	// PermissionScreenRecording is capturing the screen and its audio, on macOS, which tells a change only after the app starts again.
	PermissionScreenRecording Permission = driver.PermissionScreenRecording
	// PermissionInputMonitoring is reading the keyboard and the mouse while other apps are in front, on macOS.
	PermissionInputMonitoring Permission = driver.PermissionInputMonitoring
	// PermissionFullDiskAccess is the files macOS protects, which it tells by reading one.
	PermissionFullDiskAccess Permission = driver.PermissionFullDiskAccess
	// PermissionAppManagement is changing other apps, on macOS, which never tells it (PermissionUnknown).
	PermissionAppManagement Permission = driver.PermissionAppManagement
	// PermissionDeveloperTools is running software that does not meet the system's security policy, on macOS, which never tells it (PermissionUnknown).
	PermissionDeveloperTools Permission = driver.PermissionDeveloperTools
	// PermissionMicrophone is recording; asking needs NSMicrophoneUsageDescription in apple.info.
	PermissionMicrophone Permission = driver.PermissionMicrophone
	// PermissionCamera is the camera; asking needs NSCameraUsageDescription.
	PermissionCamera Permission = driver.PermissionCamera
	// PermissionCalendars is the user's calendars; asking needs NSCalendarsFullAccessUsageDescription from macOS 14 and iOS 17, NSCalendarsUsageDescription before.
	PermissionCalendars Permission = driver.PermissionCalendars
	// PermissionReminders is the user's reminders; asking needs NSRemindersFullAccessUsageDescription from macOS 14 and iOS 17, NSRemindersUsageDescription before.
	PermissionReminders Permission = driver.PermissionReminders
	// PermissionBluetooth is Bluetooth devices; asking needs NSBluetoothAlwaysUsageDescription.
	PermissionBluetooth Permission = driver.PermissionBluetooth
	// PermissionMediaLibrary is Media & Apple Music: iOS tells and asks it (NSAppleMusicUsageDescription), macOS never tells it.
	PermissionMediaLibrary Permission = driver.PermissionMediaLibrary
	// PermissionLocation is the device's location while the app shows (Locate, WatchLocation): asking needs NSLocationWhenInUseUsageDescription, or NSLocationUsageDescription on macOS, and on Android ACCESS_COARSE_LOCATION, with ACCESS_FINE_LOCATION for a precise one, in android.permissions. Whether the user allowed only an approximate location shows on each fix (LocationFix.Approximate).
	PermissionLocation Permission = driver.PermissionLocation
	// PermissionBackgroundLocation is a location stream going on in the background (LocationOptions.Background): on Apple platforms PermissionLocation with UIBackgroundModes' location, and on Android also ACCESS_BACKGROUND_LOCATION where android.permissions lists it, which Android 11 and later give only on the app's page of the settings, which asking opens. Ask for it after PermissionLocation.
	PermissionBackgroundLocation Permission = driver.PermissionBackgroundLocation
	// PermissionMotion is the accelerometer, gyroscope, magnetometer and device motion (WatchMotion): iOS and watchOS keep it from 27.2, asking with NSMotionUsageDescription, and Android grants it.
	PermissionMotion Permission = driver.PermissionMotion
)

func Permissions

func Permissions() []Permission

Permissions returns every Permission, in the order of macOS's Privacy & Security, then the sensors'.

type PermissionGuideOptions

type PermissionGuideOptions struct {
	// App is the path of the app the user drags into System Settings' list. Empty means this app: its bundle, or its executable outside one, as under nsgo dev, where macOS charges what the app does to the terminal that started it instead. Code under an Access must leave it empty.
	App string
	// Name is what the guide calls the app: App's name without its extension when empty.
	Name string
}

PermissionGuideOptions are desktop.GuidePermission's.

type PermissionStatus

type PermissionStatus uint8

PermissionStatus is whether the app has a Permission.

const (
	// PermissionNotAsked is the user not asked yet: RequestPermission shows the system's prompt. macOS never reports it for Accessibility, Screen Recording and Input Monitoring, which are PermissionDenied until granted.
	PermissionNotAsked PermissionStatus = driver.PermissionNotAsked
	// PermissionGranted is the app having it.
	PermissionGranted PermissionStatus = driver.PermissionGranted
	// PermissionDenied is the user or an administrator having refused it; only the system's settings change it.
	PermissionDenied PermissionStatus = driver.PermissionDenied
	// PermissionUnknown is a permission the system keeps but cannot tell without asking, or that the platform's backend cannot tell yet.
	PermissionUnknown PermissionStatus = driver.PermissionUnknown
	// PermissionNotGated is a permission the system does not keep from this app, which may use what it guards: on Linux outside a sandbox, and on Windows for all but the microphone and the camera.
	PermissionNotGated PermissionStatus = driver.PermissionNotGated
	// PermissionUnavailable is a permission the platform has no such thing for, such as Accessibility on iOS or the web, a key that names none, or one the current owner's Access does not grant AccessPermissions for.
	PermissionUnavailable PermissionStatus = driver.PermissionUnavailable
)

func (PermissionStatus) Allowed

func (s PermissionStatus) Allowed() bool

Allowed reports whether the app may use what the permission guards: PermissionGranted or PermissionNotGated.

func (PermissionStatus) String

func (s PermissionStatus) String() string

String returns "prompt", "granted", "denied", "unknown", "not-gated" or "unavailable".

type PersistOptions

type PersistOptions struct {
	// Version is the version of the value's form the app writes; 0 for a form that never changed.
	Version int
	// Migrate turns the JSON of a value written at an older version into the JSON of the current form. Without it, or when it fails, an older value reads as the default.
	Migrate func(version int, data json.RawMessage) (json.RawMessage, error)
}

PersistOptions are how a Persisted reads entries an older version of the app wrote.

type Persisted

type Persisted[T any] struct {
	// contains filtered or unexported fields
}

Persisted is a typed value the app's storage keeps under a key as JSON, read as a signal is: it follows the entry, as the app sets it here or elsewhere and as other graphs of the app change it, and decodes it once per change.

Like a signal's, its methods belong to the graph's goroutine.

func NewPersisted

func NewPersisted[T any](cx *Scope, key string, def T, opts PersistOptions) *Persisted[T]

NewPersisted returns the value the current owner's storage keeps under key, def when it holds none or what it holds does not decode. It reads the storage Scope.Storage returns, so a partition Scope.ProvideStorage gives holds it.

func (*Persisted[T]) Err

func (p *Persisted[T]) Err() error

Err returns why the entry the storage holds reads as the default: it does not decode, it is at a version the app cannot read, or its migration failed; nil when it reads as stored or there is none. It subscribes the running computation.

func (*Persisted[T]) Get

func (p *Persisted[T]) Get() T

Get returns the value, subscribing the running computation to its entry.

func (*Persisted[T]) Reset

func (p *Persisted[T]) Reset()

Reset removes the entry, so the value reads as the default.

func (*Persisted[T]) Set

func (p *Persisted[T]) Set(v T) error

Set stores v at the current version. It fails when v does not encode, and with a *StorageFullError when the storage would grow past its quota, keeping what it held.

func (*Persisted[T]) Update

func (p *Persisted[T]) Update(fn func(T) T) error

Update stores what fn returns for the current value.

type PhotoOptions

type PhotoOptions struct {
	// MaxDimension scales a photo whose longer side has more pixels down
	// to it; 0 keeps its size.
	MaxDimension int
	// Quality is the quality the JPEG is encoded at, from 0 (smallest) to
	// 1; 0 means 0.9.
	Quality float32
}

PhotoOptions say how TakePhoto prepares the photo taken.

type PhysicalBorders

type PhysicalBorders struct {
	Widths, Colors Sides
	// Corners has SideLeft for the left corners and SideRight for the
	// right ones.
	Corners Sides
}

PhysicalBorders are the parts of a style's border that stay on their sides right to left (Style.PhysicalBorders).

type PhysicalEdges

type PhysicalEdges struct {
	Margin, Padding, Inset Sides
}

PhysicalEdges are the sides of a style's box that stay on their sides right to left (Style.PhysicalEdges).

type PickDirectoriesOptions

type PickDirectoriesOptions struct {
	// Multiple lets the user pick several folders, at most Limit (0: up
	// to MaxPicked).
	Multiple bool
	Limit    int
	// Title, Button and Start are hints as in PickFilesOptions.
	Title  string
	Button string
	Start  string
}

PickDirectoriesOptions say how PickDirectories picks folders.

type PickEncoding

type PickEncoding = driver.PickEncoding

PickEncoding is what a platform does with one picked image.

type PickFilesOptions

type PickFilesOptions struct {
	// Multiple lets the user pick several files, at most Limit (0: up to
	// MaxPicked).
	Multiple bool
	Limit    int
	// Types are the files offered: media types (application/pdf), families (image/*) and extensions (.zip); none offers every file.
	Types []string
	// TypesName names Types in the type menu of the pickers that have one, Windows' and Linux's; "" shows the English "Files", or on Windows "All files" where every file is offered.
	TypesName string
	// Title, Button and Start are hints a platform without the setting ignores, each "" for the system's own: Title says what the picker is for, as its title or, on macOS, whose sheets have none, its message; Button labels the button that picks; Start is the absolute path of the folder it opens in, ignored where no such folder exists. macOS, Windows and Linux take all three, iOS only Start, Android and the web none.
	Title  string
	Button string
	Start  string
}

PickFilesOptions say which files PickFiles offers.

type PickFormat

type PickFormat = driver.PickFormat

PickFormat says which formats picked images come in.

type PickOptions

type PickOptions struct {
	// Multiple lets the user pick several images, at most Limit (0: up
	// to MaxPicked).
	Multiple bool
	Limit    int
	// MaxDimension scales images whose longer side has more pixels down
	// to it, encoding them again; 0 keeps their size.
	MaxDimension int
	// Quality is the quality JPEGs are encoded at, from 0 (smallest) to
	// 1; 0 means 0.9, and keeps JPEGs that need no other change as they
	// are.
	Quality float32
	// Format says which formats images come in: by default JPEG, PNG, GIF
	// and WebP as they are and anything else, such as HEIC, as JPEG.
	Format PickFormat
}

PickOptions say how PickImages picks and prepares images.

type PickRequest

type PickRequest = driver.PickRequest

PickRequest is a pick as the platform carries it out, PickOptions resolved.

type PickedFile

type PickedFile = driver.PickedFile

PickedFile is an image the user picked: its name, type, bytes, size in pixels and modification time.

type Placement

type Placement uint8

Placement is the side of its anchor an overlay goes on.

const (
	// PlaceDefault is the component's own default: below for overlays.
	PlaceDefault Placement = iota
	PlaceBottom
	PlaceTop
	PlaceLeft
	PlaceRight
)

type PlaybackDirection

type PlaybackDirection uint8

PlaybackDirection is which way the iterations of keyframes play, as CSS's animation-direction.

const (
	PlayNormal PlaybackDirection = iota
	PlayReverse
	PlayAlternate
	PlayAlternateReverse
)

type Point

type Point = driver.Point

Point is a position in points.

type PointerEvents

type PointerEvents = driver.PointerEvents

PointerEvents says which of a view and its children take touches and the pointer.

type Points

type Points = driver.Points

Points is a length in platform-independent points (iOS points, Android dp, CSS pixels at a zoom of 1).

type Position

type Position uint8

Position says how a node is placed in its parent.

const (
	// Relative nodes flow in their parent; Top and Left offset them.
	Relative Position = iota + 1
	// Absolute nodes leave the flow and are placed by Top, Right, Bottom
	// and Left in the padding box of their nearest positioned ancestor.
	Absolute
	// Static nodes flow in their parent and ignore Top, Right, Bottom and
	// Left, so absolute nodes inside them are placed by an ancestor.
	Static
	// Fixed nodes leave the flow and are placed by Top, Right, Bottom and
	// Left in the root view, or the modal they are in, whatever scrolls.
	Fixed
	// Sticky nodes flow as relative ones, then stick in the nearest scroll view around them: Top (Left in a horizontal one) from its start, or Bottom (Right) from its end when the start inset is auto. Travel stays inside their parent's content. They draw above their siblings with the same ZIndex.
	Sticky
)

type PositionAxis

type PositionAxis = driver.PositionAxis

PositionAxis is an ObjectPosition along one axis: Offset from the start edge (left, top), or from the end edge (right, bottom) when FromEnd.

type PreparedText

type PreparedText = driver.PreparedText

type Presence

type Presence struct {
	When func() bool
	Then func(cx *Scope) Node
	Else func(cx *Scope) Node
	Wait bool
}

Presence is Show whose branches leave with their exits, as gpui-base's Presence and Motion's AnimatePresence: when When changes, the branch it held stays in the region, before the one built for the new value, until every exit its parts registered with Scope.OnExit has called done. A branch whose parts registered none goes at once, as Show's does.

A leaving branch never comes back: if When changes back before it is gone, a new branch is built beside it. With Wait, the new branch is built only once the branches leaving are gone, as AnimatePresence's wait mode, so in-flow content never shows twice.

func (Presence) Render

func (p Presence) Render(*Scope) Node

Render implements Node.

type PressEvent

type PressEvent struct {
	// Position is in the pressed view, its transforms undone; for a
	// pressed span, in its text's view.
	Position Point
	// PagePosition is in the root view the view is in: the surface, or
	// its modal.
	PagePosition Point
	Modifiers    Modifiers
	// Clicks counts consecutive clicks at the same place: 1 for a click,
	// 2 for a double click.
	Clicks int
	// Keyboard is set when the last input was a key, as Return or Space
	// pressing the focused view: a menu opened so focuses its first item.
	Keyboard bool
}

PressEvent is where the pointer was at a press. Backends that know them report the modifier keys held when the press began and the click count; a keyboard press keeps its modifiers where the platform reports them. Keyboard and assistive-technology presses are at the view's origin with one click.

type Product added in v0.2.0

type Product = driver.Product

Product is what the store sells, in the user's storefront's language and currency: show DisplayPrice as it is and never a price of the app's own, as stores price each storefront themselves.

type ProductType added in v0.2.0

type ProductType = driver.ProductType

ProductType is what kind of thing a product sells: ProductConsumable, ProductNonConsumable, ProductAutoRenewable or ProductNonRenewable.

type PromotionalOffer added in v0.2.0

type PromotionalOffer = driver.PromotionalOffer

PromotionalOffer is a subscription's promotional offer as a purchase takes it, which the app's server signs with its In-App Purchase key.

type PurchaseCommand added in v0.2.0

type PurchaseCommand = driver.PurchaseCommand

PurchaseCommand is what a PurchaseRequest asks of the store.

type PurchaseError added in v0.2.0

type PurchaseError string

PurchaseError is why an in-app purchase service answered without what it was asked for. A failure the platform explains wraps PurchaseFailed with its words, so test it with errors.Is.

const (
	// PurchaseCancelled: the user closed the store's sheet, which is no failure.
	PurchaseCancelled PurchaseError = driver.PurchaseCancelled
	// PurchasePending: the purchase waits for someone's approval, as Ask to Buy's, or for the user to act outside the app; its transaction comes later through OnPurchaseUpdate.
	PurchasePending PurchaseError = driver.PurchasePending
	// PurchaseFailed: the store refused or could not answer, such as for a product it does not sell, a network error or a device that may not make payments.
	PurchaseFailed PurchaseError = driver.PurchaseFailed
	// PurchaseNotFound: no unfinished transaction has the ID FinishTransaction was given, as one already finished has not.
	PurchaseNotFound PurchaseError = driver.PurchaseNotFound
	// PurchasesUnavailable: this platform or build has no store to buy from (Env.CanPurchase).
	PurchasesUnavailable PurchaseError = driver.PurchasesUnavailable
)

func (PurchaseError) Error added in v0.2.0

func (e PurchaseError) Error() string

type PurchaseOptions added in v0.2.0

type PurchaseOptions struct {
	// AccountToken is a UUID of the app's own that ties the purchase to its user, which the transaction and the store's notifications to the app's server carry: StoreKit's appAccountToken. "" sends none.
	AccountToken string
	// Quantity is how many of a consumable to buy; 0 is 1.
	Quantity int
	// Offer is the promotional offer a subscription is bought with, nil for none; an introductory offer the user is eligible for applies without one.
	Offer *PromotionalOffer
}

PurchaseOptions are what Purchase buys with.

type PurchaseRequest added in v0.2.0

type PurchaseRequest = driver.PurchaseRequest

PurchaseRequest is an in-app purchase service's request as the platform carries it out, as a test's model sees it.

type QuitRequest

type QuitRequest struct {
	// contains filtered or unexported fields
}

QuitRequest is the core's part of desktop.QuitRequest, which apps use: a quit the user asked for, which a handler may cancel, or defer while it asks the user what to do.

func (*QuitRequest) Cancel

func (q *QuitRequest) Cancel()

Cancel keeps the app running. It has an effect only while the request handler is running.

func (*QuitRequest) Canceled added in v0.2.0

func (q *QuitRequest) Canceled() bool

Canceled reports whether a handler canceled the quit: what a test of a handler reads.

func (*QuitRequest) Defer

func (q *QuitRequest) Defer() func(quit bool)

Defer keeps the platform's quit request pending and returns a one-shot answer. quit true proceeds with quitting; false cancels it. The returned function is safe to call from another goroutine. Call it in every case: until it is called, a later quit request, such as a second Cmd+Q, waits for this one's answer. A handler that panics after Defer, without having answered, cancels the request, and the function it got then does nothing.

type Ref

type Ref struct {
	// contains filtered or unexported fields
}

Ref refers to a mounted element: an overlay's anchor, focus, its bounds. Its zero value is ready to use; pass its address in an element's Ref field.

Its focus, blur, scroll, zoom and reveal requests do nothing while the element is in a Holder's content that no place shows, and those still queued when it leaves the tree are dropped; placing the content again does not replay them.

func (*Ref) Before

func (r *Ref) Before(other *Ref) bool

Before reports whether r's view comes before other's in tree order, the order Tab goes through them; views not mounted come last.

func (*Ref) Blur

func (r *Ref) Blur()

Blur takes keyboard focus away from the element.

func (*Ref) Bounds

func (r *Ref) Bounds() (Bounds, bool)

Bounds returns the element's frame in surface points after the last commit, and false while it is not mounted.

func (*Ref) Command

func (r *Ref) Command(name string, args any)

Command has the component of the native view r names run name with args.

func (*Ref) ContentBounds

func (r *Ref) ContentBounds() (Bounds, bool)

ContentBounds is the box around what the view holds, in the surface, its own frame while it holds nothing, and false while it is not mounted.

func (*Ref) Evaluate

func (r *Ref) Evaluate(script string, done func(json string, err error))

Evaluate runs script in the web view's page, as an expression, and calls done on the engine's goroutine, while the web view lives, with its result as JSON, or the error it threw: a promise it returns is awaited, undefined is null, and what JSON cannot hold (a function, a cycle) is an error. The answer comes through the page's channel to the app, as OnMessage's, on every backend with web views. A page that leaves first ends it with an error, as does a view with NoJavaScript, and a view that goes never answers.

func (*Ref) Focus

func (r *Ref) Focus()

Focus moves keyboard focus to a text field or, on desktops, the web and Apple TV, an enabled pressable or Focusable view. Plain, hidden and NoFocus views and views below a modal do not take focus. Under a confined owner it does only as Scope.Confine allows. It does nothing in unplaced Holder content, with no focus deferred until it is placed again.

func (*Ref) Frame

func (r *Ref) Frame() (Bounds, bool)

Frame returns the element's frame in its parent after the last commit, as OnLayout receives it, and false while it is not mounted.

func (*Ref) GoBack

func (r *Ref) GoBack()

GoBack goes back in the web view's history. On native targets, going back to the page of the app's own source is not held to AccessWebSchemes.

func (*Ref) GoForward

func (r *Ref) GoForward()

GoForward goes forward in the web view's history. On native targets, going forward to the page of the app's own source is not held to AccessWebSchemes.

func (*Ref) HoldsFocus

func (r *Ref) HoldsFocus() bool

HoldsFocus reports whether the keyboard focus is on the element or inside it, as the platform last reported it; it is not tracked.

func (*Ref) InjectJavaScript

func (r *Ref) InjectJavaScript(script string)

InjectJavaScript runs script in the web view's page.

func (*Ref) ListPosition

func (r *Ref) ListPosition() (ListPosition, bool)

ListPosition reads where the element, a List, has its viewport start among its rows after the last commit, from the list's own row positions: ScrollToIndexAt(p.Index, 0, -p.Offset, false) brings a list made anew back there. In a header before the first row the index is 0 and the offset negative; false for a list without rows, or no list.

func (*Ref) Load added in v0.2.0

func (r *Ref) Load(src WebSource)

Load loads src in the web view, as a new Source would, even when it is the source the view already shows: the page loads with the view's Headers, and a source Access refuses reaches OnError and loads nothing. It navigates the view, as a link does, and leaves the source alone: Source or SourceFunc's next change loads again, a change to the scripts or headers loads the source again, and messages come by default from the source's origin, not src's.

func (*Ref) Measure

func (r *Ref) Measure(done func(frame, page Bounds, ok bool))

Measure calls done with the element's frame in its parent and in the surface once the changes made so far are laid out, after the next commit; ok is false while it is not mounted.

func (*Ref) PostMessage

func (r *Ref) PostMessage(data string)

PostMessage dispatches a MessageEvent carrying data on the web view's page.

func (*Ref) Reload

func (r *Ref) Reload()

Reload loads the web view's page again. On native targets, reloading the page of the app's own source is not held to AccessWebSchemes.

func (*Ref) Reveal

func (r *Ref) Reveal(opts RevealOptions)

Reveal scrolls every scroll view around the element until it shows, innermost first, each clamped to its content: at the commit, with that commit's layout, so a view made in the same turn is revealed where it lands. The word is NSH's (`reveal`), as GPUI Kit's `reveal_item`; the alignments are physical, as NSH's.

func (*Ref) RevealBox

func (r *Ref) RevealBox(box Bounds, opts RevealOptions)

RevealBox scrolls every scroll view around the element until box, in the element's frame as TextRangeBoxes gives a text's ranges, shows, as Reveal shows the whole element: a match in a long line of code reaches its column, not only the code's block.

func (*Ref) ScrollTo

func (r *Ref) ScrollTo(at Point, animated bool)

ScrollTo scrolls the element, a Scroll or List, so its content's offset is at.

func (*Ref) ScrollToEnd

func (r *Ref) ScrollToEnd(animated bool)

ScrollToEnd scrolls the element, a Scroll or List, to the end of its content. A list keeps following the end as the rows there are measured, until the user scrolls away.

func (*Ref) ScrollToIndex

func (r *Ref) ScrollToIndex(index int, animated bool)

ScrollToIndex scrolls the element, a List, so row index is at the start of its viewport.

func (*Ref) ScrollToIndexAt

func (r *Ref) ScrollToIndexAt(index int, viewPosition float32, viewOffset Points, animated bool)

ScrollToIndexAt scrolls the element, a List, so row index is at viewPosition of its viewport (0 its start, 0.5 its middle, 1 its end), viewOffset before it. Sizes of rows never shown are estimates, so the list keeps following the row as the rows around it are measured, until the user scrolls away or the rows change.

func (*Ref) Seek

func (r *Ref) Seek(position time.Duration)

Seek jumps the video r names to position. In the update that unpauses a video that played to its end, the video plays again from position.

func (*Ref) SendInput

func (r *Ref) SendInput(in WebInput)

SendInput gives the web view's page input as the user's own, whose events are trusted and carry user activation, which no script the page runs can make: a click, typed text or a key. It takes the keyboard focus first. It does nothing where Env.CanSendInput is false.

func (*Ref) SetAccessibilityFocus

func (r *Ref) SetAccessibilityFocus()

SetAccessibilityFocus moves the screen reader's focus to the element, as after a change the user should hear about first. The web and desktops move the keyboard focus with it, to a field at least, so under a confined owner it does only as Scope.Confine allows.

func (*Ref) SetSelection

func (r *Ref) SetSelection(start, end int)

SetSelection selects start to end, in UTF-16 units, in the element, a text field; equal offsets place the caret.

func (*Ref) StopLoading

func (r *Ref) StopLoading()

StopLoading stops the web view's page loading.

func (*Ref) TextCaretAt

func (r *Ref) TextCaretAt(p Point) (offset int, upstream, ok bool)

TextCaretAt returns the caret nearest p, a point in the text's frame, after the last commit: its UTF-16 offset, and upstream when it stays at the end of a wrapped line. False while the text is not laid out.

func (*Ref) TextCaretBox

func (r *Ref) TextCaretBox(offset int, upstream bool) (Bounds, bool)

TextCaretBox returns the caret's box at UTF-16 offset, a box of no width as tall as its line, in the text's frame; upstream takes the earlier line where one offset is at both.

func (*Ref) TextRangeBoxes

func (r *Ref) TextRangeBoxes(start, end int) []Bounds

TextRangeBoxes returns the line-high boxes of the UTF-16 range from start to end, in the text's frame.

func (*Ref) ZoomTo

func (r *Ref) ZoomTo(scale float32, center *Point, animated bool)

ZoomTo zooms the element, a Scroll that zooms, to scale (clamped to its limits), with content point center (unzoomed) in the middle of the viewport, or keeping the middle when center is nil.

type Region

type Region = driver.Region

Region is a part of a surface an app can lay out in.

type ResizeMode

type ResizeMode = driver.ResizeMode

ResizeMode fits an image or a video into its view.

type Resource

type Resource[T any] struct {
	// contains filtered or unexported fields
}

Resource is a value loaded on another goroutine from a source, loaded again when the source changes or on Refetch, as NSH's resource and Solid's createResource are. Its value, error and state are signals: bindings that read them follow its loads. Only the latest load counts: a newer one cancels the context of the one running, and so does the owner's disposal.

Like a signal's, its methods belong to the graph's goroutine.

func NewResource

func NewResource[S, T any](cx *Scope, source func() (S, bool), fetch func(ctx context.Context, source S, info ResourceInfo) (T, error)) *Resource[T]

NewResource returns a resource that loads fetch(ctx, s) whenever source gives a new s with ok true, and on Refetch. source is tracked and runs on the graph's goroutine; with ok false the resource loads nothing, as for a user not signed in yet, and a nil source loads once with S's zero value. fetch runs on a goroutine of its own, so it may block on the network or the disk; ctx is cancelled when a newer load starts or the owner is disposed, and the result of a load that no longer counts is dropped. A panic in fetch fails the load with a *PanicError and goes to the nearest Catch, as a panic in app code does.

Its results reach the graph through Post, so the graph needs a host: an engine or a test driver.

func NewResourceWithValue

func NewResourceWithValue[S, T any](cx *Scope, value T, source func() (S, bool), fetch func(ctx context.Context, source S, info ResourceInfo) (T, error)) *Resource[T]

NewResourceWithValue returns a resource as NewResource does that holds value until its first load ends, which is a refresh (TSX's initialValue).

func (*Resource[T]) Err

func (r *Resource[T]) Err() error

Err returns the last load's error, nil once a load gave a value; it subscribes the running computation.

func (*Resource[T]) Get

func (r *Resource[T]) Get() (v T, ok bool)

Get returns the latest value, kept while loading again and after a failure, with ok false before the first; it subscribes the running computation, and has a Suspense around it wait while the first value loads.

func (*Resource[T]) Loading

func (r *Resource[T]) Loading() bool

Loading reports whether a load runs; it subscribes the running computation.

func (*Resource[T]) Mutate

func (r *Resource[T]) Mutate(v T)

Mutate sets the value with no load, as an optimistic update does, and clears the last error; a load still running replaces it when it ends.

func (*Resource[T]) Refetch

func (r *Resource[T]) Refetch()

Refetch loads the resource again from the same source, as a retry or a pull to refresh does, keeping the value meanwhile. A resource whose source is not set stays as it is.

func (*Resource[T]) State

func (r *Resource[T]) State() ResourceState

State returns where the resource is; it subscribes the running computation.

type ResourceInfo

type ResourceInfo struct {
	// Refetching says Refetch started the load: the source did not change.
	Refetching bool
}

ResourceInfo is what a load is told besides its source.

type ResourceState

type ResourceState uint8

ResourceState is where a Resource is (NSH's ResourceState).

const (
	// ResourceUnresolved has nothing loaded and nothing loading: its source is not set.
	ResourceUnresolved ResourceState = iota
	// ResourcePending is loading, with no value yet.
	ResourcePending
	// ResourceReady has a value, and nothing loading.
	ResourceReady
	// ResourceRefreshing is loading again, with the last value kept.
	ResourceRefreshing
	// ResourceErrored says the last load failed.
	ResourceErrored
)

func (ResourceState) Loading

func (s ResourceState) Loading() bool

Loading reports whether a load runs.

func (ResourceState) String

func (s ResourceState) String() string

String returns its name in TSX: "unresolved", "pending", "ready", "refreshing" or "errored".

type Responder

type Responder struct {
	// Claims are asked in order.
	Claims []TouchClaim
	// Keep refuses to hand the touches to a view that claims them later;
	// OnTerminationRequest, when set, is asked instead each time one does.
	Keep                 bool
	OnTerminationRequest func(ResponderEvent) bool
	// OnGrant: the view became the responder. OnReject: it claimed, but
	// the responder kept the touches.
	OnGrant, OnReject func(ResponderEvent)
	// BlockNative, when set, decides after OnGrant whether the scroll
	// views around stop taking the touches, over the claim's LetNative.
	BlockNative func(ResponderEvent) bool
	// OnStart, OnMove and OnEnd follow the fingers while it is the
	// responder.
	OnStart, OnMove, OnEnd func(ResponderEvent)
	// OnRelease: the last finger lifted. OnTerminate: another view or the
	// system took the touches.
	OnRelease, OnTerminate func(ResponderEvent)
}

Responder makes a view take part in the touch responder, React Native's: it claims the touches as its Claims say, and as the responder hears where they go.

type ResponderEvent

type ResponderEvent struct {
	// Position is in the view hearing it, PagePosition in the surface.
	Position     Point
	PagePosition Point
	Time         time.Duration
	Gesture      PanGesture
}

ResponderEvent is what a responder or a claim hears: the finger the event is about and the gesture.

type ReturnKeyType

type ReturnKeyType = driver.ReturnKeyType

ReturnKeyType labels the software keyboard's return key.

type RevealOptions

type RevealOptions struct {
	Vertical, Horizontal ScrollAlignment
	Animated             bool
	// Margin is kept clear at the outermost scroll view's edges, for the bars that cover them, such as a find bar over a transcript.
	Margin Edges
}

RevealOptions say where Reveal puts a view along vertical and horizontal scroll views, and whether the scrolls animate.

type Ripple

type Ripple = driver.Ripple

Ripple is Android's ripple over a pressed view (AndroidViewProps).

type Role

type Role = driver.Role

Role is a view's accessibility role.

type RootOptions

type RootOptions struct {
	// CheckCommits compares incremental commits with a full layout and panics on changes the incremental pass missed. Tests enable it; performance measurements leave it off for their own graph. In a native test build (nsgotest or nsgocheck, not WebAssembly) it also records the goroutine that calls NewRoot as the graph's owner and panics when another goroutine writes to the graph, commits it or runs code in it; a development build (nsgodev) checks every native graph whatever this says.
	CheckCommits bool
	// Post runs fn on the graph's goroutine later. It must be safe to
	// call from any goroutine and must not block.
	Post func(fn func())
	// Clock schedules timers; the system's when nil.
	Clock Clock
	// Report receives failures no Catch handles; they are dropped when nil.
	Report func(error)
	// RequestFrame tells the host that the app waits for the next display
	// frame: it calls Scope.RunFrame when that frame begins, and is not
	// asked again until then. It runs on the graph's goroutine, so it must
	// not block. A host without display frames leaves it nil, and the
	// callbacks wait.
	RequestFrame func()
	// Storage keeps the app's entries; a store in memory when nil.
	Storage *Store
	// Secrets is the platform's secure store, which Scope.Secrets keeps secrets in; nil where there is none, so Secrets fails with ErrSecretsUnavailable.
	Secrets SecretStore
	// DataDir, CacheDir and LogsDir are the app's directories, "" where the target has none.
	DataDir, CacheDir, LogsDir string
	// Host is the channel to the host app that embeds the app: its
	// parameters, events, handlers and URL handler. The graph attaches to
	// it until its root is disposed.
	Host *Host
	// Windows, set where the platform opens windows, are the main
	// window's options (SetMainView): the first tree is then the app's
	// own surface, which shows no view.
	Windows *WindowOptions
	// HotKeys, set where the platform registers global shortcuts but opens no windows, sends RegisterHotKey's shortcuts to the first tree, as a platform that opens windows has them sent to the app's own surface. The platform answers each with EventHotKeyState; elsewhere RegisterHotKey's handles are unsupported at once.
	HotKeys bool
	// Tray is set where the platform supports app-level tray icons without
	// opening additional windows.
	Tray bool
}

RootOptions connect a graph to its host, an engine or a test driver.

type SVG

type SVG = driver.SVG

SVG is a parsed SVG document: vector shapes that stay sharp at any size.

func MustParseSVG

func MustParseSVG(data []byte) *SVG

MustParseSVG is ParseSVG for documents that are part of the program, such as embedded icons: it panics when one is in error.

func ParseSVG

func ParseSVG(data []byte) (*SVG, error)

ParseSVG parses an SVG document.

type SVGView

type SVGView struct {
	// Class is Tailwind CSS classes, as View's.
	Class     string
	SVG       *SVG
	SVGFunc   func() *SVG
	Style     Style
	StyleFunc func() Style
	OnPress   func(PressEvent)
	OnLayout  func(Bounds)
	Ref       *Ref
	Label     string
	TestID    string
}

SVGView draws an SVG document as authored, as an <svg> written inline in a web page: in its own colors, sized by its width and height, else its viewBox, where Style sets no size. Its shapes are vectors, sharp at any size, and currentColor is the text color it inherits.

func (SVGView) Render

func (v SVGView) Render(*Scope) Node

Render implements Node.

type SaveOptions

type SaveOptions struct {
	// Name is the file name the dialog suggests; Path's when empty.
	Name string
	// MIME is its media type; Name's extension says when empty.
	MIME string
	Path string
	Data []byte
}

SaveOptions say what SaveFile saves: the file at Path, or else Data.

type SaveRequest

type SaveRequest = driver.SaveRequest

SaveRequest is a save as the platform carries it out, SaveOptions resolved.

type Scope

type Scope struct {
	// contains filtered or unexported fields
}

Scope owns what is created under it: memos, effects, cleanups, child scopes and the views of its elements. Components receive one as cx.

Go has no goroutine-local state, so cx is how code finds its graph. While the graph runs code, what it creates belongs to the innermost running owner, whichever cx the code captured.

func NewRoot

func NewRoot(opts RootOptions) *Scope

NewRoot returns the root scope of a new graph.

func (*Scope) Abort added in v0.2.0

func (cx *Scope) Abort()

Abort implements internal/engine's fault shutdown: stop scheduling work, then dispose the graph and cancel its resources. Only a root may abort. Cleanups still run, but cannot restart effects on a partially committed tree.

func (*Scope) AddRecentFile added in v0.2.0

func (cx *Scope) AddRecentFile(path string)

AddRecentFile is the core's part of desktop.AddRecentFile, which apps use. A relative path is taken from the working directory.

func (*Scope) AfterFunc

func (cx *Scope) AfterFunc(d time.Duration, fn func()) (stop func() bool)

AfterFunc runs fn on the graph's goroutine after d, unless the current owner is disposed first or stop is called. stop reports whether it stopped the timer before fn ran, and may be called on any goroutine. A timer that has fired or been stopped keeps nothing on its owner, so re-arming one under a long-lived scope, as a debounce or a repeating tick does, does not grow it.

func (*Scope) Animate

func (cx *Scope) Animate(d time.Duration, curve Curve, step func(progress float64)) (stop func())

Animate calls step with the eased progress from 0 to 1 once a display frame for d, on the graph's goroutine, ending with exactly 1, unless the current owner is disposed or stop is called first. Each step's changes commit as one batch, so prefer a style Transition for what a platform can animate itself.

func (*Scope) AnimateLayout

func (cx *Scope) AnimateLayout(a LayoutAnimation)

AnimateLayout animates the changes of the next commit that has any with a: views move and resize, and appear and go, on the platform.

func (*Scope) Announce

func (cx *Scope) Announce(text string)

Announce has the screen reader say text. A confined owner's is said only as Scope.Confine allows, else dropped.

func (*Scope) AppleCredentialState added in v0.2.0

func (cx *Scope) AppleCredentialState(user string, done func(AppleCredentialState, error))

AppleCredentialState answers done with the state of user's credential, the ID an AppleCredential gave, or with an AppleSignInError: check it as the app starts, to sign out a user who revoked it. An empty user is AppleCredentialNotFound without asking the platform. It is held as SignInWithApple is.

func (*Scope) AuthSession added in v0.2.0

func (cx *Scope) AuthSession(url func(redirect string) string, opts AuthSessionOptions, done func(callback string, err error)) (cancel func())

AuthSession signs the user in with an OAuth provider in the system's authentication session (RFC 8252): it prepares the redirect opts say, asks url for the authorization URL to open with it, which is the redirect_uri the URL names, and calls done once with the URL the provider redirected to, its query holding the code and state, or with an AuthError: AuthCancelled when the user closes the session. The app makes the PKCE verifier and the state and checks them. macOS and iOS open ASWebAuthenticationSession; desktops otherwise open the default browser and serve the redirect on loopback, and the web a popup. Elsewhere, or for a redirect a platform cannot catch, done hears AuthUnavailable. cancel ends the session with AuthCancelled; a session outlives the owner that started it, done running under the root then, as other answers do.

func (*Scope) AuthenticateBiometric

func (cx *Scope) AuthenticateBiometric(reason string, done func(BiometricResult))

AuthenticateBiometric asks the user to authenticate with reason, which the prompt shows and must not be empty: an empty one answers BiometricFailure without a prompt. It never falls back to a passcode; the app chooses that separately.

func (*Scope) Batch

func (cx *Scope) Batch(fn func())

Batch runs fn and then the effects its writes scheduled, once each.

func (*Scope) BiometricAvailability

func (cx *Scope) BiometricAvailability(done func(BiometricKind))

BiometricAvailability answers whether an enrolled biometric is available, and which kind it is. It does not show a system prompt.

func (*Scope) CacheDir

func (cx *Scope) CacheDir() string

CacheDir returns the directory for files the app can make again, which the system may delete when space runs low; "" on the web.

func (*Scope) CallHost

func (cx *Scope) CallHost(name string, data any, done func(result any, err error))

CallHost calls the embedding host's handler of name with data (any value JSON encodes) and has done hear its answer on the app's goroutine, unless the current owner is disposed first. It fails at once without a host or a handler of name, and after HostCallTimeout without an answer.

func (*Scope) CallHostTimeout

func (cx *Scope) CallHostTimeout(name string, data any, timeout time.Duration, done func(result any, err error))

CallHostTimeout is CallHost waiting timeout for the answer; 0 waits without a deadline.

func (*Scope) CanInstallPackages

func (cx *Scope) CanInstallPackages(done func(allowed bool))

CanInstallPackages is the core's part of mobile.CanInstallPackages, which apps use: it asks Android whether the user lets the app install packages.

func (*Scope) CanReadFrontmostApp added in v0.2.0

func (cx *Scope) CanReadFrontmostApp() bool

CanReadFrontmostApp is the core's part of desktop.CanReadFrontmostApp, which apps use: whether FrontmostApp follows the application in front, read tracked, false where the platform does not or the current owner's Access refuses AccessFrontmostApp. Asking logs no refusal.

func (*Scope) CheckAccess

func (cx *Scope) CheckAccess(req AccessRequest) error

CheckAccess returns AccessDenied when the current owner's Access refuses req, for the requests core does not make itself, such as a fetch of tsx's. Call it on the graph's goroutine, as it reads the current owner; Scope.Post enters the receiving scope on that goroutine.

func (*Scope) CheckForUpdates

func (cx *Scope) CheckForUpdates(background bool, done func(UpdateCheck))

CheckForUpdates is the core's part of updater.Check and updater.CheckInBackground, which apps use: it asks the platform's updater for a newer version of the app, quietly when background, and done hears its answer. A platform with no updater, such as the web, never answers.

func (*Scope) Child

func (cx *Scope) Child() *Scope

Child returns a new scope owned by the current one.

func (*Scope) Cleanup

func (cx *Scope) Cleanup(fn func())

Cleanup registers fn to run when the current owner is disposed or runs again, last registered first, as testing.T.Cleanup does. Readers of what fn writes run once the disposal, or the owner's new run, is over, never against a half-disposed tree.

func (*Scope) ClearRecentFiles added in v0.2.0

func (cx *Scope) ClearRecentFiles()

ClearRecentFiles is the core's part of desktop.ClearRecentFiles, which apps use.

func (*Scope) CloseNotification

func (cx *Scope) CloseNotification(id string)

CloseNotification removes the notification called id, if it still shows, or keeps it from showing if it is scheduled.

func (*Scope) CloseNotifications

func (cx *Scope) CloseNotifications()

CloseNotifications removes every notification ShowNotification showed or scheduled, also those earlier runs left where the system keeps them: on macOS, iOS, Windows and Android. Linux and the web reach only those this run showed. It leaves the app's other notifications alone, such as Android's Live Updates and its foreground services', and the badge.

func (*Scope) CloseWindow

func (cx *Scope) CloseWindow()

CloseWindow is the core's part of desktop.CloseWindow, which apps use.

func (*Scope) Confine

func (cx *Scope) Confine()

Confine holds what the current owner shows, whoever makes it, to its place in the window, as a browser holds a cross-origin frame. Its key bindings (OnKey) and back handlers (OnBackPress) fire only while the keyboard focus is on a view it owns, itself or through the owners below it: never while the focus is elsewhere or nowhere, so what it shows cannot take the keys or back presses of the views around it; a press they leave goes on to the others, as if they were not there. Its views draw and take input only within its frame, the nearest view around them it does not own, which clips them: its overlays and Fixed views are hosted, sized and placed there rather than in the root view or a modal, and its overlays take back only under the focus rule above. Give it a view of its own, as tsx's sandbox does, or the views beside it in that frame stay within its reach. What a frame cannot hold, and the focus, wait for the user: a Ref's Focus and SetAccessibilityFocus, an input's AutoFocus, DismissKeyboard, a Modal, ShowAlert, PopupMenu, LookUp and Announce act only while the focus is already in its views or the user's input just landed on one (confinedMay), else they are refused, and the first refusal of each kind logs; a modal so shown stays and hears back wherever the focus is, and back takes it away whether or not it removes the modal. Its navigation stacks pop on back only under the focus rule above. Confine it before it renders. tsx's sandbox confines a bundle's scope.

func (*Scope) Context

func (cx *Scope) Context() context.Context

Context returns a context cancelled when the current owner is disposed or runs again; pass it to work the owner starts on other goroutines.

func (*Scope) CurrentEntitlements added in v0.2.0

func (cx *Scope) CurrentEntitlements(done func([]Transaction, error))

CurrentEntitlements answers done with the latest transaction of each product the user is entitled to now: non-consumables, subscriptions in their period and non-renewing subscriptions, refunded and revoked ones left out. Read them as the app starts to unlock what the user bought, on this device or another. It is held and unavailable as Products is.

func (*Scope) CurrentWindow

func (cx *Scope) CurrentWindow() *Window

CurrentWindow is the core's part of desktop.CurrentWindow, which apps use: the window cx is in, nil in the app's own scope or where the platform opens no windows.

func (*Scope) Dark

func (cx *Scope) Dark() bool

Dark reports whether cx's subtree shows dark: as the nearest SetSubtreeAppearance forces it, else as the app shows (Env.Dark).

func (*Scope) DataDir

func (cx *Scope) DataDir() string

DataDir returns the directory the app keeps its files in: Application Support on Apple platforms, %APPDATA% on Windows, the files directory on Android, each with a directory of the app's own. It is "" on the web, which has none.

func (*Scope) DismissKeyboard

func (cx *Scope) DismissKeyboard()

DismissKeyboard takes focus away from the focused text field, hiding the software keyboard. Under a confined owner it does only as Scope.Confine allows.

func (*Scope) Dispose

func (cx *Scope) Dispose()

Dispose disposes everything the scope owns, runs its cleanups and cancels its Context.

func (*Scope) Disposed

func (cx *Scope) Disposed() bool

Disposed reports whether the scope has been disposed.

func (*Scope) Effect

func (cx *Scope) Effect(fn func()) (stop func())

Effect runs fn after the current batch and again whenever what it read changes, until the current owner is disposed or stop is called.

func (*Scope) Env

func (cx *Scope) Env() *Env

Env returns the environment of the window cx is in: its size, scale and safe area are the window's, and what the app forces is every window's.

func (*Scope) ExitApp

func (cx *Scope) ExitApp()

ExitApp is the core's part of mobile.ExitApp, which apps use: it leaves the app as Android's back button does when nothing takes it.

func (*Scope) FinishTransaction added in v0.2.0

func (cx *Scope) FinishTransaction(id string, done func(error))

FinishTransaction tells the store the app delivered what the transaction whose ID is id bought, and answers done: nil, or PurchaseNotFound when no unfinished transaction has the ID. Finish each transaction Purchase, OnPurchaseUpdate or CurrentEntitlements gives once its server verified it: the store hands an unfinished one to the app again at each launch, and refunds an unfinished purchase after some days. It is held and unavailable as Products is.

func (*Scope) FrontmostApp added in v0.2.0

func (cx *Scope) FrontmostApp() FrontmostAppInfo

FrontmostApp is the core's part of desktop.FrontmostApp, which apps use: the application in front, read tracked, zero where the platform does not follow it (CanReadFrontmostApp) or the current owner's Access refuses AccessFrontmostApp.

func (*Scope) GuidePermission

func (cx *Scope) GuidePermission(p Permission, opts PermissionGuideOptions, done func(PermissionStatus)) (stop func())

GuidePermission is the core's part of desktop.GuidePermission, which apps use. One guide shows at a time: a new one ends the one before, and the current owner's going ends it as stop does. done runs once, with the status as it ends, under the root once the owner is gone.

func (*Scope) HasClipboardImage

func (cx *Scope) HasClipboardImage(done func(bool))

HasClipboardImage calls done with whether the clipboard holds an image, without reading it.

func (*Scope) HasClipboardText

func (cx *Scope) HasClipboardText(done func(bool))

HasClipboardText calls done with whether the clipboard holds text, without reading it, so iOS shows no paste notice.

func (*Scope) HasHost

func (cx *Scope) HasHost() bool

HasHost reports whether a host embeds the app, to answer its calls.

func (*Scope) Hiding

func (cx *Scope) Hiding() bool

Hiding runs the OnQuit handlers as Quitting does but keeps them, for an app the system hides and may end without a word: a page the browser keeps in its back-forward cache, or a watchOS app in the background. It may show the app again, which runs them again at its next hide or quit.

func (*Scope) HostParams

func (cx *Scope) HostParams() map[string]any

HostParams returns the parameters the embedding host gave the app before it started (Host.SetParams): an empty map without a host or any.

func (*Scope) ImageSize

func (cx *Scope) ImageSize(src ImageSource, done func(pixels Size, err error))

ImageSize calls done with the size in pixels of the image src names, as Image's OnLoad reports it, or the error loading or reading it (NSH's Image.getSize). The platform loads it as an Image would, the variant of an "asset:" source with Scales included, and keeps its bytes for the views that show it next. A source with Pixels loads nothing: done is called at once with the buffer's size.

func (*Scope) InstallPackage

func (cx *Scope) InstallPackage(path string, done func(started bool, err error))

InstallPackage is the core's part of mobile.InstallPackage, which apps use: it hands the APK at path to Android's package installer.

func (*Scope) KeepAwake

func (cx *Scope) KeepAwake(reason string, opts KeepAwakeOptions) (release func())

KeepAwake keeps the computer from idle sleep until release is called or the current scope is disposed. The reason is shown by platforms that list power assertions. Releasing more than once is safe.

func (*Scope) KeyLabel

func (cx *Scope) KeyLabel(key string) string

KeyLabel is key as the platform the app runs on shows it, as core.KeyLabel says.

func (*Scope) LaunchAtLogin

func (cx *Scope) LaunchAtLogin(done func(on bool))

LaunchAtLogin is the core's part of desktop.LaunchAtLogin, which apps use: done hears whether the system starts the app at login.

func (*Scope) LoadSound

func (cx *Scope) LoadSound(src AudioSource, done func(*Sound, error))

LoadSound has the platform read and decode src into memory once and calls done with the sound or why not, an AudioError: the core's part of audio.LoadSound, which apps use. A source this engine's surface already holds, the same URI or bytes of the same digest, shares its decoded sound. The current owner closes the sound as it goes; done, which runs in a later turn, never runs once it went.

func (*Scope) Locate added in v0.2.0

func (cx *Scope) Locate(opts LocationOptions, done func(LocationFix, error)) (*SensorStream, error)

Locate waits for a new provider fix unless MaxAge explicitly allows a cached one, under PermissionLocation, which it never asks for. It waits through background pauses and stops after one fix. The default foreground timeout is 30 seconds; Stop cancels silently.

func (*Scope) LogsDir added in v0.2.0

func (cx *Scope) LogsDir() string

LogsDir returns the directory for the app's log files, where the platform's tools look for them: ~/Library/Logs/<id> on macOS, %LOCALAPPDATA%\<id>\Logs on Windows (inside CacheDir, so an app that empties its cache must spare Logs), $XDG_STATE_HOME/<id> on Linux (~/.local/state by default), and logs in DataDir on Android, iOS and watchOS. A host's data directory and nsgotest move it with DataDir. It is "" on the web, which has none. NSGo writes nothing there: the app owns its log files.

func (*Scope) LookUp added in v0.2.0

func (cx *Scope) LookUp(text string, in *Ref, at Bounds) bool

LookUp is the core's part of desktop.LookUp, which apps use: it shows the platform's dictionary panel for text at at, a box in the view in refers to (the surface's without in), as a TextSelection's Bounds is in its view. It reports whether it asked the platform: false for blank text, an in that is not mounted, where Env.CanLookUp is false, and for a confined owner as Scope.Confine allows a PopupMenu.

func (*Scope) MainWindow

func (cx *Scope) MainWindow() *Window

MainWindow is the core's part of desktop.MainWindow, which apps use.

func (*Scope) MeasureText

func (cx *Scope) MeasureText(text string, font Font) TextMetrics

MeasureText returns the advance width and the metrics of text's first line in font, laid out by the platform's text engine as a canvas measures it (Drawing.TextMetrics): a column fitted to its widest text, a monospaced font's character width.

func (*Scope) MinimizeWindow

func (cx *Scope) MinimizeWindow()

MinimizeWindow is the core's part of desktop.MinimizeWindow, which apps use.

func (*Scope) NewAudioPlayer

func (cx *Scope) NewAudioPlayer(src AudioSource, opts AudioPlayerOptions) *AudioPlayer

NewAudioPlayer makes a player of src, loading nothing until Play or Preload: the core's part of audio.NewPlayer, which apps use. The current owner closes it as it goes.

func (*Scope) NewTray

func (cx *Scope) NewTray(opts TrayOptions) *Tray

NewTray is the core's part of desktop.NewTray, which apps use: it adds a tray icon, the macOS menu bar's or the Windows notification area's, which the current owner keeps.

func (*Scope) NotificationPermission

func (cx *Scope) NotificationPermission(done func(NotificationPermission))

NotificationPermission answers done with whether the app may show notifications, without asking the user. On macOS checking uses the notification center as asking does, so from then on the app's Dock badge shows only while the user allows its badges.

func (*Scope) Now

func (cx *Scope) Now() time.Time

Now returns the time on the graph's clock: the system's, or a test's manual clock.

func (*Scope) OnBackPress

func (cx *Scope) OnBackPress(fn func() bool)

OnBackPress runs fn when back is pressed (Escape, the back button or gesture, the browser's back) while the current owner lives and the user can see what it shows, as for OnKey: after the overlays and modals, which take it first, and before the navigation stacks, the newest handler first. fn returns true to take it; when none does, the top stack pops, else the platform goes back itself.

func (*Scope) OnExit

func (cx *Scope) OnExit(exit func(done func()))

OnExit has exit play when the Presence branch cx is in leaves: exit starts what the part does to leave, such as a Motion's exit, and calls done once it ends, which it may do at once. The branch goes once every exit registered in it has called done. Outside a Presence, exit never runs and the part goes with its branch at once.

func (*Scope) OnHostEvent

func (cx *Scope) OnHostEvent(name string, fn func(data any))

OnHostEvent calls fn with each event of name the embedding host sends (Host.Send), until the current owner is disposed. Events sent before the app had a listener of name are kept for it: the first listener hears them, in order, once the code adding it has run.

func (*Scope) OnKey

func (cx *Scope) OnKey(key string, fn func())

OnKey runs fn when key is pressed, while the current owner lives and the user can see what it shows. key names modifiers and a key joined by "+": "mod+s" (Command on Apple platforms, Control elsewhere), "ctrl+shift+z", "alt+left", "escape", "enter", "f5", "a". Of the bindings of a key that fire where the focus is, the newest wins, and only it runs. It fires once while the key is held, and not while the view with the keyboard focus uses the key itself, a text input its editing keys, a button Return and Space, a slider or a tab bar its arrows (KeyAuto); OnKeyWith says else. A control that binds its own keys while it has the focus binds them with KeyNotEditing, or the focus it holds would keep them from it.

What the owner shows are the views of the nearest owner at or above it that has any. The binding rests while none of them shows: in a Holder's content no place shows, under a DisplayNone view such as a navigation stack's screen below the top, in a dismissed modal. While a modal is shown it rests too if any of them is outside the topmost modal, as the page under a dialog is, unless KeyOptions.OverModals. It fires again once they show, without binding it again.

func (*Scope) OnKeyWith

func (cx *Scope) OnKeyWith(key string, opts KeyOptions, fn func())

OnKeyWith is OnKey firing as opts say.

func (*Scope) OnNotificationPress

func (cx *Scope) OnNotificationPress(fn func(id string))

OnNotificationPress runs fn, while the current owner lives, with the ID of a notification the user pressed, which brings the app to the front. Presses that came before any handler, as the one that started the app, go to the first one registered.

func (*Scope) OnOpenFiles

func (cx *Scope) OnOpenFiles(fn func(paths []string))

OnOpenFiles is the core's part of desktop.OnOpenFiles, which apps use: fn runs, while the current owner lives, with the paths of files the system asks the app to open. Files that came before any handler, as those the app launched to open, go to the first one registered.

func (cx *Scope) OnOpenLinks(fn func(links []string))

OnOpenLinks is the core's part of desktop.OnOpenLinks, which apps use: fn runs, while the current owner lives, with the links of the app's own URL schemes the system asks it to open. Links that came before any handler, as one the app launched to open, go to the first one registered.

func (*Scope) OnPurchaseUpdate added in v0.2.0

func (cx *Scope) OnPurchaseUpdate(fn func(Transaction))

OnPurchaseUpdate runs fn, while the current owner lives, with each transaction the store makes or changes outside a Purchase call: a renewal, a purchase approved after Ask to Buy or completed outside the app, one made on another device, a refund or a revocation, and as the app starts each transaction it has not finished. Transactions that came before any handler go to the first one registered, so register it as the app starts. Code whose Access does not grant AccessPurchases hears none.

func (*Scope) OnQuit

func (cx *Scope) OnQuit(fn func(ctx context.Context))

OnQuit runs fn, while the current owner lives, as the app quits, however it stops: its own Quit, the last window closing, the Dock's or the system's quit, the runtime ending on Android, a host removing its view. A page hiding on the web and a watchOS app going to the background run it too, as the system may end either unheard, and keep it for the next time in case the app shows again. fn cleans up, such as saving a draft or closing a connection; it cannot keep the app running. The handlers run on the engine goroutine, oldest first, with one context that ends QuitTimeout after the first starts: a handler may wait on it for its own goroutines' work, and the engine ends once they return or the time is up.

func (*Scope) OnQuitRequest

func (cx *Scope) OnQuitRequest(fn func(*QuitRequest))

OnQuitRequest is the core's part of desktop.OnQuitRequest, which apps use: fn runs, while the current owner lives, when the user asks the app to quit, by Cmd+Q, the Dock, a tray menu's Quit or the system, on macOS. Handlers run newest first. A handler that does not cancel or defer lets the request continue to the next handler; when all handlers do so, the app quits. Scope.Quit and Restart remain immediate.

func (*Scope) OnReopen

func (cx *Scope) OnReopen(fn func())

OnReopen is the core's part of desktop.OnReopen, which apps use: fn runs, while the current owner lives, when the user opens the app again while it runs, from the Dock or by launching it a second time. With no handler the main window shows and takes the focus.

func (*Scope) OpenFile

func (cx *Scope) OpenFile(f SharedFile, done func(opened bool, err error))

OpenFile opens the file f names in the app the system associates with its type, the user choosing where several are: NSWorkspace on macOS, the shell on Windows, GtkFileLauncher on Linux, a document interaction's options on iOS and Intent.ACTION_VIEW on Android. On macOS, Windows and Linux f may name a folder, which opens in the file manager; phones have none to open it in, and answer an error. done, when not nil, learns whether an app opened it: false with no error when none opens its type, and the error when the file is missing or the platform failed. On Android the file is in the app's own storage, such as DataDir and CacheDir, and the app opening it reads it through a content URI the runtime grants it, until its activity finishes; the file stays the app's to keep there that long and to delete. The web opens no files.

func (*Scope) OpenInstallSettings

func (cx *Scope) OpenInstallSettings(done func(opened bool))

OpenInstallSettings is the core's part of mobile.OpenInstallSettings, which apps use: it opens Android's setting that lets the app install packages.

func (*Scope) OpenOverlay

func (cx *Scope) OpenOverlay(opts OverlayOptions, content func(cx *Scope) Node) *Window

OpenOverlay is the core's part of mobile.OpenOverlay, which apps use: it opens an overlay over other apps showing content, a tree of its own that belongs to the current owner and closes as that owner goes. The app has one overlay at a time: it returns nil while another is open, off Android and where Access does not grant AccessOverlay. Without the permission the platform ends it at once (OverlayEndDenied).

func (*Scope) OpenPanel

func (cx *Scope) OpenPanel(opts PanelOptions, content func(cx *Scope) Node) *Window

OpenPanel is the core's part of desktop.OpenPanel, which apps use: it opens a hidden panel showing content, for Show, Toggle or a tray icon to show. It returns nil where the platform opens no windows.

func (*Scope) OpenPermissionSettings

func (cx *Scope) OpenPermissionSettings(p Permission, done func(opened bool))

OpenPermissionSettings opens the page of the system's settings that gives p, and answers done, when not nil, with whether one opened: Privacy & Security at p's pane on macOS, the app's page in Settings on iOS, and the microphone's or the camera's page of Privacy & security on Windows. Elsewhere it answers false.

func (*Scope) OpenURL

func (cx *Scope) OpenURL(u string, done func(opened bool))

OpenURL opens u outside the app: a web page in the browser, a mailto: or tel: link in its app, any scheme another app registered. An embedding host's handler (Host.HandleOpenURL) takes it first. done, when not nil, learns whether it opened: false for a URL CheckURL refuses, or one no app handles.

func (*Scope) OpenWindow

func (cx *Scope) OpenWindow(opts WindowOptions, content func(cx *Scope) Node) *Window

OpenWindow is the core's part of desktop.OpenWindow, which apps use: it opens a window showing content, which belongs to the current owner and closes when that owner goes. It returns nil where the platform opens no windows.

func (*Scope) OrderFront

func (cx *Scope) OrderFront()

OrderFront is the core's part of desktop.OrderFront, which apps use.

func (*Scope) OverlayPermission

func (cx *Scope) OverlayPermission(done func(OverlayPermission))

OverlayPermission is the core's part of mobile.OverlayPermission, which apps use: done hears whether the app may show overlays, without asking the user.

func (*Scope) Palette

func (cx *Scope) Palette() Palette

Palette returns the colors of cx's subtree: its theme's palette in the appearance it shows, with the host's tokens over it. A binding that reads it runs again when any of them changes.

func (*Scope) PauseTracking

func (cx *Scope) PauseTracking() (resume func())

PauseTracking stops subscribing the running computation to what is read until resume is called: for code that runs within a computation without belonging to it, as a promise's continuation the tsx package's VM runs as a JS call returns.

func (*Scope) PermissionStatus

func (cx *Scope) PermissionStatus(p Permission, done func(PermissionStatus))

PermissionStatus answers done with whether the app has p, without asking the user.

func (*Scope) PickDirectories

func (cx *Scope) PickDirectories(o PickDirectoriesOptions, done func(dirs []Directory, err error))

PickDirectories shows the system's folder picker and calls done with the folders the user picked, or none when they cancelled; err says what failed. Each is the user's own folder, which the app reads as an fs.FS: NSOpenPanel on macOS, IFileOpenDialog on Windows, GtkFileDialog, through the desktop portal where there is one, on Linux and UIDocumentPickerViewController on iOS give its path; Android's document tree picker and the web's folder picker give none, so the Directory reads through the platform and the app reads it off the engine's goroutine. Android and the web pick one folder. The pickers need no permission.

func (*Scope) PickFiles

func (cx *Scope) PickFiles(o PickFilesOptions, done func(files []File, err error))

PickFiles shows the system's file picker and calls done with the files the user picked, as they are, or none when they cancelled; err says what failed. Each is a file on disk the app opens and streams: the user's own on desktops, a copy in the app's storage on iOS and Android (File.Temporary) that is the app's to delete, and none on the web, where File.Open reads it. The pickers need no permission.

func (*Scope) PickImages

func (cx *Scope) PickImages(o PickOptions, done func(files []PickedFile))

PickImages shows the system's photo picker and calls done with the images the user picked, in the order picked, prepared as o says, or none when they cancelled: PHPickerViewController on iOS, Android's photo picker, an open panel on the desktops and a file chooser on the web. The mobile pickers need no permission.

func (*Scope) PickScreenColor

func (cx *Scope) PickScreenColor(done func(c Color, ok bool))

PickScreenColor lets the user pick a color anywhere on the screen and calls done with it, or with false when they cancel or the platform has no way to (Env.CanPickScreenColor). base.ColorEyeDropper is its button.

func (*Scope) PlayHaptic

func (cx *Scope) PlayHaptic(h Haptic)

PlayHaptic is the core's part of mobile.PlayHaptic, which apps use: it plays h on iOS and Android, and does nothing elsewhere.

func (*Scope) PopupMenu

func (cx *Scope) PopupMenu(items []MenuItem, at Point, closed func())

PopupMenu is the core's part of desktop.PopupMenu, which apps use. A confined owner shows one only as Scope.Confine allows, else closed runs at once.

func (*Scope) Post

func (cx *Scope) Post(fn func())

Post runs fn later on the graph's goroutine, under cx and in one batch. It is safe to call from any goroutine; fn does not run if cx is disposed first.

func (*Scope) PostHost

func (cx *Scope) PostHost(name string, data any)

PostHost sends data to the embedding host's handler of name, which has nothing to answer. Without a host or a handler it is dropped.

func (*Scope) PrefetchImage

func (cx *Scope) PrefetchImage(src ImageSource, done func(ok bool))

PrefetchImage loads the image src names ahead of showing it, keeping its bytes for the views that show it next (NSH's Image.prefetch), and calls done, when not nil, with whether it loaded.

func (*Scope) Present

func (cx *Scope) Present() bool

Present reports whether the Presence branch cx is in is shown, false once it started leaving: a part reads it to stop taking presses as it goes. Outside a Presence it is true.

func (*Scope) Products added in v0.2.0

func (cx *Scope) Products(ids []string, done func([]Product, error))

Products answers done with the products of ids the store sells, in the store's order, leaving out IDs it does not know; no IDs answer none without asking. Their prices are the store's, formatted for the user's storefront. Where the platform has no store, as Env.CanPurchase says, it answers PurchasesUnavailable without asking. Code whose Access does not grant AccessPurchases gets AccessDenied.

func (*Scope) ProvideAccess

func (cx *Scope) ProvideAccess(a Access)

ProvideAccess holds the current owner and what it owns to a: what they render and the services they call, until the owner is disposed. An owner below with an Access of its own is held to both.

func (*Scope) ProvideHost

func (cx *Scope) ProvideHost(h *Host)

ProvideHost has the current owner and what it owns reach h in place of the app's host, until the owner is disposed: CallHost, PostHost, OnHostEvent, HostParams and the URLs OpenURL offers h's handler. nil leaves them with no host. A host app gives each view of code it did not write a channel of its own this way (tsx.View).

func (*Scope) ProvideSecrets added in v0.2.0

func (cx *Scope) ProvideSecrets(name string)

ProvideSecrets gives the current owner and what it owns a partition of the app's secrets, name's: their Secrets keep their items under a service of their own, the app's own Service and the partition's name, and cannot name another service or access group. A host app gives code it did not write a partition of its own this way (tsx.View), as ProvideStorage does its storage.

func (*Scope) ProvideStorage

func (cx *Scope) ProvideStorage(name string, quota int)

ProvideStorage gives the current owner and what it owns a partition of the app's storage, name's, in place of the whole: its keys are only theirs, the app's own Storage neither lists nor clears them, and they hold at most quota bytes, 0 for no quota of their own; they count against the app's StorageQuota too. A host app gives code it did not write a partition of its own this way (tsx.View).

func (*Scope) Purchase added in v0.2.0

func (cx *Scope) Purchase(product string, opts PurchaseOptions, done func(Transaction, error))

Purchase buys the product whose ID is product through the store's sheet, from the app's own button, and answers done once: with the transaction, which the app's server verifies before the app delivers what was bought and finishes it, or with a PurchaseError, PurchaseCancelled when the user closes the sheet and PurchasePending while the purchase waits for approval, whose transaction comes through OnPurchaseUpdate. An AccountToken that is no UUID fails without asking. It is held and unavailable as Products is.

func (*Scope) Quit

func (cx *Scope) Quit()

Quit ends the app: desktops close the window, the app's last, and return from nsgo.Run; Android finishes the app's activity. iOS apps do not quit themselves, and the web leaves the page open.

func (*Scope) Quitting

func (cx *Scope) Quitting() bool

Quitting runs the OnQuit handlers of the graph whose root cx is, for the engine as it stops, and reports whether there were any. Each runs once: a second call runs none.

func (*Scope) ReadClipboard

func (cx *Scope) ReadClipboard(done func(text string))

ReadClipboard calls done with the clipboard's text, "" when it holds none. On iOS, reading it may show the system's paste notice.

func (*Scope) ReadClipboardFiles

func (cx *Scope) ReadClipboardFiles(done func(uris []string))

ReadClipboardFiles calls done with the file: URLs of the local files on the clipboard, such as files copied in a file manager, which FileFromURL opens, none when it holds none.

func (*Scope) ReadClipboardImage

func (cx *Scope) ReadClipboardImage(done func(img ClipboardImage, ok bool, err error))

ReadClipboardImage calls done with the clipboard's image as a PNG, or ok false when it holds none. An image it cannot read, or whose PNG is over MaxClipboardImage bytes (CodeQuotaExceeded), fails. On iOS, reading it may show the system's paste notice.

func (*Scope) RegisterFont

func (cx *Scope) RegisterFont(data []byte) error

RegisterFont registers the font file data (TrueType, OpenType or a collection) with the platform, so text finds its families as a Style's FontFamily names them, as nsgo.Fonts' are, and prepares the text shown and records the canvases shown again once the font is available: call it before the text that uses it shows. Without a platform that registers fonts as the app runs (a headless test's) it does nothing.

func (*Scope) RegisterHotKey

func (cx *Scope) RegisterHotKey(key string, fn func()) *HotKey

RegisterHotKey is the core's part of desktop.RegisterHotKey, which apps use: fn runs when key, in OnKey's form, is pressed whichever app has the focus, while the current owner lives. The handle it returns says whether the platform registered it.

func (*Scope) RenderEffect

func (cx *Scope) RenderEffect(fn func())

RenderEffect runs fn now and again, before the app's effects, whenever what it read changes, as element bindings do: the tsx package's bindings (NSH's render effects).

func (*Scope) RequestAnimationFrame

func (cx *Scope) RequestAnimationFrame(fn func(at time.Time)) (stop func())

RequestAnimationFrame calls fn once, on the graph's goroutine, when the next display frame begins, with the frame's time from the graph clock. The core asks the host for that frame when the first callback waits (RootOptions.RequestFrame), and the host calls RunFrame when it begins. A host without display frames never does, so the callback waits.

stop cancels the wait, and a callback whose owner is disposed does not run. A callback that wants every frame registers again from within fn:

var loop func(at time.Time)
loop = func(at time.Time) {
	move(at)
	cx.RequestAnimationFrame(loop)
}
cx.RequestAnimationFrame(loop)

func (*Scope) RequestNotificationPermission

func (cx *Scope) RequestNotificationPermission(done func(NotificationPermission))

RequestNotificationPermission asks the user to let the app show notifications, with the system's prompt the first time, and answers done with the permission. Ask as the user does something that needs them: browsers refuse a prompt the user did not cause, and iOS and Android ask only once. An iOS app's badge needs it too, as does a macOS app's once it checks or asks for the permission or shows a notification.

func (*Scope) RequestOverlayPermission

func (cx *Scope) RequestOverlayPermission(done func(OverlayPermission))

RequestOverlayPermission is the core's part of mobile.RequestOverlayPermission, which apps use: it opens the system's setting that lets the app show overlays and done hears the permission as the app comes back to the front, or at once where there is nothing to ask. Call it as the user does something that needs it.

func (*Scope) RequestPermission

func (cx *Scope) RequestPermission(p Permission, done func(PermissionStatus))

RequestPermission asks the user for p with the system's prompt, where it has one and has not asked yet, and answers done with the status then. Ask as the user does something that needs it. An Apple build whose Info.plist lacks p's usage description answers PermissionUnavailable and logs the key it needs, as the system would end the app as it asks. macOS lists the app under Accessibility, Screen Recording and Input Monitoring as it asks, and answers before the user turns it on there, which desktop.GuidePermission waits for.

func (*Scope) Restart

func (cx *Scope) Restart()

Restart is the core's part of desktop.Restart, which apps use: the app quits as Quit ends it, and nsgo.Run starts it again.

func (*Scope) RestoreInputSource

func (cx *Scope) RestoreInputSource()

RestoreInputSource is the core's part of base.Command's InputSource: it goes back to the source SelectInputSource replaced, unless the user chose another since.

func (*Scope) RevealFile

func (cx *Scope) RevealFile(path string, done func(error))

RevealFile is the core's part of desktop.RevealFile, which apps use: it opens the file manager with the file or folder at path selected, and answers an error when the path is missing or the platform has no file manager.

func (*Scope) Run

func (cx *Scope) Run(fn func())

Run runs fn untracked with cx owning what it creates, whichever owner runs now, as Solid's runWithOwner: the tsx package's roots and rows (NSH's with_root). A panic goes to the nearest Catch above cx.

func (*Scope) RunFrame

func (cx *Scope) RunFrame()

RunFrame runs the callbacks waiting for the display frame that begins now, on the graph's goroutine, and asks the host for another frame for those that wait for one. A host calls it once for each RequestFrame it was told about.

func (*Scope) SaveFile

func (cx *Scope) SaveFile(o SaveOptions, done func(saved bool, path string, err error))

SaveFile shows the system's save dialog and copies the file o names to where the user chose, streaming it, then calls done with whether it was saved, false with no error when they cancelled, and on desktops the path it was saved at, which an app saves to directly next time. A save that fails leaves nothing where the user chose, or the file that was there. The web has no files on disk, so it saves Data: a save picker where the browser has one, else a download, which counts as saved.

func (*Scope) Secrets added in v0.2.0

func (cx *Scope) Secrets() Secrets

Secrets returns the app's secure store under its own service, or under its partition's (ProvideSecrets). Code whose Access does not grant AccessSecrets gets one that fails with AccessDenied.

func (*Scope) SelectInputSource

func (cx *Scope) SelectInputSource(id string)

SelectInputSource is the core's part of base.Command's InputSource: it selects the enabled keyboard input source of id, remembering the one it replaces. An id is the platform's: a Text Input Sources ID on macOS ("com.apple.keylayout.ABC"), a keyboard layout ID on Windows ("00000409"), and a Fcitx 5 input method ("keyboard-us") or an IBus engine ("xkb:us::eng") on Linux. Phones and the web ignore it.

func (*Scope) ServeScheme

func (cx *Scope) ServeScheme(scheme string, handler func(url string) []byte) error

ServeScheme registers an app-owned URL scheme for web views created under cx: cx and what it owns, where the nearest scope serving a scheme answers it, and no other subtree or window. A web view serves the schemes registered before its native view is made; the handler runs on the platform's UI thread and returns the response body. The response's content type is inferred from the URL and bytes by the native backend. It refuses the schemes web views handle themselves, such as http, ws or javascript.

func (*Scope) SetAppearance

func (cx *Scope) SetAppearance(a Appearance)

SetAppearance shows the app light or dark whatever the system's appearance, or follows it again with AppearanceSystem: Env.Dark reports the one shown, and the platform's own chrome, such as title bars, alerts, menus, system headers and the views it hosts, follows.

func (*Scope) SetApplicationMenu

func (cx *Scope) SetApplicationMenu(items []MenuItem)

SetApplicationMenu is the core's part of desktop.SetApplicationMenu, which apps use.

func (*Scope) SetBadge

func (cx *Scope) SetBadge(count int)

SetBadge shows count on the app's icon, and 0 or less clears it: the Dock's on macOS, which needs the user to allow the app's badges once it checks or asks for the notification permission or shows a notification, the Home Screen's on iOS, which needs the notification permission, the taskbar button's on Windows, the launcher's on Linux where it follows Unity's LauncherEntry API, such as Ubuntu's dock, Plasma and Dash to Dock, and an installed web app's. Android has no count to set: launchers mark an app whose notifications show, and count goes with those shown after it. Elsewhere nothing happens.

func (*Scope) SetClipboard

func (cx *Scope) SetClipboard(text string)

SetClipboard puts text on the system clipboard, replacing what it holds.

func (*Scope) SetClipboardImage

func (cx *Scope) SetClipboardImage(data []byte)

SetClipboardImage puts the image data encodes on the system clipboard, replacing what it holds: PNG, JPEG, GIF or WebP bytes, as ReadClipboardImage gives them or an ImageSource holds them.

func (*Scope) SetDockMenu added in v0.2.0

func (cx *Scope) SetDockMenu(items []MenuItem)

SetDockMenu is the core's part of desktop.SetDockMenu, which apps use. The menu belongs to the current owner, and replaces the one any surface set before.

func (*Scope) SetDockVisible

func (cx *Scope) SetDockVisible(on bool)

SetDockVisible is the core's part of desktop.SetDockVisible, which apps use: on macOS it shows the app in the Dock and the app switcher, or leaves it to its tray icon and windows.

func (*Scope) SetLaunchAtLogin

func (cx *Scope) SetLaunchAtLogin(on bool)

SetLaunchAtLogin is the core's part of desktop.SetLaunchAtLogin, which apps use: the system starts the app as the user logs in, or no more.

func (*Scope) SetLocale

func (cx *Scope) SetLocale(locale string)

SetLocale makes the app run in locale, a BCP 47 tag, whatever the user's or the host's: the language it shows, its formats and its direction follow. "" follows theirs again. The app keeps the choice for later launches itself, as in its storage.

func (*Scope) SetMainView

func (cx *Scope) SetMainView(view func(cx *Scope) Node)

SetMainView is the core's part of nsgo.SetMainView, which apps use: it shows view in the main window, which it opens where the platform opens windows, or in the app's one surface elsewhere. A later call replaces the view.

func (*Scope) SetMainWindow

func (cx *Scope) SetMainWindow(w *Window)

SetMainWindow is the core's part of desktop.SetMainWindow, which apps use: the window ShutdownOnMainWindowClose follows and the Dock shows again.

func (*Scope) SetMenuBar

func (cx *Scope) SetMenuBar(mode MenuBarMode)

SetMenuBar is the core's part of desktop.SetMenuBar, which apps use.

func (*Scope) SetScrollbars

func (cx *Scope) SetScrollbars(m ScrollbarMaker)

SetScrollbars is the core's part of base.SetScrollbarTheme, which apps use: m draws the bar of every scroll view and list of the surface that shows its indicator and has no bar of its own; nil gives them the platform's back.

func (*Scope) SetShutdownMode

func (cx *Scope) SetShutdownMode(m ShutdownMode)

SetShutdownMode is the core's part of desktop.SetShutdownMode, which apps use.

func (*Scope) SetSkipTaskbar added in v0.2.0

func (cx *Scope) SetSkipTaskbar(on bool)

SetSkipTaskbar is the core's part of desktop.SetSkipTaskbar, which apps use.

func (*Scope) SetStatusBar

func (cx *Scope) SetStatusBar(patch StatusBarSetting)

SetStatusBar patches the app's default status bar, under the screens' and modals' settings, with the fields patch sets. Desktops and the web have no status bar.

func (*Scope) SetSubtreeAppearance

func (cx *Scope) SetSubtreeAppearance(a Appearance)

SetSubtreeAppearance shows cx and everything it builds from now on light or dark whatever the appearance above it, the platform's views in it too where the platform scopes appearance to a view; AppearanceSystem follows the one above again. Scope.SetAppearance forces the app's.

func (*Scope) SetTaskProgress

func (cx *Scope) SetTaskProgress(p TaskProgress)

SetTaskProgress shows p on the taskbar button of the scope's window on Windows, or on the app's icon on macOS and Linux. On Windows, a scope whose surface has no button, such as the app's own scope where it opens its windows, a panel or a tray icon's view, sets the progress every window of the app shows while it sets none of its own. Android, iOS and the web ignore it. Where one indicator shows the progress of several windows, the latest call wins, whichever window's changes commit first. Repeating the value the same window sent last sends nothing, unless another window changed the progress since.

func (*Scope) SetTheme

func (cx *Scope) SetTheme(t *Theme)

SetTheme gives cx and everything it builds from now on theme t; a nil t takes back what an earlier call gave, so the theme above shows. Called at the app's root it is the app's theme; a deeper call wins for its subtree, so a sidebar or a panel can take another. A theme changed after it is set is not followed: set a changed copy instead.

func (*Scope) SetTitle

func (cx *Scope) SetTitle(title string)

SetTitle is the core's part of desktop.SetTitle, which apps use.

func (*Scope) SetTitleBar

func (cx *Scope) SetTitleBar(style TitleBarStyle, height Points)

SetTitleBar is the core's part of desktop.SetTitleBar, which apps use.

func (*Scope) SetWebCookies added in v0.2.0

func (cx *Scope) SetWebCookies(cookies []WebCookie, done func(err error))

SetWebCookies adds cookies to the store every web view of the app shares, replacing those of the same name, domain and path, HttpOnly ones included, which page scripts can neither read nor write, and calls done on the engine's goroutine once the store holds them, so that a page loaded after it sends them: an app carries a sign-in into its web views this way. It works whether or not a web view is shown. The store is the persistent one: a cookie with an Expires outlives the app, and an Incognito web view never sees these, but on Android, which keeps one cookie store per app. Apple platforms write WKWebsiteDataStore's default store, Windows the WebView2 profile the app's web views share, through a hidden web view while none shows, Linux the app's WebKitGTK network session and Android CookieManager. Where the platform has no store, as on the web and where Env.HasWebView is false, done gets an Unavailable error, and a cookie no platform would take, such as one without a name or a domain, SameSite None without Secure, or a "__Secure-" or "__Host-" name without what its prefix needs, fails before any is written. Code an Access holds needs the webview capability's cookies (AccessCookies) for each cookie's URL.

func (*Scope) SetWindowConstraints

func (cx *Scope) SetWindowConstraints(c WindowConstraints)

SetWindowConstraints is the core's part of desktop.SetWindowConstraints, which apps use.

func (*Scope) SetWindowControls

func (cx *Scope) SetWindowControls(c WindowControls)

SetWindowControls is the core's part of desktop.SetWindowControls, which apps use.

func (*Scope) SetWindowFrame

func (cx *Scope) SetWindowFrame(f WindowFrame)

SetWindowFrame is the core's part of desktop.SetWindowFrame, which apps use.

func (*Scope) SetWindowLevel

func (cx *Scope) SetWindowLevel(level WindowLevel)

SetWindowLevel is the core's part of desktop.SetWindowLevel, which apps use.

func (*Scope) SetWindowMaterial

func (cx *Scope) SetWindowMaterial(m WindowMaterial)

SetWindowMaterial is the core's part of desktop.SetWindowMaterial, which apps use.

func (*Scope) SetWindowPointerEvents added in v0.2.0

func (cx *Scope) SetWindowPointerEvents(p WindowPointerEvents)

SetWindowPointerEvents is the core's part of desktop.SetWindowPointerEvents, which apps use.

func (*Scope) SetWindowShadow added in v0.2.0

func (cx *Scope) SetWindowShadow(on bool)

SetWindowShadow is the core's part of desktop.SetWindowShadow, which apps use.

func (*Scope) SetWindowTransparent added in v0.2.0

func (cx *Scope) SetWindowTransparent(on bool)

SetWindowTransparent is the core's part of desktop.SetWindowTransparent, which apps use.

func (*Scope) SetWindowWorkspaces added in v0.2.0

func (cx *Scope) SetWindowWorkspaces(w WindowWorkspaces)

SetWindowWorkspaces is the core's part of desktop.SetWindowWorkspaces, which apps use.

func (*Scope) Share

func (cx *Scope) Share(o ShareOptions, done func(shown bool, err error))

Share shows the system's share sheet for what o names, for the user to send it to another app: UIActivityViewController on iOS, NSSharingServicePicker on macOS and an Intent.ACTION_SEND chooser on Android. Files go by path or content URI, never through the platform's bridge, so large ones cost nothing more. done, when not nil, learns whether the sheet showed, with the error when it did not: a missing file, or a platform without a share sheet (Windows, Linux and the web). That it showed says nothing of what the app the user chose did with what it received. On Android the files are in the app's own storage, such as DataDir and CacheDir, and the app chosen reads them through content URIs the runtime grants it, until its activity finishes; the files stay the app's to keep there that long and to delete.

func (*Scope) ShowAlert

func (cx *Scope) ShowAlert(a AlertConfig, done func(index int))

ShowAlert is the core's part of base.ShowAlertDialog, which apps use: it shows a native alert and calls done with the index of the button chosen, or -1 when it was dismissed without one. done runs even when the owner that showed the alert is gone, such as a closed menu. A confined owner shows one only as Scope.Confine allows, else done gets -1 at once.

func (*Scope) ShowNotification

func (cx *Scope) ShowNotification(n Notification, done func(shown bool)) error

ShowNotification shows n, also while the app is in front, or schedules it for its At or Repeat, and answers done, when not nil, with whether the system took it: false without the permission, and for a scheduled one where Env.CanScheduleNotifications is false. It returns ErrNotification, calling no done, for n without an ID or a title, or with a Repeat but no At.

func (*Scope) SignInWithApple added in v0.2.0

func (cx *Scope) SignInWithApple(opts AppleSignInOptions, done func(AppleCredential, error))

SignInWithApple shows the system's Sign in with Apple sheet, from the app's own button, and answers done once: with the credential, or with an AppleSignInError, AppleSignInCancelled when the user closes the sheet. macOS, iOS and tvOS show it to an app signed with the com.apple.developer.applesignin entitlement, which nsgo build claims when nsgo.yaml's apple.sign_in_with_apple is set; elsewhere it answers AppleSignInUnavailable without asking the platform. Code whose Access does not grant AccessSignInWithApple gets AccessDenied.

func (*Scope) Speak added in v0.2.0

func (cx *Scope) Speak(text string, voice Voice, done func(stopped bool, err error)) error

Speak speaks text aloud in voice, one utterance at a time in an engine: a new one stops the one speaking, and so do StopSpeaking and the end of the scope that spoke it. done, which may be nil, runs once, after Speak returns, when the utterance finished, with stopped when it was stopped first, or with a SpeakError when it failed. macOS, iOS and tvOS speak with AVSpeechSynthesizer, Android with TextToSpeech, Windows with SpeechSynthesizer, Linux with speech-dispatcher and the web with speechSynthesis; elsewhere it fails with SpeakUnavailable (Env.CanSpeak). It returns an error only for a voice's Lang that is no language tag, without calling done.

func (*Scope) StartAnimation

func (cx *Scope) StartAnimation(a *Animation, done func(finished bool)) *AnimationRun

StartAnimation runs a on the platform and calls done, if not nil, under the current owner with whether it ran to its end, once. Stopping or resetting it, a value's Set or Stop, or another animation of one of its values ends it early. The owner going stops it.

func (*Scope) StartSpeech

func (cx *Scope) StartSpeech(opts SpeechOptions) (*SpeechSession, error)

StartSpeech recognizes what the user says, one session at a time: a new one aborts the one running, and the scope that started it going aborts it too. macOS and iOS recognize with the Speech framework, the app's Info.plist declaring NSMicrophoneUsageDescription and NSSpeechRecognitionUsageDescription; elsewhere the session ends with SpeechUnavailable. It fails only for a Lang that is no language tag.

func (*Scope) StopSpeaking added in v0.2.0

func (cx *Scope) StopSpeaking()

StopSpeaking stops the utterance the engine speaks, whose done hears it stopped; it does nothing when none is spoken.

func (*Scope) Storage

func (cx *Scope) Storage() Storage

Storage returns the app's storage: the host's Store, or one in memory for the graph's life when the host gave none.

func (*Scope) SyncPurchases added in v0.2.0

func (cx *Scope) SyncPurchases(done func(error))

SyncPurchases has the store bring the user's transactions up to date, which it does on its own otherwise, and answers done: nil, then CurrentEntitlements answers what it found, or a PurchaseError, PurchaseCancelled when the user declines to sign in. Call it only from a Restore Purchases button the user presses, as it may ask them to sign in to their account. It is held and unavailable as Products is.

func (*Scope) TakePhoto

func (cx *Scope) TakePhoto(o PhotoOptions, done func(photo *PickedFile, err error))

TakePhoto shows the system's camera for the user to take one photo and calls done with it, a JPEG turned upright and prepared as o says, or with nil when they cancelled; err says what failed, such as a refused permission or ErrNoCamera. iOS shows UIImagePickerController and needs NSCameraUsageDescription in the app's Info.plist; Android starts the camera app, and the web a file chooser that offers it.

func (*Scope) Theme

func (cx *Scope) Theme() *Theme

Theme returns the theme of cx's subtree: the nearest SetTheme's, else DefaultTheme. Host tokens reach its colors through Palette. A binding that reads it runs again when it changes.

func (*Scope) ToggleFullScreen

func (cx *Scope) ToggleFullScreen()

ToggleFullScreen is the core's part of desktop.ToggleFullScreen, which apps use.

func (*Scope) ToggleMaximize

func (cx *Scope) ToggleMaximize()

ToggleMaximize is the core's part of desktop.ToggleMaximize, which apps use.

func (*Scope) TrashFile

func (cx *Scope) TrashFile(path string, done func(trashedAt string, err error))

TrashFile is the core's part of desktop.TrashFile, which apps use: it moves the file or folder at path to the user's Trash or Recycle Bin, and never deletes it permanently, answering ErrNoTrash where it cannot be recycled. trashedAt is the item's path in the trash where the platform reports it, and "" elsewhere, such as on Linux.

func (*Scope) Untrack

func (cx *Scope) Untrack(fn func())

Untrack runs fn without subscribing the running computation to what it reads.

func (*Scope) Voices added in v0.2.0

func (cx *Scope) Voices(lang string, done func([]VoiceInfo))

Voices answers with the voices installed that speak lang, a BCP 47 tag that matches itself and the tags under it ("en" matches "en-US" and "en-GB"), or with every voice when lang is "", sorted by language and name, so an app can tell the user to install a voice it lacks. Where Env.CanSpeak is false, or the current owner's Access refuses AccessTextToSpeech, it answers with none without asking the platform.

func (*Scope) WallTime

func (cx *Scope) WallTime() time.Time

WallTime returns the date and time the app shows: Now, local time on the system's clock, unless a test's manual clock set its wall time apart (ManualClock.SetWallTime), in the location of the time it was given.

func (*Scope) WatchLocation added in v0.2.0

func (cx *Scope) WatchLocation(opts LocationOptions, sample func(LocationFix), failed func(error)) (*SensorStream, error)

WatchLocation starts a stream under PermissionLocation, which it never asks for. Foreground streams pause in background and mark their first resumed fix with Gap. Background streams require AccessLocation and AccessBackgroundLocation, the platform's declaration and PermissionBackgroundLocation; they never restart a killed process.

func (*Scope) WatchMotion added in v0.2.0

func (cx *Scope) WatchMotion(opts MotionOptions, sample func(MotionSample), failed func(error)) (*SensorStream, error)

WatchMotion starts raw or fused sensors at the requested interval, clamped to 10 ms–1 s, under PermissionMotion, which it never asks for. Zero requests accelerometer at 20 ms. Samples use natural device axes, with +9.80665 m/s² on z face-up, and report dropped samples. Motion always pauses in background; it never keeps a process alive.

func (*Scope) WatchScroll

func (cx *Scope) WatchScroll(target func() *Ref, fn func(ScrollEvent))

WatchScroll has fn hear where the scroll view or list target returns is whenever its offset, viewport or content changes, from the first time it is laid out, as long as cx lives. target is read in each commit, so a ref bound later in the same render is found once it is mounted. The report follows the commit, or the platform's event, that moved it.

type Screen

type Screen struct {
	Title     string
	TitleFunc func() string
	Header    Node
	// HeaderLeft, HeaderRight and HeaderTitle are views the system header
	// shows at its start, at its end and in place of the title, each at
	// its content's size.
	HeaderLeft, HeaderRight, HeaderTitle Node
	// IOS holds what only iOS's header has.
	IOS IOSScreenProps
	// HeaderHidden hides the system header.
	HeaderHidden bool
	// HeaderTransparent lays the content out under a header without a
	// background.
	HeaderTransparent bool
	// HeaderLargeTitle shows iOS's large title.
	HeaderLargeTitle bool
	// HeaderBackHidden hides the back button.
	HeaderBackHidden bool
	// HeaderBackTitle labels the back button leading back to this screen;
	// its title by default.
	HeaderBackTitle string
	HeaderStyle     Style
	HeaderStyleFunc func() Style
	// HeaderClass gives the system header its colors as classes: bg-*, text-* for the title, tint-* for the buttons. HeaderStyle wins over them. The header has no siblings: peer-* variants are logged and ignored.
	HeaderClass string
	// Animation is how the screen enters and leaves (iOS slides it by
	// default).
	Animation ScreenAnimation
	// TransitionShader, when set, is how it enters and leaves instead,
	// where the platform draws it.
	TransitionShader *TransitionShader
	// StatusBar is set over the app's status bar while the screen is in
	// the tree and not popped.
	StatusBar     StatusBarSetting
	StatusBarFunc func() StatusBarSetting
	// Class is Tailwind CSS classes, as View's.
	Class     string
	Style     Style
	StyleFunc func() Style
	Children  []Node
	// NoPopOnBack keeps the screen when back is pressed;
	// NoPopOnBackFunc, when set, says so as the graph changes.
	NoPopOnBack     bool
	NoPopOnBackFunc func() bool
	// NoPopOnSwipe turns off iOS's swipe from the leading edge back to
	// the screen below; NoPopOnSwipeFunc, when set, as the graph changes.
	NoPopOnSwipe     bool
	NoPopOnSwipeFunc func() bool
	// OnBackPress receives every back press while the screen is on top.
	OnBackPress func()
	// OnDismiss reports that the user popped the screen; remove it.
	OnDismiss func()
	TestID    string
}

Screen is one page of a Stack, filling it: the core's part of base.NavPage, which apps use.

On iOS and Android the platform draws the system header, a navigation bar or a toolbar: Title, the header views, a back button to the screen below, and HeaderStyle's Background, Color (the title's) and TintColor (the buttons'). The content is laid out below it. Elsewhere Header, when set, is drawn at the top and the header options are ignored.

func (Screen) Render

func (s Screen) Render(*Scope) Node

Render implements Node.

type ScreenAnimation

type ScreenAnimation = driver.ScreenAnimation

ScreenAnimation is how a screen of a stack enters and leaves.

type ScreenEffect

type ScreenEffect struct {
	Program         *ShaderProgram
	Uniforms        Uniforms
	UniformsFunc    func() Uniforms
	Progress        float64
	ProgressFunc    func() float64
	ProgressNode    AnimatedNode
	MaxSampleOffset float64
	Paused          bool
	PausedFunc      func() bool
}

ScreenEffect draws the whole surface through a WGSL program, which reads it with sample_content(uv). It takes no space and has no children; dialogs a platform presents in windows of their own are outside it.

func (ScreenEffect) Render

func (e ScreenEffect) Render(*Scope) Node

Render implements Node.

type ScreenTransition

type ScreenTransition struct {
	Program         *ShaderProgram
	NoFallback      bool
	Uniforms        Uniforms
	UniformsFunc    func() Uniforms
	Value           func() any
	Duration        time.Duration
	MaxSampleOffset float64
	Paused          bool
	PausedFunc      func() bool
}

ScreenTransition draws the whole surface through a WGSL program as it changes, when Value's result changes, as ShaderTransition does its children.

func (ScreenTransition) Render

func (e ScreenTransition) Render(*Scope) Node

Render implements Node.

type Scroll

type Scroll struct {
	// Class is Tailwind CSS classes, as View's.
	Class         string
	Horizontal    bool
	HideIndicator bool
	// Bar draws its scroll bar in place of the platform's indicator, over
	// the app's (Scope.SetScrollbars).
	Bar ScrollbarMaker
	// Behavior is how it scrolls: paging, snapping, deceleration,
	// bounces, insets and the keyboard.
	Behavior     ScrollBehavior
	BehaviorFunc func() ScrollBehavior
	// ContentOffset is where it starts.
	ContentOffset Point
	// EdgeEffects set the bars over its sides (View.EdgeBar) apart from
	// the content scrolling under them (EdgeEffect).
	EdgeEffects EdgeEffects
	Style       Style
	StyleFunc   func() Style
	Children    []Node
	// OnScroll receives where it is as it scrolls, at most once a turn,
	// and at most once per ScrollEventThrottle when that is set: then the
	// latest offset waits for the interval to pass.
	OnScroll            func(ScrollEvent)
	ScrollEventThrottle time.Duration
	// OnScrollDragStart and OnScrollDragEnd bracket the user dragging it
	// (its content or its scroll bar); OnMomentumStart and
	// OnMomentumEnd the glide or snap after. A glide a new drag catches
	// ends with OnMomentumEnd.
	OnScrollDragStart func(ScrollEvent)
	OnScrollDragEnd   func(ScrollEvent)
	OnMomentumStart   func(ScrollEvent)
	OnMomentumEnd     func(ScrollEvent)
	// OnScrollEnd hears it come to rest: a drag that set nothing in
	// motion ended, or a glide, a snap, an animated scroll or the wheel's
	// turns did.
	OnScrollEnd func(ScrollEvent)
	// OnRefresh makes it refreshable: pulling the content down past its
	// top calls it and shows the platform's spinner while Refreshing
	// returns true. Set Refreshing in OnRefresh, clear it when done.
	// Behavior.RefreshIndicator replaces the spinner with the app's own
	// indicator, which PullValue animates.
	OnRefresh  func()
	Refreshing func() bool
	// PullValue follows how far the content is pulled past its top on
	// the platform's main thread: 0 at rest, the indicator's room while
	// it refreshes. Draw an indicator of the app's own over the top of
	// the scroll view with styles bound to it.
	PullValue *AnimatedValue
	// MaxZoomScale above MinZoomScale (both 1 when 0) lets pinches zoom
	// the content, which then scrolls both ways. ZoomScale is the scale
	// it starts at, and ZoomScaleFunc zooms to its value when it
	// changes; the user's zoom stays otherwise. NoBouncesZoom stops
	// pinches at the limits, NoPinchZoom ignores them, and CenterContent
	// centers content smaller than the viewport.
	MinZoomScale  float32
	MaxZoomScale  float32
	ZoomScale     float32
	ZoomScaleFunc func() float32
	NoBouncesZoom bool
	NoPinchZoom   bool
	CenterContent bool
	// OffsetValues follow the offset on the platform's main thread, in
	// the same frame as it scrolls.
	OffsetValues AnimatedXY
	OnLayout     func(Bounds)
	Ref          *Ref
	// Role and Label are what it is for assistive technology, as a list
	// box's, and Busy says it is still loading.
	Role   Role
	Label  string
	Busy   func() bool
	TestID string
}

Scroll scrolls its children, laid out as a column (or a row when Horizontal) as long as they need. Like React Native's ScrollView, it shrinks to fit its parent (FlexShrink 1) unless its style says else.

func (Scroll) Render

func (s Scroll) Render(*Scope) Node

Render implements Node.

type ScrollAlignment

type ScrollAlignment uint8

ScrollAlignment is where Reveal puts a view along a scroll view's axis.

const (
	// ScrollAlignDefault is the axis's own: ScrollAlignStart vertically,
	// ScrollAlignNearest horizontally.
	ScrollAlignDefault ScrollAlignment = iota
	ScrollAlignStart
	ScrollAlignCenter
	ScrollAlignEnd
	// ScrollAlignNearest scrolls the least that shows it, and not at all
	// while it shows whole.
	ScrollAlignNearest
)

type ScrollBehavior

type ScrollBehavior = driver.ScrollBehavior

ScrollBehavior is how a scroll view scrolls, as NSH's Scrollable props (React Native's ScrollView props) say: Scroll's Behavior.

type ScrollEvent

type ScrollEvent struct {
	// Offset is the content's offset, UIKit's contentOffset: negative
	// past the start, as ContentInset allows.
	Offset Point
	// ContentSize is the content's size, zoomed.
	ContentSize Size
	// Size is the scroll view's.
	Size Size
	// ZoomScale is how far the content is zoomed; 1 unzoomed.
	ZoomScale float32
	// Stale says the platform reported Offset before applying a scroll
	// the app asked for (Ref.ScrollTo, ScrollToEnd): the content is on
	// its way elsewhere, and Offset is not where the user moved it.
	Stale bool
}

ScrollEvent is where a scroll view is: what its scroll, drag and momentum events report.

type ScrollbarMaker

type ScrollbarMaker interface {
	// Scrollbar is the bar of target, or nil to keep the platform's
	// indicator.
	Scrollbar(cx *Scope, target *Ref, horizontal bool) Node
}

ScrollbarMaker makes a scroll view's bar: base.ScrollbarTheme's.

type SecretAccessible added in v0.2.0

type SecretAccessible = driver.SecretAccessible

SecretAccessible says when Apple platforms let the app read a secret, Apple's kSecAttrAccessible; the zero value leaves it to the system, which reads it only while the device is unlocked. Other platforms ignore it.

type SecretItem added in v0.2.0

type SecretItem = driver.SecretItem

SecretItem names a secret in the platform's secure store, SecretStore is where a platform keeps secrets (RootOptions.Secrets), and MemorySecrets is one in memory, which tests keep theirs in (nsgotest.App.Secrets).

type SecretStore added in v0.2.0

type SecretStore = driver.SecretStore

SecretItem names a secret in the platform's secure store, SecretStore is where a platform keeps secrets (RootOptions.Secrets), and MemorySecrets is one in memory, which tests keep theirs in (nsgotest.App.Secrets).

type Secrets added in v0.2.0

type Secrets struct {
	// Service names the items with the account: kSecAttrService on Apple platforms, the first part of the generic credential's target "Service/Account" on Windows, the service attribute on Linux. Scope.Secrets sets it to the app's ID (App().ID), else its executable's name.
	Service string
	// AccessGroup is the keychain access group of the items on Apple platforms, "" for the app's default. On macOS one keeps the items in the data protection keychain rather than the login keychain, which needs a signed app whose keychain-access-groups entitlement lists the group.
	AccessGroup string
	// Accessible is when iOS, tvOS and watchOS, and macOS's data protection keychain (AccessGroup), let the app read an item it writes; macOS's login keychain ignores it, as other platforms do.
	Accessible SecretAccessible
	// contains filtered or unexported fields
}

Secrets is the app's secure store: strings by account under a service, which the platform protects, unlike Storage's plain file. It keeps them as generic passwords of the keychain on macOS, iOS, tvOS and watchOS, generic credentials of the Credential Manager on Windows, items of the Secret Service on Linux and values encrypted with a key of the Android Keystore in the app's private files on Android; elsewhere, as on the web, every call fails with ErrSecretsUnavailable.

Service, AccessGroup and Accessible name and protect the items, so an app keeps reading what an earlier build, or another framework, wrote with the same ones. Its methods may run on any goroutine, and as the system may make them wait, as a keychain asking the user to allow a read does, an app may call them off the engine's.

func (Secrets) Delete added in v0.2.0

func (s Secrets) Delete(account string) error

Delete removes what is kept for account; deleting what is not there is no failure.

func (Secrets) Get added in v0.2.0

func (s Secrets) Get(account string) (string, bool, error)

Get returns the value kept for account and whether there is one; a missing one is ("", false, nil).

func (Secrets) Set added in v0.2.0

func (s Secrets) Set(account, value string) error

Set keeps value for account, replacing what it held.

type Selectable

type Selectable = driver.Selectable

Selectable says whether the user can select a text.

type SensorError added in v0.2.0

type SensorError string

SensorError is a stable provider failure; it never contains location data.

const (
	SensorNotAllowed    SensorError = "not-allowed"
	SensorNotAvailable  SensorError = "unavailable"
	SensorTimedOut      SensorError = "timeout"
	SensorFailed        SensorError = "failed"
	SensorNotConfigured SensorError = "not-configured"
)

func (SensorError) Error added in v0.2.0

func (e SensorError) Error() string

type SensorNumber added in v0.2.0

type SensorNumber = driver.SensorNumber

SensorNumber is a measurement with an explicit availability flag.

type SensorQuaternion added in v0.2.0

type SensorQuaternion = driver.SensorQuaternion

SensorQuaternion rotates device axes into world axes.

type SensorStream added in v0.2.0

type SensorStream struct {
	// contains filtered or unexported fields
}

SensorStream owns a pending location or a live stream. Its callbacks run on the engine goroutine only while its scope is alive.

func (*SensorStream) Stop added in v0.2.0

func (s *SensorStream) Stop()

Stop cancels this request and its provider; queued answers are ignored.

func (*SensorStream) Stopped added in v0.2.0

func (s *SensorStream) Stopped() bool

Stopped reports cancellation, completion or a terminal provider failure.

type SensorVector added in v0.2.0

type SensorVector = driver.SensorVector

SensorVector is a vector in the natural device frame, in SI units (µT for magnetism).

type Shader

type Shader struct {
	Program      *ShaderProgram
	Uniforms     Uniforms
	UniformsFunc func() Uniforms
	// Paused stops a WGSL program's clock, nsh.time; PausedFunc, when
	// set, says so as the graph changes.
	Paused     bool
	PausedFunc func() bool
	// Images are what the program's image0At to image3At read, in order, loaded as an Image loads its source. They take no Pixels: an image that names only pixels reads as an empty one.
	Images     []ImageSource
	ImagesFunc func() []ImageSource
	// Class is Tailwind CSS classes, as View's.
	Class     string
	Style     Style
	StyleFunc func() Style
	// Children draw over the shader.
	Children []Node
	OnPress  func(PressEvent)
	OnLayout func(Bounds)
	Ref      *Ref
	// Label names what the shader shows for assistive technology, which
	// skips an unlabeled shader as a decoration.
	Label  string
	TestID string
}

Shader fills its box with a fragment shader, which the GPU runs for each pixel: an animated background, a gradient no style describes. It draws again when its size, its uniforms or the animated nodes they hold change; a platform without a GPU path for shaders yet leaves it empty.

func (Shader) Render

func (s Shader) Render(*Scope) Node

Render implements Node.

type ShaderEffect

type ShaderEffect struct {
	Program      *ShaderProgram
	Uniforms     Uniforms
	UniformsFunc func() Uniforms
	// Progress is nsh.progress; ProgressFunc, when set, follows the graph,
	// and ProgressNode, when set, moves it on the platform's frame clock.
	Progress     float64
	ProgressFunc func() float64
	ProgressNode AnimatedNode
	// MaxSampleOffset is how far beyond each side of the box, in points,
	// the shader draws and its pictures reach (nsh.overflow).
	MaxSampleOffset float64
	// Paused stops nsh.time; PausedFunc follows the graph.
	Paused     bool
	PausedFunc func() bool
	Class      string
	Style      Style
	StyleFunc  func() Style
	Children   []Node
	OnLayout   func(Bounds)
	Ref        *Ref
	TestID     string
}

ShaderEffect draws its children through a WGSL program, which reads what they draw with sample_content(uv): over them and in their place, while they still take touches, the pointer and focus. Without a Program the children show as they are.

func (ShaderEffect) Render

func (e ShaderEffect) Render(*Scope) Node

Render implements Node.

type ShaderProgram

type ShaderProgram struct {
	// contains filtered or unexported fields
}

ShaderProgram is a fragment shader written in Go's syntax: Ebitengine's Kage language, as MyGo's shaders are. The source is a Go file of package main whose function Fragment returns the color of a pixel, premultiplied:

package main

var Time float

func Fragment(dst vec4, pos vec2) vec4 {
	v := 0.5 + 0.5*sin(pos.x/20+Time)
	return vec4(v, v, 1, 1)
}

dst is the pixel's center in pixels from the shader view's top left corner, and pos the same point in points. The language has the types bool, int, uint, float, vec2 to vec4, ivec2 to ivec4, uvec2 to uvec4, mat2 to mat4 and arrays of them, GLSL's built-in functions (sin, mix, smoothstep, dot, ...), functions of its own, if, and for loops. Exported variables at the package level are uniforms, which Shader.Uniforms sets. rectSize returns the view's size in points, and pixelScale the pixels a point. image0At(pos) to image3At(pos) read Shader.Images at a position in their pixels, premultiplied and transparent outside them, and image0Size() to image3Size() give their sizes in pixels.

Each platform translates the program for its GPU once, the first time a view shows it.

A program may be written in WGSL instead (CompileWGSL), as TSX apps write theirs and as effects and transitions need.

func CompileShader

func CompileShader(src string) (*ShaderProgram, error)

CompileShader compiles a shader's source, as ShaderProgram describes it. Its errors give the source's lines.

func CompileWGSL

func CompileWGSL(src string) (*ShaderProgram, error)

CompileWGSL compiles a shader written in WGSL, as NSH's are: it defines

fn shade(uv: vec2f) -> vec4f

the straight (not premultiplied) sRGB color of the point uv of the view's box, 0 to 1 from its top left corner, with whatever helpers and consts it needs. It reads nsh.size (the box in points), nsh.time (seconds since the shader appeared, standing still while paused), nsh.scale (pixels a point), nsh.progress (an effect's progress or how far a transition is, 0 to 1) and nsh.overflow (MaxSampleOffset). When it declares struct Uniforms, of f32, i32, u32, vec2f, vec3f, vec4f and array<vec4f, N> members in at most 4096 bytes, it reads them through uniforms, which Uniforms sets by name. sample_content, sample_backdrop, sample_from and sample_to read what an effect or a transition pictures at a point of the box, straight, transparent outside the picture.

Its errors give the source's lines and columns. A source compiles once for the process, as an app sets the same one again.

func MustCompileShader

func MustCompileShader(src string) *ShaderProgram

MustCompileShader is CompileShader for a source that is part of the program, such as a package variable's: it panics when it does not compile.

func MustCompileWGSL

func MustCompileWGSL(src string) *ShaderProgram

MustCompileWGSL is CompileWGSL for a source that is part of the program: it panics when it does not compile.

func (*ShaderProgram) HasUniform

func (p *ShaderProgram) HasUniform(name string) bool

HasUniform reports whether the program has a uniform named name, which Uniforms may set.

type ShaderTransition

type ShaderTransition struct {
	Program      *ShaderProgram
	NoFallback   bool
	Uniforms     Uniforms
	UniformsFunc func() Uniforms
	// Value runs the transition when its result changes; compare by ==.
	Value func() any
	// Duration is how long a transition runs, 300 ms when 0.
	Duration        time.Duration
	MaxSampleOffset float64
	Paused          bool
	PausedFunc      func() bool
	Class           string
	Style           Style
	StyleFunc       func() Style
	Children        []Node
	OnLayout        func(Bounds)
	Ref             *Ref
	TestID          string
}

ShaderTransition shows its children as they are, and draws them through a WGSL program as they change: when Value's result changes (not its first), sample_from(uv) is a picture of what they showed, sample_to(uv) what they show, and nsh.progress goes from 0 to 1 over Duration. Without a Program it cross-fades, unless NoFallback.

func (ShaderTransition) Render

func (e ShaderTransition) Render(*Scope) Node

Render implements Node.

type ShareOptions

type ShareOptions struct {
	Files []SharedFile
	// Text goes with the files, or alone: a message or a link.
	Text string
	// Anchor is the element the sheet points at where it shows as a
	// popover, on macOS and iPads; nil points at the root's center.
	Anchor *Ref
}

ShareOptions say what Share shares: files, text, or both.

type ShareRequest

type ShareRequest = driver.ShareRequest

ShareRequest is a share as the platform carries it out, ShareOptions resolved.

type SharedFile

type SharedFile = driver.SharedFile

SharedFile is a file on disk the app hands another app, with OpenFile or Share: its path, and the name the other app sees and its type, which Path's name and extension say when empty.

type Show

type Show struct {
	When func() bool
	Then func(cx *Scope) Node
	Else func(cx *Scope) Node
}

Show builds Then while When is true and Else otherwise. Each branch is built only when When changes, and goes before its bindings can run again, so a binding in Then never runs once When has turned false.

func (Show) Render

func (s Show) Render(*Scope) Node

Render implements Node.

type ShutdownMode

type ShutdownMode uint8

ShutdownMode says when a desktop app ends by itself: the core's part of desktop.SetShutdownMode, which apps use. Scope.Quit ends it in any mode.

const (
	// ShutdownOnLastWindowClose ends the app as its last window closes;
	// panels and tray icons do not count.
	ShutdownOnLastWindowClose ShutdownMode = iota
	// ShutdownOnMainWindowClose ends it as its main window closes.
	ShutdownOnMainWindowClose
	// ShutdownOnExplicit ends it only by Scope.Quit, as a tray app does.
	ShutdownOnExplicit
)

type Sides

type Sides uint8

Sides is a set of sides of a box.

type Signal

type Signal[T any] struct {
	// contains filtered or unexported fields
}

Signal is a value computations subscribe to by reading it.

func NewSignal

func NewSignal[T comparable](cx *Scope, v T) *Signal[T]

NewSignal returns a signal holding v. Setting an equal value does nothing.

func NewSignalFunc

func NewSignalFunc[T any](cx *Scope, v T, equal func(a, b T) bool) *Signal[T]

NewSignalFunc returns a signal holding v that compares values with equal; with a nil equal every Set notifies, as slices and maps need.

func (*Signal[T]) Get

func (s *Signal[T]) Get() T

Get returns the value and subscribes the running computation to it.

func (*Signal[T]) GetUntracked

func (s *Signal[T]) GetUntracked() T

GetUntracked returns the value without subscribing.

func (*Signal[T]) Set

func (s *Signal[T]) Set(v T)

Set stores v and schedules the computations that read the signal.

func (*Signal[T]) Update

func (s *Signal[T]) Update(fn func(T) T)

Update sets the value fn returns for the current one.

type Size

type Size = driver.Size

Size is a width and a height in points.

type SnapAlignment

type SnapAlignment = driver.SnapAlignment

SnapAlignment is where a snapped item sits in the viewport.

type Sound

type Sound struct {
	// contains filtered or unexported fields
}

Sound is a short sound decoded into memory, played any number of times, overlapping: the core's part of audio.Sound, which apps use. Its methods are called on the engine's goroutine.

func (*Sound) Close

func (s *Sound) Close()

Close lets the sound go: the decoded audio goes with the last Sound over it. Calling it again does nothing.

func (*Sound) Duration

func (s *Sound) Duration() time.Duration

Duration returns how long the sound plays.

func (*Sound) Play

func (s *Sound) Play(v SoundVoice)

Play starts a playback of the sound, over those playing, within a frame: it is a command in the batch of the turn that calls it. A playback that cannot be heard, the device muted or one dropped past 32 at once, is no error.

func (*Sound) Stop

func (s *Sound) Stop()

Stop stops every playback of the sound's source.

type SoundVoice

type SoundVoice struct {
	Volume, Rate float32
}

SoundVoice is how a playback of a sound plays: the core's part of audio.Voice, which apps use. Volume runs from 0 to 1 and Rate from 0.5 to 2; 0 is 1 for both, as Video's, and other values are clamped.

type Span

type Span struct {
	// Class is Tailwind CSS classes under Style, as View's, except that a span has no siblings: peer-* variants are logged and ignored.
	Class       string
	Content     string
	ContentFunc func() string
	// Style's text fields merge over the Text's. Its Background and
	// CornerRadius draw behind the span's characters, a box per line.
	// Cursor overrides the containing Text's cursor over these characters
	// when it is not Auto.
	Style     Style
	StyleFunc func() Style
	// OnPress and OnLongPress take the presses on the span's characters,
	// over the Text's.
	OnPress     func(PressEvent)
	OnLongPress func(PressEvent)
	// Attachment, when set, is a view in the text's lines in place of Content: laid out at its content size, it wraps with the words around it and takes its own presses. Style is then its view's style, and Style.VerticalAlign places it in its line, else the VerticalAlign of the one view Attachment makes; aligned to the baseline, an Em canvas puts its own baseline on the line's (Canvas.Em). Content is then what copying text takes in its place, as a formula copies as its TeX, and without it a copy leaves the attachment out; screen readers read the attachment's labels instead. When a Text's SpansFunc runs again, each attachment the new spans hold again, with the same Class and Style, keeps its view, whatever text lies around it and wherever it moves among the others; only the new ones are made, and those the spans no longer hold go. An attachment is the same as the same pointer, or as an equal value of a type that compares; a Func, or a struct holding a func or a slice, as View does, is never the same, so a SpansFunc that should keep such an attachment's view gives a pointer to it, made once.
	Attachment Node
}

Span is a run of a Text with a style of its own.

type SpeakError added in v0.2.0

type SpeakError string

SpeakError is why an utterance failed, named as the Web Speech API's SpeechSynthesisErrorEvent's errors.

const (
	// SpeakNotAllowed: the current owner's Access refuses AccessTextToSpeech, or the platform refused to speak, as a browser does before the user's first gesture.
	SpeakNotAllowed SpeakError = driver.SpeakNotAllowed
	// SpeakLanguageUnavailable: no voice installed speaks the language.
	SpeakLanguageUnavailable SpeakError = driver.SpeakLanguageUnavailable
	// SpeakVoiceUnavailable: the platform has no voice of Voice.ID.
	SpeakVoiceUnavailable SpeakError = driver.SpeakVoiceUnavailable
	// SpeakTextTooLong: the text is longer than the platform speaks at once, as Android's engines' limit, 4000 characters by default.
	SpeakTextTooLong SpeakError = driver.SpeakTextTooLong
	// SpeakAudioBusy: the platform's audio output could not be had, such as iOS's audio session.
	SpeakAudioBusy SpeakError = driver.SpeakAudioBusy
	// SpeakUnavailable: this platform speaks no text (Env.CanSpeak).
	SpeakUnavailable SpeakError = driver.SpeakUnavailable
	// SpeakFailed: the synthesizer failed otherwise.
	SpeakFailed SpeakError = driver.SpeakFailed
)

func (SpeakError) Error added in v0.2.0

func (e SpeakError) Error() string

type SpeechCommand

type SpeechCommand = driver.SpeechCommand

SpeechCommand is what a SpeechRequest asks of its session.

type SpeechError

type SpeechError string

SpeechError is why a speech session ended without its transcript, named as the Web Speech API's errors.

const (
	// SpeechNotAllowed: the user or the system refused the microphone or
	// the recognizer.
	SpeechNotAllowed SpeechError = driver.SpeechNotAllowed
	// SpeechNoSpeech: nothing was said.
	SpeechNoSpeech SpeechError = driver.SpeechNoSpeech
	// SpeechAudioCapture: the microphone could not record.
	SpeechAudioCapture SpeechError = driver.SpeechAudioCapture
	// SpeechNetwork: the recognizer needed the network.
	SpeechNetwork SpeechError = driver.SpeechNetwork
	// SpeechLanguageUnsupported: the recognizer has no model for the
	// language.
	SpeechLanguageUnsupported SpeechError = driver.SpeechLanguageUnsupported
	// SpeechUnavailable: this platform recognizes no speech
	// (Env.CanRecognizeSpeech).
	SpeechUnavailable SpeechError = driver.SpeechUnavailable
	// SpeechFailed: the recognizer failed otherwise.
	SpeechFailed SpeechError = driver.SpeechFailed
)

func (SpeechError) Error

func (e SpeechError) Error() string

type SpeechOptions

type SpeechOptions struct {
	// Lang is the BCP 47 tag of the language spoken; "" is the app's
	// locale.
	Lang string
	// Interim reports results before they are final.
	Interim bool
	// OnStart runs once the recognizer listens.
	OnStart func()
	// OnResult runs with the whole transcript so far, and whether the
	// recognizer will not change it.
	OnResult func(text string, final bool)
	// OnEnd runs once, last, with the last transcript and why it ended
	// early: a SpeechError, nil when it finished or was stopped or
	// aborted.
	OnEnd func(text string, err error)
}

SpeechOptions are a speech session's, as NSH's Speech.start takes them.

type SpeechRequest

type SpeechRequest = driver.SpeechRequest

SpeechRequest is what a speech session asks of the platform, as a test's model sees it.

type SpeechSession

type SpeechSession struct {
	// contains filtered or unexported fields
}

SpeechSession is speech being recognized, from the microphone.

func (*SpeechSession) Abort

func (s *SpeechSession) Abort()

Abort ends the session at once with the transcript so far.

func (*SpeechSession) Ended

func (s *SpeechSession) Ended() bool

Ended reports whether the session ended.

func (*SpeechSession) Stop

func (s *SpeechSession) Stop()

Stop has the recognizer finish what it heard: a last final result, then the end.

func (*SpeechSession) Text

func (s *SpeechSession) Text() string

Text returns the transcript so far.

type SpringConfig

type SpringConfig = driver.SpringConfig

SpringConfig is a damped spring's: Stiffness 100, Damping 10 and Mass 1 when 0.

type Stack

type Stack struct {
	Style    Style
	Children []Node
	TestID   string
}

Stack shows the last of its screens: the core's part of base.Nav's Stack, which apps use. Pushing is adding a screen, popping is removing it. Back pops the top screen, which reports OnDismiss and stays hidden until the app removes it.

func (Stack) Render

func (s Stack) Render(*Scope) Node

Render implements Node.

type StatusBarSetting

type StatusBarSetting struct {
	Foreground StatusBarStyle
	Hidden     Toggle
	// Animated animates the change to this layer's settings.
	Animated Toggle
}

StatusBarSetting is one layer of the status bar's settings. Fields left at their zero values keep the layers' below.

type StatusBarStyle

type StatusBarStyle = driver.StatusBarStyle

StatusBarStyle is the color of a phone's status bar content.

type StepPosition

type StepPosition = driver.StepPosition

StepPosition is where a steps easing jumps, as CSS's step positions.

type StickyCell

type StickyCell = driver.StickyCell

StickyCell is a sticky list cell and its travel, in its scroll view's main-axis offsets: from Start it moves with the offset, as far as End (which may be infinite). End below Start pins to the viewport's end with a negative shift.

type Storage

type Storage struct {
	// contains filtered or unexported fields
}

Storage is the app's key-value storage: strings by string key, kept on the device and shared by every graph of the app. Reads are synchronous, as the entries are in memory, and reading in a computation subscribes it to changes, the app's own and other graphs'. Use it where the app's code runs: components, handlers, effects and posted functions.

func (Storage) Clear

func (s Storage) Clear()

Clear removes every entry.

func (Storage) GetItem

func (s Storage) GetItem(key string) (string, bool)

GetItem returns the value of key and whether it has one.

func (Storage) Keys

func (s Storage) Keys() []string

Keys returns every key, sorted.

func (Storage) RemoveItem

func (s Storage) RemoveItem(key string)

RemoveItem removes key.

func (Storage) SetItem

func (s Storage) SetItem(key, value string) error

SetItem sets key to value. It fails with a *StorageFullError when the storage would grow past StorageQuota, keeping what it held.

type StorageChange

type StorageChange = driver.StorageChange

StorageChange is a change to the entries, for the backend to keep.

type StorageFullError

type StorageFullError struct {
	// Bytes is what the storage would have held, and Quota the most it
	// may.
	Bytes, Quota int
}

StorageFullError refuses a value that would grow the storage past its quota: StorageQuota, or a partition's (Scope.ProvideStorage).

func (*StorageFullError) Error

func (e *StorageFullError) Error() string

type StorageOp

type StorageOp = driver.StorageOp

StorageOp says what a StorageChange does.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store holds an app's entries in memory, loaded from its backend on first use. Graphs given the same Store share its entries and quota, and each sees the others' changes through its signals. Hosts make one per app with NewStore and pass it in RootOptions.

func NewStore

func NewStore(backend driver.StorageBackend) *Store

NewStore returns a store kept by backend, or only in memory when backend is nil.

type Style

type Style struct {
	// Layout, with React Native's defaults: a column flexbox, items that
	// do not shrink and stretch on the cross axis, border-box sizes, no
	// automatic minimum sizes. Grid and block layout are CSS's.
	Display        Display
	Position       Position
	Direction      FlexDirection
	Wrap           FlexWrap
	JustifyContent Justify
	AlignItems     Align
	AlignSelf      Align
	AlignContent   Align
	// JustifyItems and JustifySelf align grid items (and block children)
	// along the row.
	JustifyItems Align
	JustifySelf  Align
	FlexGrow     float32
	FlexShrink   float32
	FlexBasis    Length

	Width, Height       Length
	MinWidth, MinHeight Length
	MaxWidth, MaxHeight Length
	// AspectRatio is width divided by height; 0 is unset.
	AspectRatio float32
	// BoxSizing says whether sizes include padding and borders, which they
	// do unless it is ContentBox.
	BoxSizing BoxSizing

	// Top, Right, Bottom and Left place an absolutely positioned node in
	// its parent, or offset a relative one. Right to left, left and right
	// swap, as in React Native, so they are its start and end, as are the
	// left and right of margins, paddings, borders and corners.
	Top, Right, Bottom, Left Length
	// RowByDefault lays a flex container out in a row unless a Direction
	// says otherwise, as CSS's display: flex, wherever it was written.
	RowByDefault bool
	// PhysicalEdges marks the sides of Margin, Padding and the insets that
	// stay on their sides right to left, as CSS's left and right.
	PhysicalEdges PhysicalEdges
	// LayoutDirection lays the node and what it holds out left to right
	// or right to left, over the app's direction; the zero value inherits
	// the parent's.
	LayoutDirection LayoutDirection
	// ZIndex stacks the node above its siblings with lower ones, keeping
	// the order of equals; it changes neither layout nor what sees the
	// node first in the tree.
	ZIndex int

	Margin Edges
	// AutoMargin makes the margins on those sides auto: they take the free
	// space, centering a node between two of them.
	AutoMargin Sides
	Padding    Edges
	// MarginPercent and PaddingPercent mark the sides whose Margin and
	// Padding are percentages of the containing block's width, as CSS's.
	MarginPercent, PaddingPercent Sides
	// PaddingEnv and MarginEnv add the safe area's insets or the software
	// keyboard's height to the padding and margin on their edges.
	PaddingEnv, MarginEnv EnvEdges
	// Gap separates children; RowGap and ColumnGap override it per axis.
	Gap, RowGap, ColumnGap Points

	// GridTemplateColumns and GridTemplateRows are a grid's tracks in CSS
	// syntax, such as "repeat(3, 1fr)" or "[full-start] 100px minmax(0, 1fr)";
	// GridAutoColumns and GridAutoRows size the tracks it adds.
	GridTemplateColumns, GridTemplateRows GridTracks
	GridAutoColumns, GridAutoRows         GridTracks
	GridAutoFlow                          GridFlow
	// GridRow and GridColumn place the node in its parent grid.
	GridRow, GridColumn GridLines

	// Look.
	Background Color
	// Gradients are drawn over Background, the first on top. A state
	// style that sets Background and no Gradients replaces them, so press
	// feedback shows.
	Gradients    []Gradient
	CornerRadius Points
	// CornerRadii, when set, gives each corner its own radius instead of
	// CornerRadius.
	CornerRadii Corners
	// BorderCurve Continuous eases the corners into their edges, as iOS's
	// continuous corners and Figma's corner smoothing do; pills stay pills.
	BorderCurve BorderCurve
	// BorderWidth is the width of the border on every side. Borders, when
	// set, gives each side's width to layout instead.
	BorderWidth Points
	Borders     Edges
	// BorderColor is the border's color, the text color while 0, as CSS's
	// currentColor: Transparent draws none.
	BorderColor Color
	// BorderColors, when set, colors each side; a side left 0 takes
	// BorderColor.
	BorderColors EdgeColors
	// PhysicalBorders marks the sides of Borders, BorderColors and
	// CornerRadii that stay where their names say right to left, as CSS's
	// border-left does, where the others are starts and ends.
	PhysicalBorders PhysicalBorders
	// BorderStyle dashes or dots the border; BorderNone and BorderHidden
	// take it away, in layout too.
	BorderStyle BorderStyle
	// OutlineWidth draws a line around the border box, OutlineOffset away
	// (inside when negative), following its corners, outside layout.
	OutlineWidth  Points
	OutlineOffset Points
	OutlineColor  Color
	OutlineStyle  BorderStyle
	Opacity       Opacity
	// Visibility Hidden hides the node and what it holds from sight, the
	// pointer and screen readers, keeping its place in layout.
	Visibility Visibility
	// Overflow Hidden clips children to the node's bounds and corners, and keeps their overflow out of an enclosing scroll view's content. The node's own outer shadows and outline stay outside the clip, as in CSS, on Windows, Linux and the web, and on Apple for views, images and macOS scroll views. Android, Apple's other views (texts, canvases, inputs, web, video and native views, and iOS scroll views) and an Apple image or scroll view whose corners differ in radius clip them too, which putting the clip on an inner view avoids, as ui.Dialog's Bare does.
	// OverflowX and OverflowY override it per axis.
	Overflow             Overflow
	OverflowX, OverflowY Overflow
	// ShadowColor, ShadowOffset and ShadowRadius are React Native's
	// shadow: ShadowRadius is the blur's standard deviation.
	ShadowColor  Color
	ShadowOffset Point
	ShadowRadius Points
	// Shadows are CSS's box shadows, the first on top; Ring makes
	// Tailwind's rings.
	Shadows []BoxShadow
	// Filters change what the node and its children draw, in order.
	Filters []Filter
	// BackdropFilters change what is behind the node, seen through its background, as CSS's backdrop-filter does: Blur frosts it by its radius, and brightness, contrast, grayscale, hue rotation, invert, opacity, saturate and sepia change its colors; a drop shadow draws nothing. iOS draws the system material a view's IOS.BackdropMaterial names for a blur and leaves the color filters out, as macOS does for a blur under a material other than BackdropUltraThin, drawn as AppKit's closest one. Linux and Android draw no backdrop filters. GlassEffect draws Liquid Glass in its place on iOS and macOS 26; give a glass view a blur to fall back to.
	BackdropFilters []Filter
	GlassEffect     GlassEffect
	// Mask draws the node, backdrop included, as much as the gradient's
	// alpha says.
	Mask *Gradient
	// BlendMode mixes the node's pixels with what is drawn behind it.
	BlendMode BlendMode
	// TintColor recolors an image's opaque pixels.
	TintColor Color
	// Cursor is the pointer's look over the view; Auto inherits the
	// nearest ancestor's, and a pressable view's is a pointer on the web.
	Cursor Cursor
	// ObjectPosition places an image in its view once ResizeMode has
	// sized it; centered when unset.
	ObjectPosition ObjectPosition
	// VerticalAlign places an attachment in its text's line, set on the
	// span or on the attachment's view.
	VerticalAlign VerticalAlign
	// Transform is CSS's translate, rotate and scale, each set on its own
	// by Merge, and the fixed functions of its transform property.
	Transform Transform
	// Transforms is CSS's transform as a list, its functions in the order
	// they are given, after Transform; it replaces Transform's functions
	// as it merges (ParseTransform reads the CSS).
	Transforms []TransformStep
	// TransformOrigin is where Transform acts: its zero value is the
	// center, and its percentages are of the node's size.
	TransformOrigin ObjectPosition
	// TransformOriginZ moves the origin toward the viewer, CSS's third
	// transform-origin value.
	TransformOriginZ Points
	// Perspective is the depth children's rotations out of their plane
	// are seen from, at this node's center, as CSS's perspective.
	Perspective Points
	// BackfaceHidden hides the node while its rotations turn its back to
	// the viewer.
	BackfaceHidden bool
	// Transition animates changes of the look on the platform.
	Transition Transition
	// Animation runs keyframes over the node on the platform, on top of
	// its transform and opacity; Spin, Ping, Pulse and Bounce make
	// Tailwind's.
	Animation KeyframeAnimation
	// Animated binds properties to animated values the platform moves
	// every frame, over the ones above.
	Animated *AnimatedStyle

	// Color is the text color, inherited by descendants that set none. Without an explicit color above, it follows the subtree's Palette.Text, including changes of theme, appearance and host tokens.
	Color Color
	// FontFamily names a font family or a CSS list of them, each used for
	// the characters those before it lack; empty is the system font, and
	// FontMonospace the system's fixed-pitch font.
	FontFamily string
	// Language is the text's BCP 47 tag ("ja", "zh-Hant"), which picks the glyph forms of characters languages share, such as Han, and the fallback fonts and line breaking where the platform takes it. Empty inherits it, and the root's is the language the app shows (Env.Language), else its locale.
	Language   string
	FontSize   Points
	FontWeight FontWeight
	FontStyle  FontStyle
	// FontVariant turns on small capitals and the forms and widths of
	// figures; FontVariantNormal undoes an inherited one. A node's
	// variant replaces its parent's.
	FontVariant FontVariant
	// LineHeight is the height of each line. LineHeightMultiple is one in
	// multiples of the font size, which descendants inherit as a multiple
	// of theirs; LineHeightEm is one too, resolved where it is set and
	// inherited as a length. Whichever the nearest node sets wins.
	LineHeight         Points
	LineHeightMultiple float32
	LineHeightEm       float32
	// LetterSpacing is the room added after each character;
	// LetterSpacingEm is one in multiples of the font size, resolved
	// where it is set, as LineHeightEm. The one set last wins.
	LetterSpacing   Points
	LetterSpacingEm float32
	TextAlign       TextAlign
	TextDecoration  TextDecoration
	// TextDecorationStyle draws the decoration's lines solid, double,
	// dotted, dashed or wavy; TextDecorationColor colors them, the text's
	// color when 0.
	TextDecorationStyle TextDecorationStyle
	TextDecorationColor Color
	// TextDecorationThickness is how thick the decoration's lines are,
	// and TextUnderlineOffset how far below the baseline an underline's
	// top is; percentages are of the font size, and auto is the font's.
	TextDecorationThickness Length
	TextUnderlineOffset     Length
	// TextTransform changes the case of the characters, as written in the
	// text it is set on.
	TextTransform TextTransform
	// TextShadowColor, TextShadowOffset and TextShadowRadius draw a shadow
	// behind a text's glyphs, the text's own style's for its whole block.
	// An offset or radius without a color is black at a third of opacity.
	TextShadowColor  Color
	TextShadowOffset Point
	TextShadowRadius Points
	// TextAlignVertical moves text shorter than its box down within it.
	TextAlignVertical TextAlignVertical
	// SelectionColor is the highlight of selected text, and an input's
	// caret without a CaretColor; 0 is the platform's, but for an input,
	// which takes its theme's Selection and Accent.
	SelectionColor Color
	// CaretColor is an input's caret, as CSS's caret-color, but for the
	// inputs inside the view: it is not inherited. iOS tints the selection
	// with it too.
	CaretColor Color
	// PlaceholderColor colors an input's placeholder; 0 is the platform's.
	PlaceholderColor Color
	// Fill, Stroke, StrokeWidth and StrokeDash are SVG's paint properties,
	// inherited as CSS inherits them. Views draw nothing with them; a
	// canvas's drawing paints with them where it takes its view's paint
	// (Drawing.FillFromView and the like), so a component's shapes follow
	// the app's styles. A StrokeWidth of 0 is unset; a StrokeDash that is
	// empty but not nil is solid.
	Fill, Stroke Paint
	StrokeWidth  Points
	StrokeDash   []Points
	// WhiteSpace NoWrap keeps text on one line per paragraph, overflowing
	// its box.
	WhiteSpace WhiteSpace
	// UserSelect lets the user select the texts inside, unless a text's
	// own Selectable says otherwise.
	UserSelect UserSelect
	// NumberOfLines limits a text's lines over its MaxLines, and
	// TextOverflow says where it is cut over its EllipsizeMode;
	// NoLineLimit lifts a limit, as line-clamp-none does.
	NumberOfLines int
	TextOverflow  EllipsizeMode
	// PointerEvents says which of the view and its children take the
	// pointer, over the element's own. PointerEventsNone is inherited, as
	// CSS's none: a view inside it takes the pointer again with
	// PointerEventsOn, or either of the box values, which are the view's
	// alone.
	PointerEvents PointerEvents
	// ObjectFit fits an image or a video to its view, over its own
	// ResizeMode.
	ObjectFit ResizeMode
	// WritingDirection is the base direction of text, which orders runs of
	// mixed directions and says where TextAlignStart is; the zero value is
	// the layout direction.
	WritingDirection WritingDirection

	// Group makes the node a group, named so, whose states the GroupStyle
	// of nodes inside it follows.
	Group string
	// GroupStyle merges styles over the rest while the nearest group
	// around the node is in their states, under the node's own states.
	GroupStyle *GroupStyle

	// State styles merge over the rest while the node is in the state, in NSH's order of precedence, lowest first: checked, indeterminate and selected, which the app sets; FocusWithin, while the focus is on the node or inside it; hovered, focused (text fields) and pressed, which the platform reports (pressed only for a node with a press handler or a responder holding the touch: Active alone never makes a node pressable or a Tab stop); the aria-* states of its accessibility state, busy, checked, expanded, invalid, pressed (a toggle that is on, not a press) and selected; the data-* attributes a control's parts show; then disabled over all. While the node is disabled only Disabled applies of its own, as NSH's state styles; its classes' variants (checked:, hover:, ...) apply.
	Hover, Focus, Active, Selected, Checked, Indeterminate, Disabled    *Style
	FocusWithin, AriaBusy, AriaChecked, Expanded, Pressed, AriaSelected *Style
	FocusVisible, AriaInvalid                                           *Style
	// Data are styles of data-* attributes, sorted by name.
	Data []DataStyle
}

Style is a node's layout, look and text. Every field's zero value means unset, so styles compose with Merge and text fields inherit from the parent as in CSS. A style with nothing set draws nothing: NSGo has no look of its own.

func (Style) IsZero

func (s Style) IsZero() bool

IsZero reports whether s sets nothing.

func (Style) Merge

func (s Style) Merge(o Style) Style

Merge returns s with every field o sets replacing s's.

type SubmitBehavior

type SubmitBehavior = driver.SubmitBehavior

SubmitBehavior is what Return does in a text field.

type Subscription added in v0.2.0

type Subscription = driver.Subscription

Subscription is what an auto-renewable subscription's product says of it: its group, its period and its offers.

type SubscriptionOffer added in v0.2.0

type SubscriptionOffer = driver.SubscriptionOffer

SubscriptionOffer is an introductory or promotional offer of a subscription.

type SubscriptionPeriod added in v0.2.0

type SubscriptionPeriod = driver.SubscriptionPeriod

SubscriptionPeriod is how long a subscription or an offer's period lasts, Value of Unit.

type Suggest

type Suggest struct {
	// contains filtered or unexported fields
}

Suggest follows a trigger query in a text field, such as a mention after "@", and replaces it with the text a list beside the field accepts. It holds no rows: base.SuggestList shows them. Pass it to the field's Input.Suggest. It is created in the field's owner scope and is safe on that scope's engine goroutine, like signals and the rest of the reactive graph.

func NewSuggest

func NewSuggest(cx *Scope, o SuggestOptions) *Suggest

NewSuggest creates a suggestion state for a field in cx's scope.

func (*Suggest) Accept

func (s *Suggest) Accept(text string)

Accept replaces the trigger and the query with text, puts the caret after it and closes the query, dismissing the trigger as Close does, so a text that starts with the trigger, such as "@alice", does not reopen it. An uncontrolled field takes the text itself, a controlled one through its OnChange.

func (*Suggest) Anchor

func (s *Suggest) Anchor() Bounds

Anchor is the caret's latest page bounds, suitable for Overlay.AnchorBounds.

func (*Suggest) Close

func (s *Suggest) Close()

Close ends an active query without changing the field. It stays closed on the trigger it closed, however the query grows or the caret moves within it, until that match ends or a trigger starts elsewhere.

func (*Suggest) Composing

func (s *Suggest) Composing() bool

Composing reports whether an input method composes in the field, when a list leaves the keys to it.

func (*Suggest) Open

func (s *Suggest) Open() bool

Open reports whether a query is active: the field has the focus, and its caret, with no selection, follows a trigger with nothing between them that ends the query.

func (*Suggest) Query

func (s *Suggest) Query() string

Query is the text after the trigger and before the caret.

type SuggestOptions

type SuggestOptions struct {
	// Trigger starts a query, "@" when empty.
	Trigger string
	// AllowSpaces lets a query contain spaces.
	AllowSpaces bool
	// AllowedPrefixes are what may precede Trigger besides a line's start, a space when nil.
	AllowedPrefixes []string
	// OnOpen and OnClose hear a query start and end.
	OnOpen, OnClose func()
}

SuggestOptions tune a Suggest.

type Suspense

type Suspense struct {
	Content  func(cx *Scope) Node
	Fallback func(cx *Scope) Node
}

Suspense shows Fallback while a resource that Content reads loads its first value, as Solid's Suspense does, and Content once none does. Content stays mounted, hidden and out of layout meanwhile, so what it reads keeps it suspended until the resources are ready, and it shows at once then. A resource loading again, with a value already (ResourceRefreshing), keeps Content shown rather than going back to Fallback, as does one read outside a computation, as in a handler. A Suspense inside Content takes what is read under it.

func (Suspense) Render

func (s Suspense) Render(*Scope) Node

Render implements Node.

type SystemClock

type SystemClock struct{}

SystemClock is the system's time.

func (SystemClock) AfterFunc

func (SystemClock) AfterFunc(d time.Duration, f func()) func() bool

func (SystemClock) Now

func (SystemClock) Now() time.Time

type SystemSwitch

type SystemSwitch struct {
	Ref        *Ref
	LabelledBy []*Ref
	Invalid    func() bool
	Checked    func() bool
	Disabled   func() bool
	// OnChange receives the value the user chose, which the native component reports as its "change" event with a bool: a test reports one with nsgotest's Emit(selector, "change", value), or flips the switch with Press.
	OnChange func(checked bool)
	// Size is macOS's control size, "small" or "large", else the regular
	// one; UISwitch has one size.
	Size   string
	Label  string
	Style  Style
	TestID string
}

SystemSwitch is the platform's own switch, NSSwitch on macOS and UISwitch on iOS, a native component they register; ui.Switch's SwitchSystem variant shows it there. Elsewhere it shows nothing, and SystemSwitchAvailable says whether it shows. The switch shows the user's choice at once, as the system's does, and its size is the system's where the style leaves it open.

func (SystemSwitch) Render

func (s SystemSwitch) Render(cx *Scope) Node

Render implements Node.

type TabBar

type TabBar struct {
	Items     []TabBarItem
	ItemsFunc func() []TabBarItem
	// Selected is the selected tab's index; one past the tabs selects
	// none. The bar shows the user's choice at once, as the system's does.
	Selected func() int
	OnChange func(index int)
	Style    Style
	TestID   string
}

TabBar is the core's part of mobile.TabBar, which apps use: the system's tab bar, a native component iOS and Android register. The selected tab takes the theme's accent; the others keep the system's.

func (TabBar) Render

func (b TabBar) Render(cx *Scope) Node

Render implements Node.

type TabBarItem

type TabBarItem struct {
	Title string
	// Icon is the platform's name for an icon: an SF Symbol on iOS
	// ("house"), and on Android a drawable of the app or, prefixed
	// "android:", of the system ("android:ic_menu_search").
	Icon string
	// SVG is the tab's icon on Android where Icon names no drawable the app or system has, such as an SF Symbol name shared with iOS: fitted into 24 points and tinted by the bar as a drawable is. iOS uses only Icon.
	SVG *SVG
}

TabBarItem is one tab of a TabBar. Apps name it mobile.TabBarItem.

type Tailwind

type Tailwind struct {
	// contains filtered or unexported fields
}

Tailwind is Tailwind CSS 4's default theme extended for the classes of a theme's subtree (Theme.Tailwind), as NSH's nsh.json tailwind extends an app's.

func ParseTailwind

func ParseTailwind(data []byte) (*Tailwind, error)

ParseTailwind reads an extension of Tailwind's default theme, an entry with an existing name replacing the default's:

colors: { brand: { 500: "#7c3aed", DEFAULT: "#6d28d9" }, accent: "#f59e0b" }
spacing: 4
breakpoints: { tablet: 600 }
fontFamily: { display: Inter }
fontSize: { huge: [48, 1.1] }
fontWeight: { heavy: 850 }
radius: { card: 14 }
shadow: { card: "0 2px 8px rgb(0 0 0 / 0.12)" }
tracking: { label: 0.08 }
leading: { dense: 1.15 }
blur: { glass: 20 }
aspect: { photo: 1.5 }
ease: { snappy: [0.2, 0, 0, 1] }
container: { content: 680 }

insetShadow, dropShadow, perspective and rem take their scales too. Lengths are points; an unknown key is an error. JSON is YAML, so NSH's tailwind object reads as it is.

type TaskProgress

type TaskProgress struct {
	State TaskProgressState
	Value float64
}

TaskProgress is how far a task has gone on the app's icon. Value is a fraction from 0 to 1 for Normal, Paused and Error; it is ignored for the other states.

type TaskProgressState

type TaskProgressState uint8

TaskProgressState says what a task progress indicator shows.

const (
	// TaskProgressNone clears the indicator.
	TaskProgressNone TaskProgressState = iota
	// TaskProgressNormal shows Value as a completed fraction.
	TaskProgressNormal
	// TaskProgressIndeterminate shows that the task has no fraction yet.
	TaskProgressIndeterminate
	// TaskProgressPaused shows a paused task. Windows and macOS give it a paused color.
	TaskProgressPaused
	// TaskProgressError shows a task that failed. Windows and macOS give it an error color.
	TaskProgressError
)

type Text

type Text struct {
	// Class is Tailwind CSS classes, as View's.
	Class       string
	ClassFunc   func() string
	Content     string
	ContentFunc func() string
	Style       Style
	StyleFunc   func() Style
	// MaxLines limits the lines shown, cutting the rest as EllipsizeMode
	// says: an ellipsis at the last line's end by default.
	MaxLines      int
	EllipsizeMode EllipsizeMode
	// NoFontScaling keeps the text's sizes whatever the user's text size
	// setting; MaxFontSizeMultiplier, when 1 or more, caps the setting's
	// multiplier for it.
	NoFontScaling         bool
	MaxFontSizeMultiplier float32
	// AdjustsFontSizeToFit shrinks the text's fonts, line heights and
	// letter spacing, down to MinimumFontScale of them (at least 0.1),
	// until it fits its box and MaxLines.
	AdjustsFontSizeToFit bool
	MinimumFontScale     float32
	// Spans, when set, are the text: runs in order, each styled over the
	// Text's style. A span with OnPress is a link; a press on another
	// span is the Text's OnPress.
	Spans []Span
	// SpansFunc's spans are the text again whenever what it reads changes, as a code editor's rows recolor as their highlighting comes: runs of text with their classes, styles and presses, and attachments.
	SpansFunc func() []Span
	// Selectable lets the user select and copy the text; the highlight is
	// the style's SelectionColor.
	Selectable Selectable
	// PointerEvents says whether the text takes the pointer, as View's.
	PointerEvents PointerEvents

	OnPress func(PressEvent)
	// OnLongPress runs when the text is held, after DelayLongPress's
	// 500 ms.
	OnLongPress func(PressEvent)
	OnLayout    func(Bounds)
	// OnTextLayout receives the text's lines each time it is laid out
	// anew, after the commit.
	OnTextLayout func(lines []TextLine)
	Ref          *Ref
	Role         Role
	// Label replaces the text for assistive technology.
	Label     string
	LabelFunc func() string
	// LabelFor and LabelledBy are a View's label associations.
	LabelFor   *Ref
	LabelledBy []*Ref
	Hint       string
	// LiveRegion has screen readers announce the text as it changes; a RoleStatus text is a polite one when 0.
	LiveRegion LiveRegion
	TestID     string
}

Text is a run of text the engine lays out and the platform draws.

func (Text) Render

func (t Text) Render(*Scope) Node

Render implements Node.

type TextAlign

type TextAlign = driver.TextAlign

TextAlign aligns lines of text.

type TextAlignVertical

type TextAlignVertical uint8

TextAlignVertical is where text shorter than its box sits in it.

const (
	TextAlignVerticalTop TextAlignVertical = iota + 1
	TextAlignVerticalCenter
	TextAlignVerticalBottom
)

type TextAttachment

type TextAttachment = driver.TextAttachment

TextAttachment is a view inside a text, which FontExtent's font around it places on its line.

type TextBackground

type TextBackground = driver.TextBackground

type TextBaseline

type TextBaseline = driver.TextBaseline

TextBaseline is the line of a canvas text that the point it is drawn at sits on.

type TextDecoration

type TextDecoration = driver.TextDecoration

TextDecoration draws lines on text; the values combine.

type TextDecorationStyle

type TextDecorationStyle = driver.TextDecorationStyle

TextDecorationStyle is how a text's decoration lines are drawn; the zero value is solid.

type TextEngine

type TextEngine = driver.TextEngine

TextEngine shapes, measures and lays out text: a platform's, or ApproxTextEngine's without one. PreparedText is what it shapes from an AttributedText, a TextLayout what it lays out to draw.

type TextLayout

type TextLayout = driver.TextLayout

type TextLine

type TextLine = driver.TextLine

TextLine is a line of laid-out text, as Text.OnTextLayout reports it.

type TextMetrics

type TextMetrics = driver.TextMetrics

TextMetrics are a text's measurements in a font.

type TextRange

type TextRange = driver.TextRange

TextRange is a selection in a text field, in UTF-16 units as the platforms' text APIs count; Start equals End for a caret.

type TextSelection added in v0.2.0

type TextSelection struct {
	// Text is the selected text as a copy gives it: texts on one row joined by a tab and the others by a line break.
	Text string
	// Bounds is the box of the texts the selection touches, in the view: no Size without a selection. Ref.Bounds of the view gives the surface's.
	Bounds Bounds
}

TextSelection is the selection of a Selectable view, as OnTextSelection receives it.

type TextShadow

type TextShadow = driver.TextShadow

TextShadow is a shadow behind a text's glyphs.

type TextSpan

type TextSpan = driver.TextSpan

type TextStyle

type TextStyle = driver.TextStyle

TextStyle is a text's resolved style, TextSpan a byte range of it styled over it, and TextBackground what a span draws behind its characters.

type TextTransform

type TextTransform uint8

TextTransform changes the case of text as it is laid out.

const (
	TextTransformNone TextTransform = iota + 1
	TextTransformUppercase
	TextTransformLowercase
	// TextTransformCapitalize upper-cases the first letter or digit of
	// each word.
	TextTransformCapitalize
)

func (TextTransform) Apply

func (x TextTransform) Apply(s string) string

Apply returns s in the case x asks for.

type Theme

type Theme struct {
	Light, Dark Palette
	Radius      Points
	Sans, Mono  string
	// Tokens are the theme's design tokens that are no colors, by name:
	// lengths ("12px") and font families, as a shadcn/ui theme file's
	// theme section names them.
	Tokens map[string]string
	// Tailwind is the Tailwind theme the subtree's classes resolve
	// against; nil is Tailwind's default.
	Tailwind *Tailwind
}

Theme is a look in both appearances: a palette for each, the corner radius components start from and font families, empty for the system's. Scope.SetTheme gives it to a subtree; treat a theme given as read-only.

func DefaultTheme

func DefaultTheme() *Theme

DefaultTheme returns NSGo's theme, which a tree shows until the app sets one: neutral grays with a blue accent. Its Colors hold shadcn/ui's tokens, which theme files and classes name, and the roles package ui's components read (ui.Colors): insets and tracks recess with the text's color, fields take the border, hairlines a fainter text color, light is the inverse of the page.

func ParseTheme

func ParseTheme(data []byte) (*Theme, error)

ParseTheme reads a theme file over DefaultTheme: radius, sans and mono, and light and dark maps of role names, as Palette.Color names them, to CSS colors. YAML reads JSON as well.

radius: 8
light:
  accent: "#007aff"
  inset: "#f1f1f1"
dark:
  accent: "#0a84ff"

It reads a shadcn/ui theme file too, as NSH's apps name theirs: the CSS variables of cssVars' theme, light and dark sections, where a value may name another (var(--brand)) and dark's go over light's. A variable that is a color is a role of the palettes; the others are Tokens, radius and font-sans and font-mono setting Radius, Sans and Mono too.

func (*Theme) Clone

func (t *Theme) Clone() *Theme

Clone returns a copy of t that shares nothing with it.

type TimingConfig

type TimingConfig = driver.TimingConfig

TimingConfig is a timing animation's: Duration (500 ms when 0) along Easing, after Delay.

type TitleBarStyle

type TitleBarStyle = driver.TitleBarStyle

TitleBarStyle is whether the system draws the window's title bar.

type Toggle

type Toggle uint8

Toggle is an option a layer turns on or off, or leaves to the layers below.

const (
	ToggleInherit Toggle = iota
	ToggleOn
	ToggleOff
)

type Tokens

type Tokens struct {
	Values, Dark map[string]string
}

Tokens are colors an embedding host themes the app with, by the role names of Palette.Color ("accent", "inset"), written as CSS writes them. They go over every theme's palette (Scope.Palette): Values in both appearances, and Dark's over them where a subtree shows dark. A value that is no color is dropped.

type Touch

type Touch = driver.Touch

Touch is one finger of a TouchEvent.

type TouchClaim

type TouchClaim struct {
	// OnMove claims as a finger moves (onMoveShouldSetResponder) rather
	// than as one goes down (onStartShouldSetResponder).
	OnMove bool
	// Capture asks the view before the views inside it.
	Capture bool
	// Ask decides with the gesture whether to claim; nil claims.
	Ask func(ResponderEvent) bool
	// LetNative lets the scroll views around go on taking the touches;
	// by default a responder stops them.
	LetNative bool
	// OnPan claims as the platform activates the view's pan by its
	// PanActivation, deciding on the main thread so the scroll views
	// around share the touch until then. A view with such a claim is the
	// responder exactly while its pan is active: its other claims are not
	// asked.
	OnPan bool
}

TouchClaim is when a view asks to become the touch responder.

type TouchEvent

type TouchEvent struct {
	Phase TouchPhase
	// Time is since an arbitrary origin.
	Time    time.Duration
	Touches []Touch
	// contains filtered or unexported fields
}

TouchEvent is the fingers on the surface as one of them changes. An end or a cancel lists the fingers that lifted too.

func (TouchEvent) StopPropagation

func (e TouchEvent) StopPropagation()

StopPropagation keeps the views after this one on the path from hearing the event.

type TouchPhase

type TouchPhase uint8

TouchPhase is what happened to the fingers of a TouchEvent.

const (
	// TouchStart is fingers going down (the changed ones).
	TouchStart TouchPhase = iota + 1
	// TouchMove is fingers moving.
	TouchMove
	// TouchEnd is fingers lifting (the changed ones).
	TouchEnd
	// TouchCancel is the system or a native gesture, such as a scroll
	// view, taking the touches.
	TouchCancel
)

type Transaction added in v0.2.0

type Transaction = driver.Transaction

Transaction is a purchase the store recorded. Send Signed, the store's JWS, to the app's server to verify, deliver what was bought, then finish it with FinishTransaction; until then the store hands it to the app again at each launch.

type Transform

type Transform = driver.Transform

Transform moves, scales and rotates a view without changing its layout, around its center: translate, then rotate, then scale.

type TransformKind

type TransformKind uint8

TransformKind is a function of CSS's transform property.

const (
	TransformTranslateX TransformKind = iota + 1
	TransformTranslateY
	TransformScaleX
	TransformScaleY
	TransformRotate
	TransformRotateX
	TransformRotateY
	TransformSkewX
	TransformSkewY
	TransformPerspective
)

type TransformStep

type TransformStep struct {
	Kind    TransformKind
	Value   float32
	Percent bool
}

TransformStep is one function of a transform list: Value is in points, degrees or a factor, and for Percent a translation's percentage of the view's own size.

func ParseTransform

func ParseTransform(s string) ([]TransformStep, error)

ParseTransform reads CSS's transform: its functions, or none, which is an empty list.

type Transition

type Transition = driver.Transition

Transition animates a view's look when its style changes: the platform runs it on the main thread, with no work for the engine per frame.

type TransitionProperty

type TransitionProperty = driver.TransitionProperty

TransitionProperty is a set of animatable properties.

type TransitionShader

type TransitionShader struct {
	Program  *ShaderProgram
	Uniforms Uniforms
	Duration time.Duration
}

TransitionShader is a WGSL program a page (Screen) or a dialog (Modal) comes and goes through instead of its Animation: sample_from(uv) is the lower side (the page under it, the surface without the dialog), sample_to(uv) the upper, and nsh.progress goes from 0 to 1 as it comes and from 1 to 0 as it goes, over Duration (350 ms when 0). When the user asks for less motion, or where the platform cannot draw it, the page or the dialog takes its own Animation.

type Tray

type Tray struct {
	// contains filtered or unexported fields
}

Tray is a tray icon: the core's part of desktop.Tray, which apps use. Its methods do nothing on a nil Tray, which NewTray returns where the platform has no tray support.

func (*Tray) Remove

func (tr *Tray) Remove()

Remove takes the icon away, as its owner going does.

func (*Tray) SetIcon

func (tr *Tray) SetIcon(png []byte, template bool)

SetIcon shows png as the icon, in the menu bar's colors when template.

func (*Tray) SetTitle

func (tr *Tray) SetTitle(title string)

SetTitle sets the text beside the icon, on macOS.

func (*Tray) SetTooltip

func (tr *Tray) SetTooltip(tooltip string)

SetTooltip sets what shows as the pointer rests on the icon.

type TrayOptions

type TrayOptions struct {
	// Icon is the icon as PNG; Template draws it in the menu bar's
	// colors on macOS, as its own icons are.
	Icon     []byte
	Template bool
	// View draws the icon instead, Width points wide (22 by default) and
	// as tall as the menu bar, so it can change and move: on macOS.
	View  func(cx *Scope) Node
	Width Points
	// Title is text beside the icon, on macOS; Tooltip shows on hover.
	Title, Tooltip string
	// Panel shows under the icon on a primary click, and hides on the
	// next.
	Panel *Window
	// OnClick runs on a primary click without a Panel.
	OnClick func()
	// Menu returns the menu a secondary click shows, and a primary click
	// without a Panel or OnClick.
	Menu func() []MenuItem
}

TrayOptions are a tray icon's: the core's part of desktop.TrayOptions, which apps use.

type Tree

type Tree struct {
	// contains filtered or unexported fields
}

Tree is the shadow tree of one surface. Commit turns its changes into a MountBatch. It is not safe for concurrent use: the engine owns it.

func NewTree

func NewTree(root *Scope, text driver.TextEngine) *Tree

NewTree returns an empty tree under root, laying text out with text.

func (*Tree) Changed

func (t *Tree) Changed() bool

Changed reports whether a Commit would produce items.

func (*Tree) Closed

func (t *Tree) Closed() bool

Closed reports whether an opened surface closed: the platform destroys its window, and the engine forgets it.

func (*Tree) Commit

func (t *Tree) Commit() *driver.MountBatch

Commit resolves styles, prepares text, lays the tree out and returns what changed since the last commit, or nil when nothing did. Changes that OnLayout handlers make go into the same batch.

func (*Tree) CommitShared

func (t *Tree) CommitShared() *driver.MountBatch

CommitShared is Commit for a platform that applies a batch before the next commit, as the web does on its one thread: the batch's items are the tree's own, until the next commit writes over them, so a commit copies nothing. A busy table's commit copied half a megabyte, which Go's collector paid for on the page's thread.

func (*Tree) Dispatch

func (t *Tree) Dispatch(ev driver.Event)

Dispatch handles a platform event.

func (*Tree) FontsChanged

func (t *Tree) FontsChanged()

FontsChanged prepares every text and records every canvas again, with fonts the platform made available since they were prepared.

func (*Tree) Forget

func (t *Tree) Forget()

Forget drops a closed surface's tree.

func (*Tree) HitTest

func (t *Tree) HitTest(p Point) NodeID

HitTest returns the innermost pressable view at p in surface points, for platforms that draw their own views.

func (*Tree) ID

func (t *Tree) ID() uint32

ID numbers an opened surface's tree, which ItemOpenSurface names; the first tree's is 0.

func (*Tree) KeyDown added in v0.2.0

func (t *Tree) KeyDown(ev driver.Event) bool

KeyDown dispatches EventKeyDown ev to its view's OnKeyDown, as Dispatch does, and reports whether the handler consumed the key, for the platform that waits to know whether the keymap and the view still take it (Engine.DispatchKeyDown).

func (*Tree) Language

func (t *Tree) Language() string

Language returns the language the app shows (Env.Language): of its catalogs' languages, the one that suits the locale best, "" for an app without catalogs. The engine reads it for platform services that take a language only as they start, as WinSparkle does.

func (*Tree) Mount

func (t *Tree) Mount(app func(cx *Scope) Node)

Mount builds what app returns as the root view's content.

func (*Tree) Pacing

func (t *Tree) Pacing() bool

Pacing reports whether views wait for display frames to be made, or lists to bind the rest of their windows.

func (*Tree) PendingTransitionEnds added in v0.2.0

func (t *Tree) PendingTransitionEnds() bool

PendingTransitionEnds reports whether a live view waits for its style transition to end before its OnTransitionEnd runs. It is nsgotest's: a step takes frames until it is false.

func (*Tree) PressAt

func (t *Tree) PressAt(ev driver.Event)

PressAt dispatches ev as a press on the innermost pressable view at its Page, in surface points, with its Point in that view.

func (*Tree) Resize

func (t *Tree) Resize(size Size, g Geometry)

Resize sets the surface size the root fills and the fold geometry measured at it (Env.Geometry), in one batch, so what reads either sees both new. A geometry without regions is divided at size; the zero Geometry is a surface without a fold. A new geometry at the same size still applies.

func (*Tree) SetAppearance

func (t *Tree) SetAppearance(a Appearance)

SetAppearance forces the appearance the app shows, as Scope.SetAppearance does: a host sets the one the app starts in.

func (*Tree) SetEnvironment

func (t *Tree) SetEnvironment(env Environment)

SetEnvironment records what the platform reports about where the app runs.

func (*Tree) SetTokens

func (t *Tree) SetTokens(tokens Tokens)

SetTokens gives the app the host's tokens, from now on: what reads Env.Token runs again.

func (*Tree) SetViewPacing

func (t *Tree) SetViewPacing(on bool)

SetViewPacing turns pacing views over frames on, as it starts, or off, as a test host does so its steps reach every view: what waits is made in the next commit.

func (*Tree) Size

func (t *Tree) Size() Size

Size returns the surface size.

func (*Tree) Surfaces

func (t *Tree) Surfaces() []*Tree

Surfaces returns the trees of the windows, panels and tray views the app opened, which the engine commits to the platforms that attach them, the closed ones until Forget.

func (*Tree) Window added in v0.2.0

func (t *Tree) Window() *Window

Window returns the window, panel or tray view an opened surface's tree shows, nil for the first tree: what a host compares with Scope.MainWindow to find the main window's tree.

type Uniforms

type Uniforms map[string]any

Uniforms are the values of a shader's uniform variables, by name. A value is a number (any of Go's integer or float kinds, or a bool), an AnimatedNode, a Color, or a slice of numbers or nodes or of any of these ([]any), which fill the uniform's lanes in turn: a vector's components, a matrix's columns, an array's elements. A Color fills four lanes, red, green, blue and alpha from 0 to 1, not premultiplied, or three for a vec3. Lanes left out are 0.

An AnimatedNode's lane follows the node on the platform's frame clock, with no engine work per frame: a Loop of a Timing makes a clock, and a value Set with each pointer move puts a glow under the pointer.

type UpdateCheck

type UpdateCheck struct {
	// Shown says the platform's own updater showed what it found in its
	// windows, as Sparkle on macOS and WinSparkle on Windows do: they
	// offer the newer version, install it and restart the app. Nothing
	// else is set then.
	Shown bool
	// App and Current are the app's name and running version.
	App, Current string
	// Version is the newer version found, "" when Current is the newest,
	// and URL the page that gets it: the App Store's on iOS, the
	// release's elsewhere.
	Version, URL string
	// Download is the signed package for Version, when this target can
	// install it itself. Signature and SHA256 authenticate its bytes; Key is
	// the public Ed25519 key from the app's update configuration.
	Download, Signature, SHA256, Key string
	Size                             int64
	// Err says why the updater could not check.
	Err error
}

UpdateCheck is what the platform's updater answers CheckForUpdates with.

type UpdateDownloadProgress

type UpdateDownloadProgress struct{ Loaded, Total int64 }

UpdateDownloadProgress reports bytes received by DownloadUpdate.

type UpdateHighlights

type UpdateHighlights struct {
	// NoUpdates starts it without outlining commits, which DevTools turn on (devtools.Surface.Highlight): the dev client sets it without -highlight.
	NoUpdates bool
	// Layout is what the layout audit shows as it starts: nsgo dev -layout's. DevTools show and hide it, and so does Mod+Alt+Shift+L when it starts showing (LayoutAudit).
	Layout LayoutAudit
}

UpdateHighlights is DevTools' overlay: it outlines for a moment each view a commit of its surface changed, as React DevTools' highlight updates and Flutter's repaint rainbow do, so work an update did not need shows, and holds the layout audit, which outlines every view's boxes with a grid and a ruler. It draws above the app's overlays and modals (Overlay.Topmost) and leaves its own views out. nsgo's dev client mounts it over the app under nsgo dev -highlight, -layout and -devtools; it needs a host, an engine or a test driver, and shows nothing without one.

func (UpdateHighlights) Render

func (h UpdateHighlights) Render(*Scope) Node

Render implements Node.

type UserSelect

type UserSelect uint8

UserSelect says whether the user may select text.

const (
	UserSelectText UserSelect = iota + 1
	UserSelectNone
)

type VerticalAlign

type VerticalAlign = driver.VerticalAlign

VerticalAlign is where an attachment sits in its line, as CSS's vertical-align places a replaced inline box, against the font of the text around it.

type VerticalBarEdge

type VerticalBarEdge = driver.VerticalBarEdge

VerticalBarEdge is the edge where the system places a vertical bar: Env.VerticalBarEdge.

type Video

type Video struct {
	// Source is a URL, a file path or an "asset:" path in the app's resources.
	Source     string
	SourceFunc func() string
	// Paused applies when the source opens and when its value changes. A non-repeating video stays at its end through other prop changes: set Paused true then false to replay it from the start, or from where its built-in controls scrubbed it back to, or Seek before the end, which plays on from there when Paused is false.
	Paused     bool
	PausedFunc func() bool
	Muted      bool
	MutedFunc  func() bool
	// Volume runs from 0 to 1; 0 plays at full volume, and Muted
	// silences the video.
	Volume     float32
	VolumeFunc func() float32
	// Rate is the playback speed; 0 plays at 1.
	Rate     float32
	RateFunc func() float32
	// Repeat starts the video over when it ends.
	Repeat         bool
	ResizeMode     ResizeMode
	ResizeModeFunc func() ResizeMode
	Controls       bool
	// ProgressInterval is the time between OnProgress calls while the
	// video plays: 250 milliseconds when 0, and at least 16.
	ProgressInterval time.Duration
	// AudioSession is what the sound does to other apps' audio while it plays: by default the app's settings decide, and on iOS the device's silent mode silences it; a video of speech, as an audiobook's, plays in silent mode with AudioSessionPlayback or AudioSessionMixWithOthers. AudioSessionFunc changes it as the video plays: iOS holds the new session before letting the old go, so playback goes on without a gap, and Android opens the source again.
	AudioSession     AudioSession
	AudioSessionFunc func() AudioSession
	// Class is Tailwind CSS classes, as View's.
	Class     string
	Style     Style
	StyleFunc func() Style

	// OnLoadStart is called when a source starts opening, and OnLoad once
	// its duration and size are known.
	OnLoadStart func()
	OnLoad      func(VideoInfo)
	// OnProgress receives the position and duration while the video
	// plays, and once more when it pauses or ends.
	OnProgress func(position, duration time.Duration)
	// OnEnd is called each time the video reaches its end, before a
	// repeating one starts over.
	OnEnd func()
	// OnBuffer receives whether playback waits for data.
	OnBuffer func(buffering bool)
	// OnPause reports that the platform paused the video, not the app: its built-in controls, or the system for an interruption or a lost audio output. The video stays paused until Paused changes, or the controls or the system play it again (OnPlay); an app that shows its own play state sets Paused to true, and then false to play again.
	OnPause func(VideoPauseReason)
	// OnPlay reports that the platform played the video, not the app: its built-in controls, or the system as an interruption that paused it ends. The video plays on until Paused changes, even while Paused is true.
	OnPlay   func()
	OnError  func(err error)
	OnPress  func(PressEvent)
	OnLayout func(Bounds)
	Ref      *Ref
	Label    string
	TestID   string
}

Video plays a video in the platform's player, filling the view: the picture fits it by ResizeMode, and Controls shows playback controls. It plays unless Paused; Ref.Seek jumps to a time.

A video with an alpha channel shows what is behind its transparent pixels where the platform decodes the alpha: HEVC with alpha in a QuickTime or MPEG-4 file on macOS (iOS uses the same player layer but is unchecked), and VP8 or VP9 with alpha in WebM on Linux with GStreamer's codecalpha plug-in (gst-plugins-bad). On macOS, iOS, Windows and Linux, a local file whose alpha the platform cannot keep (WebM with alpha on Apple platforms; any clip with alpha on Windows, until a Windows machine has checked what Media Foundation's decoders output for it; HEVC with alpha on Linux, and VP8 or VP9 with alpha there without codecalpha) reports OnError, a *MediaError whose Reason is MediaErrorAlphaUnsupported, instead of showing an opaque picture. Android and the web, and a remote source anywhere, play such clips as their decoder outputs them, which may be opaque. With Controls, AVKit's player draws black behind the picture.

func (Video) Render

func (v Video) Render(*Scope) Node

Render implements Node.

type VideoInfo

type VideoInfo struct {
	Duration time.Duration
	// Size is the picture's natural size in points.
	Size Size
}

VideoInfo is what a video reports when it loads. Duration is 0 for a stream without one, such as a live broadcast.

type VideoPauseReason added in v0.2.0

type VideoPauseReason uint8

VideoPauseReason says why the platform paused a video (Video.OnPause).

const (
	// VideoPauseInterruption is the system's: a call, Siri, another app taking the audio, or the app going to the background.
	VideoPauseInterruption VideoPauseReason = iota
	// VideoPauseRouteLost is the audio's output going away, such as headphones unplugged.
	VideoPauseRouteLost
	// VideoPauseControls is the platform's built-in controls (Controls), its Picture in Picture window or Control Center.
	VideoPauseControls
)

func (VideoPauseReason) String added in v0.2.0

func (r VideoPauseReason) String() string

String names a video pause reason for logs and diagnostics.

type View

type View struct {
	// Class is Tailwind CSS classes ("flex-row gap-4 p-4 bg-white
	// dark:bg-zinc-900"), meaning what they mean in Tailwind CSS 4, under
	// Style; an unknown class is logged once.
	Class     string
	ClassFunc func() string
	Style     Style
	StyleFunc func() Style
	Children  []Node

	// OnPress runs on a completed press: tap, click or accessibility
	// action. Pressable views capture presses on their descendants.
	OnPress     func(PressEvent)
	OnLongPress func(PressEvent)
	OnPressDown func(PressEvent)
	OnPressUp   func(PressEvent)
	// OnMouseEnter and OnMouseLeave follow the mouse over the view or a
	// view inside it, as the DOM's events do, OnMouseLeave saying where it
	// was last. OnMouseMove hears it move there, with or without a button
	// down (PressedButton), and a modifier key change while it rests
	// there with none down. Touches never hover.
	OnMouseEnter func(MouseEvent)
	OnMouseLeave func(MouseEvent)
	OnMouseMove  func(MouseEvent)
	// OnContextMenu receives a secondary click in the view.
	OnContextMenu func(ContextMenuEvent)
	// OnTouch hears the fingers on the surface while one that went down
	// on the view or inside it is down, from the innermost view out, after
	// OnTouchCapture from the outermost in, as the DOM's events capture
	// and bubble; TouchEvent.StopPropagation ends the round. Responder
	// makes the view take part in the touch responder.
	OnTouch        func(TouchEvent)
	OnTouchCapture func(TouchEvent)
	Responder      *Responder
	// NoFocus keeps a view that takes presses out of the keyboard focus's Tab stops on desktops and the web: a backdrop that closes a popover, rows a list moves through with the arrow keys.
	NoFocus bool
	// Focusable, when set, says whether the view is a Tab stop on desktops and the web, over NoFocus and whether it takes presses, following what it reads: a chart in a pressable card takes keys while focused without taking presses of its own, and a group of radios keeps one of them a stop. Return and Space press a stop only when it takes presses.
	Focusable func() bool
	// Follow names the view whose frame this absolutely positioned view
	// follows, nil for none: along its parent's main axis it spans that
	// view's frame, a view inside its parent, inside its own margins on
	// that axis, and across it its own layout stands, as a tab list's
	// indicator does. The core places it, so a layout that moves the
	// other view moves it in the same batch, and FollowTransition runs
	// when it moves to another view.
	Follow           func() *Ref
	FollowTransition *LayoutTransition
	// MatchID makes the view one with a view of the same ID that the
	// commit inserting it removes, as SwiftUI's matchedGeometryEffect and
	// Motion's layoutId: under Scope.AnimateLayout's Update, it moves and
	// resizes from the frame the removed view showed, which leaves at
	// once, rather than appearing with Create. A thumbnail and the page
	// it opens into share one, so the picture travels between them.
	MatchID string
	// OnFocus and OnBlur follow the keyboard focus to and from a view that takes presses or is Focusable, on desktops and the web; a click presses without focusing. A focused view that leaves the tree hears OnBlur once, after the commit that removed it, or before the next view's OnFocus when the platform reports that first.
	OnFocus func()
	OnBlur  func()
	// OnKeyDown hears each key going down on a hardware keyboard while the view itself has the keyboard focus, as a Tab stop, before the keymap's bindings and the view's own Return and Space do, a modifier pressed alone included; returning true consumes the key, so no binding fires and the view does not press, as a shortcut recorder takes Command+S without the app's Save running. Global shortcuts (desktop.RegisterHotKey) take their keys before the app sees them. It reports on macOS, Windows, Linux and the web, where the browser keeps the shortcuts it gives no page; Android and iOS do not report it yet.
	OnKeyDown func(KeyEvent) bool
	// OnFocusIn and OnFocusOut hear the keyboard focus come to the view or a view inside it from elsewhere, and leave them: a move inside the view is neither, as CSS's :focus-within sees it. A view that stays hears OnFocusOut as the focused view inside it leaves the tree.
	OnFocusIn, OnFocusOut func()
	// PointerEvents says which of the view and its children take
	// touches and the pointer.
	PointerEvents PointerEvents
	// HitSlop extends where the view takes touches beyond its bounds.
	HitSlop Edges
	// HitSlopFunc is HitSlop following what it reads.
	HitSlopFunc func() Edges
	// DelayLongPress is how long a press is held to be a long press; 0
	// is 500 ms.
	DelayLongPress time.Duration
	// OnLayout receives the view's frame after each layout that moves or
	// sizes it.
	OnLayout func(Bounds)
	// OnTransitionEnd runs once a change to the view's style or classes
	// has had its transition's time: its new style's Transition.Delay and
	// Duration after the commit that sends it, at once without a duration
	// or while the user asks for reduced motion. A later change starts it
	// over. The core times it, so it runs whether or not anything moved.
	OnTransitionEnd func()

	// OnPan follows a drag on the view, once PanActivation activates it;
	// an active pan takes the touch from presses and scroll views.
	OnPan         func(PanEvent)
	PanActivation PanActivation
	// PanScrollHandoff lets a vertical pan share a drag with the scroll
	// view inside the view where it starts, on iOS, as a bottom sheet's
	// does: the drag scrolls it back to its top first, and only what goes
	// on past that moves the pan. Other platforms leave the drag to the
	// scroll view.
	PanScrollHandoff bool
	// OnPinch follows a two-finger pinch (a trackpad's on desktops);
	// OnRotation a two-finger rotation.
	OnPinch    func(GestureEvent)
	OnRotation func(GestureEvent)
	// OnWheel takes the mouse wheel's turns and touchpads' scrolls over
	// the view, before the scroll views around it, for what pans and
	// zooms itself, such as a canvas; content that scrolls takes a
	// Scroll. A scroll view inside the view takes its own first. Turns
	// with Control held stay pinches where the platform makes them one.
	OnWheel func(WheelEvent)
	// PanValues are animated values a drag on the view moves on the
	// platform's main thread, by its translation from where they were as
	// it began, with no engine work per move. They need no OnPan.
	PanValues AnimatedXY
	// PinchValue is scaled by pinches on the view, and RotationValue turned
	// by rotations, in radians, on the main thread as PanValues are: from
	// where they were as the gesture began. They need no OnPinch or
	// OnRotation.
	PinchValue    *AnimatedValue
	RotationValue *AnimatedValue
	// OnFileDrop receives the URLs of files dropped on the view from another app, on desktops and the web: file: URLs on desktops, and on the web, which hides paths, blob: URLs with each file's name as the fragment; FileFromURL opens either. OnFileDragEnter and OnFileDragLeave follow them while they are dragged over it. The innermost view with OnFileDrop under the pointer takes them, unless it is Disabled.
	OnFileDrop      func(uris []string)
	OnFileDragEnter func()
	OnFileDragLeave func()
	// IOS, Android and Desktop hold the props only iOS, Android or the
	// desktops have; other platforms ignore them.
	IOS     IOSViewProps
	Android AndroidViewProps
	Desktop DesktopViewProps
	// EdgeBar, when its Scroll is set, makes the view a bar over that
	// scroll view's side, which the scroll view's edge effect sets apart
	// from the content scrolling under it (Scroll.EdgeEffects).
	EdgeBar EdgeBar
	// Selectable makes the texts inside select together, as a web page's
	// do: one selection runs from a place in one text to a place in
	// another, across views. On desktops it is made by dragging, a double
	// click (a word) or a triple click (a whole text), and extended by
	// Shift-clicks; on touch screens by a long press. Cmd or Ctrl+A
	// selects the view's texts, Cmd or Ctrl+C copies and Escape clears.
	// Texts with SelectableOff stay out, and a selectable view inside
	// another is part of the outer one. The highlight is each text's
	// SelectionColor.
	Selectable bool
	// OnTextSelection, with Selectable, receives the selection as the user moves it: its text and the box of the texts it touches, in the view; no Text and no Size when it clears.
	OnTextSelection func(TextSelection)

	Ref *Ref
	// Disabled stops presses and is reported to assistive technology.
	Disabled func() bool
	Selected func() bool
	Checked  func() bool
	// Indeterminate is neither checked nor unchecked, as a "select all"
	// over a partial selection.
	Indeterminate func() bool
	// PartStates styles the view in the states it returns without
	// reporting them, as a part of a control in them: a checkbox's
	// indicator follows the checkbox. Assistive technology hears the
	// states from the control alone.
	PartStates func() PartStates
	// Pressed is a toggle that is on, for screen readers and pressed
	// styles; Busy an element still loading.
	Pressed, Busy func() bool
	// ShowsExpanded shows the view's Expanded state to the views it holds
	// directly, for their styles, as a popup's trigger does to the app's
	// content; screen readers hear this view alone.
	ShowsExpanded bool
	// Expanded makes the element expandable, as a disclosure or a menu
	// button, and expanded while it returns true.
	Expanded func() bool
	// Expandable, with Expanded, says whether the element expands at all,
	// as a tree's row that may be a folder or a leaf.
	Expandable func() bool
	Role       Role
	// AccessibilityLevel is the element's level for assistive technology,
	// from 1: a heading's among the page's, a tree item's depth.
	AccessibilityLevel func() int
	// Label is what assistive technology reads.
	Label     string
	LabelFunc func() string
	// LabelFor makes this view a visible label for the referenced control: pressing it focuses the control and runs its press action. The label follows the control's Disabled and Invalid states. References must be mounted in the same tree and confinement scope.
	LabelFor *Ref
	// LabelledBy names the view from these visible elements, in order, ahead of Label. Without it or Label, LabelFor labels name a control in tree order. Missing, hidden, repeated and cyclic references are ignored. LabelledBy alone does not forward presses.
	LabelledBy []*Ref
	// Hint says what activating the element does, read after its label.
	Hint string
	// AccessibilityDescription says more about the element, read after
	// its label and before Hint, as ARIA's aria-description: a dialog's
	// message, what a field expects.
	AccessibilityDescription     string
	AccessibilityDescriptionFunc func() string
	// Invalid marks a field or control whose content or value the app rejected, for screen readers and the aria-invalid: styles (ARIA's aria-invalid).
	Invalid func() bool
	// AccessibilityValue is a range's or a textual element's value, as
	// a slider's or a progress bar's.
	AccessibilityValue func() AccessibilityValue
	// AccessibilityActions are the actions assistive technology offers
	// on the element: the standard ones (ActionActivate, ActionIncrement,
	// ...) through the screen reader's own gestures, others in its
	// actions menu. OnAccessibilityAction receives their names.
	AccessibilityActions  []AccessibilityAction
	OnAccessibilityAction func(name string)
	// Accessible makes the view one element: its descendants are not
	// exposed separately, and without a label it reads their text.
	Accessible                bool
	ImportantForAccessibility Importance
	// AccessibilityElementsHidden hides the view and its subtree from
	// assistive technology while it returns true, as content behind a
	// drawer.
	AccessibilityElementsHidden func() bool
	// LiveRegion has screen readers announce changes of the label and text inside the view; a RoleStatus view is a polite one when 0, and reads its whole text.
	LiveRegion LiveRegion
	// Tooltip shows above the view, 4 points away, once the pointer has
	// rested on it for half a second on desktops, until the pointer leaves
	// or presses; it never takes the pointer. The keyboard moving the
	// focus onto the view or into it shows it at once, in every idiom,
	// until the focus leaves or Escape is pressed; a press that focuses
	// it leaves it to the pointer. Touch screens show none otherwise. A
	// HintTooltip (base.Tooltip) decides itself when and where it shows.
	Tooltip Node
	TestID  string
}

View is a container. Its look is its style; it has none of its own.

func (View) Render

func (v View) Render(*Scope) Node

Render implements Node.

type ViewPaint

type ViewPaint = driver.ViewPaint

ViewPaint is an op of a drawing whose value is its view's paint.

type ViewPaintKind

type ViewPaintKind = driver.ViewPaintKind

ViewPaintKind is the paint property a ViewPaint takes.

type ViewToken

type ViewToken struct {
	Index      int
	Key        any
	IsViewable bool
}

ViewToken is a row in ViewableItems: its index, its Key (nil without List.Key) and whether it is viewable.

type ViewabilityConfig

type ViewabilityConfig struct {
	// ViewAreaCoveragePercentThreshold is the percent of the viewport a
	// row must cover; it wins over ItemVisiblePercentThreshold.
	ViewAreaCoveragePercentThreshold float32
	// ItemVisiblePercentThreshold is the percent of a row that must be
	// visible.
	ItemVisiblePercentThreshold float32
	// MinimumViewTime is how long rows must stay viewable before they
	// are reported.
	MinimumViewTime time.Duration
}

ViewabilityConfig is when a row counts as viewable. Without a threshold any visible point counts.

type ViewableItems

type ViewableItems struct {
	Viewable []ViewToken
	Changed  []ViewToken
}

ViewableItems is what OnViewableItemsChange reports: the viewable rows and the rows that became or stopped being viewable since the last report.

type Visibility

type Visibility uint8

Visibility says whether a node is seen while it keeps its place.

const (
	VisibilityVisible Visibility = iota + 1
	VisibilityHidden
)

type VisibleContentPosition

type VisibleContentPosition struct {
	// AutoscrollToBottomThreshold is how near the end the list must be
	// to follow it.
	AutoscrollToBottomThreshold Points
}

VisibleContentPosition is List.MaintainVisibleContentPosition's.

type Voice added in v0.2.0

type Voice struct {
	Lang, ID    string
	Rate, Pitch float32
}

Voice is how Speak speaks: in the language Lang, a BCP 47 tag ("en-US", "ja-JP", "zh-TW"), "" being the app's locale; in the voice ID names, one of Voices' IDs, "" being the platform's default voice for Lang; at Rate and Pitch, from 0.5 to 2 with 1 the voice's own, 0 standing for 1 and other values clamped.

type VoiceInfo added in v0.2.0

type VoiceInfo = driver.Voice

VoiceInfo is a voice installed on the platform: the ID Voice takes, the name the platform gives it and the BCP 47 tag of its language.

type WebCookie added in v0.2.0

type WebCookie = driver.WebCookie

WebCookie is a cookie of the store the app's web views share: its name and value, the Domain and Path it goes to, when it Expires (zero for a session cookie, which goes as the app ends; Apple platforms, Windows and Android keep one at most 400 days, as browsers do), whether it goes only over HTTPS (Secure) and stays out of page scripts' reach (HTTPOnly), and its SameSite attribute. Domain is a host, which alone takes the cookie, or with a leading dot (".example.com") the host and every host under it, as a Set-Cookie Domain attribute makes it; Path "" is "/".

type WebDownload

type WebDownload = driver.WebDownload

WebDownload is a download of a web view, which OnDownload follows.

type WebDownloadState

type WebDownloadState = driver.WebDownloadState

WebDownloadState is how far a WebDownload got.

type WebError

type WebError struct {
	URL     string
	Message string
	// Domain and Code are the platform's: NSError's domain and code on Apple platforms, the GError domain's name and its code on Linux, COREWEBVIEW2_WEB_ERROR_STATUS and its value, or HRESULT and the HRESULT of a navigation WebView2 refused, on Windows. Both are empty for a source Access refused and on Android, whose WebView reports its errors without them (the web reports none).
	Domain string
	Code   int
}

WebError is a page that failed to load, or a navigation the platform refused; URL is the page's, when known.

func (*WebError) Error

func (e *WebError) Error() string

type WebInput

type WebInput = driver.WebInput

WebInput is input a web view's page takes as the user's own (Ref.SendInput): WebClick, WebText or WebKey.

func WebClick

func WebClick(x, y Points) WebInput

WebClick is a primary click at x, y in CSS pixels from the page's viewport, as getBoundingClientRect reports them.

func WebKey

func WebKey(key string) WebInput

WebKey presses key, as KeyboardEvent.key names it: Enter, Tab, Escape or Backspace.

func WebText

func WebText(text string) WebInput

WebText types text into what has the page's focus.

type WebInputKind

type WebInputKind = driver.WebInputKind

WebInputKind is what a WebInput gives.

type WebMedia

type WebMedia = driver.WebMedia

WebMedia is the devices a web view's pages may capture (WebView.Media).

type WebMessage

type WebMessage struct {
	Data   string
	Origin string
}

WebMessage is what a web view's page posted, and the page's origin: scheme://host, with the port when it is not the scheme's own, in lower case ("https://example.com", "app://bundle"), "file://" for a file and "null" for a page without an origin of its own, such as HTML without a base URL.

type WebNavigation

type WebNavigation = driver.WebNavigation

WebNavigation is a web view's page and history.

type WebSameSite added in v0.2.0

type WebSameSite = driver.WebSameSite

WebSameSite is a WebCookie's SameSite attribute.

type WebSource

type WebSource = driver.WebSource

WebSource is what a web view shows: the page at Src, or HTML, whose relative links resolve against BaseURL, instead when it is set. With neither Src nor HTML it loads about:blank and reports the usual load and navigation events, clearing any previous page.

func WebHTML

func WebHTML(html, baseURL string) WebSource

WebHTML returns the source showing html, with relative links resolved against baseURL ("" for none).

func WebSrc

func WebSrc(url string) WebSource

WebSrc returns the source loading the page at url.

type WebView

type WebView struct {
	// Source loads about:blank when neither Src nor HTML is set, clearing the previous page and reporting the usual load and navigation events.
	Source WebSource
	// The page loads again when SourceFunc's source changes.
	SourceFunc func() WebSource
	// InjectedJavaScript runs after each page loads, and
	// InjectedJavaScriptBeforeContent before each page's own scripts.
	InjectedJavaScript              string
	InjectedJavaScriptBeforeContent string
	// UserAgent replaces the platform's.
	UserAgent string
	// Headers are sent with the initial URL request where the platform
	// supports custom request headers. HTML sources do not make one.
	Headers map[string]string
	// Incognito keeps website data in memory for this view, apart from the app's other web views, on Apple platforms, Windows and Linux. Android has one cookie store and one set of website data per app, so there it only keeps the view from the HTTP cache, DOM storage and saved form data. It is read when the native view is first made; changing it afterwards has no effect.
	Incognito bool
	// NoScroll keeps the user from scrolling the page; NoJavaScript keeps
	// pages from running scripts.
	NoScroll     bool
	NoJavaScript bool
	// PinchZoom lets the user magnify the page with a pinch: a trackpad's on macOS, a touchpad's or a touch screen's on Windows, where it also allows Ctrl with the wheel or with + and -, as a touchpad's pinch reaches the page as Ctrl with the wheel, and a touch screen's on Android. Without it the page keeps its size on those platforms. iOS zooms as the page's viewport says, and WebKitGTK on Linux and the browser on the web keep their own handling, having no switch for it.
	PinchZoom bool
	// BackForwardGestures lets swipes go back and forward where the
	// platform has them (iOS, macOS trackpads).
	BackForwardGestures bool
	// Media is what the pages may capture through getUserMedia:
	// WebMicrophone, WebCamera or both. The system still asks the user
	// for each device once, and a page asking for one Media leaves out is
	// refused. Packages declare their use: NSMicrophoneUsageDescription
	// and NSCameraUsageDescription in nsgo.yaml's apple.info, without
	// which Apple's platforms refuse the page, and RECORD_AUDIO and
	// CAMERA in android.permissions. It applies to the pages' next
	// requests, and on the web to the next page loaded.
	Media WebMedia
	// Class is Tailwind CSS classes, as View's.
	Class     string
	Style     Style
	StyleFunc func() Style

	// OnLoadStart, OnLoad and OnNavigationStateChange receive the page's
	// state as it starts loading, finishes and navigates.
	OnLoadStart             func(WebNavigation)
	OnLoad                  func(WebNavigation)
	OnNavigationStateChange func(WebNavigation)
	// OnError receives a *WebError. A load cut short, by StopLoading, a new source, another navigation or a download it turned into, is no error.
	OnError func(err error)
	// MessageOrigins are the origins whose pages reach OnMessage and OnMessageFrom, written as WebMessage.Origin is ("https://example.com"), or "*" for any. Without them only pages of the source's own origin do: Src's, or for HTML BaseURL's, and "null" for HTML without one. "null" is the origin of every page without one of its own, a data: URL a frame sent the view to as much as the source's HTML, so "null", by default or listed, lets in only the source's page; "*" lets in every page. Only the page posts, never a frame in it, on every platform; a frame reaches the app through the page, with window.parent.postMessage, whose event tells the page the frame's origin.
	MessageOrigins []string
	// OnMessage receives what the page posted, as a string, and OnMessageFrom with the origin of the page that posted it.
	OnMessage     func(data string)
	OnMessageFrom func(WebMessage)
	// OnDownload follows what the page downloads, which only a web view
	// with one saves, to downloads/<id>/ in the app's data directory:
	// files WebKit cannot show and links that ask for a download, on
	// Apple platforms, Linux, Windows and Android.
	OnDownload func(WebDownload)
	OnLayout   func(Bounds)
	Ref        *Ref
	Label      string
	TestID     string
}

WebView shows a web page in the platform's web view, which fills the view and takes its own pointer, wheel and keyboard input. Pages reach the app with window.nsgo.postMessage(data), which OnMessage and OnMessageFrom receive from the pages MessageOrigins allows; Ref.PostMessage dispatches a MessageEvent on the page's window.

func (WebView) Render

func (w WebView) Render(*Scope) Node

Render implements Node.

type WheelEvent

type WheelEvent struct {
	// Position is the pointer's place in the view.
	Position  Point
	Delta     Point
	Modifiers Modifiers
	// Touchpad marks a touch surface's scroll, a Magic Mouse's included:
	// what a canvas pans by where a wheel's notches zoom it.
	Touchpad bool
	// Phase is a touchpad's gesture: GestureBegan as the fingers start,
	// GestureChanged as they move, GestureEnded as they lift. Where the
	// system carries the content on after them, as macOS and the web do,
	// its momentum reports more GestureChanged and a GestureEnded of its
	// own. A wheel's notches are GestureChanged.
	Phase GesturePhase
	// Velocity, on GestureEnded, is how fast the fingers moved the content
	// as they lifted, in points a second, where the platform's momentum
	// does not follow them; the view carries it on itself (Decay).
	Velocity Point
}

WheelEvent is a turn of the mouse wheel or a scroll on a touchpad over a view (View.OnWheel). Delta is how far it moves the content, positive right and down: a wheel's notch counts its lines at 40 points on macOS, iOS and the web, 33 on Windows and Linux, as browsers scroll about 100 points a notch.

type WhiteSpace

type WhiteSpace uint8

WhiteSpace says whether text wraps.

const (
	WhiteSpaceNormal WhiteSpace = iota + 1
	WhiteSpaceNoWrap
)

type Window

type Window struct {
	// contains filtered or unexported fields
}

Window is a window or a panel the app opened: the core's part of desktop.Window, which apps use. Its methods do nothing on a nil Window, which OpenWindow returns where the platform opens no windows, or once it closed.

func (*Window) Close

func (w *Window) Close()

Close closes the window for good, as its owner going does, without asking OnClosing.

func (*Window) Closed

func (w *Window) Closed() bool

Closed reports whether the window is closed.

func (*Window) Focus

func (w *Window) Focus()

Focus shows the window in front of the others and activates the app; a panel with PanelOptions.NoActivate comes to the front without the keyboard or activating it.

func (*Window) Hide

func (w *Window) Hide()

Hide hides the window, keeping it and what it shows.

func (*Window) MoveTo

func (w *Window) MoveTo(anchor Bounds, placement Placement) error

MoveTo places a panel beside anchor as ShowAt does, without showing, hiding or focusing it: a panel that shows moves there at once, as one following a caret does, and a hidden one goes there when it next shows. It returns an unavailable error for a window that is not a panel.

func (*Window) OnClosing

func (w *Window) OnClosing(cx *Scope, fn func(*WindowClosing))

OnClosing runs fn when the user asks to close the window, newest first, while the current owner of cx lives; fn may cancel the close.

func (*Window) OnPlacementError

func (w *Window) OnPlacementError(cx *Scope, fn func(error))

OnPlacementError runs fn, under cx, when the platform cannot place the panel where ShowAt or MoveTo asked, as Linux cannot on Wayland, whose compositor places windows itself: the panel stays hidden and the app may show something else instead.

func (*Window) Show

func (w *Window) Show()

Show shows the window: a window without taking the focus from another app; a panel where ShowAt or MoveTo last placed it, else at its platform's default spot, taking the keyboard, without activating the app where the platform can, unless PanelOptions.NoActivate keeps it from the keyboard.

func (*Window) ShowAt

func (w *Window) ShowAt(anchor Bounds, placement Placement) error

ShowAt shows a panel beside anchor, a rectangle in the desktop's screen coordinates (those of Env.Displays and SetWindowFrame) such as a text caret's, on placement's side of it, below for PlaceDefault: it flips to the opposite side when only that one fits on the display that holds anchor's center, and is clamped into that display's visible frame when neither does. A zero-sized anchor is a point, such as the pointer's. Show, Focus and Toggle keep the placement until a tray icon shows the panel under itself. It returns an unavailable error for a window that is not a panel; a platform that cannot place it, Linux on Wayland, reports so to OnPlacementError and leaves it hidden.

func (*Window) Toggle

func (w *Window) Toggle()

Toggle hides the window if it shows, else shows and focuses it.

func (*Window) Visible

func (w *Window) Visible() bool

Visible reports whether the window shows, tracked: what the app's own Show, Hide and Focus calls, and a panel that hides as it loses the focus, made it. A window the user minimizes, or an app the user hides, stays visible here; desktop.Minimized and Env.Lifecycle in the window's content say so.

type WindowAction

type WindowAction = driver.WindowAction

WindowAction is what an ItemWindow asks of the window.

type WindowClosing

type WindowClosing struct {
	// contains filtered or unexported fields
}

WindowClosing is a close the user asked for, as with the window's close button: the core's part of desktop.WindowClosing, which apps use.

func (*WindowClosing) Cancel

func (c *WindowClosing) Cancel()

Cancel keeps the window open, as an app that hides it instead does.

func (*WindowClosing) Canceled added in v0.2.0

func (c *WindowClosing) Canceled() bool

Canceled reports whether a handler canceled the close: what a test of a handler reads.

type WindowCommand

type WindowCommand = driver.WindowCommand

WindowCommand is an ItemWindow's request.

type WindowConstraints

type WindowConstraints = driver.WindowConstraints

WindowConstraints limit a window's size and what the user may do to it.

type WindowControls

type WindowControls = driver.WindowControls

WindowControls is how a hidden title bar shows the system's window controls: hidden, or macOS's traffic lights moved.

type WindowDrag

type WindowDrag = driver.WindowDrag

WindowDrag marks a view as a handle that moves the desktop window, or keeps a view inside such a handle clickable.

type WindowFrame

type WindowFrame = driver.WindowFrame

WindowFrame is where a window moves and how large it becomes, in points from the main screen's top left.

type WindowLevel

type WindowLevel = driver.WindowLevel

WindowLevel is where a window stacks among the others.

type WindowMaterial

type WindowMaterial = driver.WindowMaterial

WindowMaterial is a translucent material behind a desktop window's content, where the app draws nothing opaque.

type WindowOptions

type WindowOptions struct {
	// Title is the window's; empty is the app's name.
	Title string
	// Width and Height are the content's size in points; zero is the
	// main window's (nsgo.WindowSize).
	Width, Height Points
	// Frame, when it moves, opens the window there at its size instead of
	// centered, as an app restoring a window does: Width and Height give
	// way to it, and a window no screen would show opens centered.
	Frame WindowFrame
	// Key, when set, finds a window opened with the same key and still
	// open: OpenWindow shows and focuses it instead of opening another.
	Key string
	// Hidden opens the window without showing it.
	Hidden bool
	// Material is the material behind the content (WindowMaterial).
	Material WindowMaterial
	// Constraints limit the window's size, which Width and Height keep
	// to, and what the user may do to it.
	Constraints WindowConstraints
	// Workspaces are the workspaces the window shows on (desktop.SetWindowWorkspaces).
	Workspaces WindowWorkspaces
	// PointerEvents is where the window takes the pointer (SetWindowPointerEvents), from its first frame.
	PointerEvents WindowPointerEvents
	// Transparent leaves the window without a background or frame: what is behind it shows wherever the app draws nothing, as for a desktop pet or a widget, and WindowDrag views move it. desktop.SetWindowTransparent changes it later, which on Windows needs a window opened transparent; desktop.CanMakeWindowsTransparent says in the window's scope whether what is behind it shows; where it does not, the window stays opaque. desktop.Transparent says whether the window is transparent now.
	Transparent bool
	// NoShadow drops the system's shadow around the window; on Windows only a transparent window has none.
	NoShadow bool
	// SkipTaskbar keeps the window off the Windows taskbar and Alt+Tab, off the task list on X11, and out of macOS's Window menu and Cmd+`; the Dock is the app's (desktop.SetDockVisible), and Wayland has no such hint (desktop.CanSkipTaskbar).
	SkipTaskbar bool
}

WindowOptions are a window's: the core's part of desktop.WindowOptions, which apps use.

type WindowPlacement

type WindowPlacement = driver.WindowPlacement

WindowPlacement is the side of a screen rectangle where a panel goes.

type WindowPointerEvents added in v0.2.0

type WindowPointerEvents = driver.WindowPointerEvents

WindowPointerEvents is where a desktop window takes the pointer: the core's part of desktop.WindowPointerEvents, which apps use.

type WindowWorkspaces added in v0.2.0

type WindowWorkspaces = driver.WindowWorkspaces

WindowWorkspaces are the workspaces a window shows on.

type WritingDirection

type WritingDirection uint8

WritingDirection is the base direction of a text's paragraphs.

const (
	WritingLTR WritingDirection = iota + 1
	WritingRTL
	// WritingAuto takes the direction of the text's first strong
	// character, as HTML's dir="auto".
	WritingAuto
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL